chore(lean): model cache, keys, scan policy, access, release age and stats

Six Lean 4 + Mathlib modules prove or refute the audited properties and cite the Go files they model. FINDINGS.md records each verdict with its Lean theorem, Go test and fix commit. The axiom audit and the currency check live in lean4/scripts.
This commit is contained in:
2026-11-23 13:16:52 +00:00
parent 3143de3a3f
commit a7b9917696
15 changed files with 1109 additions and 0 deletions
+2
View File
@@ -72,6 +72,7 @@ tests/fixtures/temp/
# Markdown files (except README.md)
*.md
!README.md
!lean4/FINDINGS.md
/gohoarder
*.log
@@ -83,3 +84,4 @@ data/storage
# Local worktrees
.worktrees/
lean4/.lake
+1
View File
@@ -0,0 +1 @@
.lake/
+72
View File
@@ -0,0 +1,72 @@
# Lean audit findings
Audit of GoHoarder at c98720c (v0.1.303) with Lean 4 + Mathlib v4.36.0. Models live in
`lean4/Gohoarder/*.lean`; each cites the Go files it models. Statements are "proved about the model".
A Lean counterexample is never the evidence alone: every fixed row has a Go test that failed first.
Build: `cd lean4 && lake exe cache get && lake build && lake env lean scripts/Axioms.lean`.
Currency: `sh lean4/scripts/check_currency.sh origin/main`.
## Fixed
| id | area | claim | class | severity | evidence (Lean / Go test) | fix commit |
|----|------|-------|-------|----------|---------------------------|------------|
| GH-01 | PyPI fetch | the file fetched from `original_url` is the file the cache key names | security, CWE-345 | high | `Access.old_guard_allows_key_poisoning`, `fixed_guard_binds_key` / `TestHandlePackageFile_OriginalURLFilenameBound` | 5c9f7e6 |
| GH-02 | scan decision | a bypassed CVE never blocks, under any `block_on_severity` | correctness (over-block) | low | `Security.old_low_ignores_bypass`, `fully_bypassed_never_blocks` / `TestCheckVulnerabilities_BypassedCVENeverBlocks` | 4713524 |
| GH-03 | PyPI scan | scanners are asked about the release version, not the file name | security, CWE-693 | high when a block policy is set | `Security.scan_asks_release_version`, `file_name_is_not_release_version` / `TestScanAsksScannersForReleaseVersion` | 3143de3 |
| GH-04 | scan gate | an npm or PyPI package named `*.info` or `*.mod` is scanned | security, CWE-693 | medium | `Cache.npm_named_like_go_metadata_is_scanned`, `old_exempted_npm_package` / `TestCacheHitScansPackagesNamedLikeGoMetadata`, `TestIsMetadataEntry` | f0b37ea |
| GH-05 | storage quota | `used` equals bytes on disk after an overwrite | correctness | low | `Cache.put_keeps_usage_exact`, `old_put_inflates_usage` / `TestPutOverwriteKeepsUsageExact`, `TestPutOverwriteWithinQuota` | 1f31256 |
| GH-06 | LRU eviction | eviction terminates; an overlapping store waits instead of failing | correctness | medium | `Cache.old_evict_is_stuck`, `fixed_evict_measure_falls` / `TestEvictTerminatesWhenDeletesFail`, `TestEvictWaitsForRunningEviction` | 440279a |
| 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 |
### Exploit paths and reach
- **GH-01.** A client requests `/pypi/<victim>/<victim-file>?original_url=https://files.pythonhosted.org/.../<attacker-file>`.
The host is on the allowlist, the key is `pypi/<victim>/<victim-file>`, and an uncached key stores the attacker's
file. Every later client gets it; OSV judges the victim's name and version. The attacker publishes the file on PyPI
and needs no credentials. Reach: any network client of `/pypi`, unauthenticated when `auth.enabled` is false (production).
- **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-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.
## Not fixed
| id | area | claim | verdict | why |
|----|------|-------|---------|-----|
| GH-10 | key path | `keyToPath` rewrites `..` instead of rejecting; distinct keys share a path | hardening, unreachable | `Keys.keyToPath_not_injective`. A probe through the full app showed the HTTP layer resolves literal `..` and answers 404 to encoded slashes (`/npm/lodash/-/lodash-1.0.0/../../x.tgz` reached upstream as `/lodash/-/lodash-x.tgz`). No key with `..` reaches storage. |
| GH-11 | cache hit | the stored SHA-256 is not re-verified on read | by-design | `Put` verifies the stream it just hashed; no doc promises read-side integrity. A check reads up to 2 GB per hit. Disk corruption is outside the proxy's threat model. |
| 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
Served: a package with no scan row while a scan is in flight, and a package whose every scanner failed on infrastructure
(`Security.unscanned_served_iff`, `infra_error_served_forever`). Retries: at most 6 at 5 minute spacing, 7 scans, 30
minutes (`retry_terminates`, `retry_window_minutes`); after that the error row stays and the package stays served until
the rescan worker runs (needs `rescan_interval`). Quoted intent: `pkg/cache/cache.go` "A wait that times out serves the
package unless FailClosed is set"; `scanner.go` "Scan failed on infrastructure, serving package; scan will be retried";
production config "A scan that fails on infrastructure is retried and the package is served (fail_closed false)".
Verdict: acceptable for production, whose only scanner is OSV, a remote service that cannot be made to time out by package
content. Residual risk: with file-based scanners (trivy, grype, pip-audit) a crafted package that makes the scanner time out
is served unscanned, because a deadline counts as infrastructure. Run those with `fail_closed: true`. No code change.
## Negative matrices (do not re-run)
| surface | runs | a leak would look like | verdict |
|---------|------|------------------------|---------|
| frontend nginx blocklist (`Dockerfile.frontend` template on nginx:alpine, stub backend) | 30 raw paths: `//npm`, `/./npm`, `%6Epm`, `/api/../npm`, `/api/..%2fnpm`, `/health/..%2fnpm`, `/ws/..%2fnpm`, `/api/..\npm`, `/api/..;/npm`, `/api/%5c..%5cnpm`, `/api/..%252fnpm`, `/npm?x=1`, `/metrics/` and more | 200 from the backend for `/npm`, `/pypi`, `/go` or `/metrics` | all 404 or SPA. `/NPM/x` returns the SPA page, not the proxy. |
| backend re-interpretation of the six paths nginx forwarded raw | `/api/..\npm/x`, `/api/..;/npm/x`, `/api/%5c..%5cnpm/x`, `/api/%2e%2e%5cnpm/x`, `/api/..%252fnpm/x`, `/api/;/../npm/x` against the full app | 200 from the npm handler | all 404 |
| WebSocket origin check | `Access.default_port_equivalent`, `scheme_mismatch_rejected`, `port_mismatch_rejected`, `glob_rejects_label_prefix`, `glob_rejects_suffix_trick` | an origin outside the allowlist accepted | clean. Same-origin mode compares host only; documented: "the Origin host must match the Host header". |
| history totals under eviction | existing `TestPostgresHistoryTablesHaveNoPackageForeignKey`, `checkDeleteKeepsDownloadHistory` | totals fall after a package delete | clean: history tables carry no foreign key to packages. |
+6
View File
@@ -0,0 +1,6 @@
import Gohoarder.Cache
import Gohoarder.Keys
import Gohoarder.Security
import Gohoarder.Access
import Gohoarder.Release
import Gohoarder.Stats
+151
View File
@@ -0,0 +1,151 @@
import Mathlib
/-!
# Access control and upstream fetch guards
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`.
Omits: the TLS layer, bcrypt internals, DNS.
-/
namespace Gohoarder.Access
/-! ### WebSocket origin -/
inductive Scheme | http | https
deriving DecidableEq
def defaultPort : Scheme → ℕ
| Scheme.http => 80
| Scheme.https => 443
/-- An origin after `strings.ToLower`: host labels plus an optional explicit port. -/
structure Origin where
scheme : Scheme
host : List Char
port : Option ℕ
/-- `normalizeOriginHost`: a port equal to the scheme default is dropped; compare on the effective port. -/
def effPort (o : Origin) : ℕ := o.port.getD (defaultPort o.scheme)
/-- An exact allowlist rule matches iff scheme, host and effective port agree (`buildCheckOrigin`). -/
def matchesExact (rule o : Origin) : Bool :=
decide (rule.scheme = o.scheme) && decide (rule.host = o.host) && decide (effPort rule = effPort o)
theorem default_port_equivalent (s : Scheme) (h : List Char) :
matchesExact ⟨s, h, none⟩ ⟨s, h, some (defaultPort s)⟩ = true := by
simp [matchesExact, effPort]
theorem scheme_mismatch_rejected (rule o : Origin) (h : rule.scheme ≠ o.scheme) :
matchesExact rule o = false := by
simp [matchesExact, h]
theorem port_mismatch_rejected (s : Scheme) (h : List Char) (p q : ℕ) (hp : p ≠ q) :
matchesExact ⟨s, h, some p⟩ ⟨s, h, some q⟩ = false := by
simp [matchesExact, effPort, hp]
/-- Wildcard rule `https://*.d`: `strings.HasSuffix(host, ".d")` or host = `d`. -/
def matchesGlob (d host : List Char) : Bool :=
decide (host = d) || decide (('.' :: d) <:+ host)
/-- The leading dot pins the match to a label boundary: `evilexample.com` is not under `example.com`. -/
theorem glob_rejects_label_prefix :
matchesGlob "example.com".toList "evilexample.com".toList = false := by decide
theorem glob_accepts_subdomain :
matchesGlob "example.com".toList "app.example.com".toList = true := by decide
theorem glob_rejects_suffix_trick :
matchesGlob "example.com".toList "example.com.evil.net".toList = false := by decide
/-! ### Admin gate -/
inductive Role | readonly | readwrite | admin
deriving DecidableEq
/-- `getPermissionsForRole`, restricted to the bypass-management and key-management permissions. -/
def canManageBypasses : Role → Bool
| Role.admin => true
| _ => false
def canManageKeys : Role → Bool
| Role.admin => true
| _ => false
/-- `requireAdmin` admits a key with the admin role or the `bypasses:manage` permission; it also
guards `/api/admin/keys`. No other role holds that permission, so no escalation to key minting. -/
def requireAdminPasses (r : Role) : Bool := decide (r = Role.admin) || canManageBypasses r
theorem admin_gate_implies_key_manager (r : Role) (h : requireAdminPasses r = true) :
canManageKeys r = true := by
cases r <;> simp_all [requireAdminPasses, canManageBypasses, canManageKeys]
/-- `ValidateAPIKey`: a key is a candidate iff it has no expiry or `now <= expiresAt`. -/
def keyLive (now : ℤ) (exp : Option ℤ) : Bool :=
match exp with
| none => true
| some e => decide (now ≤ e)
theorem expired_key_rejected (now e : ℤ) (h : e < now) : keyLive now (some e) = false := by
simp [keyLive, not_le.mpr h]
/-! ### PyPI `original_url` guards -/
/-- A fetch the handler would perform: host and file name of `original_url`. -/
structure Fetch where
host : String
file : String
def allowedHosts : List String := ["pypi.org", "files.pythonhosted.org", "pythonhosted.org"]
/-- `isAllowedPyPIHost`: listed hosts, or a subdomain of pythonhosted.org (suffix on characters). -/
def hostAllowed (h : String) : Bool :=
decide (h ∈ allowedHosts) || decide (".pythonhosted.org".toList <:+ h.toList)
/-- Before the fix: host allowlist only. The cache key is `pypi/<name>/<requested file>`. -/
def acceptsOld (f : Fetch) : Bool := hostAllowed f.host
/-- After the fix: the fetched file must be the requested one. -/
def acceptsNew (requested : String) (f : Fetch) : Bool := hostAllowed f.host && decide (f.file = requested)
/-- Integrity of the cache key: what is stored under a key is the file the key names. -/
theorem fixed_guard_binds_key (requested : String) (f : Fetch) (h : acceptsNew requested f = true) :
f.file = requested := by
simp only [acceptsNew, Bool.and_eq_true, decide_eq_true_eq] at h
exact h.2
/-- Before the fix any file on an allowed host was stored under any requested name. -/
theorem old_guard_allows_key_poisoning :
∃ requested f, acceptsOld f = true ∧ f.file ≠ requested := by
exact ⟨"requests-2.31.0-py3-none-any.whl", ⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl"⟩,
by decide, by decide⟩
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
theorem redirect_escapes_allowlist :
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = true ∧
hostAllowed "169.254.169.254" = false := by decide
/-! ### Frontend blocklist (`Dockerfile.frontend`) -/
/-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/
def blocked (first : String) (rest : String) : Bool :=
decide (first ∈ ["npm", "pypi", "go", "metrics"]) && (decide (rest.toList = []) || decide (rest.toList.head? = some '/'))
theorem blocklist_covers_registries :
blocked "npm" "/x" = true ∧ blocked "pypi" "" = true ∧ blocked "go" "/@v/list" = true ∧
blocked "metrics" "" = true := by decide
/-- A prefix that merely starts with a registry name is not blocked, and is not proxied either: the
`/health` and `/api/` locations are the only ones with a backend. -/
theorem blocklist_is_segment_exact : blocked "npmx" "" = false := by decide
end Gohoarder.Access
+211
View File
@@ -0,0 +1,211 @@
import Mathlib
/-!
# Cache lifecycle
Models `pkg/cache/cache.go`: `store` (expiry), `getOrFetch` and `Get` (hit path,
retry), `purge` and `cleanup` (idle eviction), `evict` (LRU).
What it omits: wall-clock skew, the storage backend, byte-level I/O.
-/
namespace Gohoarder.Cache
/-! ### Expiry: artifacts never expire by age, metadata pages do -/
/-- `pkg/cache/cache.go` `store`: only metadata entries get `now + DefaultTTL`. -/
def expiryFor (isMeta : Bool) (now ttl : ℤ) : Option ℤ :=
if isMeta then some (now + ttl) else none
/-- `pkg/cache/cache.go` `getOrFetch`: `pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt)`. -/
def expired (e : Option ℤ) (now : ℤ) : Prop := ∃ x, e = some x ∧ x < now
theorem artifact_never_expires (now ttl t : ℤ) : ¬ expired (expiryFor false now ttl) t := by
simp [expiryFor, expired]
theorem metadata_expires_after_ttl (now ttl t : ℤ) (h : now + ttl < t) :
expired (expiryFor true now ttl) t :=
⟨now + ttl, by simp [expiryFor], h⟩
theorem metadata_fresh_within_ttl (now ttl t : ℤ) (h : t ≤ now + ttl) :
¬ expired (expiryFor true now ttl) t := by
simp only [expired, expiryFor, ite_true, Option.some.injEq, exists_eq_left']
omega
/-! ### Idle eviction -/
/-- `pkg/cache/cache.go` `cleanup`: cutoff = now - IdleTTL; due iff `LastAccessed.Before(cutoff)`. -/
def idleDue (now idleTTL lastAccessed : ℤ) : Prop := lastAccessed < now - idleTTL
theorem idle_keeps_recent (now idleTTL la : ℤ) (h : now - la ≤ idleTTL) :
¬ idleDue now idleTTL la := by
unfold idleDue; omega
theorem idle_removes_stale (now idleTTL la : ℤ) (h : idleTTL < now - la) :
idleDue now idleTTL la := by
unfold idleDue; omega
/-- A request refreshes `LastAccessed` (`UpdateDownloadCount`), so a hit is never idle-due at that instant. -/
theorem touch_defers_idle (now idleTTL : ℤ) (h : 0 ≤ idleTTL) : ¬ idleDue now idleTTL now := by
unfold idleDue; omega
/-! ### Interleavings of a hit and a purge -/
/-- One step of the concurrent schedule on a single entry. -/
inductive Step
| touch (t : ℤ) -- a request refreshes LastAccessed
| check -- purge's `stillDue` re-read
| del -- purge's `deletePackage`
deriving DecidableEq
structure World where
last : ℤ
present : Bool
checked : Bool -- the last `check` found the entry due
deriving DecidableEq
def run (cutoff : ℤ) : World → List Step → World
| w, [] => w
| w, Step.touch t :: s => run cutoff { w with last := t } s
| w, Step.check :: s => run cutoff { w with checked := decide (w.last < cutoff) } s
| w, Step.del :: s => run cutoff { w with present := if w.checked then false else w.present } s
/-- Check and delete are two steps (`purge`: `stillDue(current)` then `deletePackage`), so a
request between them is lost: the entry is deleted although `LastAccessed >= cutoff`. This is
the window `Get` now covers with its retry. -/
theorem purge_window_deletes_fresh_entry :
let w := run 10 ⟨0, true, false⟩ [Step.check, Step.touch 20, Step.del]
w.present = false ∧ 10 ≤ w.last := by
decide
/-- With no request inside the window the purge honours `stillDue`. -/
theorem purge_without_window_keeps_fresh (cutoff t : ℤ) (h : cutoff ≤ t) :
(run cutoff ⟨0, true, false⟩ [Step.touch t, Step.check, Step.del]).present = true := by
simp [run, not_lt.mpr h]
/-! ### `Get`: probe, then open -/
inductive Outcome | served | refetched | error
deriving DecidableEq
/-- Before the fix: probe in `getOrFetch`, open after the singleflight; `purgedBetween` is a delete
between the two. -/
def getOnce (present purgedBetween : Bool) : Outcome :=
if present then (if purgedBetween then Outcome.error else Outcome.served) else Outcome.refetched
/-- `Get` with `getAttempts = 2`: the second pass re-probes the (now missing) blob and fetches. -/
def getRetry (present d1 d2 : Bool) : Outcome :=
match getOnce present d1 with
| Outcome.error => if d2 then Outcome.error else Outcome.refetched
| o => o
theorem getOnce_errors_on_purge : getOnce true true = Outcome.error := rfl
/-- At most one purge per `Get` never reaches the client as an error. -/
theorem getRetry_survives_one_purge (present d1 d2 : Bool) (h : ¬ (d1 = true ∧ d2 = true)) :
getRetry present d1 d2 ≠ Outcome.error := by
cases present <;> cases d1 <;> cases d2 <;> simp_all [getRetry, getOnce]
/-! ### LRU eviction -/
/-- `evict`: delete oldest first until `freed >= needed`; `sizes` is the oldest-first listing. -/
def evictFreed : List ℕ → ℕ → ℕ
| [], _ => 0
| s :: rest, needed => if needed = 0 then 0 else s + evictFreed rest (needed - s)
theorem evictFreed_le_total (sizes : List ℕ) (needed : ℕ) : evictFreed sizes needed ≤ sizes.sum := by
induction sizes generalizing needed with
| nil => simp [evictFreed]
| cons s rest ih =>
unfold evictFreed
split_ifs
· simp
· simp only [List.sum_cons]; have := ih (needed - s); omega
theorem evictFreed_ge (sizes : List ℕ) (needed : ℕ) (h : needed ≤ sizes.sum) :
needed ≤ evictFreed sizes needed := by
induction sizes generalizing needed with
| nil => simpa [evictFreed] using h
| cons s rest ih =>
unfold evictFreed
split_ifs with h0
· omega
· simp only [List.sum_cons] at h
have := ih (needed - s) (by omega)
omega
/-- After `store` evicts for `needed = used + size - limit` and the listing held enough bytes,
usage including the new entry is within the cap. -/
theorem lru_keeps_cap (used size limit : ℕ) (sizes : List ℕ)
(hroom : used + size - limit ≤ sizes.sum) :
used + size - evictFreed sizes (used + size - limit) ≤ limit := by
have h1 := evictFreed_ge sizes (used + size - limit) hroom
omega
/-- When the listing cannot free enough (`freed < needed`) `evict` still returns nil, so the cap
rests on the backend's `Put` quota check (`filesystem.go` `Put`). The hypothesis of `lru_keeps_cap`
fails here, and the result exceeds the cap. -/
theorem lru_cap_needs_enough_evictable :
∃ used size limit : ℕ, ∃ sizes : List ℕ,
used + size - evictFreed sizes (used + size - limit) > limit := by
exact ⟨100, 10, 100, [5], by decide⟩
/-- The entry being stored is not in the metadata listing (`SavePackage` runs after `Put`), so
eviction never deletes it. -/
theorem evict_spares_unlisted (listed : List String) (new : String) (h : new ∉ listed) :
∀ victim ∈ listed.take 100, victim ≠ new := by
intro v hv hv'
exact h (hv' ▸ List.mem_of_mem_take hv)
/-- One eviction pass: `n` listed rows of which `d` can be deleted; the rest are listed again. -/
def passRemaining (n d : ℕ) : ℕ := n - d
/-- Before the fix the loop continued on `n >= limit` only; a pass that deletes nothing re-lists
the same rows and never ends. -/
theorem old_evict_is_stuck (n : ℕ) : passRemaining n 0 = n := by simp [passRemaining]
/-- After the fix a pass continues only if it deleted a row, so the row count strictly falls. -/
theorem fixed_evict_measure_falls (n d : ℕ) (hd : 0 < d) (hdn : d ≤ n) : passRemaining n d < n := by
unfold passRemaining; omega
/-! ### Quota accounting: overwriting a key
`pkg/storage/filesystem/filesystem.go` `Put`: `fs.used` tracks bytes on disk. -/
/-- After the fix: an overwrite releases the bytes of the file it replaces. -/
def usedAfterPut (used replaced written : ℕ) : ℕ := used - replaced + written
/-- Before the fix: the replaced bytes stayed counted. -/
def usedAfterPutOld (used written : ℕ) : ℕ := used + written
/-- If `used` is the sum of the stored sizes, `other + replaced`, the counter stays exact. -/
theorem put_keeps_usage_exact (other replaced written : ℕ) :
usedAfterPut (other + replaced) replaced written = other + written := by
unfold usedAfterPut; omega
/-- Two writes of one key (400 then 300 bytes) leave 700 counted, 300 on disk. -/
theorem old_put_inflates_usage : usedAfterPutOld (usedAfterPutOld 0 400) 300 = 700 ∧
usedAfterPut (usedAfterPut 0 0 400) 400 300 = 300 := by decide
/-! ### Which entries skip the scan
`pkg/metadata/interface.go` `IsMetadataEntry`; the scan gate in `getOrFetch` and `store`. -/
def metaVersions : List String := ["list", "page", "latest", "metadata"]
/-- After the fix the `.mod` / `.info` name suffix exempts Go entries only. -/
def scanExempt (registry : String) (nameSuffixMeta : Bool) (version : String) : Bool :=
decide (version ∈ metaVersions) || (decide (registry = "go") && nameSuffixMeta)
/-- Before the fix the suffix exempted any registry. -/
def scanExemptOld (nameSuffixMeta : Bool) (version : String) : Bool :=
decide (version ∈ metaVersions) || nameSuffixMeta
theorem npm_named_like_go_metadata_is_scanned (v : String) (hv : v ∉ metaVersions) :
scanExempt "npm" true v = false := by
simp [scanExempt, hv]
theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decide
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
end Gohoarder.Cache
+146
View File
@@ -0,0 +1,146 @@
import Mathlib
/-!
# Storage keys, path safety, canonicalisation
Models `pkg/cache/cache.go` `generateStorageKey`, `pkg/storage/filesystem/filesystem.go`
`keyToPath`, `pkg/proxy/npm/npm.go` `CanonicalPath`, and `pkg/proxy/pypi/pypi.go`
`extractVersionFromFilename`. Omits: symlinks (the store writes through `os.Root`), Unicode.
-/
namespace Gohoarder.Keys
/-! ### `keyToPath`: segment normalisation -/
/-- `filepath.Clean` plus the strip loop in `keyToPath`: `.` and empty segments vanish, `..` pops
a segment and is dropped at the root. Segments are kept in reverse order. -/
def cleanRev : List String → List String → List String
| acc, [] => acc
| acc, seg :: rest =>
if seg = "." ∨ seg = "" then cleanRev acc rest
else if seg = ".." then cleanRev acc.tail rest
else cleanRev (seg :: acc) rest
def clean (segs : List String) : List String := (cleanRev [] segs).reverse
theorem cleanRev_no_dotdot (segs acc : List String) (h : ".." ∉ acc) : ".." ∉ cleanRev acc segs := by
induction segs generalizing acc with
| nil => simpa [cleanRev] using h
| cons seg rest ih =>
unfold cleanRev
split_ifs with h1 h2
· exact ih acc h
· exact ih acc.tail (fun hm => h (List.mem_of_mem_tail hm))
· apply ih
simp only [List.mem_cons, not_or]
exact ⟨fun e => h2 e.symm, h⟩
/-- No cleaned key contains a `..` segment, so the joined path stays under the store root. -/
theorem clean_stays_in_root (segs : List String) : ".." ∉ clean segs := by
unfold clean
simpa using cleanRev_no_dotdot segs [] (by simp)
/-- The sanitiser rewrites; it does not reject. Distinct keys collapse onto one path. -/
theorem keyToPath_not_injective :
clean ["npm", "pkg", "..", "other", "1.0.0"] = clean ["npm", "other", "1.0.0"] ∧
["npm", "pkg", "..", "other", "1.0.0"] ≠ ["npm", "other", "1.0.0"] := by
decide
theorem keyToPath_traversal_is_clamped :
clean ["..", "..", "etc", "passwd"] = ["etc", "passwd"] := by decide
/-! ### Key injectivity: `registry/name/version` -/
/-- `generateStorageKey`: join with `/`. -/
def key (registry name version : String) : List String := [registry, name, version]
/-- Over segment lists the tuple is recoverable; `String.intercalate "/"` is injective exactly
when the parts contain no `/`. -/
theorem key_injective (r n v r' n' v' : String) (h : key r n v = key r' n' v') :
r = r' ∧ n = n' ∧ v = v' := by
simp only [key, List.cons.injEq, and_true] at h
exact ⟨h.1, h.2.1, h.2.2⟩
/-- With `/` inside a part the joined string collides: npm `@x/y` + `b` and `@x` + `y/b`. The
second tuple needs an upstream 200 at a path npm never serves, so the proxy cannot store it. -/
theorem joined_key_collides_with_slash :
String.intercalate "/" ["npm", "@x/y", "b"] = String.intercalate "/" ["npm", "@x", "y/b"] := by
decide
/-! ### `npm.CanonicalPath`: escaped scope separator -/
inductive Tok | scope | esc | sl | other
deriving DecidableEq
/-- Rewrites the first escaped `/` of the first segment (`CanonicalPath`'s `strings.Cut`). -/
def rewriteFirst : List Tok → List Tok
| [] => []
| Tok.sl :: r => Tok.sl :: r
| Tok.esc :: r => Tok.sl :: r
| Tok.scope :: r => Tok.scope :: rewriteFirst r
| Tok.other :: r => Tok.other :: rewriteFirst r
/-- `CanonicalPath` acts only on a segment starting with `@`. -/
def canon : List Tok → List Tok
| Tok.scope :: r => Tok.scope :: rewriteFirst r
| p => p
theorem rewriteFirst_idem (r : List Tok) : rewriteFirst (rewriteFirst r) = rewriteFirst r := by
induction r with
| nil => rfl
| cons t rest ih => cases t <;> simp [rewriteFirst, ih]
/-- Canonicalisation is idempotent: a second pass finds the separator the first one wrote. -/
theorem canon_idem (p : List Tok) : canon (canon p) = canon p := by
cases p with
| nil => rfl
| cons t r => cases t <;> simp [canon, rewriteFirst_idem]
/-- The rewrite adds at most one separator, so a name cannot smuggle extra path segments. -/
theorem rewriteFirst_adds_one_sep (r : List Tok) :
(rewriteFirst r).count Tok.sl ≤ r.count Tok.sl + 1 := by
induction r with
| nil => simp [rewriteFirst]
| cons t rest ih =>
cases t <;> simp [rewriteFirst, List.count_cons] at * <;> omega
theorem canon_adds_one_sep (p : List Tok) : (canon p).count Tok.sl ≤ p.count Tok.sl + 1 := by
cases p with
| nil => simp [canon]
| cons t r =>
have := rewriteFirst_adds_one_sep r
cases t <;> simp [canon, List.count_cons] at * <;> omega
/-- The escape that survives in the name part (`@a%2fb%2fc` gives `@a/b%2fc`) is later rejected:
Fiber answers 404 to an escaped slash, which `TestNPMScopedNames` and the traversal probe
(`/npm/@s%2fn%2f..%2f..%2fx` returns 404) exercise. -/
theorem canon_keeps_later_escape :
canon [Tok.scope, Tok.esc, Tok.other, Tok.esc, Tok.other] =
[Tok.scope, Tok.sl, Tok.other, Tok.esc, Tok.other] := by decide
/-! ### PyPI version from a file name -/
/-- Wheel (PEP 427): the version is the second `-` segment when it starts with a digit. -/
def startsWithDigit (v : String) : Bool :=
match v.toList with
| c :: _ => c.isDigit
| [] => false
def wheelVersion (segs : List String) : Option String :=
match segs with
| _ :: v :: _ => if startsWithDigit v then some v else none
| _ => none
/-- A well-formed wheel name `dist-version-...` yields its version, whatever follows. -/
theorem wheelVersion_correct (d v : String) (rest : List String) (hv : startsWithDigit v = true) :
wheelVersion (d :: v :: rest) = some v := by
simp [wheelVersion, hv]
/-- The cache version for a PyPI file is the file name, which is unique per file, while the
release version is shared by all files of a release (`release_version`). Two files of one release
have different keys and one release key: bypasses by release cover both, by design. -/
theorem pypi_key_per_file_release_shared (name f1 f2 : String) (h : f1 ≠ f2) :
key "pypi" name f1 ≠ key "pypi" name f2 := by
intro e; exact h (key_injective _ _ _ _ _ _ e).2.2
end Gohoarder.Keys
+63
View File
@@ -0,0 +1,63 @@
import Mathlib
/-!
# Release-age passthrough
Models `pkg/proxy/npm/npm.go` `rewriteMetadataURLs`, `pkg/proxy/pypi/simple_json.go`
`rewriteJSONPage`, and the packument/index freshness TTL in `pkg/cache/cache.go`. A client gate
accepts a version when `now - publishedAt >= gate`. Omits: JSON parsing, number formatting.
-/
namespace Gohoarder.Release
/-- A JSON object as key/value pairs. -/
abbrev Obj := List (String × String)
/-- `rewriteJSONPage`: only the `url` value of a file entry changes. -/
def rewriteFile (proxy : String) (o : Obj) : Obj :=
o.map fun kv => if kv.1 = "url" then (kv.1, proxy) else kv
theorem rewrite_preserves_upload_time (proxy : String) (o : Obj) (t : String)
(h : ("upload-time", t) ∈ o) : ("upload-time", t) ∈ rewriteFile proxy o := by
unfold rewriteFile
exact List.mem_map.mpr ⟨("upload-time", t), h, by simp⟩
theorem rewrite_preserves_other_keys (proxy : String) (o : Obj) (k v : String) (hk : k ≠ "url")
(h : (k, v) ∈ o) : (k, v) ∈ rewriteFile proxy o := by
unfold rewriteFile
exact List.mem_map.mpr ⟨(k, v), h, by simp [hk]⟩
theorem rewrite_keeps_keys (proxy : String) (o : Obj) : (rewriteFile proxy o).map Prod.fst = o.map Prod.fst := by
unfold rewriteFile
simp only [List.map_map]
congr 1
funext kv
simp only [Function.comp]
split_ifs <;> simp
/-! ### Staleness against a minimum-age gate -/
/-- The gate accepts a version published at `t` when it is at least `gate` old. -/
def gateAccepts (gate now t : ℤ) : Prop := gate ≤ now - t
/-- A version missing from a snapshot taken at `s` was published after `s`. If the snapshot is at
most `ttl` old and `ttl <= gate`, the missing version is younger than the gate, so the gate would
have refused it anyway: staleness hides nothing the gate allows. -/
theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ ttl) (httl : ttl ≤ gate)
(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
/-- 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 :
∃ 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⟩
/-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/
theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t :=
Iff.rfl
end Gohoarder.Release
+200
View File
@@ -0,0 +1,200 @@
import Mathlib
/-!
# Security decision logic
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `scheduleRetry`,
`pkg/metadata/gormstore/gormstore_v2.go` `GetActiveCVEBypasses`, and the scan gate in
`pkg/cache/cache.go` `getOrFetch`. Severities are ranks (low 1 .. critical 4). Omits: the
scanners themselves, threshold counters (`block_thresholds`), network.
-/
namespace Gohoarder.Security
structure Vuln where
id : ℕ
sev : ℕ
structure Bypass where
cve : ℕ
covers : Bool -- `AppliesTo` empty or equal to this package
active : Bool
expiresAt : ℤ
/-- `GetActiveCVEBypasses`: `active = true AND expires_at > now`. -/
def activeAt (now : ℤ) (b : Bypass) : Bool := b.active && decide (now < b.expiresAt)
def bypassedIds (now : ℤ) (bs : List Bypass) : List ℕ :=
(bs.filter fun b => activeAt now b && b.covers).map (·.cve)
/-- The vulnerabilities no bypass covers (`severityCounts` loop). -/
def remaining (now : ℤ) (bs : List Bypass) (vs : List Vuln) : List Vuln :=
vs.filter fun v => decide (v.id ∉ bypassedIds now bs)
/-- `block_on_severity`: `none` for "none"/empty, else block when a remaining vulnerability has
rank at or above the threshold. -/
def blocksBySeverity (policy : Option ℕ) (vs : List Vuln) : Bool :=
match policy with
| none => false
| some t => vs.any fun v => decide (t ≤ v.sev)
def decideSev (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) : Bool :=
blocksBySeverity policy (remaining now bs vs)
/-- The LOW branch before the fix: `len(result.Vulnerabilities) > 0`, bypasses ignored. -/
def decideLowOld (vs : List Vuln) : Bool := decide (0 < vs.length)
theorem expired_bypass_inactive (now : ℤ) (b : Bypass) (h : b.expiresAt ≤ now) : activeAt now b = false := by
simp [activeAt, not_lt.mpr h]
theorem inactive_bypass_ignored (now : ℤ) (b : Bypass) (h : b.active = false) : activeAt now b = false := by
simp [activeAt, h]
/-- Every vulnerability bypassed by an active, covering bypass: nothing blocks, for any policy. -/
theorem fully_bypassed_never_blocks (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln)
(h : ∀ v ∈ vs, v.id ∈ bypassedIds now bs) : decideSev policy now bs vs = false := by
have : remaining now bs vs = [] := by
simp only [remaining, List.filter_eq_nil_iff, decide_eq_true_eq, not_not]
exact h
simp [decideSev, this, blocksBySeverity]
cases policy <;> simp
/-- A vulnerability at or above the policy that no active bypass covers blocks. -/
theorem uncovered_vuln_blocks (t : ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln)
(hv : v ∈ vs) (hsev : t ≤ v.sev) (hun : v.id ∉ bypassedIds now bs) :
decideSev (some t) now bs vs = true := by
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq]
refine ⟨v, ?_, hsev⟩
simp [remaining, hv, hun]
/-- Adding a bypass never turns an allow into a block. -/
theorem bypass_monotone (policy : Option ℕ) (now : ℤ) (b : Bypass) (bs : List Bypass) (vs : List Vuln)
(h : decideSev policy now (b :: bs) vs = true) : decideSev policy now bs vs = true := by
cases policy with
| none => simp [decideSev, blocksBySeverity] at h
| some t =>
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq, remaining,
List.mem_filter] at h ⊢
obtain ⟨v, ⟨hv, hn⟩, hs⟩ := h
refine ⟨v, ⟨hv, ?_⟩, hs⟩
intro hmem
apply hn
simp only [bypassedIds, List.filter_cons] at hmem ⊢
split_ifs <;> simp_all
/-- Before the fix, LOW blocked a package whose only vulnerability was bypassed. -/
theorem old_low_ignores_bypass :
let vs := [Vuln.mk 1 1]
let bs := [Bypass.mk 1 true true 100]
decideLowOld vs = true ∧ decideSev (some 1) 0 bs vs = false := by
decide
/-! ### Serve decision -/
inductive Scan
| missing (inflight : Bool) -- no result row; `isInflight` while a scan runs
| err (infra : Bool) -- every scanner failed
| ok (vs : List Vuln)
/-- `CheckVulnerabilities` and the gate: `true` means the package is served. -/
def serves (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
Scan → Bool
| s =>
if pkgBypass then true else
match s with
| Scan.missing inflight => !failClosed && inflight
| Scan.err infra => !failClosed && infra
| Scan.ok vs => !decideSev policy now bs vs
theorem fail_closed_blocks_without_verdict (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (s : Scan)
(hs : (∃ i, s = Scan.missing i) ∨ (∃ i, s = Scan.err i)) :
serves true false policy now bs s = false := by
rcases hs with ⟨i, rfl⟩ | ⟨i, rfl⟩ <;> simp [serves]
/-- A vulnerable package is not served when policy blocks, unless a package bypass covers it. -/
theorem vulnerable_not_served (policy : Option ℕ) (t : ℕ) (hp : policy = some t) (failClosed : Bool)
(now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
(hun : v.id ∉ bypassedIds now bs) :
serves failClosed false policy now bs (Scan.ok vs) = false := by
subst hp
simp [serves, uncovered_vuln_blocks t now bs vs v hv hsev hun]
/-- With `fail_closed = false`, exactly these states serve a package with no verdict: a scan in
flight, or every scanner failing on infrastructure. A package bypass serves in any state. -/
theorem unscanned_served_iff (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
(bs : List Bypass) (i : Bool) :
(serves failClosed pkgBypass policy now bs (Scan.missing i) = true ↔
pkgBypass = true ∨ (failClosed = false ∧ i = true)) ∧
(serves failClosed pkgBypass policy now bs (Scan.err i) = true ↔
pkgBypass = true ∨ (failClosed = false ∧ i = true)) := by
cases failClosed <;> cases pkgBypass <;> cases i <;> simp [serves]
/-- The infra-error record never changes with retries, so the package stays served. -/
theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
serves false false policy now bs (Scan.err true) = true := by
simp [serves]
/-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/
def servesDisabled : Bool := true
/-! ### Retry budget -/
def maxRetries : ℕ := 6
def retryIntervalMin : ℕ := 5
/-- Scans run from `attempt`: `scan` schedules attempt+1 only when infra-only and `attempt < maxRetries`. -/
def scansFrom : ℕ → ℕ
| 0 => 1
| k + 1 => 1 + scansFrom k
theorem scansFrom_eq (k : ℕ) : scansFrom k = k + 1 := by
induction k with
| zero => rfl
| succ k ih => simp only [scansFrom, ih]; omega
theorem scans_total : scansFrom maxRetries = maxRetries + 1 := scansFrom_eq _
theorem retry_window_minutes : maxRetries * retryIntervalMin = 30 := by decide
/-- The attempt counter is bounded, so a package that keeps failing on infrastructure is scanned at most 7 times. -/
theorem retry_terminates (attempt : ℕ) : scansFrom (maxRetries - attempt) ≤ maxRetries + 1 := by
rw [scansFrom_eq]; omega
/-! ### Which version scanners are asked about
`pkg/scanner/scanner.go` `scanVersion`: PyPI artifacts are cached under their file name. -/
def scanVersion (release cacheVersion : String) : String :=
if release = "" then cacheVersion else release
theorem scan_asks_release_version (release cacheVersion : String) (h : release ≠ "") :
scanVersion release cacheVersion = release := by
simp [scanVersion, h]
theorem npm_scan_keeps_cache_version (cacheVersion : String) :
scanVersion "" cacheVersion = cacheVersion := by
simp [scanVersion]
/-- Before the fix scanners received the file name, which is never a release version. -/
theorem file_name_is_not_release_version :
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
/-! ### Merge: worst status wins, but a failed scanner leaves no trace -/
/-- ranks: clean 0, pending 1, error 2, vulnerable 3 (`mergeResults`). -/
def mergeRank (xs : List ℕ) : ℕ := xs.foldr max 0
theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRank xs := by
induction xs with
| nil => simp at h
| cons y ys ih =>
simp only [mergeRank, List.foldr_cons]
rcases List.mem_cons.mp h with rfl | h
· exact le_max_left _ _
· exact le_trans (ih h) (le_max_right _ _)
/-- Results exist only for scanners that returned; with one scanner failing and one clean, the
merged status is clean and no retry is scheduled (`scan`: retry only when no scanner succeeded). -/
theorem partial_failure_reads_clean : mergeRank [0] = 0 := by decide
end Gohoarder.Security
+90
View File
@@ -0,0 +1,90 @@
import Mathlib
/-!
# Stats and time series
Models `pkg/metadata/gormstore/aggregation_worker.go` (`AggregateHourly`, `AggregateDaily`) and
`pkg/metadata/gormstore/gormstore_v2.go` `GetTimeSeriesStats`. Time is in whole minutes since the
epoch; an hour is 60 minutes and a day 24 hours. Omits: unique IPs, packages, registries.
-/
namespace Gohoarder.Stats
/-! ### Hourly pass: each event is counted once -/
/-- `AggregateHourly`: cutoff hour = floor((now - 5min) / 60); events in earlier hours move to
`hr` and are deleted, in one transaction. -/
def cutoffHour (nowMin : ℤ) : ℤ := (nowMin - 5) / 60
def moveEvents (c : ℤ) (ev hr : ℤ → ℕ) : (ℤ → ℕ) × (ℤ → ℕ) :=
(fun h => if h < c then 0 else ev h, fun h => hr h + if h < c then ev h else 0)
/-- Per hour, events plus hourly rows are unchanged by a pass: nothing is counted twice or dropped. -/
theorem hourly_pass_conserves (c : ℤ) (ev hr : ℤ → ℕ) (h : ℤ) :
(moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h = ev h + hr h := by
simp only [moveEvents]
split_ifs <;> omega
theorem hourly_pass_conserves_sum (c : ℤ) (ev hr : ℤ → ℕ) (S : Finset ℤ) :
∑ h ∈ S, ((moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h) = ∑ h ∈ S, (ev h + hr h) :=
Finset.sum_congr rfl fun h _ => hourly_pass_conserves c ev hr h
/-- Within five minutes after the hour the cutoff is still the previous hour, so the last hour of a
day is not aggregated by a pass at `hh:00`-`hh:04`. -/
theorem early_tick_leaves_last_hour (hourIdx m : ℤ) (hm0 : 0 ≤ m) (hm : m < 5) :
cutoffHour (60 * hourIdx + m) = hourIdx - 1 := by
unfold cutoffHour; omega
theorem late_tick_covers_last_hour (hourIdx m : ℤ) (hm0 : 5 ≤ m) (hm : m < 60) :
cutoffHour (60 * hourIdx + m) = hourIdx := by
unfold cutoffHour; omega
/-! ### Daily pass: which days are rolled up -/
def retentionDays : ℕ := 7
/-- Days recomputed by each pass (`rollupDays`). -/
def rollupDays : ℕ := 6
/-- A pass on day `t` rolls up day `d` (before: only yesterday). -/
def oldRolls (t d : ℕ) : Prop := d + 1 = t
def newRolls (t d : ℕ) : Prop := d + 1 ≤ t ∧ t ≤ d + rollupDays
theorem rollup_window_below_retention : rollupDays < retentionDays := by decide
/-- The pass on day `t` deletes hourly rows older than 7 days: hours of day `d` survive it
whenever `t < d + 7`. The new window ends at `d + 6`, inside that bound. -/
theorem new_window_inside_retention (t d : ℕ) (h : newRolls t d) : t < d + retentionDays := by
unfold newRolls at h; unfold retentionDays rollupDays at *; omega
/-- A day is rolled up if some pass day (hour-0 tick) falls in its window. -/
def covered (rolls : ℕ → ℕ → Prop) (passes : Set ℕ) (d : ℕ) : Prop := ∃ t ∈ passes, rolls t d
/-- Before: skipping the one pass on day d+1 (restart at midnight) loses day d for good. -/
theorem old_loses_day_on_one_skip (d : ℕ) :
¬ covered oldRolls {t | t ≠ d + 1} d := by
rintro ⟨t, ht, h⟩
unfold oldRolls at h
exact ht h.symm
/-- After: any single surviving pass in the next six days repairs it. -/
theorem new_repairs_after_skip (d : ℕ) : covered newRolls {t | t ≠ d + 1} d :=
⟨d + 2, by simp, by unfold newRolls rollupDays; omega⟩
/-! ### Chart: rollup against hourly rows and events -/
/-- Before: `counts[day] = rollup`. After: the larger of rollup and hourly+events. -/
def chartOld (rollup live : ℕ) : ℕ := rollup
def chartNew (rollup live : ℕ) : ℕ := max rollup live
/-- Rollup and live (hourly rows + events) each count a subset of the day's downloads, so the
larger is the better lower bound and never exceeds the truth. -/
theorem chartNew_sound (truth rollup live : ℕ) (hr : rollup ≤ truth) (hl : live ≤ truth) :
chartNew rollup live ≤ truth := max_le hr hl
theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ chartNew rollup live :=
le_max_left _ _
/-- 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
end Gohoarder.Stats
+96
View File
@@ -0,0 +1,96 @@
{"version": "1.3.0",
"packagesDir": ".lake/packages",
"packages":
[{"url": "https://github.com/leanprover-community/mathlib4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
"name": "mathlib",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": false,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/plausible",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "054b228ce0ac61d767c6e71ba73a24728f191b72",
"name": "plausible",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/LeanSearchClient",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9",
"name": "LeanSearchClient",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/import-graph",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0",
"name": "importGraph",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/ProofWidgets4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "2f0f3520daeac2d9310ff25b7a877a0e5cdaa203",
"name": "proofwidgets",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/aesop",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "66ff77cf0c4c898799e4b94d14db55f7a02d0c5a",
"name": "aesop",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/quote4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "ff055a2fcc835935e0ae607339b455a5f5896b4b",
"name": "Qq",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/batteries",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "b4b25a3886a16daacaf6615c2eea7170a6e8f458",
"name": "batteries",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover/lean4-cli",
"type": "git",
"subDir": null,
"scope": "leanprover",
"rev": "50810f72af7618bee62fe9800dc26e806c188703",
"name": "Cli",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": true,
"configFile": "lakefile.toml"}],
"name": "gohoarder",
"lakeDir": ".lake",
"fixedToolchain": false}
+10
View File
@@ -0,0 +1,10 @@
name = "gohoarder"
defaultTargets = ["Gohoarder"]
[[require]]
name = "mathlib"
scope = "leanprover-community"
rev = "v4.36.0"
[[lean_lib]]
name = "Gohoarder"
+1
View File
@@ -0,0 +1 @@
leanprover/lean4:v4.36.0
+27
View File
@@ -0,0 +1,27 @@
import Gohoarder
import Lean
/-! Fails unless every theorem under `Gohoarder` depends only on `propext`, `Classical.choice` and
`Quot.sound`. Run from `lean4/`: `lake env lean scripts/Axioms.lean`. -/
open Lean Elab Command
elab "#audit_axioms" : command => do
let env ← getEnv
let allowed : List Name := [``propext, ``Classical.choice, ``Quot.sound]
let mut audited : Nat := 0
let mut bad : Array String := #[]
for (n, ci) in env.constants.map₁.toList do
if `Gohoarder |>.isPrefixOf n then
if let .thmInfo _ := ci then
audited := audited + 1
let axs ← liftCoreM (collectAxioms n)
for a in axs do
if !allowed.contains a then
bad := bad.push s!"{n} uses {a}"
if bad.isEmpty then
logInfo m!"{audited} theorems audited, axioms within {allowed}"
else
throwError "unexpected axioms:\n{"\n".intercalate bad.toList}"
#audit_axioms
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# Fails when a Go file cited by the Lean model changed in the range with no change under lean4/.
# Usage: lean4/scripts/check_currency.sh [base-ref] (default origin/main)
set -eu
base="${1:-origin/main}"
root="$(git rev-parse --show-toplevel)"
cd "$root"
changed="$(git diff --name-only "$base"...HEAD)"
cited="$(grep -rhoE '(pkg|cmd)/[A-Za-z0-9_./-]+\.go|Dockerfile\.frontend' lean4/Gohoarder | sort -u)"
if printf '%s\n' "$changed" | grep -q '^lean4/'; then
lean_changed=yes
else
lean_changed=no
fi
status=0
for file in $cited; do
if [ ! -f "$file" ]; then
echo "MISSING: $file is cited by the Lean model but does not exist"
status=1
continue
fi
if printf '%s\n' "$changed" | grep -qx "$file" && [ "$lean_changed" = no ]; then
echo "REVIEW: $file is cited by the Lean model and changed with no lean4/ change"
status=1
fi
done
[ "$status" -eq 0 ] && echo "currency: every cited file exists and none changed without a model change"
exit "$status"