mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-02 07:06:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d31e535ff | ||
|
|
fe2d9f8b3a | ||
|
|
a84f080b79 | ||
|
|
9b4659218c | ||
|
|
1256756057 | ||
|
|
262771d224 | ||
|
|
536f35ab55 | ||
|
|
5a9d104b37 | ||
|
|
f2049383cb | ||
|
|
549d56e0a1 | ||
|
|
31db940014 | ||
|
|
f46e079cee | ||
|
|
ae5167ffa9 | ||
|
|
787c757827 |
@@ -85,6 +85,8 @@ server {
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
proxy_set_header Connection "";
|
||||
# The backend authenticates by API-key header; browser session cookies only bloat the request.
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# Timeouts for long-running operations
|
||||
proxy_connect_timeout 60s;
|
||||
@@ -122,6 +124,7 @@ server {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# WebSocket timeouts
|
||||
proxy_connect_timeout 7d;
|
||||
|
||||
@@ -193,6 +193,7 @@ server:
|
||||
host: "0.0.0.0"
|
||||
read_timeout: "5m"
|
||||
write_timeout: "5m"
|
||||
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
|
||||
storage:
|
||||
backend: "filesystem" # Options: filesystem, s3, smb
|
||||
@@ -235,6 +236,8 @@ security:
|
||||
cache:
|
||||
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
|
||||
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
|
||||
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
|
||||
pypi: 12h
|
||||
cleanup_interval: 1h
|
||||
|
||||
logging:
|
||||
@@ -252,7 +255,7 @@ upstream:
|
||||
Every `cleanup_interval` the cleanup run removes:
|
||||
|
||||
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
|
||||
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl`. They refresh on the next request.
|
||||
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
|
||||
|
||||
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
|
||||
|
||||
|
||||
+10
-5
@@ -10,8 +10,13 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080 # Backend API server port
|
||||
read_timeout: "5m"
|
||||
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
write_timeout: "5m"
|
||||
idle_timeout: "2m"
|
||||
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
|
||||
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
|
||||
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
|
||||
allowed_origins: []
|
||||
tls:
|
||||
enabled: false
|
||||
cert_file: ""
|
||||
@@ -89,15 +94,15 @@ metadata:
|
||||
log_level: "warn" # GORM log level: silent, error, warn, info
|
||||
|
||||
cache:
|
||||
default_ttl: "168h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
cleanup_interval: "1h"
|
||||
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
max_size_bytes: 536870912000 # 500GB
|
||||
per_project_quota: 53687091200 # 50GB
|
||||
ttl_overrides:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
security:
|
||||
enabled: false
|
||||
|
||||
@@ -10,8 +10,10 @@ data:
|
||||
host: {{ .Values.server.host | quote }}
|
||||
port: {{ .Values.server.port }}
|
||||
read_timeout: {{ .Values.server.readTimeout | quote }}
|
||||
read_buffer_size: {{ .Values.server.readBufferSize }}
|
||||
write_timeout: {{ .Values.server.writeTimeout | quote }}
|
||||
idle_timeout: {{ .Values.server.idleTimeout | quote }}
|
||||
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
|
||||
tls:
|
||||
enabled: false
|
||||
|
||||
|
||||
@@ -91,8 +91,11 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080
|
||||
readTimeout: "5m"
|
||||
readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
writeTimeout: "5m"
|
||||
idleTimeout: "2m"
|
||||
# Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
allowedOrigins: []
|
||||
|
||||
# Additional environment variables for server container
|
||||
# Use this to override config via environment variables
|
||||
@@ -375,15 +378,15 @@ migration:
|
||||
|
||||
# Cache configuration
|
||||
cache:
|
||||
defaultTTL: "168h" # 7 days
|
||||
defaultTTL: "24h" # Freshness window for metadata pages; keep below the 72h client release-age gate
|
||||
cleanupInterval: "1h"
|
||||
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
maxSizeBytes: 536870912000 # 500GB
|
||||
perProjectQuota: 53687091200 # 50GB
|
||||
ttlOverrides:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
# Security scanning configuration
|
||||
security:
|
||||
|
||||
+35
-6
@@ -20,6 +20,13 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 |
|
||||
| GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 |
|
||||
| GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f |
|
||||
| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e |
|
||||
| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 |
|
||||
| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f |
|
||||
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
|
||||
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
|
||||
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
|
||||
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | this change |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
@@ -30,9 +37,37 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
- **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name
|
||||
returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong
|
||||
scan results rather than serving blocked packages; any deployment with a block policy served such packages.
|
||||
- **GH-17.** A page at any origin issued `DELETE /api/packages/<registry>/<name>/<version>` from a visitor's browser, and
|
||||
`Access-Control-Allow-Origin: *` let it read every `/api` response. Reach: any visitor to a hostile page when
|
||||
`auth.enabled` is false (production); impact is cache eviction. Fixed by `apiOriginGuard` against `server.allowed_origins`;
|
||||
with none set, only same-origin passes.
|
||||
- **GH-19.** An allowed host that answered 302 reached any target (`169.254.169.254`, `127.0.0.1`, `10.x`), by name or by
|
||||
DNS rebinding. No allowed host redirects today; the fix removes the dependency on that. Hops are capped at 10, limited to
|
||||
http(s), vetted against the allowlist, and a hop to another host dials through a guard that refuses private, loopback,
|
||||
link-local and carrier-grade addresses after resolution. A redirect inside one host is left alone: a private index is
|
||||
operator-trusted.
|
||||
- **GH-04.** The publisher of an npm or PyPI package named `x.info` skipped the scan and the block policy. Reach: any package
|
||||
publisher; needs a block policy to matter.
|
||||
|
||||
### Notes on the fixed rows
|
||||
|
||||
- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry
|
||||
(`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no
|
||||
age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown
|
||||
registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`,
|
||||
`TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`.
|
||||
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
|
||||
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
|
||||
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
|
||||
legacy path. Production holds none.
|
||||
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
|
||||
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
|
||||
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
|
||||
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
|
||||
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
|
||||
source. `TestHandlersSetNoCORSHeaders` and `TestAPIResponsesNeverCarryWildcardOrigin` guard it.
|
||||
|
||||
## Not fixed
|
||||
|
||||
| id | area | claim | verdict | why |
|
||||
@@ -42,13 +77,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
|
||||
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
|
||||
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. |
|
||||
| GH-15 | release age | a cached packument or index hides new or yanked entries for up to the TTL | by-design | Quoted intent, `pkg/cache/cache.go` store: "TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed based on upstream Cache-Control". Passthrough proved: `Release.rewrite_preserves_upload_time`, `stale_hides_only_gated` (needs TTL <= gate; production 24h <= 72h holds, the compiled default 168h does not, and then the proxy is stricter than the gate). |
|
||||
| GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. |
|
||||
| GH-17 | auth off | with `auth.enabled: false` (production) `DELETE /api/packages/*` is unauthenticated, and `Access-Control-Allow-Origin: *` lets a browser page issue it | by-design, product decision | Quoted intent, `pkg/app/app.go`: "routes are mounted bare to preserve backward-compatible public access". Impact is cache eviction only. Enabling auth is a configuration change the operator owns. |
|
||||
| GH-18 | api keys | `ValidateAPIKey` bcrypt-compares every stored key per request | hardening, CWE-400 | N keys cost N bcrypt checks per bad key. A key-id prefix needs an API change. Zero keys in production. |
|
||||
| GH-19 | SSRF | `network.Client` follows redirects without re-checking the allowlist | hardening | `Access.redirect_escapes_allowlist`. No allowed host redirects (pypi.org, files.pythonhosted.org); a private index host is operator-trusted. |
|
||||
| GH-20 | stats, sqlite | `INSERT OR REPLACE` has no unique index on SQLite, so every pass duplicates registry rows | correctness, SQLite only | Seen in a row dump (three NULL-package hourly rows for one bucket after three passes). Production is PostgreSQL, where `statsUpsertIndexes` exist. Needs a dedupe migration; left open. |
|
||||
| GH-21 | scan retry | a retry on S3 or SMB storage rescans a temp file already removed | suspected, unconfirmed | `cache.go` store removes `tempPath` after the first scan. Production is filesystem. No test written. |
|
||||
|
||||
### Decision: `fail_closed: false` with recurring infrastructure errors
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import Mathlib
|
||||
|
||||
Models `pkg/app/app.go` `buildCheckOrigin` / `normalizeOriginHost`, `pkg/app/handlers_admin.go`
|
||||
`requireAdmin`, `pkg/auth/auth.go` (`getPermissionsForRole`, `ValidateAPIKey` expiry),
|
||||
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards), `Dockerfile.frontend`.
|
||||
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards, `get`), `pkg/network/client.go` (`send`), `pkg/auth/auth.go` (`ValidateAPIKey` cost), `pkg/app/cors.go` (`apiOriginGuard`), `Dockerfile.frontend`.
|
||||
Omits: the TLS layer, bcrypt internals, DNS.
|
||||
-/
|
||||
|
||||
@@ -125,15 +125,64 @@ theorem internal_hosts_rejected :
|
||||
hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧
|
||||
hostAllowed "metadata.google.internal" = false := by decide
|
||||
|
||||
/-- The allowlist is checked once, on the first hop. `network.Client` follows redirects without
|
||||
re-checking, so an allowed host that answers 302 reaches any target. Acceptable only while no
|
||||
allowed host redirects (pypi.org and files.pythonhosted.org do not). -/
|
||||
def hopAllowed (hops : List String) : Bool := hops.head?.any hostAllowed
|
||||
/-- Before the fix the allowlist was checked once, on the first hop. `network.Client` followed
|
||||
redirects without re-checking, so an allowed host that answers 302 reached any target. -/
|
||||
def hopAllowedOld (hops : List String) : Bool := hops.head?.any hostAllowed
|
||||
|
||||
/-- After the fix (`network.Client.send`, `pypi.Handler.get`) every hop must pass the allowlist. -/
|
||||
def hopAllowed (hops : List String) : Bool := hops.all hostAllowed
|
||||
|
||||
theorem redirect_escapes_allowlist :
|
||||
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = true ∧
|
||||
hopAllowedOld ["files.pythonhosted.org", "169.254.169.254"] = true ∧
|
||||
hostAllowed "169.254.169.254" = false := by decide
|
||||
|
||||
theorem fixed_redirect_stays_allowlisted :
|
||||
hopAllowed ["pypi.org", "files.pythonhosted.org"] = true ∧
|
||||
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = false := by decide
|
||||
|
||||
/-- A hop is accepted only if every hop is on the allowlist. -/
|
||||
theorem hopAllowed_implies_each (hops : List String) (h : hopAllowed hops = true) :
|
||||
∀ x ∈ hops, hostAllowed x = true := by
|
||||
simpa [hopAllowed] using h
|
||||
|
||||
/-! ### API key validation cost (`pkg/auth/auth.go` `ValidateAPIKey`) -/
|
||||
|
||||
/-- bcrypt compares for one request when every stored key is a candidate (before the fix). -/
|
||||
def compareCostOld (storedKeys : ℕ) : ℕ := storedKeys
|
||||
|
||||
/-- A key carrying its id selects one stored key: one compare, hit or miss (a miss compares a dummy hash). -/
|
||||
def compareCostNew (_storedKeys : ℕ) : ℕ := 1
|
||||
|
||||
theorem old_cost_grows_with_keys : compareCostOld 1000 = 1000 := rfl
|
||||
|
||||
theorem new_cost_independent_of_keys (n m : ℕ) : compareCostNew n = compareCostNew m := rfl
|
||||
|
||||
/-! ### Cross-origin writes on `/api` (`pkg/app/cors.go` `apiOriginGuard`) -/
|
||||
|
||||
/-- Before the fix every handler answered `Access-Control-Allow-Origin: *`, so any page could call them. -/
|
||||
def corsOld (_ : Origin) : Bool := true
|
||||
|
||||
/-- After the fix a state-changing request passes iff it names no origin (non-browser client) or an
|
||||
allowed one; the same rule as the WebSocket origin check. -/
|
||||
def writeAllowed (rules : List Origin) : Option Origin → Bool
|
||||
| none => true
|
||||
| some o => rules.any (fun r => matchesExact r o)
|
||||
|
||||
def dashboard : Origin := ⟨Scheme.https, "gohoarder.example.com".toList, none⟩
|
||||
def attacker : Origin := ⟨Scheme.https, "evil.example.net".toList, none⟩
|
||||
|
||||
theorem old_cors_admits_any_page : corsOld attacker = true := rfl
|
||||
|
||||
theorem fixed_refuses_foreign_origin : writeAllowed [dashboard] (some attacker) = false := by decide
|
||||
|
||||
theorem fixed_admits_dashboard_and_cli :
|
||||
writeAllowed [dashboard] (some dashboard) = true ∧ writeAllowed [dashboard] none = true := by decide
|
||||
|
||||
/-- With nothing configured only a request with no origin passes the allowlist step; browsers fall to the
|
||||
same-origin host comparison in the handler. -/
|
||||
theorem empty_allowlist_refuses_any_origin (o : Origin) : writeAllowed [] (some o) = false := by
|
||||
simp [writeAllowed]
|
||||
|
||||
/-! ### Frontend blocklist (`Dockerfile.frontend`) -/
|
||||
|
||||
/-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/
|
||||
|
||||
@@ -47,15 +47,36 @@ theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ tt
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t := by
|
||||
unfold gateAccepts; omega
|
||||
|
||||
/-- Production: `default_ttl: 24h` against a 72h gate. -/
|
||||
theorem prod_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
|
||||
/-- Production and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/
|
||||
theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
|
||||
|
||||
/-- The compiled default is 7 days. Against a 72h gate a version aged 84h is eligible but absent
|
||||
from a 7-day-old snapshot: the proxy withholds it, which is stricter than the gate, never looser. -/
|
||||
theorem default_ttl_exceeds_gate :
|
||||
/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but
|
||||
absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/
|
||||
theorem old_default_ttl_exceeded_gate :
|
||||
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
|
||||
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
|
||||
|
||||
/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/
|
||||
|
||||
/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/
|
||||
def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default
|
||||
|
||||
/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/
|
||||
theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ)
|
||||
(hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default)
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t :=
|
||||
stale_hides_only_gated gate _ now s t hstale hcfg hnew
|
||||
|
||||
/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/
|
||||
theorem override_replaces_default (default o : ℤ) :
|
||||
effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩
|
||||
|
||||
/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/
|
||||
theorem override_above_gate_breaks_bound :
|
||||
∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧
|
||||
gateAccepts gate now t ∧ gate = 72 := by
|
||||
exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, 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
|
||||
|
||||
@@ -137,6 +137,20 @@ theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List
|
||||
/-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/
|
||||
def servesDisabled : Bool := true
|
||||
|
||||
/-! ### Retry input (`pkg/cache/cache.go` `store`, `ScanFile`; `scheduleRetry`) -/
|
||||
|
||||
/-- Before the fix a retry reused the first scan's path. Remote storage scans a temp file removed
|
||||
after the first attempt, so only local backends kept it. -/
|
||||
def retryReadableOld (localBackend : Bool) : Bool := localBackend
|
||||
|
||||
/-- After the fix a retry whose file is gone re-reads the blob through the file source. -/
|
||||
def retryReadableNew (localBackend fileSourceSet : Bool) : Bool := localBackend || fileSourceSet
|
||||
|
||||
theorem old_remote_retry_unreadable : retryReadableOld false = false := rfl
|
||||
|
||||
theorem fixed_retry_always_readable : retryReadableNew false true = true ∧ retryReadableNew true false = true := by
|
||||
decide
|
||||
|
||||
/-! ### Retry budget -/
|
||||
|
||||
def maxRetries : ℕ := 6
|
||||
|
||||
@@ -87,4 +87,24 @@ theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ char
|
||||
/-- A download aggregated after the rollup ran: the old chart shows 1 of 2. -/
|
||||
theorem chartOld_drops_late_download : chartOld 1 2 < chartNew 1 2 := by decide
|
||||
|
||||
/-! ### SQLite upsert (`aggregation_worker.go`, `sqlite_stats.go`) -/
|
||||
|
||||
/-- A bucket is a list of stored rows; the chart sums them. Before the fix SQLite had no unique index,
|
||||
so `INSERT OR REPLACE` appended a row per pass. -/
|
||||
def chartTotal (rows : List ℕ) : ℕ := rows.sum
|
||||
|
||||
/-- Three passes over a bucket whose registry total is 3: three copies. -/
|
||||
theorem old_sqlite_duplicates_rows : chartTotal [3, 3, 3] ≠ 3 := by decide
|
||||
|
||||
/-- `ON CONFLICT ... DO UPDATE` over the unique index keeps one row per bucket: a derived row is set,
|
||||
a package row adds the new events, as on PostgreSQL. -/
|
||||
def upsertDerived (_old new : ℕ) : List ℕ := [new]
|
||||
def upsertAdditive (old new : ℕ) : List ℕ := [old + new]
|
||||
|
||||
theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
|
||||
chartTotal (upsertDerived old new) = new := by simp [chartTotal, upsertDerived]
|
||||
|
||||
theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) :
|
||||
chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive]
|
||||
|
||||
end Gohoarder.Stats
|
||||
|
||||
+14
-8
@@ -232,6 +232,7 @@ func (a *App) initializeComponents() error {
|
||||
}
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
@@ -308,10 +309,12 @@ func (a *App) initializeComponents() error {
|
||||
}
|
||||
bootCancel()
|
||||
|
||||
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval)
|
||||
}
|
||||
|
||||
// Initialize WebSocket server
|
||||
@@ -389,10 +392,11 @@ func (a *App) initializeComponents() error {
|
||||
func (a *App) setupServer() error {
|
||||
// Create Fiber app
|
||||
a.app = fiber.New(fiber.Config{
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ReadBufferSize: a.config.Server.ReadBufferSize,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
})
|
||||
|
||||
// Auth middleware factories. Built once, reused on every gated route.
|
||||
@@ -411,6 +415,8 @@ func (a *App) setupServer() error {
|
||||
_ = mwOptional // reserved for future endpoints with anonymous fallback
|
||||
}
|
||||
|
||||
a.app.Use("/api", apiOriginGuard(a.config.Server.AllowedOrigins))
|
||||
|
||||
// Health endpoints — ALWAYS public (k8s liveness/readiness probes).
|
||||
a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler()))
|
||||
a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler()))
|
||||
@@ -888,13 +894,13 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
|
||||
}
|
||||
ou, err := url.Parse(origin)
|
||||
if err != nil || ou.Scheme == "" || ou.Host == "" {
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
|
||||
return false
|
||||
}
|
||||
originScheme := strings.ToLower(ou.Scheme)
|
||||
originHost, ok := normalizeOriginHost(originScheme, ou.Host)
|
||||
if !ok {
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -925,7 +931,7 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
|
||||
log.Warn().
|
||||
Str("origin", origin).
|
||||
Str("host", r.Host).
|
||||
Msg("Rejecting WebSocket upgrade: Origin not in allowlist")
|
||||
Msg("Rejecting origin: Origin not in allowlist")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
headerOrigin = "Origin"
|
||||
corsAllowedMethods = "GET, POST, PATCH, DELETE, OPTIONS"
|
||||
corsAllowedHeaders = "Content-Type, Authorization, X-API-Key"
|
||||
corsPreflightMaxAge = "600"
|
||||
headerACRMethod = "Access-Control-Request-Method"
|
||||
headerACAllowOrigin = "Access-Control-Allow-Origin"
|
||||
headerACAllowMethods = "Access-Control-Allow-Methods"
|
||||
headerACAllowHeaders = "Access-Control-Allow-Headers"
|
||||
headerACMaxAge = "Access-Control-Max-Age"
|
||||
)
|
||||
|
||||
// apiOriginGuard enforces server.allowed_origins on /api. A browser at another origin cannot
|
||||
// read responses (no CORS grant) and cannot change state (403), whatever the handlers set.
|
||||
// With nothing configured only the request's own host counts as same-origin.
|
||||
// Requests with neither Origin nor Referer come from non-browser clients and pass.
|
||||
func apiOriginGuard(allowed []string) fiber.Handler {
|
||||
check := buildCheckOrigin(allowed)
|
||||
originAllowed := func(c fiber.Ctx, origin string) bool {
|
||||
r := &http.Request{Header: http.Header{headerOrigin: {origin}}, Host: c.Host()}
|
||||
return check(r)
|
||||
}
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
origin := c.Get(headerOrigin)
|
||||
method := c.Method()
|
||||
|
||||
if method == http.MethodOptions && origin != "" && c.Get(headerACRMethod) != "" {
|
||||
if !originAllowed(c, origin) {
|
||||
return c.SendStatus(fiber.StatusForbidden)
|
||||
}
|
||||
setCORSGrant(c, origin)
|
||||
c.Set(headerACMaxAge, corsPreflightMaxAge)
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
if !isSafeMethod(method) {
|
||||
source := origin
|
||||
if source == "" {
|
||||
source = refererOrigin(c.Get(fiber.HeaderReferer))
|
||||
}
|
||||
if source != "" && !originAllowed(c, source) {
|
||||
log.Warn().Str("method", method).Str("path", c.Path()).Str("origin", source).Msg("Rejecting cross-origin state-changing request")
|
||||
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "cross-origin request not allowed"})
|
||||
}
|
||||
}
|
||||
|
||||
err := c.Next()
|
||||
|
||||
// Drop any grant a handler or upstream set; the allowlist decides.
|
||||
c.Response().Header.Del(headerACAllowOrigin)
|
||||
c.Response().Header.Del(headerACAllowMethods)
|
||||
c.Response().Header.Del(headerACAllowHeaders)
|
||||
c.Vary(headerOrigin)
|
||||
if origin != "" && originAllowed(c, origin) {
|
||||
setCORSGrant(c, origin)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func setCORSGrant(c fiber.Ctx, origin string) {
|
||||
c.Set(headerACAllowOrigin, origin)
|
||||
c.Set(headerACAllowMethods, corsAllowedMethods)
|
||||
c.Set(headerACAllowHeaders, corsAllowedHeaders)
|
||||
c.Vary(headerOrigin)
|
||||
}
|
||||
|
||||
func isSafeMethod(m string) bool {
|
||||
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
|
||||
}
|
||||
|
||||
// refererOrigin returns scheme://host of a Referer, or "" when it is absent or malformed.
|
||||
func refererOrigin(referer string) string {
|
||||
if strings.TrimSpace(referer) == "" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(referer)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return "null" // present but unusable: never matches the allowlist
|
||||
}
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const dashboardOrigin = "https://gohoarder.example.com"
|
||||
|
||||
func seedPackage(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
entry, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*cache.FetchResult, error) {
|
||||
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
}
|
||||
|
||||
func apiCall(t *testing.T, a *App, method, target string, headers map[string]string) *http.Response {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, nil)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
return resp
|
||||
}
|
||||
|
||||
func corsApp(t *testing.T, origins ...string) *App {
|
||||
return newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = origins })
|
||||
}
|
||||
|
||||
const deletePath = "/api/packages/npm/left-pad/1.3.0"
|
||||
|
||||
func TestAPIDeleteFromDisallowedOriginForbidden(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
seedPackage(t, a)
|
||||
|
||||
for _, h := range []map[string]string{
|
||||
{"Origin": "https://evil.example.net"},
|
||||
{"Origin": "null"},
|
||||
{"Referer": "https://evil.example.net/page"},
|
||||
{"Origin": "https://evil.example.net", "Referer": dashboardOrigin + "/x"},
|
||||
} {
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode, "%v", h)
|
||||
}
|
||||
resp := apiCall(t, a, http.MethodGet, "/api/packages/npm", nil)
|
||||
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
|
||||
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
|
||||
assert.NoError(t, err, "a refused request must not delete")
|
||||
}
|
||||
|
||||
func TestAPIDeleteFromAllowedOriginWorks(t *testing.T) {
|
||||
for name, h := range map[string]map[string]string{
|
||||
"origin": {"Origin": dashboardOrigin},
|
||||
"referer": {"Referer": dashboardOrigin + "/packages"},
|
||||
"no-fetch": nil, // curl and server-to-server callers send neither header
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
seedPackage(t, a)
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
|
||||
assert.Error(t, err, "package must be gone")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPostFromDisallowedOriginForbidden(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
resp := apiCall(t, a, http.MethodPost, "/api/admin/prewarming/trigger", map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAPIGetStaysPublicWithoutWildcardCORS(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
|
||||
resp := apiCall(t, a, http.MethodGet, "/api/stats", nil)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
|
||||
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": dashboardOrigin})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, dashboardOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
assert.Contains(t, resp.Header.Values("Vary"), "Origin")
|
||||
|
||||
// Served, but a browser at a foreign origin cannot read it.
|
||||
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
}
|
||||
|
||||
func TestAPIPreflightAnswersOnlyAllowedOrigins(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
preflight := func(origin string) *http.Response {
|
||||
return apiCall(t, a, http.MethodOptions, deletePath, map[string]string{
|
||||
"Origin": origin, "Access-Control-Request-Method": "DELETE",
|
||||
})
|
||||
}
|
||||
|
||||
ok := preflight(dashboardOrigin)
|
||||
assert.Equal(t, http.StatusNoContent, ok.StatusCode)
|
||||
assert.Equal(t, dashboardOrigin, ok.Header.Get("Access-Control-Allow-Origin"))
|
||||
assert.Contains(t, ok.Header.Get("Access-Control-Allow-Methods"), "DELETE")
|
||||
|
||||
bad := preflight("https://evil.example.net")
|
||||
assert.Equal(t, http.StatusForbidden, bad.StatusCode)
|
||||
assert.Empty(t, bad.Header.Get("Access-Control-Allow-Origin"))
|
||||
}
|
||||
|
||||
// With nothing configured, only the host the request was sent to counts as same-origin.
|
||||
func TestAPISameOriginRuleWhenNoOriginsConfigured(t *testing.T) {
|
||||
a := corsApp(t)
|
||||
seedPackage(t, a)
|
||||
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
|
||||
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "http://example.com"}) // httptest.NewRequest Host
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAPIOriginMatchingUsesAllowlistRules(t *testing.T) {
|
||||
a := corsApp(t, "https://*.example.org")
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://ui.example.org"})
|
||||
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
|
||||
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://example.org.evil.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
|
||||
func TestHandlersSetNoCORSHeaders(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
|
||||
continue
|
||||
}
|
||||
parsed, err := parser.ParseFile(fset, f, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", f, err)
|
||||
}
|
||||
ast.Inspect(parsed, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
|
||||
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
|
||||
const dashboard = "https://dash.example.com"
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
|
||||
targets := []string{
|
||||
"/api/stats", "/api/info", "/api/config", "/api/packages",
|
||||
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
|
||||
"/api/analytics/search?q=x", "/api/stats/timeseries",
|
||||
}
|
||||
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
|
||||
for _, target := range targets {
|
||||
hdr := map[string]string{}
|
||||
if origin != "" {
|
||||
hdr["Origin"] = origin
|
||||
}
|
||||
code, h, _ := doRequest(t, a, target, hdr)
|
||||
if code == http.StatusNotFound {
|
||||
t.Errorf("GET %s = 404, route missing", target)
|
||||
}
|
||||
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
|
||||
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func doDelete(t *testing.T, a *App, target string) (int, string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodDelete, target, nil)
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("DELETE %s: %v", target, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return resp.StatusCode, string(body)
|
||||
}
|
||||
|
||||
func TestDeleteMissingPackageIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, target := range []string{
|
||||
"/api/packages/npm/nope/1.0.0",
|
||||
"/api/packages/pypi/nope/1.0.0",
|
||||
"/api/packages/go/example.com/nope/v1.0.0",
|
||||
} {
|
||||
code, body := doDelete(t, a, target)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
|
||||
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExistingPackageIs200(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
|
||||
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
|
||||
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
|
||||
}
|
||||
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
|
||||
t.Errorf("second DELETE = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
+6
-15
@@ -2,11 +2,13 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
@@ -16,9 +18,6 @@ import (
|
||||
// handlePackages handles /api/packages endpoint
|
||||
func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -291,6 +290,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
} else {
|
||||
// For NPM and PyPI, delete directly
|
||||
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
|
||||
var appErr *apperrors.Error
|
||||
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", registry).
|
||||
@@ -330,9 +333,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
// handleStats handles /api/stats endpoint
|
||||
func (a *App) handleStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -410,9 +410,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
// Returns time-series download statistics for charts
|
||||
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -452,9 +449,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
// Returns runtime configuration for the frontend
|
||||
func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -486,9 +480,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
// handleInfo handles /api/info endpoint
|
||||
func (a *App) handleInfo(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
|
||||
// handleAdminBypasses handles /api/admin/bypasses endpoint
|
||||
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
// handleAnalyticsTopPackages returns the most downloaded packages
|
||||
func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -31,7 +30,6 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrendingPackages returns trending packages
|
||||
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -52,7 +50,6 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrends returns download trends over time
|
||||
func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
trends := a.analyticsEngine.GetTrends()
|
||||
|
||||
@@ -64,7 +61,6 @@ func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
// handleAnalyticsTotalStats returns overall statistics
|
||||
func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
stats := a.analyticsEngine.GetTotalStats()
|
||||
|
||||
@@ -74,7 +70,6 @@ func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsRegistryStats returns per-registry statistics
|
||||
func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
if registry == "" {
|
||||
@@ -91,7 +86,6 @@ func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsPackageStats returns statistics for a specific package
|
||||
func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
name := c.Params("name")
|
||||
@@ -117,7 +111,6 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsSearch searches for packages matching a query
|
||||
func (a *App) handleAnalyticsSearch(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
query := c.Query("q")
|
||||
if query == "" {
|
||||
|
||||
@@ -11,9 +11,6 @@ import (
|
||||
// handleVulnerabilities handles /api/packages/{registry}/{name}/{version}/vulnerabilities endpoint
|
||||
func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// newTestApp builds a full App on temp storage with the given config tweaks.
|
||||
@@ -284,3 +286,33 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
|
||||
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = upstream.URL
|
||||
c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute}
|
||||
})
|
||||
if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %q", code, body)
|
||||
}
|
||||
|
||||
pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range pkgs {
|
||||
if p.ExpiresAt == nil {
|
||||
continue
|
||||
}
|
||||
if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute {
|
||||
t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
const recentPackagesURL = "/api/packages?page=1&page_size=10&sort=cached_at&order=desc"
|
||||
|
||||
// Fiber v3 defaults to an 8192-byte read buffer; OIDC session cookies plus a long Referer exceed it.
|
||||
func TestLargeRequestHeadersAreAccepted(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
headers := map[string]string{
|
||||
"Cookie": "session=" + strings.Repeat("a", 5000),
|
||||
"Referer": "https://dash.example.com/" + strings.Repeat("r", 5000),
|
||||
}
|
||||
code, _, body := doRequest(t, a, recentPackagesURL, headers)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET with ~10KB of headers = %d %q, want 200", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadBufferSizeIsConfigurable(t *testing.T) {
|
||||
if got := config.Default().Server.ReadBufferSize; got != 16384 {
|
||||
t.Fatalf("default server.read_buffer_size = %d, want 16384", got)
|
||||
}
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.ReadBufferSize = 4096 })
|
||||
req := httptest.NewRequest(http.MethodGet, recentPackagesURL, nil)
|
||||
req.Header.Set("Cookie", "session="+strings.Repeat("a", 6000))
|
||||
if _, err := a.app.Test(req); err == nil || !strings.Contains(err.Error(), "small read buffer") {
|
||||
t.Errorf("6KB header with a 4096 buffer: err = %v, want a small-read-buffer rejection", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func listTree(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
err := filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
names = append(names, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Join(names, "\n")
|
||||
}
|
||||
|
||||
// Shutdown must leave nothing running against the data directory: a late SQLite close deletes
|
||||
// its -wal/-shm files after Shutdown returned and breaks the removal of the directory.
|
||||
func TestShutdownLeavesDataDirectoryStable(t *testing.T) {
|
||||
for i := 0; i < 40; i++ {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.Storage.Backend = "filesystem"
|
||||
cfg.Storage.Path = filepath.Join(dir, "store")
|
||||
cfg.Metadata.Backend = "sqlite"
|
||||
cfg.Metadata.SQLite.Path = filepath.Join(dir, "meta", "meta.db")
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.Metadata.SQLite.Path), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Security.Enabled = false
|
||||
cfg.Prewarming.Enabled = false
|
||||
cfg.Auth.Enabled = false
|
||||
a, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
doRequest(t, a, "/api/stats", nil)
|
||||
if err := a.Shutdown(); err != nil {
|
||||
t.Fatalf("Shutdown: %v", err)
|
||||
}
|
||||
before := listTree(t, dir)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if after := listTree(t, dir); before != after {
|
||||
t.Fatalf("iteration %d: data directory changed after Shutdown:\nbefore:\n%s\nafter:\n%s", i, before, after)
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -16,15 +16,23 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
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)
|
||||
// Bursts stay under the 256-slot channel and wait for the loop to drain between them, so the
|
||||
// result depends on the loop running, not on how fast the scheduler runs it.
|
||||
const (
|
||||
bursts = 10
|
||||
burstLen = 100
|
||||
)
|
||||
for b := 0; b < bursts; b++ {
|
||||
for i := 0; i < burstLen; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for a.wsServer.Pending() > 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(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)
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
|
||||
}
|
||||
}
|
||||
|
||||
+107
-31
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/base64"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -154,10 +155,12 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to generate random key")
|
||||
}
|
||||
|
||||
rawKey := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
secret := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
id := keyPrefix + generateID()
|
||||
rawKey := id + keySeparator + secret
|
||||
|
||||
// Hash the key with the configured cost.
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), m.cfg.BcryptCost)
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(secret), m.cfg.BcryptCost)
|
||||
if err != nil {
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key")
|
||||
}
|
||||
@@ -169,7 +172,7 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
}
|
||||
|
||||
apiKey := &APIKey{
|
||||
ID: generateID(),
|
||||
ID: id,
|
||||
Name: name,
|
||||
HashedKey: string(hashedKey),
|
||||
Role: role,
|
||||
@@ -198,46 +201,119 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
return apiKey, rawKey, nil
|
||||
}
|
||||
|
||||
// Key format: "<id>.<secret>" with id "ghk_<random>". The id is public and selects one stored
|
||||
// key; the bcrypt hash covers the secret only. Keys minted before the format
|
||||
// existed have no id in the raw key and hash the whole raw key.
|
||||
const (
|
||||
keyPrefix = "ghk_"
|
||||
keySeparator = "."
|
||||
// maxLegacyCompares bounds concurrent bcrypt checks against pre-id keys,
|
||||
// which can only be found by trying each one.
|
||||
maxLegacyCompares = 4
|
||||
// legacyIDLen is the length of base64url(16 bytes).
|
||||
legacyIDLen = 24
|
||||
)
|
||||
|
||||
var (
|
||||
bcryptCompare = bcrypt.CompareHashAndPassword
|
||||
legacySlots = make(chan struct{}, maxLegacyCompares)
|
||||
// dummyHash keeps the cost of an unknown id equal to a wrong secret.
|
||||
dummyHash = mustHash("gohoarder-dummy-secret")
|
||||
)
|
||||
|
||||
func mustHash(s string) []byte {
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("auth: dummy hash: %v", err))
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// ValidateAPIKey validates an API key and returns the associated key object.
|
||||
// Hot path: snapshots candidates, runs bcrypt without holding the lock.
|
||||
// LastUsedAt is updated in-memory under the write lock and flushed to the
|
||||
// store via a fire-and-forget goroutine.
|
||||
// A key with an id costs exactly one bcrypt compare, whatever the number of
|
||||
// stored keys. LastUsedAt is updated in-memory under the write lock and
|
||||
// flushed to the store via a fire-and-forget goroutine.
|
||||
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) {
|
||||
// Phase 1: snapshot non-expired candidates under RLock. We hold pointers
|
||||
// to APIKey; APIKey.HashedKey is an immutable string so reading it
|
||||
// without a lock is safe even if the key is later removed from the map.
|
||||
var apiKey *APIKey
|
||||
if id, secret, ok := splitKey(rawKey); ok {
|
||||
apiKey = m.validateByID(id, secret)
|
||||
} else {
|
||||
apiKey = m.validateLegacy(ctx, rawKey)
|
||||
}
|
||||
if apiKey == nil {
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
}
|
||||
|
||||
// Re-check the key still exists to avoid resurrecting a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
func splitKey(rawKey string) (id, secret string, ok bool) {
|
||||
if !strings.HasPrefix(rawKey, keyPrefix) {
|
||||
return "", "", false
|
||||
}
|
||||
return strings.Cut(rawKey, keySeparator)
|
||||
}
|
||||
|
||||
// hasKeyID reports whether k was minted with an id embedded in its raw key.
|
||||
// Legacy ids are bare generateID output, which is always legacyIDLen long.
|
||||
func hasKeyID(k *APIKey) bool {
|
||||
return strings.HasPrefix(k.ID, keyPrefix) && len(k.ID) > legacyIDLen
|
||||
}
|
||||
|
||||
func (m *Manager) validateByID(id, secret string) *APIKey {
|
||||
m.mu.RLock()
|
||||
apiKey := m.keys[id]
|
||||
m.mu.RUnlock()
|
||||
|
||||
hash := dummyHash
|
||||
if apiKey != nil {
|
||||
hash = []byte(apiKey.HashedKey)
|
||||
}
|
||||
err := bcryptCompare(hash, []byte(secret))
|
||||
if apiKey == nil || err != nil || expired(apiKey, time.Now()) {
|
||||
return nil
|
||||
}
|
||||
return apiKey
|
||||
}
|
||||
|
||||
func (m *Manager) validateLegacy(ctx context.Context, rawKey string) *APIKey {
|
||||
m.mu.RLock()
|
||||
candidates := make([]*APIKey, 0, len(m.keys))
|
||||
now := time.Now()
|
||||
for _, apiKey := range m.keys {
|
||||
if apiKey.ExpiresAt != nil && now.After(*apiKey.ExpiresAt) {
|
||||
continue
|
||||
for _, k := range m.keys {
|
||||
if !hasKeyID(k) && !expired(k, now) {
|
||||
candidates = append(candidates, k)
|
||||
}
|
||||
candidates = append(candidates, apiKey)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
// Phase 2: run bcrypt comparisons without holding any lock so concurrent
|
||||
// auth checks can proceed in parallel.
|
||||
for _, apiKey := range candidates {
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(apiKey.HashedKey), []byte(rawKey)); err == nil {
|
||||
// Phase 3: briefly take the write lock to update LastUsedAt.
|
||||
// Re-check the key still exists in the map to avoid resurrecting
|
||||
// a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
for _, k := range candidates {
|
||||
select {
|
||||
case legacySlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
err := bcryptCompare([]byte(k.HashedKey), []byte(rawKey))
|
||||
<-legacySlots
|
||||
if err == nil {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
func expired(k *APIKey, now time.Time) bool {
|
||||
return k.ExpiresAt != nil && now.After(*k.ExpiresAt)
|
||||
}
|
||||
|
||||
// persistLastUsedAsync flushes a LastUsedAt update to the store off the hot
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// countBcrypt wraps bcryptCompare and returns the call counter.
|
||||
func countBcrypt(t *testing.T) *atomic.Int64 {
|
||||
t.Helper()
|
||||
var n atomic.Int64
|
||||
orig := bcryptCompare
|
||||
bcryptCompare = func(h, p []byte) error {
|
||||
n.Add(1)
|
||||
return orig(h, p)
|
||||
}
|
||||
t.Cleanup(func() { bcryptCompare = orig })
|
||||
return &n
|
||||
}
|
||||
|
||||
func newTestManager() *Manager { return NewWithStore(Config{BcryptCost: bcrypt.MinCost}, nil) }
|
||||
|
||||
// addLegacyKey stores a key in the pre-key-id format: bcrypt of the whole raw key, no id in the key.
|
||||
func addLegacyKey(t *testing.T, m *Manager) string {
|
||||
t.Helper()
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
raw := base64.URLEncoding.EncodeToString(b)
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
k := &APIKey{ID: generateID(), Name: "legacy", HashedKey: string(h), Role: RoleReadOnly, CreatedAt: time.Now(), Permissions: getPermissionsForRole(RoleReadOnly)}
|
||||
m.mu.Lock()
|
||||
m.keys[k.ID] = k
|
||||
m.mu.Unlock()
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestValidateAPIKeyCostIndependentOfKeyCount(t *testing.T) {
|
||||
m := newTestManager()
|
||||
_, good, err := m.GenerateAPIKey("target", RoleReadWrite, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 50; i++ {
|
||||
if _, _, err := m.GenerateAPIKey("filler", RoleReadOnly, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
n := countBcrypt(t)
|
||||
|
||||
if _, err := m.ValidateAPIKey(context.Background(), good); err != nil {
|
||||
t.Fatalf("valid key rejected: %v", err)
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("valid key: %d bcrypt compares, want 1", got)
|
||||
}
|
||||
|
||||
n.Store(0)
|
||||
idPart := strings.SplitN(good, keySeparator, 2)[0]
|
||||
cases := map[string]string{
|
||||
"known id, wrong secret": idPart + keySeparator + "AAAA",
|
||||
"unknown id": keyPrefix + "nope" + keySeparator + "AAAA",
|
||||
"no secret": idPart + keySeparator,
|
||||
}
|
||||
for name, raw := range cases {
|
||||
n.Store(0)
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("%s: %d bcrypt compares, want exactly 1", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAPIKeyRejectsSecretOfAnotherKey(t *testing.T) {
|
||||
m := newTestManager()
|
||||
a, _, _ := m.GenerateAPIKey("a", RoleAdmin, nil)
|
||||
_, rawB, _ := m.GenerateAPIKey("b", RoleReadOnly, nil)
|
||||
secretB := strings.SplitN(rawB, keySeparator, 2)[1]
|
||||
if _, err := m.ValidateAPIKey(context.Background(), a.ID+keySeparator+secretB); err == nil {
|
||||
t.Fatal("id of one key with the secret of another was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyKeysStillValidate(t *testing.T) {
|
||||
m := newTestManager()
|
||||
raw := addLegacyKey(t, m)
|
||||
for i := 0; i < 3; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
k, err := m.ValidateAPIKey(context.Background(), raw)
|
||||
if err != nil || k == nil || k.Name != "legacy" {
|
||||
t.Fatalf("legacy key rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFormatKeyNeverTouchesLegacyKeys(t *testing.T) {
|
||||
m := newTestManager()
|
||||
for i := 0; i < 20; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
_, raw, _ := m.GenerateAPIKey("new", RoleReadOnly, nil)
|
||||
n := countBcrypt(t)
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw+"x"); err == nil {
|
||||
t.Fatal("bad key accepted")
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("%d bcrypt compares with 20 legacy keys stored, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyComparesAreConcurrencyBounded(t *testing.T) {
|
||||
m := newTestManager()
|
||||
for i := 0; i < 5; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
var cur, peak atomic.Int64
|
||||
orig := bcryptCompare
|
||||
bcryptCompare = func(h, p []byte) error {
|
||||
c := cur.Add(1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if c <= p || peak.CompareAndSwap(p, c) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
cur.Add(-1)
|
||||
return orig(h, p)
|
||||
}
|
||||
t.Cleanup(func() { bcryptCompare = orig })
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 40; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = m.ValidateAPIKey(context.Background(), "bad-legacy-key-bad-legacy-key-bad-legacy-key-0000")
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if got := peak.Load(); got > maxLegacyCompares {
|
||||
t.Errorf("peak concurrent legacy compares %d, want <= %d", got, maxLegacyCompares)
|
||||
}
|
||||
}
|
||||
Vendored
+54
-11
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
hoarderconfig "github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/events"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
@@ -79,15 +80,16 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
|
||||
|
||||
// Config holds cache manager configuration
|
||||
type Config struct {
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
DefaultTTL time.Duration // Freshness TTL for metadata entries
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL
|
||||
DefaultTTL time.Duration // Freshness TTL for metadata entries
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
@@ -172,7 +174,7 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
}
|
||||
|
||||
if config.DefaultTTL == 0 {
|
||||
config.DefaultTTL = 7 * 24 * time.Hour // 7 days default
|
||||
config.DefaultTTL = hoarderconfig.DefaultMetadataTTL
|
||||
}
|
||||
|
||||
if config.CleanupInterval == 0 {
|
||||
@@ -585,7 +587,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
// entries must refresh and keep a freshness expiry.
|
||||
var expiresAt *time.Time
|
||||
if isMetadataEntry {
|
||||
exp := now.Add(m.config.DefaultTTL)
|
||||
exp := now.Add(m.metadataTTL(registry))
|
||||
expiresAt = &exp
|
||||
}
|
||||
|
||||
@@ -693,6 +695,39 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
return pkg, nil
|
||||
}
|
||||
|
||||
// ScanFile returns a local file holding a cached package, for a scan retry. Backends with a
|
||||
// local path serve it directly; others are copied to a temp file that cleanup removes.
|
||||
func (m *Manager) ScanFile(ctx context.Context, registry, name, version string) (string, func(), error) {
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if local, ok := m.storage.(storage.LocalPathProvider); ok {
|
||||
path, pathErr := local.GetLocalPath(ctx, pkg.StorageKey)
|
||||
return path, func() {}, pathErr
|
||||
}
|
||||
rc, err := m.storage.Get(ctx, pkg.StorageKey)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer func() { _ = rc.Close() }()
|
||||
tmp, err := os.CreateTemp(os.TempDir(), "gohoarder-rescan-*")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
cleanup := func() { _ = os.Remove(tmp.Name()) } // #nosec G104 -- cleanup
|
||||
if _, err := io.Copy(tmp, rc); err != nil {
|
||||
_ = tmp.Close() // #nosec G104 -- cleanup
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp.Name(), cleanup, nil
|
||||
}
|
||||
|
||||
// Delete removes a package from cache
|
||||
func (m *Manager) Delete(ctx context.Context, registry, name, version string) error {
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
@@ -703,6 +738,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er
|
||||
return m.deletePackage(ctx, pkg)
|
||||
}
|
||||
|
||||
// metadataTTL returns the freshness window for a registry's metadata entries.
|
||||
func (m *Manager) metadataTTL(registry string) time.Duration {
|
||||
if ttl, ok := m.config.TTLOverrides[registry]; ok {
|
||||
return ttl
|
||||
}
|
||||
return m.config.DefaultTTL
|
||||
}
|
||||
|
||||
// deletePackage deletes a package from both storage and metadata
|
||||
func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error {
|
||||
// Delete from storage
|
||||
|
||||
Vendored
+1
-1
@@ -370,7 +370,7 @@ func TestNew(t *testing.T) {
|
||||
|
||||
// Verify defaults were set
|
||||
if tt.config.DefaultTTL == 0 {
|
||||
assert.Equal(t, 7*24*time.Hour, manager.config.DefaultTTL)
|
||||
assert.Equal(t, 24*time.Hour, manager.config.DefaultTTL)
|
||||
}
|
||||
if tt.config.CleanupInterval == 0 {
|
||||
assert.Equal(t, 1*time.Hour, manager.config.CleanupInterval)
|
||||
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Clients gate on a 72h release age; a metadata page that stays fresh longer would hide the gate's inputs.
|
||||
func TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{})
|
||||
entry := h.get(t, "left-pad", "metadata")
|
||||
|
||||
require.NotNil(t, entry.Package.ExpiresAt)
|
||||
require.Equal(t, 24*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
}
|
||||
|
||||
func TestMetadataEntryExplicitTTLWins(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 6 * time.Hour})
|
||||
entry := h.get(t, "left-pad", "metadata")
|
||||
|
||||
require.Equal(t, 6*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
}
|
||||
Vendored
+75
@@ -0,0 +1,75 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// listingMetadata adds the full listing the rescan worker walks.
|
||||
type listingMetadata struct{ scanMetadata }
|
||||
|
||||
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
|
||||
}
|
||||
|
||||
// bodyScanner reports the bytes it can read at the path it is given.
|
||||
type bodyScanner struct{ seen chan string }
|
||||
|
||||
func (*bodyScanner) Name() string { return "body-scanner" }
|
||||
func (*bodyScanner) Health(context.Context) error { return nil }
|
||||
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
return nil, err
|
||||
}
|
||||
s.seen <- string(body)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
|
||||
// through the cache's file source instead of skipping the package.
|
||||
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
bs := &bodyScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(bs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
|
||||
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
CachedAt: clock.Now(), LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { worker.Start(runCtx); close(done) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
|
||||
select {
|
||||
case got := <-bs.seen:
|
||||
require.Equal(t, "tarball-bytes", got)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("rescan never scanned the remote-storage package")
|
||||
}
|
||||
}
|
||||
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// scanMetadata lets the real scanner.Manager record results against the in-memory store.
|
||||
type scanMetadata struct {
|
||||
*memMetadata
|
||||
}
|
||||
|
||||
func (scanMetadata) SaveScanResult(context.Context, *metadata.ScanResult) error { return nil }
|
||||
func (scanMetadata) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
|
||||
return nil, fmt.Errorf("no result")
|
||||
}
|
||||
|
||||
// fileScanner fails on infrastructure once, then succeeds; it records what it could read.
|
||||
type fileScanner struct {
|
||||
seen chan string
|
||||
mu sync.Mutex
|
||||
n int
|
||||
}
|
||||
|
||||
func (*fileScanner) Name() string { return "file-scanner" }
|
||||
func (*fileScanner) Health(context.Context) error { return nil }
|
||||
func (s *fileScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
s.mu.Lock()
|
||||
s.n++
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
} else {
|
||||
s.seen <- string(body)
|
||||
}
|
||||
if n == 1 {
|
||||
return nil, fmt.Errorf("%w: scanner timed out", scanerr.ErrInfrastructure)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "file-scanner", Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// On a backend with no local path (S3, SMB) the scan source is a temp file removed after the
|
||||
// first scan; a retry must read the blob again instead of scanning a path that is gone.
|
||||
func TestScanRetryOnRemoteStorageReadsBlobAgain(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := scanMetadata{newMemMetadata(clock)}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 50 * time.Millisecond}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
fs := &fileScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(fs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour, ScanWaitTimeout: 200 * time.Millisecond})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("tarball-bytes"))}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, entry.Data)
|
||||
_ = entry.Data.Close()
|
||||
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
select {
|
||||
case got := <-fs.seen:
|
||||
require.Equal(t, "tarball-bytes", got, "scan attempt %d must read the blob", attempt)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("scan attempt %d never ran", attempt)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry {
|
||||
t.Helper()
|
||||
entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{
|
||||
DefaultTTL: 6 * time.Hour,
|
||||
TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour},
|
||||
})
|
||||
|
||||
require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl")
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}})
|
||||
|
||||
require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry")
|
||||
}
|
||||
+39
-11
@@ -35,6 +35,7 @@ type ServerConfig struct {
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout"`
|
||||
IdleTimeout time.Duration `mapstructure:"idle_timeout" json:"idle_timeout"`
|
||||
ReadBufferSize int `mapstructure:"read_buffer_size" json:"read_buffer_size"` // bytes; caps the request line plus headers
|
||||
}
|
||||
|
||||
// TLSConfig contains TLS/HTTPS configuration
|
||||
@@ -133,6 +134,26 @@ type MySQLConfig struct {
|
||||
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
|
||||
}
|
||||
|
||||
// DefaultMetadataTTL is the freshness window for metadata pages. It stays below the 72h
|
||||
// release-age gate clients apply, so a cached page never hides the entries the gate reads.
|
||||
const DefaultMetadataTTL = 24 * time.Hour
|
||||
|
||||
// DefaultReadBufferSize is the HTTP server read buffer. Fiber's own 8192 rejects browsers
|
||||
// that send OIDC session cookies plus a long Referer or URL with 431.
|
||||
const DefaultReadBufferSize = 16384
|
||||
|
||||
// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name.
|
||||
var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"}
|
||||
|
||||
// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name.
|
||||
func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
|
||||
out := make(map[string]time.Duration, len(c.TTLOverrides))
|
||||
for key, ttl := range c.TTLOverrides {
|
||||
out[ttlOverrideRegistries[key]] = ttl
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
@@ -330,11 +351,12 @@ type PyPIHandlerConfig struct {
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
ReadBufferSize: DefaultReadBufferSize,
|
||||
TLS: TLSConfig{
|
||||
Enabled: false,
|
||||
},
|
||||
@@ -355,16 +377,11 @@ func Default() *Config {
|
||||
},
|
||||
},
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: 7 * 24 * time.Hour,
|
||||
DefaultTTL: DefaultMetadataTTL,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
"npm": 7 * 24 * time.Hour,
|
||||
"pip": 7 * 24 * time.Hour,
|
||||
"go": 7 * 24 * time.Hour,
|
||||
},
|
||||
},
|
||||
Security: SecurityConfig{
|
||||
Enabled: false,
|
||||
@@ -507,12 +524,23 @@ func (c *Config) Validate() error {
|
||||
}
|
||||
|
||||
// Validate cache
|
||||
if c.Server.ReadBufferSize < 0 {
|
||||
return fmt.Errorf("server.read_buffer_size cannot be negative")
|
||||
}
|
||||
if c.Cache.DefaultTTL < 0 {
|
||||
return fmt.Errorf("cache.default_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.IdleTTL < 0 {
|
||||
return fmt.Errorf("cache.idle_ttl cannot be negative")
|
||||
}
|
||||
for key, ttl := range c.Cache.TTLOverrides {
|
||||
if _, ok := ttlOverrideRegistries[key]; !ok {
|
||||
return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key)
|
||||
}
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
|
||||
}
|
||||
}
|
||||
if c.Cache.MaxSizeBytes < 0 {
|
||||
return fmt.Errorf("cache.max_size_bytes cannot be negative")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDefaultMetadataTTL(t *testing.T) {
|
||||
require.Equal(t, 24*time.Hour, Default().Cache.DefaultTTL)
|
||||
for registry, ttl := range Default().Cache.TTLOverrides {
|
||||
require.LessOrEqual(t, ttl, 72*time.Hour, "override %s outlives the 72h release-age gate", registry)
|
||||
}
|
||||
}
|
||||
|
||||
// The shipped examples must not teach a metadata TTL longer than the release-age gate.
|
||||
func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) {
|
||||
for file, key := range map[string]string{
|
||||
"../../config.yaml.example": `default_ttl`,
|
||||
"../../helm/gohoarder/values.yaml": `defaultTTL`,
|
||||
} {
|
||||
raw, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
m := regexp.MustCompile(`(?m)^\s*` + key + `:\s*"?(\d+h)"?`).FindSubmatch(raw)
|
||||
require.NotNil(t, m, "%s has no %s", file, key)
|
||||
ttl, err := time.ParseDuration(string(m[1]))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 24*time.Hour, ttl, file)
|
||||
|
||||
for _, o := range regexp.MustCompile(`(?m)^\s+(?:npm|pip|go):\s*"(\d+h)"`).FindAllSubmatch(raw, -1) {
|
||||
d, err := time.ParseDuration(string(o[1]))
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, d, 72*time.Hour, "%s: override %s", file, o[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTLOverridesValidation(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
overrides map[string]time.Duration
|
||||
wantErr string
|
||||
}{
|
||||
"known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""},
|
||||
"pip alias": {map[string]time.Duration{"pip": time.Hour}, ""},
|
||||
"unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"},
|
||||
"zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"},
|
||||
"negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := Default()
|
||||
c.Cache.TTLOverrides = tc.overrides
|
||||
err := c.Validate()
|
||||
if tc.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.ErrorContains(t, err, tc.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesNormalisesPip(t *testing.T) {
|
||||
c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}}
|
||||
require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides())
|
||||
}
|
||||
|
||||
func TestDefaultsKeepNoTTLOverrides(t *testing.T) {
|
||||
require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl")
|
||||
}
|
||||
|
||||
func TestLoadReadsTTLOverridesFromYAML(t *testing.T) {
|
||||
write := func(body string) string {
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
|
||||
return path
|
||||
}
|
||||
|
||||
cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides())
|
||||
|
||||
_, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n"))
|
||||
require.ErrorContains(t, err, "cache.ttl_overrides")
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
@@ -17,6 +18,8 @@ type AggregationWorker struct {
|
||||
stopChan chan struct{}
|
||||
ticker *time.Ticker
|
||||
now func() time.Time // nil means time.Now
|
||||
wg sync.WaitGroup
|
||||
stopOnce sync.Once
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -36,6 +39,15 @@ func (w *AggregationWorker) clock() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// StartAsync runs Start in a goroutine that Stop waits for.
|
||||
func (w *AggregationWorker) StartAsync() {
|
||||
w.wg.Add(1)
|
||||
go func() {
|
||||
defer w.wg.Done()
|
||||
w.Start()
|
||||
}()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -68,9 +80,10 @@ func (w *AggregationWorker) Start() {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop stops the aggregation worker
|
||||
// Stop stops the aggregation worker and waits for a started one to exit. Safe to call repeatedly.
|
||||
func (w *AggregationWorker) Stop() {
|
||||
close(w.stopChan)
|
||||
w.stopOnce.Do(func() { close(w.stopChan) })
|
||||
w.wg.Wait()
|
||||
}
|
||||
|
||||
// AggregateHourly aggregates download events into hourly stats
|
||||
@@ -139,7 +152,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
// SQLite: Use strftime for time bucketing
|
||||
// Note: SQLite doesn't support UPSERT as elegantly, need to handle separately
|
||||
aggregateSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
SELECT
|
||||
de.registry_id,
|
||||
de.package_id,
|
||||
@@ -152,6 +165,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
FROM download_events de
|
||||
WHERE de.downloaded_at < ?
|
||||
GROUP BY de.registry_id, de.package_id, time_bucket
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = download_stats_hourly.download_count + excluded.download_count,
|
||||
unique_ips = MAX(download_stats_hourly.unique_ips, excluded.unique_ips),
|
||||
auth_downloads = download_stats_hourly.auth_downloads + excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -221,7 +240,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
default:
|
||||
// SQLite
|
||||
registryAggSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
SELECT
|
||||
registry_id,
|
||||
NULL as package_id,
|
||||
@@ -234,6 +253,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
FROM download_stats_hourly
|
||||
WHERE package_id IS NOT NULL
|
||||
GROUP BY registry_id, time_bucket
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = excluded.download_count,
|
||||
unique_ips = excluded.unique_ips,
|
||||
auth_downloads = excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -317,7 +342,7 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
default: // SQLite
|
||||
aggregateSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||
INSERT INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||
SELECT
|
||||
registry_id,
|
||||
package_id,
|
||||
@@ -331,6 +356,12 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
FROM download_stats_hourly
|
||||
WHERE time_bucket >= ? AND time_bucket < ?
|
||||
GROUP BY registry_id, package_id, date(time_bucket)
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = excluded.download_count,
|
||||
unique_ips = excluded.unique_ips,
|
||||
auth_downloads = excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package gormstore
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloseIsIdempotent(t *testing.T) {
|
||||
store := openFileStore(t, true)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("first Close: %v", err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("second Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,12 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Driver == "sqlite" {
|
||||
if err := ensureSQLiteStatsIndexes(db); err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to create stats indexes")
|
||||
}
|
||||
}
|
||||
|
||||
if err := dropEmptyTable(db, legacyDownloadEventsTable); err != nil {
|
||||
log.Warn().Err(err).Str("table", legacyDownloadEventsTable).Msg("Failed to drop empty legacy table")
|
||||
}
|
||||
@@ -122,7 +128,7 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
// Start aggregation worker (skip for in-memory databases used in tests)
|
||||
if !strings.Contains(cfg.DSN, ":memory:") {
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
go store.aggregationWorker.Start()
|
||||
store.aggregationWorker.StartAsync()
|
||||
} else {
|
||||
// For tests: create worker but don't start it
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ensureSQLiteStatsIndexes gives SQLite the unique indexes PostgreSQL gets from
|
||||
// the partition manager, merging duplicate rows written before they existed.
|
||||
func ensureSQLiteStatsIndexes(db *gorm.DB) error {
|
||||
var present int64
|
||||
if err := db.Raw("SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name IN ('idx_stats_hourly_upsert', 'idx_stats_daily_upsert')").Scan(&present).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if present == int64(len(statsUpsertIndexes)) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
// Hourly package rows come from passes over disjoint events, so they add up.
|
||||
// Registry rows (NULL package) and daily rows are derived and recomputed by the
|
||||
// next pass; one copy of each is enough.
|
||||
const group = "d.registry_id = download_stats_hourly.registry_id AND d.package_id = download_stats_hourly.package_id AND d.time_bucket = download_stats_hourly.time_bucket"
|
||||
merge := `UPDATE download_stats_hourly SET
|
||||
download_count = (SELECT SUM(d.download_count) FROM download_stats_hourly d WHERE ` + group + `),
|
||||
auth_downloads = (SELECT SUM(d.auth_downloads) FROM download_stats_hourly d WHERE ` + group + `),
|
||||
unique_ips = (SELECT MAX(d.unique_ips) FROM download_stats_hourly d WHERE ` + group + `)
|
||||
WHERE package_id IS NOT NULL AND id = (SELECT MIN(d.id) FROM download_stats_hourly d WHERE ` + group + `)`
|
||||
if err := tx.Exec(merge).Error; err != nil {
|
||||
return fmt.Errorf("merge duplicate hourly stats rows: %w", err)
|
||||
}
|
||||
for _, table := range []string{"download_stats_hourly", "download_stats_daily"} {
|
||||
dedupe := fmt.Sprintf("DELETE FROM %[1]s WHERE id NOT IN (SELECT MIN(id) FROM %[1]s GROUP BY registry_id, COALESCE(package_id, 0), time_bucket)", table)
|
||||
if err := tx.Exec(dedupe).Error; err != nil {
|
||||
return fmt.Errorf("delete duplicate %s rows: %w", table, err)
|
||||
}
|
||||
}
|
||||
for _, stmt := range statsUpsertIndexes {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return fmt.Errorf("create stats upsert index: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The same scenario the SQLite test runs: both dialects must report the same totals.
|
||||
func TestPostgresHourlyTotalsMatchSQLite(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
require.Equal(t, wantHourlyScenario(), runHourlyScenario(t, store))
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// statsScenario drives the same hourly passes on any dialect and returns the
|
||||
// observable totals, so SQLite and PostgreSQL can be held to one expectation.
|
||||
type statsScenario struct {
|
||||
packageRows, registryRows int64
|
||||
packageCount, registryCnt int64
|
||||
chartTotal int64
|
||||
}
|
||||
|
||||
func runHourlyScenario(t *testing.T, store *GORMStoreV2) statsScenario {
|
||||
t.Helper()
|
||||
hour := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
|
||||
|
||||
seedEventsAt(t, store, hour.Add(10*time.Minute), hour.Add(20*time.Minute))
|
||||
tick(t, store, hour.Add(2*time.Hour), false)
|
||||
tick(t, store, hour.Add(2*time.Hour+5*time.Minute), false) // nothing new: must change nothing
|
||||
|
||||
seedEventsAt(t, store, hour.Add(50*time.Minute)) // a late download for the same bucket
|
||||
tick(t, store, hour.Add(3*time.Hour), false)
|
||||
|
||||
var s statsScenario
|
||||
db := store.db.Table("download_stats_hourly")
|
||||
require.NoError(t, db.Where("package_id IS NOT NULL").Count(&s.packageRows).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NULL").Count(&s.registryRows).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NOT NULL").Select("COALESCE(SUM(download_count),0)").Scan(&s.packageCount).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NULL").Select("COALESCE(SUM(download_count),0)").Scan(&s.registryCnt).Error)
|
||||
s.chartTotal = totalAt(t, store, hour.Add(3*time.Hour+10*time.Minute), "24hour")
|
||||
return s
|
||||
}
|
||||
|
||||
func wantHourlyScenario() statsScenario {
|
||||
return statsScenario{packageRows: 1, registryRows: 1, packageCount: 3, registryCnt: 3, chartTotal: 3}
|
||||
}
|
||||
|
||||
// SQLite carried no unique index, so INSERT OR REPLACE inserted a new row every pass.
|
||||
func TestSQLiteHourlyTotalsMatchPostgresSemantics(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
require.Equal(t, wantHourlyScenario(), runHourlyScenario(t, store))
|
||||
}
|
||||
|
||||
func TestSQLiteDailyRollupIsIdempotent(t *testing.T) {
|
||||
store := newTimeSeriesStore(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))
|
||||
tick(t, store, day.Add(24*time.Hour+30*time.Minute), false)
|
||||
for i := 0; i < 3; i++ {
|
||||
store.aggregationWorker.now = func() time.Time { return day.Add(25 * time.Hour) }
|
||||
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||
}
|
||||
|
||||
var rows, total int64
|
||||
require.NoError(t, store.db.Table("download_stats_daily").Where("package_id IS NOT NULL").Count(&rows).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_daily").Where("package_id IS NOT NULL").Select("COALESCE(SUM(download_count),0)").Scan(&total).Error)
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.EqualValues(t, 2, total)
|
||||
}
|
||||
|
||||
// Databases written by the old code hold duplicate rows; the migration merges them.
|
||||
func TestSQLiteStatsDedupeMigration(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
for _, name := range []string{"idx_stats_hourly_upsert", "idx_stats_daily_upsert"} {
|
||||
require.NoError(t, store.db.Exec("DROP INDEX IF EXISTS "+name).Error)
|
||||
}
|
||||
bucket := "2026-03-10 05:00:00"
|
||||
insert := func(table string, pkg any, n int) {
|
||||
require.NoError(t, store.db.Exec(
|
||||
"INSERT INTO "+table+" (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at) VALUES (1, ?, ?, ?, 1, 0, datetime('now'), datetime('now'))",
|
||||
pkg, bucket, n).Error)
|
||||
}
|
||||
// Package rows from separate passes hold disjoint events: they add up.
|
||||
insert("download_stats_hourly", 7, 2)
|
||||
insert("download_stats_hourly", 7, 3)
|
||||
// Registry rows are derived copies: one survives.
|
||||
insert("download_stats_hourly", nil, 5)
|
||||
insert("download_stats_hourly", nil, 5)
|
||||
insert("download_stats_daily", nil, 5)
|
||||
insert("download_stats_daily", nil, 5)
|
||||
|
||||
require.NoError(t, ensureSQLiteStatsIndexes(store.db))
|
||||
|
||||
count := func(table, where string) (rows, total int64) {
|
||||
require.NoError(t, store.db.Table(table).Where(where).Count(&rows).Error)
|
||||
require.NoError(t, store.db.Table(table).Where(where).Select("COALESCE(SUM(download_count),0)").Scan(&total).Error)
|
||||
return
|
||||
}
|
||||
rows, total := count("download_stats_hourly", "package_id = 7")
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.EqualValues(t, 5, total)
|
||||
rows, total = count("download_stats_hourly", "package_id IS NULL")
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.EqualValues(t, 5, total)
|
||||
rows, _ = count("download_stats_daily", "package_id IS NULL")
|
||||
require.EqualValues(t, 1, rows)
|
||||
|
||||
require.Error(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, NULL, ?, 1, 1, 0, datetime('now'), datetime('now'))", bucket).Error,
|
||||
"unique index must reject a duplicate registry row")
|
||||
}
|
||||
+114
-7
@@ -6,8 +6,11 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
@@ -19,6 +22,7 @@ import (
|
||||
// Client is an HTTP client with resilience features
|
||||
type Client struct {
|
||||
client *http.Client
|
||||
hopClient *http.Client
|
||||
rateLimiter *rate.Limiter
|
||||
circuitBreaker *CircuitBreaker
|
||||
retryConfig RetryConfig
|
||||
@@ -34,6 +38,9 @@ type Config struct {
|
||||
RateLimit float64
|
||||
RateBurst int
|
||||
MaxConnsPerHost int
|
||||
// AllowPrivateRedirects lets a redirect to another host reach private, loopback or
|
||||
// link-local addresses. Off by default; it exists for tests and private mirrors.
|
||||
AllowPrivateRedirects bool
|
||||
}
|
||||
|
||||
// RetryConfig holds retry configuration
|
||||
@@ -105,8 +112,19 @@ func NewClient(config Config) *Client {
|
||||
}
|
||||
|
||||
httpClient := &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
Transport: transport,
|
||||
Timeout: config.Timeout,
|
||||
Transport: transport,
|
||||
CheckRedirect: noAutoRedirect,
|
||||
}
|
||||
|
||||
hopTransport := transport.Clone()
|
||||
if !config.AllowPrivateRedirects {
|
||||
hopTransport.DialContext = (&net.Dialer{Timeout: 30 * time.Second, Control: refusePrivateAddress}).DialContext
|
||||
}
|
||||
hopClient := &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
Transport: hopTransport,
|
||||
CheckRedirect: noAutoRedirect,
|
||||
}
|
||||
|
||||
var rateLimiter *rate.Limiter
|
||||
@@ -140,6 +158,7 @@ func NewClient(config Config) *Client {
|
||||
|
||||
return &Client{
|
||||
client: httpClient,
|
||||
hopClient: hopClient,
|
||||
rateLimiter: rateLimiter,
|
||||
circuitBreaker: cb,
|
||||
retryConfig: RetryConfig{
|
||||
@@ -154,8 +173,15 @@ func NewClient(config Config) *Client {
|
||||
}
|
||||
|
||||
// Get performs a GET request with resilience features
|
||||
func (c *Client) Get(ctx context.Context, url string, headers map[string]string) (io.ReadCloser, int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
func (c *Client) Get(ctx context.Context, rawURL string, headers map[string]string) (io.ReadCloser, int, error) {
|
||||
return c.GetWithRedirectCheck(ctx, rawURL, headers, nil)
|
||||
}
|
||||
|
||||
// GetWithRedirectCheck is Get with a policy that every redirect target must pass.
|
||||
// Redirects are always capped, limited to http(s), and refused when they reach a
|
||||
// private address on another host; check adds an allowlist on top.
|
||||
func (c *Client) GetWithRedirectCheck(ctx context.Context, rawURL string, headers map[string]string, check RedirectCheck) (io.ReadCloser, int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return nil, 0, errors.Wrap(err, errors.ErrCodeUpstreamError, "failed to create request")
|
||||
}
|
||||
@@ -164,7 +190,7 @@ func (c *Client) Get(ctx context.Context, url string, headers map[string]string)
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
resp, err := c.do(ctx, req)
|
||||
resp, err := c.do(ctx, req, check)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -173,7 +199,7 @@ func (c *Client) Get(ctx context.Context, url string, headers map[string]string)
|
||||
}
|
||||
|
||||
// do executes an HTTP request with retries and circuit breaker
|
||||
func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) {
|
||||
func (c *Client) do(ctx context.Context, req *http.Request, check RedirectCheck) (*http.Response, error) {
|
||||
// Check circuit breaker
|
||||
if c.circuitBreaker != nil {
|
||||
if !c.circuitBreaker.AllowRequest() {
|
||||
@@ -226,7 +252,7 @@ func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, err
|
||||
Msg("Retrying request")
|
||||
}
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
resp, err := c.send(req, check)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
@@ -353,3 +379,84 @@ func (cb *CircuitBreaker) GetState() CircuitBreakerState {
|
||||
defer cb.mu.RUnlock()
|
||||
return cb.state
|
||||
}
|
||||
|
||||
// MaxRedirects caps the hops one request may follow.
|
||||
const MaxRedirects = 10
|
||||
|
||||
// RedirectCheck vets a redirect target before it is fetched.
|
||||
type RedirectCheck func(*url.URL) error
|
||||
|
||||
var errRedirectNotAllowed = errors.New(errors.ErrCodeUpstreamError, "redirect refused")
|
||||
|
||||
func noAutoRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
|
||||
// send performs req and follows redirects itself, so each hop is vetted and, once the
|
||||
// host changes, dialed through the guard that refuses private addresses.
|
||||
func (c *Client) send(req *http.Request, check RedirectCheck) (*http.Response, error) {
|
||||
origin := req.URL.Host
|
||||
cur := req
|
||||
httpClient := c.client
|
||||
for hop := 0; ; hop++ {
|
||||
resp, err := httpClient.Do(cur)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
loc := resp.Header.Get("Location")
|
||||
if !isRedirectStatus(resp.StatusCode) || loc == "" {
|
||||
return resp, nil
|
||||
}
|
||||
_ = resp.Body.Close() // #nosec G104 -- Cleanup, error not critical
|
||||
if hop >= MaxRedirects {
|
||||
return nil, errors.Wrap(errRedirectNotAllowed, errors.ErrCodeUpstreamError, "too many redirects")
|
||||
}
|
||||
next, err := cur.URL.Parse(loc)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeUpstreamError, "invalid redirect location")
|
||||
}
|
||||
if next.Scheme != "http" && next.Scheme != "https" {
|
||||
return nil, errors.Wrap(errRedirectNotAllowed, errors.ErrCodeUpstreamError, "redirect to non-http scheme")
|
||||
}
|
||||
if check != nil {
|
||||
if err := check(next); err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeUpstreamError, "redirect target not allowed")
|
||||
}
|
||||
}
|
||||
clone := cur.Clone(cur.Context())
|
||||
clone.URL = next
|
||||
clone.Host = ""
|
||||
if next.Host != cur.URL.Host {
|
||||
clone.Header.Del("Authorization")
|
||||
clone.Header.Del("Cookie")
|
||||
}
|
||||
cur = clone
|
||||
if next.Host != origin {
|
||||
httpClient = c.hopClient
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isRedirectStatus(code int) bool {
|
||||
switch code {
|
||||
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther,
|
||||
http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// carrierGradeNAT is 100.64.0.0/10, which net.IP.IsPrivate does not cover.
|
||||
var carrierGradeNAT = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
|
||||
|
||||
// refusePrivateAddress runs after DNS resolution, so a name cannot rebind to an internal address.
|
||||
func refusePrivateAddress(_, address string, _ syscall.RawConn) error {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() ||
|
||||
ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() || ip.IsMulticast() || carrierGradeNAT.Contains(ip) {
|
||||
return fmt.Errorf("refusing to connect to non-public address %s", host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package network_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/network"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func redirectClient(allowPrivate bool) *network.Client {
|
||||
return network.NewClient(network.Config{
|
||||
Timeout: 5 * time.Second,
|
||||
MaxRetries: 1,
|
||||
AllowPrivateRedirects: allowPrivate,
|
||||
})
|
||||
}
|
||||
|
||||
// hostPolicy allows only the listed hostnames (port ignored).
|
||||
func hostPolicy(hosts ...string) func(*url.URL) error {
|
||||
return func(u *url.URL) error {
|
||||
for _, h := range hosts {
|
||||
if u.Hostname() == h {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("host %q not allowed", u.Hostname())
|
||||
}
|
||||
}
|
||||
|
||||
func okServer(hit *atomic.Int32) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hit.Add(1)
|
||||
_, _ = w.Write([]byte("secret"))
|
||||
}))
|
||||
}
|
||||
|
||||
func TestRedirectToDisallowedHostRefused(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
target := okServer(&hit)
|
||||
defer target.Close()
|
||||
// Same loopback server under a different hostname: allowed host redirects to a disallowed one.
|
||||
redirectTo := strings.Replace(target.URL, "127.0.0.1", "localhost", 1)
|
||||
origin := httptest.NewServer(http.RedirectHandler(redirectTo, http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
_, _, err := redirectClient(true).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1"))
|
||||
require.Error(t, err)
|
||||
assert.Zero(t, hit.Load(), "disallowed hop must not be fetched")
|
||||
}
|
||||
|
||||
func TestRedirectToLoopbackRefused(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
target := okServer(&hit)
|
||||
defer target.Close()
|
||||
// Allowed by name, but resolves to loopback on a different host:port than the origin.
|
||||
origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
_, _, err := redirectClient(false).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1", "localhost"))
|
||||
require.Error(t, err)
|
||||
assert.Zero(t, hit.Load(), "loopback hop must not be fetched")
|
||||
}
|
||||
|
||||
func TestRedirectToPrivateLiteralRefused(t *testing.T) {
|
||||
for _, loc := range []string{"http://10.1.2.3/x", "http://169.254.169.254/latest/meta-data", "http://[::1]/x", "http://192.168.0.1/x"} {
|
||||
origin := httptest.NewServer(http.RedirectHandler(loc, http.StatusFound))
|
||||
_, _, err := redirectClient(false).Get(context.Background(), origin.URL, nil)
|
||||
origin.Close()
|
||||
require.Error(t, err, loc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectAllowedToAllowedWorks(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
target := okServer(&hit)
|
||||
defer target.Close()
|
||||
origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
body, status, err := redirectClient(true).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1", "localhost"))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = body.Close() }()
|
||||
data, _ := io.ReadAll(body)
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.Equal(t, "secret", string(data))
|
||||
}
|
||||
|
||||
func TestRedirectHopsCapped(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
http.Redirect(w, r, srv.URL+"/loop", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, _, err := redirectClient(true).Get(context.Background(), srv.URL, nil)
|
||||
require.Error(t, err)
|
||||
assert.LessOrEqual(t, int(hits.Load()), 11)
|
||||
}
|
||||
|
||||
func TestRedirectToNonHTTPSchemeRefused(t *testing.T) {
|
||||
origin := httptest.NewServer(http.RedirectHandler("file:///etc/passwd", http.StatusFound))
|
||||
defer origin.Close()
|
||||
_, _, err := redirectClient(true).Get(context.Background(), origin.URL, nil)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestRedirectDropsAuthorizationAcrossHosts(t *testing.T) {
|
||||
var got atomic.Value
|
||||
got.Store("unset")
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got.Store(r.Header.Get("Authorization"))
|
||||
}))
|
||||
defer target.Close()
|
||||
origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
body, _, err := redirectClient(true).Get(context.Background(), origin.URL, map[string]string{"Authorization": "Bearer x"})
|
||||
require.NoError(t, err)
|
||||
_ = body.Close()
|
||||
assert.Equal(t, "", got.Load())
|
||||
}
|
||||
|
||||
func TestSameHostRedirectToLoopbackStillWorks(t *testing.T) {
|
||||
// A private index redirecting within itself is operator-trusted.
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/b", http.StatusFound) })
|
||||
mux.HandleFunc("/b", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
body, status, err := redirectClient(false).Get(context.Background(), srv.URL+"/a", nil)
|
||||
require.NoError(t, err)
|
||||
_ = body.Close()
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
}
|
||||
+14
-4
@@ -51,6 +51,16 @@ func isAllowedPyPIHost(host string, allowed []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// get fetches from upstream; every redirect hop must be on the allowlist, as for original_url.
|
||||
func (h *Handler) get(ctx context.Context, rawURL string, headers map[string]string) (io.ReadCloser, int, error) {
|
||||
return h.client.GetWithRedirectCheck(ctx, rawURL, headers, func(u *url.URL) error {
|
||||
if !isAllowedPyPIHost(u.Host, h.allowedHosts) {
|
||||
return fmt.Errorf("redirect host %q not on allowlist", u.Hostname())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Handler implements the PyPI Simple API (PEP 503)
|
||||
type Handler struct {
|
||||
cache *cache.Manager
|
||||
@@ -130,7 +140,7 @@ func (h *Handler) handleIndex(ctx context.Context, w http.ResponseWriter, r *htt
|
||||
url := h.upstream + "/"
|
||||
|
||||
entry, err := h.cache.Get(ctx, "pypi", "index", "latest", func(ctx context.Context) (*cache.FetchResult, error) {
|
||||
body, statusCode, err := h.client.Get(ctx, url, nil)
|
||||
body, statusCode, err := h.get(ctx, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -178,7 +188,7 @@ func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter,
|
||||
}
|
||||
|
||||
entry, err := h.cache.Get(ctx, "pypi", packageName, cacheVersion, func(ctx context.Context) (*cache.FetchResult, error) {
|
||||
body, statusCode, err := h.client.Get(ctx, url, upstreamHeaders)
|
||||
body, statusCode, err := h.get(ctx, url, upstreamHeaders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -323,7 +333,7 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
|
||||
headers["Authorization"] = credentials
|
||||
}
|
||||
|
||||
body, statusCode, err := h.client.Get(ctx, originalURL, headers)
|
||||
body, statusCode, err := h.get(ctx, originalURL, headers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -454,7 +464,7 @@ func (h *Handler) serveMetadataSidecar(ctx context.Context, w http.ResponseWrite
|
||||
if credentials != "" {
|
||||
headers["Authorization"] = credentials
|
||||
}
|
||||
body, status, err := h.client.Get(ctx, upstreamURL, headers)
|
||||
body, status, err := h.get(ctx, upstreamURL, headers)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("url", upstreamURL).Msg("Failed to fetch PEP 658 metadata")
|
||||
http.Error(w, "Failed to fetch package metadata", http.StatusBadGateway)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package pypi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/network"
|
||||
)
|
||||
|
||||
// A PEP 658 sidecar fetched from an allowed host must not follow a redirect off the allowlist.
|
||||
func TestSidecarRedirectOffAllowlistRefused(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hit.Add(1)
|
||||
_, _ = w.Write([]byte("internal-secret"))
|
||||
}))
|
||||
defer internal.Close()
|
||||
allowed := httptest.NewServer(http.RedirectHandler(strings.Replace(internal.URL, "127.0.0.1", "localhost", 1)+"/example-1.0.0-py3-none-any.whl.metadata", http.StatusFound))
|
||||
defer allowed.Close()
|
||||
|
||||
client := network.NewClient(network.Config{Timeout: 5 * time.Second, MaxRetries: 1, AllowPrivateRedirects: true})
|
||||
h := &Handler{client: client, allowedHosts: []string{"127.0.0.1"}}
|
||||
|
||||
const path = "/example/example-1.0.0-py3-none-any.whl.metadata"
|
||||
q := url.Values{"original_url": {allowed.URL + "/files/example-1.0.0-py3-none-any.whl"}}
|
||||
req := httptest.NewRequest(http.MethodGet, path+"?"+q.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.handlePackageFile(req.Context(), w, req, path)
|
||||
|
||||
if w.Code != http.StatusBadGateway {
|
||||
t.Errorf("code=%d want 502 body=%q", w.Code, w.Body.String())
|
||||
}
|
||||
if hit.Load() != 0 || strings.Contains(w.Body.String(), "internal-secret") {
|
||||
t.Errorf("redirect target was fetched (hits=%d)", hit.Load())
|
||||
}
|
||||
}
|
||||
+17
-29
@@ -6,14 +6,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// RescanWorker handles periodic re-scanning of cached packages
|
||||
type RescanWorker struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
storage storage.StorageBackend
|
||||
manager *Manager
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
@@ -21,11 +19,10 @@ type RescanWorker struct {
|
||||
}
|
||||
|
||||
// NewRescanWorker creates a new rescan worker
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, storageBackend storage.StorageBackend, interval time.Duration) *RescanWorker {
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
|
||||
return &RescanWorker{
|
||||
manager: manager,
|
||||
metadataStore: metadataStore,
|
||||
storage: storageBackend,
|
||||
interval: interval,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
@@ -123,7 +120,6 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package needs rescanning")
|
||||
|
||||
// Get file path from storage using the storage key from the package metadata
|
||||
if pkg.StorageKey == "" {
|
||||
log.Warn().
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -134,7 +130,18 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
filePath, err := w.getPackageFilePath(ctx, pkg.StorageKey)
|
||||
source := w.manager.currentFileSource()
|
||||
if source == nil {
|
||||
log.Debug().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("No file source configured, skipping rescan")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if err != nil {
|
||||
log.Warn().
|
||||
Err(err).
|
||||
@@ -142,23 +149,15 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("storage_key", pkg.StorageKey).
|
||||
Msg("Failed to get package file path, skipping rescan")
|
||||
Msg("Failed to read package file, skipping rescan")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
if filePath == "" {
|
||||
log.Debug().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("No local file path available, skipping rescan")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// Perform the actual scan
|
||||
if err := w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath); err != nil {
|
||||
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
|
||||
cleanup()
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -210,14 +209,3 @@ func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// getPackageFilePath retrieves the local file path for a package from storage
|
||||
func (w *RescanWorker) getPackageFilePath(ctx context.Context, storageKey string) (string, error) {
|
||||
// Check if storage backend supports local paths
|
||||
if localProvider, ok := w.storage.(storage.LocalPathProvider); ok {
|
||||
return localProvider.GetLocalPath(ctx, storageKey)
|
||||
}
|
||||
|
||||
// If storage doesn't support local paths (S3, SMB), we can't rescan
|
||||
return "", nil
|
||||
}
|
||||
|
||||
+33
-1
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -53,11 +54,29 @@ const (
|
||||
maxScanRetries = 6
|
||||
)
|
||||
|
||||
// FileSource returns a readable local copy of a stored package for a retry, plus its cleanup.
|
||||
type FileSource func(ctx context.Context, registry, packageName, version string) (path string, cleanup func(), err error)
|
||||
|
||||
// SetFileSource lets a retry re-read the stored blob when the file its first scan used is gone,
|
||||
// as with remote storage whose scan source is a temp file removed after the first attempt.
|
||||
func (m *Manager) SetFileSource(fs FileSource) {
|
||||
m.stateMu.Lock()
|
||||
m.fileSource = fs
|
||||
m.stateMu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Manager) currentFileSource() FileSource {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
return m.fileSource
|
||||
}
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
fileSource FileSource
|
||||
inflight map[string]int
|
||||
scanners []Scanner
|
||||
config config.SecurityConfig
|
||||
@@ -121,8 +140,21 @@ func (m *Manager) scheduleRetry(registry, packageName, version, filePath string,
|
||||
m.retryTimers[key] = time.AfterFunc(interval, func() {
|
||||
m.stateMu.Lock()
|
||||
delete(m.retryTimers, key)
|
||||
source := m.fileSource
|
||||
m.stateMu.Unlock()
|
||||
if err := m.scan(context.Background(), registry, packageName, version, filePath, attempt); err != nil {
|
||||
|
||||
ctx := context.Background()
|
||||
path := filePath
|
||||
if _, statErr := os.Stat(filePath); statErr != nil && source != nil {
|
||||
fresh, cleanup, err := source(ctx, registry, packageName, version)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry could not re-read package")
|
||||
return
|
||||
}
|
||||
defer cleanup()
|
||||
path = fresh
|
||||
}
|
||||
if err := m.scan(ctx, registry, packageName, version, path, attempt); err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry failed")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -251,6 +251,11 @@ func (s *Server) Dropped() uint64 {
|
||||
return s.dropped.Load()
|
||||
}
|
||||
|
||||
// Pending returns how many events wait in the broadcast channel.
|
||||
func (s *Server) Pending() int {
|
||||
return len(s.broadcast)
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# Builds the frontend image from a Dockerfile and checks that /api and /ws do not forward the
|
||||
# browser's Cookie header to the backend. Usage: scripts/check_frontend_cookie_strip.sh [Dockerfile]
|
||||
set -eu
|
||||
|
||||
dockerfile="${1:-Dockerfile.frontend}"
|
||||
root="$(git rev-parse --show-toplevel)"
|
||||
work="$(mktemp -d)"
|
||||
tag="gohoarder-frontend-cookie-check:$$"
|
||||
net="gohoarder-cookie-check-$$"
|
||||
stub="$net-backend"
|
||||
front="$net-frontend"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$front" "$stub" >/dev/null 2>&1 || true
|
||||
docker network rm "$net" >/dev/null 2>&1 || true
|
||||
docker rmi "$tag" >/dev/null 2>&1 || true
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
mkdir -p "$work/frontend/dist"
|
||||
echo '<html></html>' >"$work/frontend/dist/index.html"
|
||||
cp "$root/$dockerfile" "$work/Dockerfile"
|
||||
docker build -q --load -t "$tag" "$work" >/dev/null
|
||||
|
||||
cat >"$work/stub.conf" <<'CONF'
|
||||
server {
|
||||
listen 8080;
|
||||
location / { default_type text/plain; return 200 "cookie=[$http_cookie]"; }
|
||||
}
|
||||
CONF
|
||||
|
||||
docker network create "$net" >/dev/null
|
||||
docker run -d --name "$stub" --network "$net" -v "$work/stub.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine >/dev/null
|
||||
docker run -d --name "$front" --network "$net" -e BACKEND_HOST="$stub" -e BACKEND_PORT=8080 "$tag" >/dev/null
|
||||
|
||||
cookie="session=$(head -c 8000 /dev/zero | tr '\0' 'a')"
|
||||
status=0
|
||||
for path in /api/packages /ws; do
|
||||
ok=no
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
body="$(docker exec "$front" wget -qO- --header "Cookie: $cookie" "http://127.0.0.1$path" 2>/dev/null || true)"
|
||||
[ -n "$body" ] && ok=yes && break
|
||||
sleep 1
|
||||
done
|
||||
if [ "$ok" = no ]; then
|
||||
echo "FAIL: $path returned no body"
|
||||
status=1
|
||||
elif [ "$body" = "cookie=[]" ]; then
|
||||
echo "ok: $path forwards no Cookie"
|
||||
else
|
||||
echo "FAIL: $path forwarded a Cookie header ($(printf '%s' "$body" | wc -c) bytes)"
|
||||
status=1
|
||||
fi
|
||||
done
|
||||
exit "$status"
|
||||
Reference in New Issue
Block a user