Compare commits

...
5 Commits
Author SHA1 Message Date
lukaszraczylo 13abb140d7 docs(lean): record the GH-24 fix commit 2026-11-23 17:24:58 +00:00
lukaszraczylo 378b8731fc fix(app): start the rescan worker
The app created the rescan worker when security.rescan_interval was set but never started it; only Shutdown called Stop. A scan lost to a restart therefore left its package unscanned for good, and old results were never refreshed with new CVEs. startWorkers now starts the worker. The ledger records it as GH-24.
2026-11-23 17:24:55 +00:00
lukaszraczylo a83cc20058 docs(lean): record the GH-23 fix commit 2026-11-23 17:08:24 +00:00
lukaszraczylo 501bf1aec8 fix(pypi): serve pip's PEP 658 metadata requests
pip builds the PEP 658 URL by appending .metadata to the whole link, so the suffix lands on original_url, not the path. The filename binding from GH-01 then rejected the request with 400, and every pip install through the proxy failed. The handler now treats that form as the requested wheel's sidecar and streams it without storing it. A sidecar of another file is still refused. The Lean model and the ledger cover the new form (GH-23).
2026-11-23 17:08:20 +00:00
lukaszraczylo 527c1759f9 fix(frontend): revalidate index.html on every load
nginx sent index.html without Cache-Control, so browsers cached it heuristically. After a deploy, a browser kept loading the previous hashed bundle until the cache expired, and fixes did not appear. The SPA location now sends Cache-Control: no-cache. Hashed assets stay immutable. scripts/check_frontend_html_cache.sh checks both.
2026-11-23 16:36:10 +00:00
9 changed files with 174 additions and 1 deletions
+2
View File
@@ -147,6 +147,8 @@ server {
# Frontend SPA - serve index.html for all other routes
location / {
# index.html names the hashed bundles; a cached copy keeps serving the previous release.
add_header Cache-Control "no-cache" always;
try_files $uri $uri/ /index.html;
}
}
+3 -1
View File
@@ -26,7 +26,9 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | this change |
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | 536f35a |
| GH-23 | PyPI sidecar | pip's PEP 658 request (`<link>.metadata`, suffix on `original_url`) is served as its wheel's sidecar; another file's sidecar is still refused | correctness (pip install failed with 400) | medium (every pip install through the proxy) | `Access.pip_form_keeps_key_binding`, `pip_sidecar_of_other_file_rejected`, `pip_sidecar_of_same_file_accepted` / `TestPipSidecarFormIsStreamed`, `TestHandlePackageFile_OriginalURLFilenameBound` | 501bf1a |
| GH-24 | rescan | with `security.rescan_interval` set, artifacts whose scan never completed are scanned and old results refreshed | correctness (scans lost to a restart stayed unscanned; new CVEs never picked up) | medium | not modelled (worker wiring) / `TestWorkersStartTheRescanWorker` | 378b873 |
### Exploit paths and reach
+24
View File
@@ -121,6 +121,30 @@ theorem old_guard_allows_key_poisoning :
exact ⟨"requests-2.31.0-py3-none-any.whl", ⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl"⟩,
by decide, by decide⟩
/-- pip requests the PEP 658 sidecar as `<link>.metadata`, so the suffix lands on `original_url` and the
request names the sidecar of the requested file. `handlePackageFile` streams it and never stores it. -/
def pipSidecar (requested : String) (f : Fetch) : Bool := decide (f.file = requested ++ ".metadata")
/-- The guard with the pip form: the requested file, or its own sidecar. -/
def acceptsPip (requested : String) (f : Fetch) : Bool :=
hostAllowed f.host && (decide (f.file = requested) || pipSidecar requested f)
/-- What the pip form stores still names the key: only the sidecar escapes, and it is not stored. -/
theorem pip_form_keeps_key_binding (requested : String) (f : Fetch)
(h : acceptsPip requested f = true) (hs : pipSidecar requested f = false) : f.file = requested := by
simp only [acceptsPip, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at h
rcases h.2 with h2 | h2
· exact h2
· rw [h2] at hs; exact absurd hs (by simp)
theorem pip_sidecar_of_other_file_rejected :
acceptsPip "example-1.0.0-py3-none-any.whl"
⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl.metadata"⟩ = false := by decide
theorem pip_sidecar_of_same_file_accepted :
acceptsPip "example-1.0.0-py3-none-any.whl"
⟨"files.pythonhosted.org", "example-1.0.0-py3-none-any.whl.metadata"⟩ = true := by decide
theorem internal_hosts_rejected :
hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧
hostAllowed "metadata.google.internal" = false := by decide
+5
View File
@@ -617,6 +617,11 @@ func (a *App) startWorkers(ctx context.Context) {
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
// Re-scans artifacts whose scan was lost to a restart and refreshes old results.
if a.rescanWorker != nil {
go a.rescanWorker.Start(ctx)
}
}
func (a *App) Run() error {
+56
View File
@@ -0,0 +1,56 @@
package app
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// A cached artifact whose scan never completed (lost to a restart) is scanned once the
// workers start, when security.rescan_interval is set.
func TestWorkersStartTheRescanWorker(t *testing.T) {
osv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"vulns":[]}`))
}))
defer osv.Close()
a := newTestApp(t, func(c *config.Config) {
c.Security.Enabled = true
c.Security.RescanInterval = time.Hour
c.Security.Scanners.OSV.Enabled = true
c.Security.Scanners.OSV.APIURL = osv.URL
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const key = "npm/left-pad/1.3.0"
if err := a.storage.Put(ctx, key, strings.NewReader("tarball"), nil); err != nil {
t.Fatalf("storage.Put: %v", err)
}
now := time.Now()
err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: key,
Size: 7, CachedAt: now, LastAccessed: now,
})
if err != nil {
t.Fatalf("SavePackage: %v", err)
}
a.startWorkers(ctx)
deadline := time.Now().Add(20 * time.Second)
for time.Now().Before(deadline) {
if _, err := a.metadata.GetScanResult(ctx, "npm", "left-pad", "1.3.0"); err == nil {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatal("no scan result after the workers started; the rescan worker never ran")
}
@@ -22,6 +22,9 @@ func TestHandlePackageFile_OriginalURLFilenameBound(t *testing.T) {
{"same file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
{"same file with query", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl?x=1", false},
{"sidecar of same file", path + ".metadata", "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
// pip appends ".metadata" to the whole link, so the suffix lands on original_url instead of the path.
{"pip sidecar of same file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl.metadata", false},
{"pip sidecar of another file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/evil-9.9.9-py3-none-any.whl.metadata", true},
}
h := newHandlerForSSRFTest()
+5
View File
@@ -288,6 +288,11 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
parsed.RawPath = ""
originalURL = parsed.String()
}
// pip appends ".metadata" to the whole link, so the suffix lands on original_url, not the path.
if !isSidecar && gopath.Base(parsed.Path) == filename+metadataSuffix {
isSidecar = true
filename += metadataSuffix
}
if !isAllowedPyPIHost(parsed.Host, h.allowedHosts) {
log.Warn().
Str("original_url", originalURL).
+28
View File
@@ -39,3 +39,31 @@ func TestSidecarRedirectOffAllowlistRefused(t *testing.T) {
t.Errorf("redirect target was fetched (hits=%d)", hit.Load())
}
}
// pip requests the PEP 658 sidecar as <link>.metadata, which puts the suffix on original_url.
// It must be streamed as a sidecar, never cached as the wheel.
func TestPipSidecarFormIsStreamed(t *testing.T) {
const meta = "Metadata-Version: 2.1\nName: example\n"
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/example-1.0.0-py3-none-any.whl.metadata") {
http.NotFound(w, r)
return
}
_, _ = w.Write([]byte(meta))
}))
defer upstream.Close()
client := network.NewClient(network.Config{Timeout: 5 * time.Second, MaxRetries: 1, AllowPrivateRedirects: true})
// No cache: touching it would panic, so a 200 proves the request never reached the wheel path.
h := &Handler{client: client, allowedHosts: []string{"127.0.0.1"}}
const path = "/example/example-1.0.0-py3-none-any.whl"
q := url.Values{"original_url": {upstream.URL + "/files/example-1.0.0-py3-none-any.whl.metadata"}}
req := httptest.NewRequest(http.MethodGet, path+"?"+q.Encode(), nil)
w := httptest.NewRecorder()
h.handlePackageFile(req.Context(), w, req, path)
if w.Code != http.StatusOK || w.Body.String() != meta {
t.Errorf("code=%d body=%q, want 200 with the metadata", w.Code, w.Body.String())
}
}
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# Builds the frontend image from a Dockerfile and checks that the SPA HTML is revalidated on every
# load while hashed assets stay immutable. A cached index.html keeps old bundles after a deploy.
# Usage: scripts/check_frontend_html_cache.sh [Dockerfile]
set -eu
dockerfile="${1:-Dockerfile.frontend}"
root="$(git rev-parse --show-toplevel)"
work="$(mktemp -d)"
tag="gohoarder-frontend-cache-check:$$"
front="gohoarder-cache-check-$$"
cleanup() {
docker rm -f "$front" >/dev/null 2>&1 || true
docker rmi "$tag" >/dev/null 2>&1 || true
rm -rf "$work"
}
trap cleanup EXIT
mkdir -p "$work/frontend/dist/assets"
echo '<html></html>' >"$work/frontend/dist/index.html"
echo 'console.log(1)' >"$work/frontend/dist/assets/index-abc123.js"
cp "$root/$dockerfile" "$work/Dockerfile"
docker build -q --load -t "$tag" "$work" >/dev/null
docker run -d --name "$front" -e BACKEND_HOST=127.0.0.1 -e BACKEND_PORT=8080 "$tag" >/dev/null
headers() {
for _ in 1 2 3 4 5 6 7 8 9 10; do
out="$(docker exec "$front" wget -S -qO /dev/null "http://127.0.0.1$1" 2>&1 || true)"
case "$out" in *"HTTP/"*) printf '%s' "$out" | grep -i 'cache-control' || true; return ;; esac
sleep 1
done
}
status=0
for path in / /index.html /packages /package/go/example.com/mod/v1.0.0; do
cc="$(headers "$path")"
case "$cc" in
*no-cache*) echo "ok: $path is revalidated" ;;
*) echo "FAIL: $path Cache-Control [$cc], want no-cache"; status=1 ;;
esac
done
cc="$(headers /assets/index-abc123.js)"
case "$cc" in
*immutable*) echo "ok: hashed asset is immutable" ;;
*) echo "FAIL: asset Cache-Control [$cc], want immutable"; status=1 ;;
esac
exit "$status"