From 5a9d104b37e73c88cff607fbf1e2ec0d04fedf3b Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Mon, 23 Nov 2026 13:39:03 +0000 Subject: [PATCH] chore(lean): model redirects, key lookup, upserts, retries, CORS, TTL --- lean4/FINDINGS.md | 34 +++++++++++++++---- lean4/Gohoarder/Access.lean | 61 +++++++++++++++++++++++++++++++---- lean4/Gohoarder/Release.lean | 10 +++--- lean4/Gohoarder/Security.lean | 14 ++++++++ lean4/Gohoarder/Stats.lean | 20 ++++++++++++ 5 files changed, 122 insertions(+), 17 deletions(-) diff --git a/lean4/FINDINGS.md b/lean4/FINDINGS.md index d1e398a..74c8593 100644 --- a/lean4/FINDINGS.md +++ b/lean4/FINDINGS.md @@ -20,6 +20,12 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. | GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 | | GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 | | GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f | +| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e | +| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 | +| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f | +| 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 | ### Exploit paths and reach @@ -30,9 +36,31 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. - **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong scan results rather than serving blocked packages; any deployment with a block policy served such packages. +- **GH-17.** A page at any origin issued `DELETE /api/packages///` from a visitor's browser, and + `Access-Control-Allow-Origin: *` let it read every `/api` response. Reach: any visitor to a hostile page when + `auth.enabled` is false (production); impact is cache eviction. Fixed by `apiOriginGuard` against `server.allowed_origins`; + with none set, only same-origin passes. +- **GH-19.** An allowed host that answered 302 reached any target (`169.254.169.254`, `127.0.0.1`, `10.x`), by name or by + DNS rebinding. No allowed host redirects today; the fix removes the dependency on that. Hops are capped at 10, limited to + http(s), vetted against the allowlist, and a hop to another host dials through a guard that refuses private, loopback, + link-local and carrier-grade addresses after resolution. A redirect inside one host is left alone: a private index is + operator-trusted. - **GH-04.** The publisher of an npm or PyPI package named `x.info` skipped the scan and the block policy. Reach: any package publisher; needs a block policy to matter. +### Notes on the fixed rows + +- **GH-15.** `cache.ttl_overrides` has no consumer in the Go code (`grep TTLOverrides pkg cmd`: the field and its compiled default + only). The per-registry keys are kept and now default to 24h; they change nothing until something reads them. +- **GH-18.** New keys read `ghk_.`; the hash covers the secret and one lookup selects the stored key. A miss + compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They + cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the + legacy path. Production holds none. +- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes. +- **GH-21.** `RescanWorker` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour. +- **GH-17 cleanup.** The per-handler `Access-Control-Allow-Origin: *` lines in `pkg/app/handlers*.go` are now overridden by the + guard and are dead; remove them once the API performance work lands. + ## Not fixed | id | area | claim | verdict | why | @@ -42,13 +70,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`. | GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. | | GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. | | GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. | -| GH-15 | release age | a cached packument or index hides new or yanked entries for up to the TTL | by-design | Quoted intent, `pkg/cache/cache.go` store: "TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed based on upstream Cache-Control". Passthrough proved: `Release.rewrite_preserves_upload_time`, `stale_hides_only_gated` (needs TTL <= gate; production 24h <= 72h holds, the compiled default 168h does not, and then the proxy is stricter than the gate). | | GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. | -| GH-17 | auth off | with `auth.enabled: false` (production) `DELETE /api/packages/*` is unauthenticated, and `Access-Control-Allow-Origin: *` lets a browser page issue it | by-design, product decision | Quoted intent, `pkg/app/app.go`: "routes are mounted bare to preserve backward-compatible public access". Impact is cache eviction only. Enabling auth is a configuration change the operator owns. | -| GH-18 | api keys | `ValidateAPIKey` bcrypt-compares every stored key per request | hardening, CWE-400 | N keys cost N bcrypt checks per bad key. A key-id prefix needs an API change. Zero keys in production. | -| GH-19 | SSRF | `network.Client` follows redirects without re-checking the allowlist | hardening | `Access.redirect_escapes_allowlist`. No allowed host redirects (pypi.org, files.pythonhosted.org); a private index host is operator-trusted. | -| GH-20 | stats, sqlite | `INSERT OR REPLACE` has no unique index on SQLite, so every pass duplicates registry rows | correctness, SQLite only | Seen in a row dump (three NULL-package hourly rows for one bucket after three passes). Production is PostgreSQL, where `statsUpsertIndexes` exist. Needs a dedupe migration; left open. | -| GH-21 | scan retry | a retry on S3 or SMB storage rescans a temp file already removed | suspected, unconfirmed | `cache.go` store removes `tempPath` after the first scan. Production is filesystem. No test written. | ### Decision: `fail_closed: false` with recurring infrastructure errors diff --git a/lean4/Gohoarder/Access.lean b/lean4/Gohoarder/Access.lean index fb7cb73..e7c0f2e 100644 --- a/lean4/Gohoarder/Access.lean +++ b/lean4/Gohoarder/Access.lean @@ -5,7 +5,7 @@ import Mathlib Models `pkg/app/app.go` `buildCheckOrigin` / `normalizeOriginHost`, `pkg/app/handlers_admin.go` `requireAdmin`, `pkg/auth/auth.go` (`getPermissionsForRole`, `ValidateAPIKey` expiry), -`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards), `Dockerfile.frontend`. +`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards, `get`), `pkg/network/client.go` (`send`), `pkg/auth/auth.go` (`ValidateAPIKey` cost), `pkg/app/cors.go` (`apiOriginGuard`), `Dockerfile.frontend`. Omits: the TLS layer, bcrypt internals, DNS. -/ @@ -125,15 +125,64 @@ theorem internal_hosts_rejected : hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧ hostAllowed "metadata.google.internal" = false := by decide -/-- The allowlist is checked once, on the first hop. `network.Client` follows redirects without -re-checking, so an allowed host that answers 302 reaches any target. Acceptable only while no -allowed host redirects (pypi.org and files.pythonhosted.org do not). -/ -def hopAllowed (hops : List String) : Bool := hops.head?.any hostAllowed +/-- Before the fix the allowlist was checked once, on the first hop. `network.Client` followed +redirects without re-checking, so an allowed host that answers 302 reached any target. -/ +def hopAllowedOld (hops : List String) : Bool := hops.head?.any hostAllowed + +/-- After the fix (`network.Client.send`, `pypi.Handler.get`) every hop must pass the allowlist. -/ +def hopAllowed (hops : List String) : Bool := hops.all hostAllowed theorem redirect_escapes_allowlist : - hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = true ∧ + hopAllowedOld ["files.pythonhosted.org", "169.254.169.254"] = true ∧ hostAllowed "169.254.169.254" = false := by decide +theorem fixed_redirect_stays_allowlisted : + hopAllowed ["pypi.org", "files.pythonhosted.org"] = true ∧ + hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = false := by decide + +/-- A hop is accepted only if every hop is on the allowlist. -/ +theorem hopAllowed_implies_each (hops : List String) (h : hopAllowed hops = true) : + ∀ x ∈ hops, hostAllowed x = true := by + simpa [hopAllowed] using h + +/-! ### API key validation cost (`pkg/auth/auth.go` `ValidateAPIKey`) -/ + +/-- bcrypt compares for one request when every stored key is a candidate (before the fix). -/ +def compareCostOld (storedKeys : ℕ) : ℕ := storedKeys + +/-- A key carrying its id selects one stored key: one compare, hit or miss (a miss compares a dummy hash). -/ +def compareCostNew (_storedKeys : ℕ) : ℕ := 1 + +theorem old_cost_grows_with_keys : compareCostOld 1000 = 1000 := rfl + +theorem new_cost_independent_of_keys (n m : ℕ) : compareCostNew n = compareCostNew m := rfl + +/-! ### Cross-origin writes on `/api` (`pkg/app/cors.go` `apiOriginGuard`) -/ + +/-- Before the fix every handler answered `Access-Control-Allow-Origin: *`, so any page could call them. -/ +def corsOld (_ : Origin) : Bool := true + +/-- After the fix a state-changing request passes iff it names no origin (non-browser client) or an +allowed one; the same rule as the WebSocket origin check. -/ +def writeAllowed (rules : List Origin) : Option Origin → Bool + | none => true + | some o => rules.any (fun r => matchesExact r o) + +def dashboard : Origin := ⟨Scheme.https, "gohoarder.example.com".toList, none⟩ +def attacker : Origin := ⟨Scheme.https, "evil.example.net".toList, none⟩ + +theorem old_cors_admits_any_page : corsOld attacker = true := rfl + +theorem fixed_refuses_foreign_origin : writeAllowed [dashboard] (some attacker) = false := by decide + +theorem fixed_admits_dashboard_and_cli : + writeAllowed [dashboard] (some dashboard) = true ∧ writeAllowed [dashboard] none = true := by decide + +/-- With nothing configured only a request with no origin passes the allowlist step; browsers fall to the +same-origin host comparison in the handler. -/ +theorem empty_allowlist_refuses_any_origin (o : Origin) : writeAllowed [] (some o) = false := by + simp [writeAllowed] + /-! ### Frontend blocklist (`Dockerfile.frontend`) -/ /-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/ diff --git a/lean4/Gohoarder/Release.lean b/lean4/Gohoarder/Release.lean index f51e247..976d4d8 100644 --- a/lean4/Gohoarder/Release.lean +++ b/lean4/Gohoarder/Release.lean @@ -47,12 +47,12 @@ theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ tt (hnew : s < t) : ¬ gateAccepts gate now t := by unfold gateAccepts; omega -/-- Production: `default_ttl: 24h` against a 72h gate. -/ -theorem prod_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide +/-- Production and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/ +theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide -/-- The compiled default is 7 days. Against a 72h gate a version aged 84h is eligible but absent -from a 7-day-old snapshot: the proxy withholds it, which is stricter than the gate, never looser. -/ -theorem default_ttl_exceeds_gate : +/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but +absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/ +theorem old_default_ttl_exceeded_gate : ∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩ diff --git a/lean4/Gohoarder/Security.lean b/lean4/Gohoarder/Security.lean index e6f3897..18790b2 100644 --- a/lean4/Gohoarder/Security.lean +++ b/lean4/Gohoarder/Security.lean @@ -137,6 +137,20 @@ theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List /-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/ def servesDisabled : Bool := true +/-! ### Retry input (`pkg/cache/cache.go` `store`, `ScanFile`; `scheduleRetry`) -/ + +/-- Before the fix a retry reused the first scan's path. Remote storage scans a temp file removed +after the first attempt, so only local backends kept it. -/ +def retryReadableOld (localBackend : Bool) : Bool := localBackend + +/-- After the fix a retry whose file is gone re-reads the blob through the file source. -/ +def retryReadableNew (localBackend fileSourceSet : Bool) : Bool := localBackend || fileSourceSet + +theorem old_remote_retry_unreadable : retryReadableOld false = false := rfl + +theorem fixed_retry_always_readable : retryReadableNew false true = true ∧ retryReadableNew true false = true := by + decide + /-! ### Retry budget -/ def maxRetries : ℕ := 6 diff --git a/lean4/Gohoarder/Stats.lean b/lean4/Gohoarder/Stats.lean index 5f48017..6e2ead8 100644 --- a/lean4/Gohoarder/Stats.lean +++ b/lean4/Gohoarder/Stats.lean @@ -87,4 +87,24 @@ theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ char /-- A download aggregated after the rollup ran: the old chart shows 1 of 2. -/ theorem chartOld_drops_late_download : chartOld 1 2 < chartNew 1 2 := by decide +/-! ### SQLite upsert (`aggregation_worker.go`, `sqlite_stats.go`) -/ + +/-- A bucket is a list of stored rows; the chart sums them. Before the fix SQLite had no unique index, +so `INSERT OR REPLACE` appended a row per pass. -/ +def chartTotal (rows : List ℕ) : ℕ := rows.sum + +/-- Three passes over a bucket whose registry total is 3: three copies. -/ +theorem old_sqlite_duplicates_rows : chartTotal [3, 3, 3] ≠ 3 := by decide + +/-- `ON CONFLICT ... DO UPDATE` over the unique index keeps one row per bucket: a derived row is set, +a package row adds the new events, as on PostgreSQL. -/ +def upsertDerived (_old new : ℕ) : List ℕ := [new] +def upsertAdditive (old new : ℕ) : List ℕ := [old + new] + +theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) : + chartTotal (upsertDerived old new) = new := by simp [chartTotal, upsertDerived] + +theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) : + chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive] + end Gohoarder.Stats