mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
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:
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user