Compare commits

...
7 Commits
30 changed files with 1383 additions and 81 deletions
+2 -1
View File
@@ -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
@@ -252,7 +253,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.
+8 -4
View File
@@ -12,6 +12,10 @@ server:
read_timeout: "5m"
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 +93,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"
npm: "24h"
pip: "24h"
go: "24h"
security:
enabled: false
+1
View File
@@ -12,6 +12,7 @@ data:
read_timeout: {{ .Values.server.readTimeout | quote }}
write_timeout: {{ .Values.server.writeTimeout | quote }}
idle_timeout: {{ .Values.server.idleTimeout | quote }}
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
tls:
enabled: false
+6 -4
View File
@@ -93,6 +93,8 @@ server:
readTimeout: "5m"
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 +377,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"
npm: "24h"
pip: "24h"
go: "24h"
# Security scanning configuration
security:
+28 -6
View File
@@ -20,6 +20,12 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 |
| GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 |
| GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f |
| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e |
| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 |
| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f |
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
### Exploit paths and reach
@@ -30,9 +36,31 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
- **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name
returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong
scan results rather than serving blocked packages; any deployment with a block policy served such packages.
- **GH-17.** A page at any origin issued `DELETE /api/packages/<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` has no consumer in the Go code (`grep TTLOverrides pkg cmd`: the field and its compiled default
only). The per-registry keys are kept and now default to 24h; they change nothing until something reads them.
- **GH-18.** New keys read `ghk_<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` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour.
- **GH-17 cleanup.** The per-handler `Access-Control-Allow-Origin: *` lines in `pkg/app/handlers*.go` are now overridden by the
guard and are dead; remove them once the API performance work lands.
## Not fixed
| id | area | claim | verdict | why |
@@ -42,13 +70,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-15 | release age | a cached packument or index hides new or yanked entries for up to the TTL | by-design | Quoted intent, `pkg/cache/cache.go` store: "TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed based on upstream Cache-Control". Passthrough proved: `Release.rewrite_preserves_upload_time`, `stale_hides_only_gated` (needs TTL <= gate; production 24h <= 72h holds, the compiled default 168h does not, and then the proxy is stricter than the gate). |
| GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. |
| GH-17 | auth off | with `auth.enabled: false` (production) `DELETE /api/packages/*` is unauthenticated, and `Access-Control-Allow-Origin: *` lets a browser page issue it | by-design, product decision | Quoted intent, `pkg/app/app.go`: "routes are mounted bare to preserve backward-compatible public access". Impact is cache eviction only. Enabling auth is a configuration change the operator owns. |
| GH-18 | api keys | `ValidateAPIKey` bcrypt-compares every stored key per request | hardening, CWE-400 | N keys cost N bcrypt checks per bad key. A key-id prefix needs an API change. Zero keys in production. |
| GH-19 | SSRF | `network.Client` follows redirects without re-checking the allowlist | hardening | `Access.redirect_escapes_allowlist`. No allowed host redirects (pypi.org, files.pythonhosted.org); a private index host is operator-trusted. |
| GH-20 | stats, sqlite | `INSERT OR REPLACE` has no unique index on SQLite, so every pass duplicates registry rows | correctness, SQLite only | Seen in a row dump (three NULL-package hourly rows for one bucket after three passes). Production is PostgreSQL, where `statsUpsertIndexes` exist. Needs a dedupe migration; left open. |
| GH-21 | scan retry | a retry on S3 or SMB storage rescans a temp file already removed | suspected, unconfirmed | `cache.go` store removes `tempPath` after the first scan. Production is filesystem. No test written. |
### Decision: `fail_closed: false` with recurring infrastructure errors
+55 -6
View File
@@ -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. -/
+5 -5
View File
@@ -47,12 +47,12 @@ theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ tt
(hnew : s < t) : ¬ gateAccepts gate now t := by
unfold gateAccepts; omega
/-- Production: `default_ttl: 24h` against a 72h gate. -/
theorem prod_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
/-- Production and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/
theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
/-- The compiled default is 7 days. Against a 72h gate a version aged 84h is eligible but absent
from a 7-day-old snapshot: the proxy withholds it, which is stricter than the gate, never looser. -/
theorem default_ttl_exceeds_gate :
/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but
absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/
theorem old_default_ttl_exceeded_gate :
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
+14
View File
@@ -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
+20
View File
@@ -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
+7 -3
View File
@@ -308,6 +308,8 @@ 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")
@@ -411,6 +413,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 +892,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 +929,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
}
}
+94
View File
@@ -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()
// Handlers set a wildcard grant; replace it with the allowlist decision.
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
}
+144
View File
@@ -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)
}
+107 -31
View File
@@ -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
+156
View File
@@ -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)
}
}
+35 -1
View File
@@ -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"
@@ -172,7 +173,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 {
@@ -693,6 +694,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)
+1 -1
View File
@@ -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)
+24
View File
@@ -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()))
}
+92
View File
@@ -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)
}
}
}
+8 -4
View File
@@ -133,6 +133,10 @@ 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
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
const DefaultIdleTTL = 7 * 24 * time.Hour
@@ -355,15 +359,15 @@ 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,
"npm": DefaultMetadataTTL,
"pip": DefaultMetadataTTL,
"go": DefaultMetadataTTL,
},
},
Security: SecurityConfig{
+39
View File
@@ -0,0 +1,39 @@
package config
import (
"os"
"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])
}
}
}
+21 -3
View File
@@ -139,7 +139,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 +152,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 +227,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 +240,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 +329,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 +343,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')
`
}
+6
View File
@@ -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")
}
+46
View File
@@ -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
View File
@@ -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
}
+147
View File
@@ -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
View File
@@ -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)
+41
View File
@@ -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())
}
}
+27 -1
View File
@@ -6,6 +6,7 @@ import (
"context"
stderrors "errors"
"fmt"
"os"
"strings"
"sync"
"time"
@@ -53,11 +54,23 @@ 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()
}
// 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 +134,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")
}
})