mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-30 06:57:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7b9917696 | ||
|
|
3143de3a3f | ||
|
|
f0b37ea719 | ||
|
|
7192e4ff3e | ||
|
|
ad4e848e2b | ||
|
|
990a1d3409 | ||
|
|
440279aa50 | ||
|
|
1f31256769 | ||
|
|
4713524778 | ||
|
|
5c9f7e6af3 | ||
|
|
6f604367da |
@@ -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
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.lake/
|
||||
@@ -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. |
|
||||
@@ -0,0 +1,6 @@
|
||||
import Gohoarder.Cache
|
||||
import Gohoarder.Keys
|
||||
import Gohoarder.Security
|
||||
import Gohoarder.Access
|
||||
import Gohoarder.Release
|
||||
import Gohoarder.Stats
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -0,0 +1,10 @@
|
||||
name = "gohoarder"
|
||||
defaultTargets = ["Gohoarder"]
|
||||
|
||||
[[require]]
|
||||
name = "mathlib"
|
||||
scope = "leanprover-community"
|
||||
rev = "v4.36.0"
|
||||
|
||||
[[lean_lib]]
|
||||
name = "Gohoarder"
|
||||
@@ -0,0 +1 @@
|
||||
leanprover/lean4:v4.36.0
|
||||
@@ -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
|
||||
Executable
+33
@@ -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"
|
||||
+14
-6
@@ -593,6 +593,19 @@ func (a *App) setupServer() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// startWorkers starts the background loops that live as long as ctx.
|
||||
func (a *App) startWorkers(ctx context.Context) {
|
||||
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
|
||||
a.wsServer.Start(ctx)
|
||||
|
||||
// Start download data aggregation worker (runs every hour)
|
||||
go a.startAggregationWorker(ctx)
|
||||
|
||||
// Start periodic stats broadcaster (every 30s) so connected WS clients
|
||||
// see live counter updates without polling.
|
||||
go a.startStatsBroadcaster(ctx)
|
||||
}
|
||||
|
||||
func (a *App) Run() error {
|
||||
// Cancellable worker context: aggregation + stats broadcaster goroutines
|
||||
// watch ctx.Done() and exit, so Shutdown can stop them before closing
|
||||
@@ -601,12 +614,7 @@ func (a *App) Run() error {
|
||||
a.cancel = cancel
|
||||
defer cancel()
|
||||
|
||||
// Start download data aggregation worker (runs every hour)
|
||||
go a.startAggregationWorker(ctx)
|
||||
|
||||
// Start periodic stats broadcaster (every 30s) so connected WS clients
|
||||
// see live counter updates without polling.
|
||||
go a.startStatsBroadcaster(ctx)
|
||||
a.startWorkers(ctx)
|
||||
|
||||
// Start Fiber server in goroutine. Branch on TLS to pick Listen vs ListenTLS.
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
|
||||
// event loop: without it the 256-slot broadcast channel fills and every later
|
||||
// event is dropped.
|
||||
func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
|
||||
const events = 1000
|
||||
for i := 0; i < events; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
if i%200 == 0 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
if dropped := a.wsServer.Dropped(); dropped != 0 {
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events)
|
||||
}
|
||||
}
|
||||
Vendored
+48
-49
@@ -8,7 +8,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -49,10 +48,9 @@ type Manager struct {
|
||||
sf singleflight.Group
|
||||
config Config
|
||||
cleanupWG sync.WaitGroup
|
||||
mu sync.RWMutex
|
||||
bcMu sync.RWMutex
|
||||
closeOnce sync.Once
|
||||
evicting bool
|
||||
evictMu sync.Mutex // serialises LRU eviction; a second caller waits and re-checks its quota
|
||||
}
|
||||
|
||||
// SetBroadcaster wires an events.Broadcaster onto the manager so cache
|
||||
@@ -97,6 +95,9 @@ const defaultScanWaitTimeout = 30 * time.Second
|
||||
// cleanupBatchSize bounds how many rows one cleanup query reads.
|
||||
const cleanupBatchSize = metadata.DefaultBatchSize
|
||||
|
||||
// getAttempts bounds how often Get re-resolves an entry whose blob vanished.
|
||||
const getAttempts = 2
|
||||
|
||||
// Eviction metric reasons.
|
||||
const (
|
||||
evictReasonTTL = "ttl"
|
||||
@@ -221,36 +222,44 @@ func (m *Manager) Get(ctx context.Context, registry, name, version string, fetch
|
||||
// Use singleflight to deduplicate concurrent requests
|
||||
key := fmt.Sprintf("%s/%s/%s", registry, name, version)
|
||||
|
||||
result, err, _ := m.sf.Do(key, func() (interface{}, error) {
|
||||
// getOrFetch returns a CacheEntry with Data == nil. Each caller
|
||||
// re-opens its own storage reader below to avoid sharing a
|
||||
// single io.ReadCloser across concurrent waiters.
|
||||
return m.getOrFetch(ctx, registry, name, version, fetchFunc)
|
||||
})
|
||||
var openErr error
|
||||
// A purge can delete the blob between the cache-hit probe and the open
|
||||
// below. The second pass sees the miss and fetches again.
|
||||
for attempt := 0; attempt < getAttempts; attempt++ {
|
||||
result, err, _ := m.sf.Do(key, func() (interface{}, error) {
|
||||
// getOrFetch returns a CacheEntry with Data == nil. Each caller
|
||||
// re-opens its own storage reader below to avoid sharing a
|
||||
// single io.ReadCloser across concurrent waiters.
|
||||
return m.getOrFetch(ctx, registry, name, version, fetchFunc)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entry := result.(*CacheEntry)
|
||||
if entry == nil || entry.Package == nil {
|
||||
return nil, errors.New(errors.ErrCodeStorageFailure, "cache entry missing package metadata")
|
||||
}
|
||||
|
||||
// Open a fresh ReadCloser per caller from storage.
|
||||
data, err := m.storage.Get(ctx, entry.Package.StorageKey)
|
||||
if err != nil {
|
||||
openErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
// Return a copy so concurrent waiters don't share the Data field.
|
||||
return &CacheEntry{
|
||||
Data: data,
|
||||
Package: entry.Package,
|
||||
UpstreamURL: entry.UpstreamURL,
|
||||
CacheControl: entry.CacheControl,
|
||||
FromCache: entry.FromCache,
|
||||
}, nil
|
||||
}
|
||||
|
||||
entry := result.(*CacheEntry)
|
||||
if entry == nil || entry.Package == nil {
|
||||
return nil, errors.New(errors.ErrCodeStorageFailure, "cache entry missing package metadata")
|
||||
}
|
||||
|
||||
// Open a fresh ReadCloser per caller from storage.
|
||||
data, err := m.storage.Get(ctx, entry.Package.StorageKey)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to retrieve cached package")
|
||||
}
|
||||
|
||||
// Return a copy so concurrent waiters don't share the Data field.
|
||||
return &CacheEntry{
|
||||
Data: data,
|
||||
Package: entry.Package,
|
||||
UpstreamURL: entry.UpstreamURL,
|
||||
CacheControl: entry.CacheControl,
|
||||
FromCache: entry.FromCache,
|
||||
}, nil
|
||||
return nil, errors.Wrap(openErr, errors.ErrCodeStorageFailure, "failed to retrieve cached package")
|
||||
}
|
||||
|
||||
// getOrFetch implements the actual get-or-fetch logic
|
||||
@@ -315,7 +324,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
// entries (index pages, lists, .mod/.info) are not scannable
|
||||
// packages, so skip them to avoid a bogus "clean" verdict and
|
||||
// the extra database round-trip.
|
||||
isMetadataEntry := metadata.IsMetadataEntry(name, version)
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
if m.scanner != nil && !isMetadataEntry {
|
||||
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
|
||||
if vulnErr != nil {
|
||||
@@ -383,8 +392,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
|
||||
// Skip security scan wait for metadata entries (index pages, lists, etc.)
|
||||
// Also skip Go module metadata files (.mod, .info)
|
||||
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
|
||||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
|
||||
// Wait briefly for initial scan to complete if scanner is enabled
|
||||
// This prevents serving vulnerable packages on first request.
|
||||
@@ -571,7 +579,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
|
||||
// Create metadata entry
|
||||
now := m.now()
|
||||
isMetadataEntry := metadata.IsMetadataEntry(name, version)
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
|
||||
// Artifacts are immutable, so only idle eviction removes them; metadata
|
||||
// entries must refresh and keep a freshness expiry.
|
||||
@@ -708,19 +716,8 @@ func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) erro
|
||||
|
||||
// evict implements LRU eviction
|
||||
func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
m.mu.Lock()
|
||||
if m.evicting {
|
||||
m.mu.Unlock()
|
||||
return errors.New(errors.ErrCodeStorageFailure, "eviction already in progress")
|
||||
}
|
||||
m.evicting = true
|
||||
m.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
m.mu.Lock()
|
||||
m.evicting = false
|
||||
m.mu.Unlock()
|
||||
}()
|
||||
m.evictMu.Lock()
|
||||
defer m.evictMu.Unlock()
|
||||
|
||||
log.Info().Int64("needed", needed).Msg("Starting LRU eviction")
|
||||
|
||||
@@ -738,12 +735,14 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
break
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
for _, pkg := range packages {
|
||||
if err := m.deletePackage(ctx, pkg); err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to evict package")
|
||||
continue
|
||||
}
|
||||
|
||||
deleted++
|
||||
freed += pkg.Size
|
||||
metrics.RecordCacheEviction("lru")
|
||||
|
||||
@@ -752,8 +751,8 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
}
|
||||
}
|
||||
|
||||
if len(packages) < opts.Limit {
|
||||
break // No more packages
|
||||
if len(packages) < opts.Limit || deleted == 0 {
|
||||
break // No more packages, or the same rows would be listed again
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -197,7 +197,7 @@ func (m *memMetadata) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
defer m.mu.Unlock()
|
||||
var n int64
|
||||
for _, p := range m.pkgs {
|
||||
if p.ExpiresAt != nil && !metadata.IsMetadataEntry(p.Name, p.Version) {
|
||||
if p.ExpiresAt != nil && !metadata.IsMetadataEntry(p.Registry, p.Name, p.Version) {
|
||||
p.ExpiresAt = nil
|
||||
n++
|
||||
}
|
||||
|
||||
Vendored
+104
@@ -0,0 +1,104 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// evictMeta adds the LRU list and a switchable delete failure to memMetadata.
|
||||
type evictMeta struct {
|
||||
*memMetadata
|
||||
listGate chan struct{}
|
||||
listing chan struct{}
|
||||
failDelete atomic.Bool
|
||||
}
|
||||
|
||||
func (m *evictMeta) ListPackages(_ context.Context, opts *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
if m.listing != nil {
|
||||
select {
|
||||
case m.listing <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-m.listGate
|
||||
}
|
||||
return m.list(opts.Limit,
|
||||
func(*metadata.Package) bool { return true },
|
||||
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
|
||||
}
|
||||
|
||||
func (m *evictMeta) DeletePackage(ctx context.Context, registry, name, version string) error {
|
||||
if m.failDelete.Load() {
|
||||
return errors.New("db down")
|
||||
}
|
||||
return m.memMetadata.DeletePackage(ctx, registry, name, version)
|
||||
}
|
||||
|
||||
func seedPackages(t *testing.T, m *memMetadata, store *memStorage, n int, size int64) {
|
||||
t.Helper()
|
||||
for i := 0; i < n; i++ {
|
||||
name := "pkg" + strings.Repeat("x", i%7) + string(rune('a'+i%26)) + time.Duration(i).String()
|
||||
key := "npm/" + name + "/1.0.0"
|
||||
require.NoError(t, store.Put(context.Background(), key, strings.NewReader("d"), nil))
|
||||
require.NoError(t, m.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: key, Size: size,
|
||||
LastAccessed: m.clock.Now().Add(time.Duration(i) * time.Second),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// evict must return when no package can be deleted instead of re-listing the same rows forever.
|
||||
func TestEvictTerminatesWhenDeletesFail(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage()
|
||||
meta := &evictMeta{memMetadata: newMemMetadata(clock)}
|
||||
seedPackages(t, meta.memMetadata, store, 250, 1)
|
||||
meta.failDelete.Store(true)
|
||||
|
||||
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- mgr.evict(context.Background(), 1000) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
require.NoError(t, err)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("evict did not terminate with failing deletes")
|
||||
}
|
||||
}
|
||||
|
||||
// A store that overlaps a running eviction must wait for it, not fail as over quota.
|
||||
func TestEvictWaitsForRunningEviction(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage()
|
||||
meta := &evictMeta{memMetadata: newMemMetadata(clock), listGate: make(chan struct{}), listing: make(chan struct{}, 1)}
|
||||
seedPackages(t, meta.memMetadata, store, 3, 10)
|
||||
|
||||
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); errs[0] = mgr.evict(context.Background(), 10) }()
|
||||
<-meta.listing // first eviction is inside its list query
|
||||
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); errs[1] = mgr.evict(context.Background(), 10) }()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
close(meta.listGate)
|
||||
wg.Wait()
|
||||
|
||||
require.NoError(t, errs[0])
|
||||
require.NoError(t, errs[1])
|
||||
}
|
||||
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// racyStorage deletes the blob and the row when the second Get opens it, as a purge would.
|
||||
type racyStorage struct {
|
||||
*memStorage
|
||||
meta *memMetadata
|
||||
gets atomic.Int32
|
||||
armed atomic.Bool
|
||||
}
|
||||
|
||||
func (s *racyStorage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
if s.armed.Load() && s.gets.Add(1) == 2 {
|
||||
_ = s.Delete(ctx, key)
|
||||
_ = s.meta.DeletePackage(ctx, "npm", "left-pad", "1.0.0")
|
||||
}
|
||||
return s.memStorage.Get(ctx, key)
|
||||
}
|
||||
|
||||
// A purge between the cache-hit probe and the caller's open must not fail the request.
|
||||
func TestGetRecoversFromPurgeBetweenProbeAndOpen(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
meta := newMemMetadata(clock)
|
||||
store := &racyStorage{memStorage: newMemStorage(), meta: meta}
|
||||
|
||||
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
fetch := func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload")), UpstreamURL: "https://upstream/x"}, nil
|
||||
}
|
||||
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.0.0", fetch)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
|
||||
store.armed.Store(true)
|
||||
entry, err = mgr.Get(context.Background(), "npm", "left-pad", "1.0.0", fetch)
|
||||
require.NoError(t, err)
|
||||
body, err := io.ReadAll(entry.Data)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
require.Equal(t, "payload", string(body))
|
||||
}
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// policyBlocker blocks every package it is asked about.
|
||||
type policyBlocker struct{ checks atomic.Int32 }
|
||||
|
||||
func (s *policyBlocker) ScanPackage(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *policyBlocker) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
|
||||
s.checks.Add(1)
|
||||
return true, "blocked by policy", nil
|
||||
}
|
||||
|
||||
// Only Go's .mod and .info files are exempt from scanning; a package of any
|
||||
// other registry whose name ends in .mod or .info is a real package.
|
||||
func TestCacheHitScansPackagesNamedLikeGoMetadata(t *testing.T) {
|
||||
tests := []struct {
|
||||
registry, name, version string
|
||||
wantBlocked bool
|
||||
}{
|
||||
{"npm", "left.info", "1.0.0", true},
|
||||
{"npm", "left.mod", "1.0.0", true},
|
||||
{"pypi", "foo.info", "foo.info-1.0.tar.gz", true},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.zip", "v1.0.0", true},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.mod", "v1.0.0", false},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.info", "v1.0.0", false},
|
||||
{"npm", "left-pad", "metadata", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.registry+"/"+tt.name, func(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage()
|
||||
meta := newMemMetadata(clock)
|
||||
key := tt.registry + "/" + tt.name + "/" + tt.version
|
||||
require.NoError(t, store.Put(context.Background(), key, strings.NewReader("data"), nil))
|
||||
require.NoError(t, meta.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: tt.registry, Name: tt.name, Version: tt.version, StorageKey: key, Size: 4, LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
scanner := &policyBlocker{}
|
||||
mgr, err := New(store, meta, scanner, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
entry, err := mgr.Get(context.Background(), tt.registry, tt.name, tt.version, nil)
|
||||
if tt.wantBlocked {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, entry.Data)
|
||||
_ = entry.Data.Close()
|
||||
require.Zero(t, scanner.checks.Load(), "metadata entries must not be scanned")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -203,7 +203,7 @@ func (s *Store) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
}
|
||||
var cleared int64
|
||||
for _, p := range all {
|
||||
if p.Registry == "" || p.Name == "" || p.ExpiresAt == nil || metadata.IsMetadataEntry(p.Name, p.Version) {
|
||||
if p.Registry == "" || p.Name == "" || p.ExpiresAt == nil || metadata.IsMetadataEntry(p.Registry, p.Name, p.Version) {
|
||||
continue
|
||||
}
|
||||
p.ExpiresAt = nil
|
||||
|
||||
@@ -7,11 +7,16 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// rollupDays is how many completed days each daily pass recomputes; it must stay
|
||||
// below the hourly retention of 7 days.
|
||||
const rollupDays = 6
|
||||
|
||||
// AggregationWorker handles background aggregation of download statistics
|
||||
type AggregationWorker struct {
|
||||
db *gorm.DB
|
||||
stopChan chan struct{}
|
||||
ticker *time.Ticker
|
||||
now func() time.Time // nil means time.Now
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -23,6 +28,14 @@ func NewAggregationWorker(db *gorm.DB) *AggregationWorker {
|
||||
}
|
||||
}
|
||||
|
||||
// clock returns the worker's current time.
|
||||
func (w *AggregationWorker) clock() time.Time {
|
||||
if w.now != nil {
|
||||
return w.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -69,7 +82,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
dialectName := w.db.Name()
|
||||
|
||||
// Calculate cutoff time (aggregate events older than 5 minutes to avoid partial data)
|
||||
cutoff := time.Now().Add(-5 * time.Minute).Truncate(time.Hour)
|
||||
cutoff := w.clock().Add(-5 * time.Minute).Truncate(time.Hour)
|
||||
|
||||
return w.db.Transaction(func(tx *gorm.DB) error {
|
||||
var aggregateSQL string
|
||||
@@ -245,9 +258,11 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
dialectName := w.db.Name()
|
||||
|
||||
// Aggregate yesterday's data
|
||||
yesterday := time.Now().AddDate(0, 0, -1).Truncate(24 * time.Hour)
|
||||
dayEnd := yesterday.Add(24 * time.Hour)
|
||||
// Roll up every completed day whose hourly rows are still held. A pass that
|
||||
// ran before its last hour was aggregated, or never ran, is repaired by the
|
||||
// next one; the hourly rows are kept for longer than rollupDays.
|
||||
dayEnd := w.clock().UTC().Truncate(24 * time.Hour)
|
||||
firstDay := dayEnd.Add(-rollupDays * 24 * time.Hour)
|
||||
|
||||
return w.db.Transaction(func(tx *gorm.DB) error {
|
||||
var aggregateSQL string
|
||||
@@ -319,12 +334,12 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
`
|
||||
}
|
||||
|
||||
if err := tx.Exec(aggregateSQL, yesterday, dayEnd).Error; err != nil {
|
||||
if err := tx.Exec(aggregateSQL, firstDay, dayEnd).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete old hourly stats (keep last 7 days)
|
||||
deleteOlder := time.Now().AddDate(0, 0, -7)
|
||||
deleteOlder := w.clock().AddDate(0, 0, -7)
|
||||
deleteResult := tx.Exec("DELETE FROM download_stats_hourly WHERE time_bucket < ?", deleteOlder)
|
||||
if deleteResult.Error != nil {
|
||||
return deleteResult.Error
|
||||
|
||||
@@ -24,7 +24,8 @@ type GORMStoreV2 struct {
|
||||
registryCache map[string]int32 // Cache registry name -> ID mapping
|
||||
aggregationWorker *AggregationWorker
|
||||
partitionManager *PartitionManager
|
||||
registryCacheMu sync.RWMutex // Protects registryCache for concurrent access
|
||||
now func() time.Time // nil means time.Now
|
||||
registryCacheMu sync.RWMutex // Protects registryCache for concurrent access
|
||||
}
|
||||
|
||||
// NewV2 creates a new GORM-based metadata store with V2 schema
|
||||
@@ -540,9 +541,14 @@ func (s *GORMStoreV2) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
query := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Where("expires_at IS NOT NULL").
|
||||
Where("version NOT IN ?", metadata.MetadataVersions)
|
||||
// The name suffixes mark metadata for Go modules only.
|
||||
suffixConds := make([]string, 0, len(metadata.MetadataNameSuffixes))
|
||||
args := []interface{}{metadata.GoRegistry}
|
||||
for _, suffix := range metadata.MetadataNameSuffixes {
|
||||
query = query.Where("name NOT LIKE ?", "%"+suffix)
|
||||
suffixConds = append(suffixConds, "name LIKE ?")
|
||||
args = append(args, "%"+suffix)
|
||||
}
|
||||
query = query.Where("NOT (registry_id IN (SELECT id FROM registries WHERE name = ?) AND ("+strings.Join(suffixConds, " OR ")+"))", args...)
|
||||
result := query.UpdateColumn("expires_at", nil)
|
||||
if result.Error != nil {
|
||||
return 0, errors.Wrap(result.Error, errors.ErrCodeStorageFailure, "failed to clear artifact expiry")
|
||||
@@ -695,6 +701,14 @@ func (s *GORMStoreV2) Close() error {
|
||||
return sqlDB.Close()
|
||||
}
|
||||
|
||||
// clock returns the store's current time.
|
||||
func (s *GORMStoreV2) clock() time.Time {
|
||||
if s.now != nil {
|
||||
return s.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// GetTimeSeriesStats returns time-series download statistics
|
||||
func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, registry string) (*metadata.TimeSeriesStats, error) {
|
||||
stats := &metadata.TimeSeriesStats{
|
||||
@@ -703,7 +717,7 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg
|
||||
DataPoints: make([]*metadata.TimeSeriesDataPoint, 0),
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
now := s.clock().UTC()
|
||||
var span, bucketDuration time.Duration
|
||||
daily := false
|
||||
switch period {
|
||||
@@ -755,13 +769,17 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg
|
||||
}
|
||||
|
||||
if daily {
|
||||
// A completed day's rollup is authoritative over its leftover hourly rows.
|
||||
rollups, err := s.aggregateRows(ctx, "download_stats_daily", since, now, registryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Hourly rows and events only ever undercount a day, so the larger of the
|
||||
// two is the better figure; a rollup alone covers days already trimmed.
|
||||
for _, r := range rollups {
|
||||
counts[r.Timestamp.UTC().Truncate(bucketDuration).Unix()] = r.Value
|
||||
day := r.Timestamp.UTC().Truncate(bucketDuration).Unix()
|
||||
if r.Value > counts[day] {
|
||||
counts[day] = r.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,10 +11,15 @@ import (
|
||||
)
|
||||
|
||||
func savePkg(t *testing.T, store *GORMStoreV2, name, version string, lastAccessed time.Time, expiresAt *time.Time) {
|
||||
t.Helper()
|
||||
savePkgIn(t, store, "npm", name, version, lastAccessed, expiresAt)
|
||||
}
|
||||
|
||||
func savePkgIn(t *testing.T, store *GORMStoreV2, registry, name, version string, lastAccessed time.Time, expiresAt *time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version,
|
||||
StorageKey: fmt.Sprintf("npm/%s/%s", name, version),
|
||||
Registry: registry, Name: name, Version: version,
|
||||
StorageKey: fmt.Sprintf("%s/%s/%s", registry, name, version),
|
||||
Size: 100, CachedAt: lastAccessed, LastAccessed: lastAccessed, ExpiresAt: expiresAt,
|
||||
}))
|
||||
}
|
||||
@@ -81,26 +86,34 @@ func checkClearArtifactExpiry(t *testing.T, store *GORMStoreV2) {
|
||||
savePkg(t, store, "lodash", "page", now, &exp)
|
||||
savePkg(t, store, "lodash", "latest", now, &exp)
|
||||
savePkg(t, store, "lodash", "metadata", now, &exp)
|
||||
savePkg(t, store, "golang.org/x/text/@v/v0.3.0.mod", "v0.3.0", now, &exp)
|
||||
savePkg(t, store, "golang.org/x/text/@v/v0.3.0.info", "v0.3.0", now, &exp)
|
||||
savePkgIn(t, store, "go", "golang.org/x/text/@v/v0.3.0.mod", "v0.3.0", now, &exp)
|
||||
savePkgIn(t, store, "go", "golang.org/x/text/@v/v0.3.0.info", "v0.3.0", now, &exp)
|
||||
// An npm package named like Go metadata is an artifact.
|
||||
savePkg(t, store, "left.info", "1.0.0", now, &exp)
|
||||
|
||||
cleared, err := store.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(2), cleared, "only the two artifacts lose their expiry")
|
||||
require.Equal(t, int64(3), cleared, "only the three artifacts lose their expiry")
|
||||
|
||||
for _, a := range [][2]string{{"lodash", "4.17.21"}, {"left-pad", "1.3.0"}} {
|
||||
for _, a := range [][2]string{{"lodash", "4.17.21"}, {"left-pad", "1.3.0"}, {"left.info", "1.0.0"}} {
|
||||
p, getErr := store.GetPackage(ctx, "npm", a[0], a[1])
|
||||
require.NoError(t, getErr)
|
||||
require.Nil(t, p.ExpiresAt, a[0])
|
||||
}
|
||||
for _, m := range [][2]string{
|
||||
{"lodash", "list"}, {"lodash", "page"}, {"lodash", "latest"}, {"lodash", "metadata"},
|
||||
{"golang.org/x/text/@v/v0.3.0.mod", "v0.3.0"}, {"golang.org/x/text/@v/v0.3.0.info", "v0.3.0"},
|
||||
} {
|
||||
p, getErr := store.GetPackage(ctx, "npm", m[0], m[1])
|
||||
require.NoError(t, getErr)
|
||||
require.NotNil(t, p.ExpiresAt, "metadata entry %s@%s keeps its freshness expiry", m[0], m[1])
|
||||
}
|
||||
for _, m := range [][2]string{
|
||||
{"golang.org/x/text/@v/v0.3.0.mod", "v0.3.0"}, {"golang.org/x/text/@v/v0.3.0.info", "v0.3.0"},
|
||||
} {
|
||||
p, getErr := store.GetPackage(ctx, "go", m[0], m[1])
|
||||
require.NoError(t, getErr)
|
||||
require.NotNil(t, p.ExpiresAt, "metadata entry %s@%s keeps its freshness expiry", m[0], m[1])
|
||||
}
|
||||
|
||||
again, err := store.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The missed-day repair on the production dialect: hourly rows are written directly so the
|
||||
// test needs no download_events partition for a past month.
|
||||
func TestPostgresDailyRollupCoversMissedDay(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, _ := newPostgresStore(t)
|
||||
day := time.Now().UTC().Truncate(24 * time.Hour).Add(-10 * 24 * time.Hour)
|
||||
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
Size: 10, CachedAt: day, LastAccessed: day,
|
||||
}))
|
||||
registryID, err := store.getRegistryID("npm")
|
||||
require.NoError(t, err)
|
||||
var packageID int64
|
||||
require.NoError(t, store.db.Table("packages").Select("id").Where("name = ?", "left-pad").Scan(&packageID).Error)
|
||||
for _, hour := range []int{5, 6, 7} {
|
||||
require.NoError(t, store.db.Exec(
|
||||
`INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
VALUES (?, ?, ?, 1, 1, 0, NOW(), NOW())`, registryID, packageID, day.Add(time.Duration(hour)*time.Hour)).Error)
|
||||
}
|
||||
|
||||
for d := 2; d <= 9; d++ {
|
||||
at := day.Add(time.Duration(d)*24*time.Hour + 30*time.Minute)
|
||||
store.aggregationWorker.now = func() time.Time { return at }
|
||||
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||
}
|
||||
|
||||
store.now = func() time.Time { return day.Add(9*24*time.Hour + time.Hour) }
|
||||
ts, err := store.GetTimeSeriesStats(ctx, "30day", "")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, sumPoints(ts))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newRollupStore adds the unique indexes Postgres gets from the partition manager,
|
||||
// so INSERT OR REPLACE upserts as the ON CONFLICT clauses do there.
|
||||
func newRollupStore(t *testing.T) *GORMStoreV2 {
|
||||
t.Helper()
|
||||
store := newTimeSeriesStore(t)
|
||||
for _, stmt := range statsUpsertIndexes {
|
||||
require.NoError(t, store.db.Exec(stmt).Error)
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
// tick mirrors AggregationWorker.Start: an hourly pass, plus the daily pass in hour 0.
|
||||
func tick(t *testing.T, store *GORMStoreV2, at time.Time, daily bool) {
|
||||
t.Helper()
|
||||
store.aggregationWorker.now = func() time.Time { return at }
|
||||
require.NoError(t, store.aggregationWorker.AggregateHourly())
|
||||
if daily && at.Hour() == 0 {
|
||||
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||
}
|
||||
}
|
||||
|
||||
func seedEventsAt(t *testing.T, store *GORMStoreV2, times ...time.Time) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
Size: 10, CachedAt: times[0], LastAccessed: times[0],
|
||||
}))
|
||||
for _, at := range times {
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "left-pad", "1.3.0"))
|
||||
var id int64
|
||||
require.NoError(t, store.db.Table("download_events").Select("MAX(id)").Scan(&id).Error)
|
||||
require.NoError(t, store.db.Exec("UPDATE download_events SET downloaded_at = ? WHERE id = ?", at, id).Error)
|
||||
}
|
||||
}
|
||||
|
||||
func totalAt(t *testing.T, store *GORMStoreV2, at time.Time, period string) int64 {
|
||||
t.Helper()
|
||||
store.now = func() time.Time { return at }
|
||||
ts, err := store.GetTimeSeriesStats(context.Background(), period, "")
|
||||
require.NoError(t, err)
|
||||
return sumPoints(ts)
|
||||
}
|
||||
|
||||
// A download in the last hour of a day that the daily pass ran before that hour was aggregated.
|
||||
func TestDailyRollupKeepsLastHourOfDay(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(23*time.Hour+30*time.Minute))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+2*time.Minute), true) // cutoff 23:00: the 23:30 event is not counted yet
|
||||
tick(t, store, day.Add(25*time.Hour+2*time.Minute), true)
|
||||
tick(t, store, day.Add(48*time.Hour+3*time.Minute), true)
|
||||
|
||||
require.EqualValues(t, 2, totalAt(t, store, day.Add(48*time.Hour+10*time.Minute), "7day"))
|
||||
}
|
||||
|
||||
// A day whose midnight daily pass never ran must still be rolled up before its hourly rows expire.
|
||||
func TestDailyRollupCoversMissedDay(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(5*time.Hour), day.Add(6*time.Hour), day.Add(7*time.Hour))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+30*time.Minute), false) // process restarting at midnight: no daily pass
|
||||
for d := 2; d <= 9; d++ {
|
||||
tick(t, store, day.Add(time.Duration(d)*24*time.Hour+30*time.Minute), true)
|
||||
}
|
||||
|
||||
require.EqualValues(t, 3, totalAt(t, store, day.Add(9*24*time.Hour+time.Hour), "30day"))
|
||||
}
|
||||
|
||||
// Hourly rows and events never overcount a day, so a rollup that is behind them must not win.
|
||||
func TestTimeSeriesKeepsLateDownloadsAheadOfRollup(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(23*time.Hour+30*time.Minute))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+2*time.Minute), true) // rollup counts one download
|
||||
tick(t, store, day.Add(25*time.Hour+2*time.Minute), true) // the 23:30 download reaches the hourly table
|
||||
|
||||
require.EqualValues(t, 2, totalAt(t, store, day.Add(26*time.Hour), "7day"))
|
||||
}
|
||||
|
||||
// A rollup larger than the hourly rows still wins once the hourly rows have been trimmed.
|
||||
func TestTimeSeriesKeepsRollupWhenHourlyRowsAreGone(t *testing.T) {
|
||||
store := newRollupStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(11*time.Hour), day.Add(12*time.Hour))
|
||||
|
||||
tick(t, store, day.Add(24*time.Hour+30*time.Minute), true)
|
||||
require.NoError(t, store.db.Exec("DELETE FROM download_stats_hourly WHERE time_bucket = ?", day.Add(12*time.Hour)).Error)
|
||||
|
||||
require.EqualValues(t, 3, totalAt(t, store, day.Add(26*time.Hour), "7day"))
|
||||
}
|
||||
@@ -23,14 +23,21 @@ var MetadataVersions = []string{"list", "page", "latest", "metadata"}
|
||||
// MetadataNameSuffixes mark Go module metadata files (.mod, .info).
|
||||
var MetadataNameSuffixes = []string{".mod", ".info"}
|
||||
|
||||
// GoRegistry is the registry whose cache keys carry the name suffixes above.
|
||||
const GoRegistry = "go"
|
||||
|
||||
// IsMetadataEntry reports whether a cache entry is a metadata page that must
|
||||
// refresh, as opposed to an immutable artifact.
|
||||
func IsMetadataEntry(name, version string) bool {
|
||||
// refresh, as opposed to an immutable artifact. The name suffixes apply to Go
|
||||
// only: an npm or PyPI package may legitimately end in .mod or .info.
|
||||
func IsMetadataEntry(registry, name, version string) bool {
|
||||
for _, v := range MetadataVersions {
|
||||
if version == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if registry != GoRegistry {
|
||||
return false
|
||||
}
|
||||
for _, suffix := range MetadataNameSuffixes {
|
||||
if strings.HasSuffix(name, suffix) {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package metadata
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsMetadataEntry(t *testing.T) {
|
||||
tests := []struct {
|
||||
registry, name, version string
|
||||
want bool
|
||||
}{
|
||||
{"npm", "lodash", "metadata", true},
|
||||
{"pypi", "foo", "page", true},
|
||||
{"go", "example.com/m/@v/list", "list", true},
|
||||
{"go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", true},
|
||||
{"go", "example.com/m/@v/v1.0.0.info", "v1.0.0", true},
|
||||
{"go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", false},
|
||||
{"npm", "left.info", "1.0.0", false},
|
||||
{"pypi", "foo.mod", "foo.mod-1.0.tar.gz", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := IsMetadataEntry(tt.registry, tt.name, tt.version); got != tt.want {
|
||||
t.Errorf("IsMetadataEntry(%q, %q, %q) = %v, want %v", tt.registry, tt.name, tt.version, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,14 @@ var (
|
||||
[]string{"reason"}, // ttl, lru, manual
|
||||
)
|
||||
|
||||
// WebSocketEventsDropped counts realtime events dropped because the broadcast channel was full.
|
||||
WebSocketEventsDropped = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "gohoarder_websocket_events_dropped_total",
|
||||
Help: "Realtime dashboard events dropped because the broadcast channel was full",
|
||||
},
|
||||
)
|
||||
|
||||
// Storage metrics
|
||||
StorageOperations = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package pypi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The cache key is pypi/<name>/<filename>, so original_url must name that same file.
|
||||
func TestHandlePackageFile_OriginalURLFilenameBound(t *testing.T) {
|
||||
const path = "/example/example-1.0.0-py3-none-any.whl"
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
originalURL string
|
||||
wantReject bool
|
||||
}{
|
||||
{"other file on allowed host", path, "https://files.pythonhosted.org/packages/ab/cd/ef/evil-9.9.9-py3-none-any.whl", true},
|
||||
{"other project same version", path, "https://files.pythonhosted.org/packages/ab/cd/ef/other-1.0.0-py3-none-any.whl", true},
|
||||
{"sidecar of another file", path + ".metadata", "https://files.pythonhosted.org/packages/ab/cd/ef/evil-9.9.9-py3-none-any.whl", true},
|
||||
{"same file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
|
||||
{"same file with query", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl?x=1", false},
|
||||
{"sidecar of same file", path + ".metadata", "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
|
||||
}
|
||||
|
||||
h := newHandlerForSSRFTest()
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
q := url.Values{}
|
||||
q.Set("original_url", tt.originalURL)
|
||||
req := httptest.NewRequest(http.MethodGet, tt.path+"?"+q.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// A nil cache panics once the guards pass; that means "not rejected".
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
h.handlePackageFile(req.Context(), w, req, tt.path)
|
||||
}()
|
||||
|
||||
rejected := w.Code == http.StatusBadRequest
|
||||
if rejected != tt.wantReject {
|
||||
t.Errorf("rejected=%v want %v (code=%d body=%q)", rejected, tt.wantReject, w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
gopath "path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -285,6 +286,17 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
|
||||
http.Error(w, "original_url host not allowed", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// The cache key is built from the request path, so the fetched file must
|
||||
// be the one the path names; otherwise any file on an allowed host could
|
||||
// be stored under another package's key.
|
||||
if gopath.Base(parsed.Path) != filename {
|
||||
log.Warn().
|
||||
Str("original_url", originalURL).
|
||||
Str("filename", filename).
|
||||
Msg("Rejected original_url naming a different file")
|
||||
http.Error(w, "original_url does not match requested file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// A PEP 658 sidecar is a view of its wheel, not a package: stream it
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A vulnerability covered by an active bypass must not block under any block_on_severity.
|
||||
func TestCheckVulnerabilities_BypassedCVENeverBlocks(t *testing.T) {
|
||||
policies := []string{"CRITICAL", "HIGH", "MODERATE", "MEDIUM", "LOW", "none", ""}
|
||||
severities := []string{"CRITICAL", "HIGH", "MODERATE", "MEDIUM", "LOW", "UNKNOWN"}
|
||||
|
||||
for _, policy := range policies {
|
||||
for _, severity := range severities {
|
||||
t.Run(policy+"/"+severity, func(t *testing.T) {
|
||||
store := &stubBypassStore{
|
||||
stubMetadataStore: &stubMetadataStore{},
|
||||
bypasses: []*metadata.CVEBypass{
|
||||
{ID: "b1", Type: metadata.BypassTypeCVE, Target: "CVE-1", Active: true, ExpiresAt: time.Now().Add(time.Hour)},
|
||||
},
|
||||
scan: &metadata.ScanResult{
|
||||
ID: "r", Scanner: "stub", ScannedAt: time.Now(), Status: metadata.ScanStatusVulnerable,
|
||||
Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: severity}},
|
||||
},
|
||||
}
|
||||
mgr, err := New(config.SecurityConfig{
|
||||
Enabled: true,
|
||||
BlockOnSeverity: policy,
|
||||
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1},
|
||||
}, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
require.False(t, blocked, "bypassed CVE blocked: %s", reason)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An unbypassed vulnerability at or above the policy severity still blocks.
|
||||
func TestCheckVulnerabilities_UnbypassedCVEBlocksAtPolicy(t *testing.T) {
|
||||
store := &stubBypassStore{
|
||||
stubMetadataStore: &stubMetadataStore{},
|
||||
bypasses: []*metadata.CVEBypass{
|
||||
{ID: "b1", Type: metadata.BypassTypeCVE, Target: "CVE-1", Active: true, ExpiresAt: time.Now().Add(time.Hour)},
|
||||
},
|
||||
scan: &metadata.ScanResult{
|
||||
ID: "r", Scanner: "stub", ScannedAt: time.Now(), Status: metadata.ScanStatusVulnerable,
|
||||
Vulnerabilities: []metadata.Vulnerability{
|
||||
{ID: "CVE-1", Severity: "LOW"},
|
||||
{ID: "CVE-2", Severity: "LOW"},
|
||||
},
|
||||
},
|
||||
}
|
||||
mgr, err := New(config.SecurityConfig{
|
||||
Enabled: true,
|
||||
BlockOnSeverity: "LOW",
|
||||
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1},
|
||||
}, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
require.True(t, blocked)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// versionRecorder remembers the version each scan asked about.
|
||||
type versionRecorder struct {
|
||||
versions []string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *versionRecorder) Name() string { return "recorder" }
|
||||
|
||||
func (s *versionRecorder) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
s.mu.Lock()
|
||||
s.versions = append(s.versions, version)
|
||||
s.mu.Unlock()
|
||||
return &metadata.ScanResult{
|
||||
ID: "r", Registry: registry, PackageName: name, PackageVersion: version,
|
||||
Scanner: "recorder", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *versionRecorder) Health(context.Context) error { return nil }
|
||||
|
||||
type packageStore struct {
|
||||
*stubMetadataStore
|
||||
pkg *metadata.Package
|
||||
}
|
||||
|
||||
func (s *packageStore) GetPackage(context.Context, string, string, string) (*metadata.Package, error) {
|
||||
return s.pkg, nil
|
||||
}
|
||||
|
||||
// PyPI artifacts are cached under their file name; scanners must be asked about the release version.
|
||||
func TestScanAsksScannersForReleaseVersion(t *testing.T) {
|
||||
const wheel = "requests-2.19.0-py3-none-any.whl"
|
||||
tests := []struct {
|
||||
name string
|
||||
pkg *metadata.Package
|
||||
want string
|
||||
}{
|
||||
{"pypi file", &metadata.Package{Version: wheel, ReleaseVersion: "2.19.0"}, "2.19.0"},
|
||||
{"npm tarball has no release version", &metadata.Package{Version: wheel}, wheel},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
store := &packageStore{stubMetadataStore: &stubMetadataStore{}, pkg: tt.pkg}
|
||||
mgr := newTestManager(t, store)
|
||||
rec := &versionRecorder{}
|
||||
mgr.RegisterScanner(rec)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "pypi", "requests", wheel, "/tmp/x"))
|
||||
require.Equal(t, []string{tt.want}, rec.versions)
|
||||
require.Len(t, store.savedResults, 1)
|
||||
require.Equal(t, wheel, store.savedResults[0].PackageVersion, "the result stays keyed by the cache version")
|
||||
})
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -262,6 +262,8 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
Str("version", version).
|
||||
Msg("Starting security scan")
|
||||
|
||||
scanVersion := m.scanVersion(ctx, registry, packageName, version)
|
||||
|
||||
// Collect results from all scanners
|
||||
var scanResults []*metadata.ScanResult
|
||||
scannerNames := make([]string, 0)
|
||||
@@ -277,7 +279,7 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
continue
|
||||
}
|
||||
|
||||
result, err := scanner.Scan(ctx, registry, packageName, version, filePath)
|
||||
result, err := scanner.Scan(ctx, registry, packageName, scanVersion, filePath)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
@@ -355,6 +357,8 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
|
||||
// Merge and deduplicate results from all scanners
|
||||
mergedResult := m.mergeResults(scanResults, scannerNames)
|
||||
// The store finds the package by its cache version, not the release version.
|
||||
mergedResult.PackageVersion = version
|
||||
|
||||
// Save consolidated result to metadata store
|
||||
if err := m.metadataStore.SaveScanResult(ctx, mergedResult); err != nil {
|
||||
@@ -384,6 +388,16 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
return nil
|
||||
}
|
||||
|
||||
// scanVersion is the version scanners are asked about. PyPI artifacts are cached
|
||||
// under their file name; the release version is on the package row.
|
||||
func (m *Manager) scanVersion(ctx context.Context, registry, packageName, version string) string {
|
||||
pkg, err := m.metadataStore.GetPackage(ctx, registry, packageName, version)
|
||||
if err != nil || pkg == nil || pkg.ReleaseVersion == "" {
|
||||
return version
|
||||
}
|
||||
return pkg.ReleaseVersion
|
||||
}
|
||||
|
||||
// mergeResults merges and deduplicates scan results from multiple scanners
|
||||
func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []string) *metadata.ScanResult {
|
||||
if len(results) == 0 {
|
||||
@@ -624,6 +638,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
|
||||
// Count vulnerabilities by severity, excluding bypassed CVEs
|
||||
severityCounts := make(map[string]int)
|
||||
remaining := 0
|
||||
for _, vuln := range result.Vulnerabilities {
|
||||
// Check if this CVE is bypassed
|
||||
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
|
||||
@@ -637,6 +652,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
continue
|
||||
}
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
remaining++
|
||||
}
|
||||
|
||||
// Check against thresholds
|
||||
@@ -687,7 +703,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
return true, "Package has MODERATE, HIGH, or CRITICAL vulnerabilities", nil
|
||||
}
|
||||
case "LOW":
|
||||
if len(result.Vulnerabilities) > 0 {
|
||||
if remaining > 0 {
|
||||
return true, "Package has vulnerabilities", nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,12 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
|
||||
// only successfully renamed files. Quota check happens before increment
|
||||
// to avoid transient inflation seen by concurrent Puts.
|
||||
fs.mu.Lock()
|
||||
if fs.quota > 0 && fs.used+written > fs.quota {
|
||||
// An overwrite releases the bytes of the file it replaces.
|
||||
var replaced int64
|
||||
if info, statErr := root.Stat(relPath); statErr == nil {
|
||||
replaced = info.Size()
|
||||
}
|
||||
if fs.quota > 0 && fs.used-replaced+written > fs.quota {
|
||||
fs.mu.Unlock()
|
||||
_ = root.Remove(tempPath)
|
||||
metrics.RecordStorageOperation("filesystem", "put", "quota_exceeded")
|
||||
@@ -174,7 +179,7 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
|
||||
metrics.RecordStorageOperation("filesystem", "put", "error")
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to rename temp file")
|
||||
}
|
||||
fs.used += written
|
||||
fs.used += written - replaced
|
||||
currentUsed := fs.used
|
||||
fs.mu.Unlock()
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Used bytes must equal the bytes on disk after a key is overwritten.
|
||||
func TestPutOverwriteKeepsUsageExact(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fs, err := New(t.TempDir(), 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("x", 400)), nil))
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("y", 300)), nil))
|
||||
|
||||
quota, err := fs.GetQuota(ctx)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 300, quota.Used)
|
||||
|
||||
require.NoError(t, fs.Delete(ctx, "npm/a/metadata"))
|
||||
quota, err = fs.GetQuota(ctx)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, quota.Used)
|
||||
}
|
||||
|
||||
// An overwrite that fits once the old bytes are released must not hit the quota.
|
||||
func TestPutOverwriteWithinQuota(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fs, err := New(t.TempDir(), 500)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("x", 400)), nil))
|
||||
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("y", 450)), nil))
|
||||
}
|
||||
+26
-1
@@ -7,10 +7,13 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
|
||||
)
|
||||
|
||||
// EventType represents the type of event being broadcast
|
||||
@@ -59,6 +62,8 @@ type Server struct {
|
||||
unregister chan *Client
|
||||
upgrader websocket.Upgrader
|
||||
mu sync.RWMutex
|
||||
dropped atomic.Uint64
|
||||
lastWarn atomic.Int64
|
||||
}
|
||||
|
||||
// Config holds WebSocket server configuration
|
||||
@@ -222,10 +227,30 @@ func (s *Server) Broadcast(eventType EventType, data map[string]interface{}) {
|
||||
select {
|
||||
case s.broadcast <- event:
|
||||
default:
|
||||
log.Warn().Msg("Broadcast channel full - dropping event")
|
||||
s.recordDrop()
|
||||
}
|
||||
}
|
||||
|
||||
// dropWarnInterval bounds the drop warning to one line per interval, so a burst does not flood the log.
|
||||
const dropWarnInterval = time.Minute
|
||||
|
||||
// recordDrop counts a dropped event and warns at most once per dropWarnInterval.
|
||||
func (s *Server) recordDrop() {
|
||||
total := s.dropped.Add(1)
|
||||
metrics.WebSocketEventsDropped.Inc()
|
||||
now := time.Now().UnixNano()
|
||||
last := s.lastWarn.Load()
|
||||
if now-last < int64(dropWarnInterval) || !s.lastWarn.CompareAndSwap(last, now) {
|
||||
return
|
||||
}
|
||||
log.Warn().Uint64("dropped_total", total).Msg("Broadcast channel full - dropping events")
|
||||
}
|
||||
|
||||
// Dropped returns how many events were dropped because the broadcast channel was full.
|
||||
func (s *Server) Dropped() uint64 {
|
||||
return s.dropped.Load()
|
||||
}
|
||||
|
||||
// BroadcastEvent satisfies the events.Broadcaster contract used by
|
||||
// cache/scanner sub-systems. It accepts a string event type and an
|
||||
// arbitrary payload (typically map[string]any) and forwards to the
|
||||
|
||||
Reference in New Issue
Block a user