mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-05 07:25:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
916e2b0aa5 | ||
|
|
30ebfaae3e | ||
|
|
3a7ffab4d5 | ||
|
|
22f2a8dfb9 | ||
|
|
4870f243fc | ||
|
|
fac30f59e6 | ||
|
|
775ed8a4aa | ||
|
|
e6d8ed0f2e | ||
|
|
40ed8f8213 | ||
|
|
ecf750adbb | ||
|
|
41f8369c43 | ||
|
|
d6044cdd2e |
@@ -110,6 +110,9 @@ security:
|
||||
block_on_severity: "high" # none, low, medium, high, critical
|
||||
scan_on_download: true # Scan packages on first download
|
||||
rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly)
|
||||
rescan_active_window: "0s" # Rescan only packages requested within this window (e.g., 720h); 0 = all packages
|
||||
rescan_on_access: false # Rescan a cached package on download when its scan is older than rescan_interval, before serving it
|
||||
rescan_concurrency: 1 # Scans run in parallel during one rescan cycle; values below 1 mean 1
|
||||
# When a scan fails on infrastructure (timeout, upstream 5xx) the package is served and the
|
||||
# scan is retried every scan_retry_interval. Set fail_closed to refuse such packages instead.
|
||||
fail_closed: false
|
||||
|
||||
@@ -32,6 +32,10 @@ data:
|
||||
severity_threshold: medium
|
||||
block_on_vulnerability: false
|
||||
rescan_interval: 24h
|
||||
rescan_active_window: 0s
|
||||
rescan_concurrency: 1
|
||||
rescan_on_access: false
|
||||
scan_wait_timeout: 30s
|
||||
|
||||
handlers:
|
||||
npm:
|
||||
|
||||
@@ -89,6 +89,10 @@ data:
|
||||
block_on_severity: {{ .Values.security.blockOnSeverity | quote }}
|
||||
scan_on_download: {{ .Values.security.scanOnDownload }}
|
||||
rescan_interval: {{ .Values.security.rescanInterval | quote }}
|
||||
rescan_active_window: {{ .Values.security.rescanActiveWindow | quote }}
|
||||
rescan_concurrency: {{ .Values.security.rescanConcurrency }}
|
||||
rescan_on_access: {{ .Values.security.rescanOnAccess }}
|
||||
scan_wait_timeout: {{ .Values.security.scanWaitTimeout | quote }}
|
||||
update_db_on_startup: {{ .Values.security.updateDbOnStartup }}
|
||||
block_thresholds:
|
||||
critical: {{ .Values.security.blockThresholds.critical }}
|
||||
|
||||
@@ -395,6 +395,10 @@ security:
|
||||
blockOnSeverity: "high" # none, low, medium, high, critical
|
||||
scanOnDownload: true
|
||||
rescanInterval: "24h"
|
||||
rescanActiveWindow: "0s" # rescan only packages requested within this window; 0 = all
|
||||
rescanConcurrency: 1 # scans run in parallel per rescan cycle
|
||||
rescanOnAccess: false # rescan a stale cache hit before serving it
|
||||
scanWaitTimeout: "30s" # how long a first download waits for its scan
|
||||
updateDbOnStartup: false
|
||||
|
||||
blockThresholds:
|
||||
|
||||
@@ -30,6 +30,9 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| GH-23 | PyPI sidecar | pip's PEP 658 request (`<link>.metadata`, suffix on `original_url`) is served as its wheel's sidecar; another file's sidecar is still refused | correctness (pip install failed with 400) | medium (every pip install through the proxy) | `Access.pip_form_keeps_key_binding`, `pip_sidecar_of_other_file_rejected`, `pip_sidecar_of_same_file_accepted` / `TestPipSidecarFormIsStreamed`, `TestHandlePackageFile_OriginalURLFilenameBound` | 501bf1a |
|
||||
| GH-24 | rescan | with `security.rescan_interval` set, artifacts whose scan never completed are scanned and old results refreshed | correctness (scans lost to a restart stayed unscanned; new CVEs never picked up) | medium | not modelled (worker wiring) / `TestWorkersStartTheRescanWorker` | 378b873 |
|
||||
| GH-25 | scanners | an error result from one scanner is left out of the merge, so the row reads error only when every scanner failed; grype, npm-audit, govulncheck and pip-audit give correct results with the scanner image tool versions | correctness (false error, false clean) | high (grype, npm-audit and pip-audit failed on every package; govulncheck and a bare-archive grype scan read vulnerable packages clean) | `Security.old_error_poisons_clean`, `error_and_clean_reads_clean`, `all_error_reads_error`, `merged_not_error_when_one_ran` / `TestScanPackage_ErrorResultPlusCleanReadsClean`, `TestScanPackage_AllErrorResultsReadError`, `TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure`, `TestScanMapsRealOutput`, `TestParseKeepsBothViaShapes`, `TestScanReadsPrettyPrintedFindings`, `TestScanAuditsTheReleaseFromARequirement` | 3731ca0 |
|
||||
| GH-26 | rescan | the rescan worker skips the entries the serve path skips, so Go `.mod` and `.info` rows are no longer scanned | cost (1316 of about 2780 rescans on production were these rows, about 3.3 s each) | low | `Cache.old_rescan_scanned_go_metadata`, `rescan_skips_what_serve_skips` / `TestRescanSkipsMetadataEntries` | d6044cd |
|
||||
| GH-27 | scanners | govulncheck counts findings in the scanned module only; dependency findings (minimum versions from its go.mod) and stdlib findings (the scanner toolchain) no longer attach to it | correctness (false vulnerable, and a false block when a dependency finding is critical) | medium (golang.org/x/net v0.56.0 carried x/crypto and x/text advisories on production) | `TestScanIgnoresFindingsInDependencies`, `TestScanReadsPrettyPrintedFindings` | 775ed8a |
|
||||
| GH-28 | scanners | OSV takes the fixed version from the range of the queried package | display (x/net findings showed the stdlib fix 1.26.9 instead of 0.60.0) | low | `TestScan_FixedVersionComesFromTheQueriedPackage` | fac30f5 |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
@@ -84,6 +87,11 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
as clean the same way grype did.
|
||||
- **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.
|
||||
- **GH-26.** `rescanPackages` kept its own list of metadata versions and never called `IsMetadataEntry`, so Go `.mod` and `.info`
|
||||
rows were scanned every cycle. Related options, whose defaults keep the old behaviour: `rescan_active_window` skips packages idle longer than the
|
||||
window, `rescan_concurrency` runs scans in parallel, and `rescan_on_access` rescans a stale cache hit before serving it.
|
||||
Model of the last: `Security.finished_rescan_verdict_younger_than_interval`, `old_verdict_only_on_timeout`,
|
||||
`stale_clean_fresh_vulnerable_blocked`, `timeout_keeps_previous`, `timeout_without_previous_is_miss_rule`, `off_is_old_hit_path`.
|
||||
|
||||
## Not fixed
|
||||
|
||||
|
||||
@@ -208,4 +208,16 @@ theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decid
|
||||
|
||||
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
|
||||
|
||||
/-- `pkg/scanner/rescanner.go` before the fix: the worker skipped only the version names, not the Go suffixes. -/
|
||||
def rescanSkipOld (version : String) : Bool := decide (version ∈ metaVersions)
|
||||
|
||||
/-- After the fix the worker asks `IsMetadataEntry`, the same predicate as the serve path. -/
|
||||
def rescanSkip : String → Bool → String → Bool := scanExempt
|
||||
|
||||
theorem old_rescan_scanned_go_metadata :
|
||||
rescanSkipOld "v1.0.0" = false ∧ scanExempt "go" true "v1.0.0" = true := by decide
|
||||
|
||||
theorem rescan_skips_what_serve_skips (registry : String) (suffixMeta : Bool) (version : String) :
|
||||
rescanSkip registry suffixMeta version = scanExempt registry suffixMeta version := rfl
|
||||
|
||||
end Gohoarder.Cache
|
||||
|
||||
@@ -271,4 +271,90 @@ theorem one_package_failure_is_not_infra : infraOnly [true, false] = false := by
|
||||
|
||||
theorem all_infra_failures_are_infra : infraOnly [true, true] = true := by decide
|
||||
|
||||
/-! ### Rescan on access (`pkg/cache/rescan_on_access.go` `refreshStaleScan`)
|
||||
|
||||
Ages are seconds since `ScannedAt`; `interval` is `Config.RescanAfter` (0 = off). A rescan that timed out
|
||||
or failed is `none`: the previous verdict stands, and with no previous verdict the first-download rule applies. -/
|
||||
|
||||
structure Verdict where
|
||||
scan : Scan
|
||||
age : ℕ
|
||||
|
||||
/-- The hit is rescanned when the feature is on and its result is missing or at least `interval` old. -/
|
||||
def rescans (interval : ℕ) (prev : Option Verdict) : Bool :=
|
||||
decide (0 < interval) && (match prev with
|
||||
| none => true
|
||||
| some v => decide (interval ≤ v.age))
|
||||
|
||||
/-- The verdict the gate decides on; a finished rescan is brand new (age 0). -/
|
||||
def hitVerdict (interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Option Verdict :=
|
||||
if rescans interval prev then
|
||||
(match rescan with
|
||||
| some s => some ⟨s, 0⟩
|
||||
| none => prev)
|
||||
else prev
|
||||
|
||||
/-- No verdict at all is a scan still in flight: `fail_closed` refuses, otherwise the package is served. -/
|
||||
def servesOnAccess (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass)
|
||||
(interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Bool :=
|
||||
match hitVerdict interval prev rescan with
|
||||
| some v => serves failClosed pkgBypass policy now bs v.scan
|
||||
| none => serves failClosed pkgBypass policy now bs (Scan.missing true)
|
||||
|
||||
/-- Key property: with the feature on, a rescan that finished leaves no verdict as old as `interval`. -/
|
||||
theorem finished_rescan_verdict_younger_than_interval (interval : ℕ) (hi : 0 < interval)
|
||||
(prev : Option Verdict) (s : Scan) (v : Verdict)
|
||||
(h : hitVerdict interval prev (some s) = some v) : v.age < interval := by
|
||||
unfold hitVerdict at h
|
||||
by_cases hr : rescans interval prev = true
|
||||
· simp only [hr, ite_true, Option.some.injEq] at h
|
||||
subst h
|
||||
simpa using hi
|
||||
· simp only [hr] at h
|
||||
subst h
|
||||
simp only [rescans, hi, decide_true, Bool.true_and, Bool.not_eq_true] at hr
|
||||
simpa using hr
|
||||
|
||||
/-- A verdict older than `interval` survives only when the rescan timed out or failed. -/
|
||||
theorem old_verdict_only_on_timeout (interval : ℕ) (hi : 0 < interval) (prev : Option Verdict)
|
||||
(rescan : Option Scan) (v : Verdict) (h : hitVerdict interval prev rescan = some v)
|
||||
(hold : interval ≤ v.age) : rescan = none := by
|
||||
cases rescan with
|
||||
| none => rfl
|
||||
| some s => exact absurd (finished_rescan_verdict_younger_than_interval interval hi prev s v h) (not_lt.mpr hold)
|
||||
|
||||
/-- A stale hit is judged on the fresh scan: a clean result that now holds a blocked vulnerability is refused. -/
|
||||
theorem stale_clean_fresh_vulnerable_blocked (policy : Option ℕ) (t : ℕ) (hp : policy = some t)
|
||||
(failClosed : Bool) (now : ℤ) (bs : List Bypass) (interval age : ℕ) (hi : 0 < interval)
|
||||
(hage : interval ≤ age) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
|
||||
(hun : v.id ∉ bypassedIds now bs) :
|
||||
servesOnAccess failClosed false policy now bs interval (some ⟨Scan.ok [], age⟩) (some (Scan.ok vs)) = false := by
|
||||
have hr : rescans interval (some ⟨Scan.ok [], age⟩) = true := by simp [rescans, hi, hage]
|
||||
simp only [servesOnAccess, hitVerdict, hr, ite_true]
|
||||
exact vulnerable_not_served policy t hp failClosed now bs vs v hv hsev hun
|
||||
|
||||
/-- A fresh result is served as is: no rescan, whatever the rescan outcome. -/
|
||||
theorem fresh_hit_not_rescanned (interval : ℕ) (v : Verdict) (hfresh : v.age < interval)
|
||||
(rescan : Option Scan) : hitVerdict interval (some v) rescan = some v := by
|
||||
have : rescans interval (some v) = false := by simp [rescans, not_le.mpr hfresh]
|
||||
simp [hitVerdict, this]
|
||||
|
||||
/-- A timeout keeps the previous verdict. -/
|
||||
theorem timeout_keeps_previous (interval : ℕ) (prev : Option Verdict) :
|
||||
hitVerdict interval prev none = prev := by
|
||||
unfold hitVerdict
|
||||
split <;> rfl
|
||||
|
||||
/-- A timeout with no previous verdict follows the first-download rule. -/
|
||||
theorem timeout_without_previous_is_miss_rule (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
|
||||
(bs : List Bypass) (interval : ℕ) :
|
||||
servesOnAccess failClosed pkgBypass policy now bs interval none none = (pkgBypass || !failClosed) := by
|
||||
simp only [servesOnAccess, timeout_keeps_previous]
|
||||
cases failClosed <;> cases pkgBypass <;> simp [serves]
|
||||
|
||||
/-- `rescan_on_access` off (`RescanAfter` 0) is the old hit path: the stored verdict decides. -/
|
||||
theorem off_is_old_hit_path (prev : Option Verdict) (rescan : Option Scan) :
|
||||
hitVerdict 0 prev rescan = prev := by
|
||||
simp [hitVerdict, rescans]
|
||||
|
||||
end Gohoarder.Security
|
||||
|
||||
+25
-7
@@ -60,6 +60,7 @@ type App struct {
|
||||
analyticsEngine *analytics.Engine
|
||||
wsServer *websocket.Server
|
||||
prewarmWorker *prewarming.Worker
|
||||
prewarmFetcher *prewarming.ProxyFetcher
|
||||
cdnMiddleware *cdn.Middleware
|
||||
}
|
||||
|
||||
@@ -234,7 +235,12 @@ func (a *App) initializeComponents() error {
|
||||
if cleanupInterval == 0 {
|
||||
cleanupInterval = 5 * time.Minute
|
||||
}
|
||||
var rescanAfter time.Duration
|
||||
if a.config.Security.RescanOnAccess {
|
||||
rescanAfter = a.config.Security.RescanInterval
|
||||
}
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
RescanAfter: rescanAfter,
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
@@ -320,7 +326,10 @@ func (a *App) initializeComponents() error {
|
||||
// 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.config.Security.RescanInterval)
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
|
||||
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
|
||||
scanner.WithConcurrency(a.config.Security.RescanConcurrency),
|
||||
)
|
||||
}
|
||||
|
||||
// Initialize WebSocket server
|
||||
@@ -340,14 +349,14 @@ func (a *App) initializeComponents() error {
|
||||
// Initialize pre-warming worker. Operator-controlled via cfg.Prewarming;
|
||||
// defaults are baked into config.Default() so unset fields stay sane.
|
||||
log.Info().Msg("Initializing pre-warming worker")
|
||||
a.prewarmFetcher = prewarming.NewProxyFetcher()
|
||||
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{
|
||||
Enabled: a.config.Prewarming.Enabled,
|
||||
Interval: a.config.Prewarming.Interval,
|
||||
MaxConcurrent: a.config.Prewarming.MaxConcurrent,
|
||||
TopPackages: a.config.Prewarming.TopPackages,
|
||||
CacheManager: a.cache,
|
||||
Analytics: a.analyticsEngine,
|
||||
NetworkClient: a.networkClient,
|
||||
Popularity: a.analyticsEngine,
|
||||
Fetcher: a.prewarmFetcher,
|
||||
})
|
||||
|
||||
// Initialize CDN middleware
|
||||
@@ -528,7 +537,9 @@ func (a *App) setupServer() error {
|
||||
SumDBURL: sumDB,
|
||||
CredStore: credStore,
|
||||
})
|
||||
goProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/go", goProxyHandler))
|
||||
goProxyMounted := http.StripPrefix("/go", goProxyHandler)
|
||||
a.prewarmFetcher.Mount("go", goProxyMounted)
|
||||
goProxyWithCDN := a.cdnMiddleware.Handler(goProxyMounted)
|
||||
if authEnabled {
|
||||
a.app.All("/go/*", mwAuth, adaptor.HTTPHandler(goProxyWithCDN))
|
||||
} else {
|
||||
@@ -544,7 +555,9 @@ func (a *App) setupServer() error {
|
||||
npmProxyHandler := npm.New(a.cache, a.networkClient, npm.Config{
|
||||
Upstream: npmUpstream,
|
||||
})
|
||||
npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler))
|
||||
npmProxyMounted := http.StripPrefix("/npm", npmProxyHandler)
|
||||
a.prewarmFetcher.Mount("npm", npmProxyMounted)
|
||||
npmProxyWithCDN := a.cdnMiddleware.Handler(npmProxyMounted)
|
||||
a.app.Use("/npm", func(c fiber.Ctx) error {
|
||||
if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() {
|
||||
c.Path(canonical)
|
||||
@@ -566,7 +579,9 @@ func (a *App) setupServer() error {
|
||||
pypiProxyHandler := pypi.New(a.cache, a.networkClient, pypi.Config{
|
||||
Upstream: pypiUpstream,
|
||||
})
|
||||
pypiProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/pypi", pypiProxyHandler))
|
||||
pypiProxyMounted := http.StripPrefix("/pypi", pypiProxyHandler)
|
||||
a.prewarmFetcher.Mount("pypi", pypiProxyMounted)
|
||||
pypiProxyWithCDN := a.cdnMiddleware.Handler(pypiProxyMounted)
|
||||
if authEnabled {
|
||||
a.app.All("/pypi/*", mwAuth, adaptor.HTTPHandler(pypiProxyWithCDN))
|
||||
} else {
|
||||
@@ -623,6 +638,9 @@ func (a *App) startWorkers(ctx context.Context) {
|
||||
if a.rescanWorker != nil {
|
||||
go a.rescanWorker.Start(ctx)
|
||||
}
|
||||
|
||||
// Start is a no-op unless prewarming.enabled is set.
|
||||
a.prewarmWorker.Start(ctx)
|
||||
}
|
||||
|
||||
func (a *App) Run() error {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -316,3 +317,35 @@ func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
|
||||
}
|
||||
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
|
||||
}
|
||||
|
||||
// The mount already strips the registry prefix, so a package named after the registry must keep its name.
|
||||
func TestPackagesNamedAfterTheRegistryKeepTheirName(t *testing.T) {
|
||||
var npmSeen, pypiSeen []string
|
||||
npmUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
npmSeen = append(npmSeen, r.URL.Path)
|
||||
_, _ = w.Write([]byte(`{"name":"x","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(npmUp.Close)
|
||||
pypiUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
pypiSeen = append(pypiSeen, r.URL.Path)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte(`<html><body></body></html>`))
|
||||
}))
|
||||
t.Cleanup(pypiUp.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = npmUp.URL
|
||||
c.Handlers.PyPI.SimpleAPIURL = pypiUp.URL + "/simple"
|
||||
})
|
||||
for _, target := range []string{"/npm/npm-run-all", "/npm/npm", "/pypi/simple/pypi-a/", "/pypi/pypi-b/"} {
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s: status = %d, body %q", target, code, body)
|
||||
}
|
||||
}
|
||||
if want := []string{"/npm-run-all", "/npm"}; !slices.Equal(npmSeen, want) {
|
||||
t.Errorf("npm upstream paths = %v, want %v", npmSeen, want)
|
||||
}
|
||||
if want := []string{"/simple/pypi-a/", "/simple/pypi-b/"}; !slices.Equal(pypiSeen, want) {
|
||||
t.Errorf("pypi upstream paths = %v, want %v", pypiSeen, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,10 @@ import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/prewarming"
|
||||
)
|
||||
|
||||
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
|
||||
@@ -36,3 +40,45 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
|
||||
}
|
||||
}
|
||||
|
||||
type recordingFetcher struct{ got chan prewarming.PackageInfo }
|
||||
|
||||
func (f recordingFetcher) Fetch(_ context.Context, pkg prewarming.PackageInfo) error {
|
||||
f.got <- pkg
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixedPopularity struct{}
|
||||
|
||||
func (fixedPopularity) GetTopPackages(int) []analytics.PopularPackage {
|
||||
return []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}}
|
||||
}
|
||||
|
||||
func (fixedPopularity) GetTrendingPackages(int) []analytics.PopularPackage { return nil }
|
||||
|
||||
// TestEnabledPrewarmWorkerStartsWithTheApp pins that startWorkers starts the pre-warm loop.
|
||||
func TestEnabledPrewarmWorkerStartsWithTheApp(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
f := recordingFetcher{got: make(chan prewarming.PackageInfo, 4)}
|
||||
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{Enabled: true, Fetcher: f, Popularity: fixedPopularity{}})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
defer a.prewarmWorker.Stop()
|
||||
|
||||
select {
|
||||
case pkg := <-f.got:
|
||||
if pkg.Name != "lodash" {
|
||||
t.Fatalf("pre-warmed %q, want lodash", pkg.Name)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("pre-warm worker never ran after startWorkers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrewarmingStaysOffByDefault(t *testing.T) {
|
||||
if config.Default().Prewarming.Enabled {
|
||||
t.Fatal("prewarming.enabled must default to false")
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+5
@@ -47,6 +47,7 @@ type Manager struct {
|
||||
bgCtx context.Context // cancelled by Close; parent of background scans
|
||||
bgCancel context.CancelFunc
|
||||
sf singleflight.Group
|
||||
rescanSF singleflight.Group
|
||||
config Config
|
||||
cleanupWG sync.WaitGroup
|
||||
bcMu sync.RWMutex
|
||||
@@ -91,6 +92,7 @@ type Config struct {
|
||||
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
|
||||
RescanAfter time.Duration // Rescan a cache hit whose scan result is older than this before serving (0 = off)
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
@@ -332,6 +334,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
// the extra database round-trip.
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
if m.scanner != nil && !isMetadataEntry {
|
||||
if rescanErr := m.refreshStaleScan(ctx, registry, name, version); rescanErr != nil {
|
||||
return nil, rescanErr
|
||||
}
|
||||
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
|
||||
if vulnErr != nil {
|
||||
log.Warn().Err(vulnErr).Str("package", name).Msg("Failed to check vulnerabilities")
|
||||
|
||||
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// refreshStaleScan rescans a cache hit whose scan result is missing or older than
|
||||
// Config.RescanAfter, so the verdict served is never older than that interval. It
|
||||
// waits up to ScanWaitTimeout; on a timeout or scan failure the previous verdict
|
||||
// stands, or the miss-path rule applies when there is none.
|
||||
func (m *Manager) refreshStaleScan(ctx context.Context, registry, name, version string) error {
|
||||
if m.config.RescanAfter <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
prev, err := m.metadata.GetScanResult(ctx, registry, name, version)
|
||||
hasPrev := err == nil && prev != nil
|
||||
if hasPrev && m.now().Sub(prev.ScannedAt) < m.config.RescanAfter {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("%s/%s/%s", registry, name, version)
|
||||
done := m.rescanSF.DoChan(key, func() (interface{}, error) {
|
||||
return nil, m.rescanArtifact(registry, name, version)
|
||||
})
|
||||
|
||||
timer := time.NewTimer(m.config.ScanWaitTimeout)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case res := <-done:
|
||||
if res.Err == nil {
|
||||
return nil
|
||||
}
|
||||
log.Warn().Err(res.Err).Str("package", name).Str("version", version).Msg("Rescan on access failed")
|
||||
case <-timer.C:
|
||||
log.Warn().Str("package", name).Str("version", version).Msg("Rescan on access timed out, scan continues in background")
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if hasPrev {
|
||||
log.Warn().Str("package", name).Str("version", version).Time("scanned_at", prev.ScannedAt).
|
||||
Msg("Serving decision uses the previous scan result")
|
||||
return nil
|
||||
}
|
||||
if m.config.FailClosed {
|
||||
log.Warn().Str("package", name).Str("version", version).
|
||||
Msg("No scan result and rescan unfinished - refusing to serve (fail-closed)")
|
||||
return errors.New(errors.ErrCodeServiceUnavailable, "package scan in progress, retry shortly")
|
||||
}
|
||||
log.Warn().Str("package", name).Str("version", version).
|
||||
Msg("No scan result and rescan unfinished - serving package, scan continues in background")
|
||||
return nil
|
||||
}
|
||||
|
||||
// rescanArtifact scans the cached artifact under the manager's background context so a
|
||||
// client disconnect does not abort it.
|
||||
func (m *Manager) rescanArtifact(registry, name, version string) error {
|
||||
path, cleanup, err := m.ScanFile(m.bgCtx, registry, name, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
return m.scanner.ScanPackage(m.bgCtx, registry, name, version, path)
|
||||
}
|
||||
Vendored
+176
@@ -0,0 +1,176 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const rescanInterval = 24 * time.Hour
|
||||
|
||||
// rescanScanner blocks a scan until release closes and blocks the package once scanned.
|
||||
type rescanScanner struct {
|
||||
release chan struct{}
|
||||
scanCtx atomic.Pointer[context.Context]
|
||||
scans atomic.Int32
|
||||
blockOnScan atomic.Bool
|
||||
}
|
||||
|
||||
func (s *rescanScanner) ScanPackage(ctx context.Context, _, _, _, _ string) error {
|
||||
s.scans.Add(1)
|
||||
s.scanCtx.Store(&ctx)
|
||||
if s.release != nil {
|
||||
<-s.release
|
||||
}
|
||||
s.blockOnScan.Store(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *rescanScanner) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
|
||||
if s.scans.Load() > 0 && s.release == nil {
|
||||
return s.blockOnScan.Load(), "critical vulnerability", nil
|
||||
}
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
func newHitManager(t *testing.T, sc ScannerInterface, cfg Config, registry, name, version string, prev *metadata.ScanResult) (*Manager, *MockMetadataStore) {
|
||||
t.Helper()
|
||||
st := &MockStorageBackend{}
|
||||
md := &MockMetadataStore{}
|
||||
key := registry + "/" + name + "/" + version
|
||||
|
||||
md.On("GetPackage", mock.Anything, registry, name, version).
|
||||
Return(&metadata.Package{Registry: registry, Name: name, Version: version, StorageKey: key}, nil)
|
||||
st.On("Get", mock.Anything, key).Return(io.NopCloser(strings.NewReader("data")), nil)
|
||||
md.On("UpdateDownloadCount", mock.Anything, registry, name, version).Return(nil)
|
||||
if prev == nil {
|
||||
md.On("GetScanResult", mock.Anything, registry, name, version).Return(nil, hoardererrors.NotFound("none")).Maybe()
|
||||
} else {
|
||||
md.On("GetScanResult", mock.Anything, registry, name, version).Return(prev, nil).Maybe()
|
||||
}
|
||||
st.On("Close").Return(nil)
|
||||
md.On("Close").Return(nil)
|
||||
|
||||
m, err := New(st, md, sc, nil, cfg)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = m.Close() })
|
||||
return m, md
|
||||
}
|
||||
|
||||
func scanAged(age time.Duration) *metadata.ScanResult {
|
||||
return &metadata.ScanResult{ScannedAt: time.Now().Add(-age), Status: metadata.ScanStatusClean}
|
||||
}
|
||||
|
||||
func errorCode(err error) string {
|
||||
var appErr *hoardererrors.Error
|
||||
if errors.As(err, &appErr) {
|
||||
return appErr.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestGetHit_RescanOnAccess(t *testing.T) {
|
||||
tests := []struct {
|
||||
prev *metadata.ScanResult
|
||||
name string
|
||||
wantCode string
|
||||
rescan time.Duration
|
||||
wantScans int32
|
||||
hang bool
|
||||
failClose bool
|
||||
}{
|
||||
{name: "stale clean result, fresh scan finds critical: blocked before serve", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, wantCode: hoardererrors.ErrCodeSecurityViolation},
|
||||
{name: "missing result is scanned before serving", prev: nil, rescan: rescanInterval, wantScans: 1, wantCode: hoardererrors.ErrCodeSecurityViolation},
|
||||
{name: "fresh result is not rescanned", prev: scanAged(time.Hour), rescan: rescanInterval, wantScans: 0},
|
||||
{name: "rescan_on_access off keeps the old hit path", prev: scanAged(48 * time.Hour), rescan: 0, wantScans: 0},
|
||||
{name: "timeout with previous result serves", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, hang: true},
|
||||
{name: "timeout with previous result serves under fail-closed", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, hang: true, failClose: true},
|
||||
{name: "timeout without result serves when fail-open", prev: nil, rescan: rescanInterval, wantScans: 1, hang: true},
|
||||
{name: "timeout without result is 503 when fail-closed", prev: nil, rescan: rescanInterval, wantScans: 1, hang: true, failClose: true, wantCode: hoardererrors.ErrCodeServiceUnavailable},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
sc := &rescanScanner{}
|
||||
if tt.hang {
|
||||
sc.release = make(chan struct{})
|
||||
t.Cleanup(func() { close(sc.release) })
|
||||
}
|
||||
m, _ := newHitManager(t, sc, Config{RescanAfter: tt.rescan, ScanWaitTimeout: 150 * time.Millisecond, FailClosed: tt.failClose},
|
||||
"npm", "lodash", "4.17.21", tt.prev)
|
||||
|
||||
entry, err := m.Get(context.Background(), "npm", "lodash", "4.17.21", nil)
|
||||
|
||||
if tt.wantCode != "" {
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, tt.wantCode, errorCode(err))
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
_ = entry.Data.Close()
|
||||
}
|
||||
assert.Equal(t, tt.wantScans, sc.scans.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHit_RescanOffDoesNotReadScanResult(t *testing.T) {
|
||||
sc := &rescanScanner{}
|
||||
m, md := newHitManager(t, sc, Config{}, "npm", "lodash", "4.17.21", scanAged(48*time.Hour))
|
||||
entry, err := m.Get(context.Background(), "npm", "lodash", "4.17.21", nil)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
md.AssertNotCalled(t, "GetScanResult", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
}
|
||||
|
||||
func TestGetHit_RescanSkipsGoMetadataRows(t *testing.T) {
|
||||
sc := &rescanScanner{}
|
||||
m, _ := newHitManager(t, sc, Config{RescanAfter: rescanInterval}, "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", nil)
|
||||
entry, err := m.Get(context.Background(), "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", nil)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
assert.Zero(t, sc.scans.Load())
|
||||
}
|
||||
|
||||
// Concurrent stale hits share one scan, and a client that disconnects does not cancel it.
|
||||
func TestRefreshStaleScan_SingleflightAndBackgroundContext(t *testing.T) {
|
||||
sc := &rescanScanner{release: make(chan struct{})}
|
||||
m, _ := newHitManager(t, sc, Config{RescanAfter: rescanInterval, ScanWaitTimeout: 5 * time.Second},
|
||||
"npm", "lodash", "4.17.21", scanAged(48*time.Hour))
|
||||
|
||||
const callers = 5
|
||||
ctx, cancelClient := context.WithCancel(context.Background())
|
||||
errs := make(chan error, callers)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < callers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
errs <- m.refreshStaleScan(ctx, "npm", "lodash", "4.17.21")
|
||||
}()
|
||||
}
|
||||
|
||||
require.Eventually(t, func() bool { return sc.scans.Load() >= 1 }, 2*time.Second, 5*time.Millisecond)
|
||||
cancelClient()
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
scanCtx := sc.scanCtx.Load()
|
||||
require.NotNil(t, scanCtx)
|
||||
assert.NoError(t, (*scanCtx).Err(), "scan must outlive the client request")
|
||||
close(sc.release)
|
||||
assert.Equal(t, int32(1), sc.scans.Load(), "concurrent hits must share one scan")
|
||||
}
|
||||
+15
-12
@@ -174,18 +174,21 @@ type CacheConfig struct {
|
||||
|
||||
// SecurityConfig contains security scanning configuration
|
||||
type SecurityConfig struct {
|
||||
BlockOnSeverity string `mapstructure:"block_on_severity" json:"block_on_severity"`
|
||||
AllowedPackages []string `mapstructure:"allowed_packages" json:"allowed_packages"`
|
||||
IgnoredCVEs []string `mapstructure:"ignored_cves" json:"ignored_cves"`
|
||||
Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"`
|
||||
BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"`
|
||||
RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"`
|
||||
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
|
||||
ScanWaitTimeout time.Duration `mapstructure:"scan_wait_timeout" json:"scan_wait_timeout"` // how long a first download waits for its scan; 0 = 30s
|
||||
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
|
||||
UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"`
|
||||
BlockOnSeverity string `mapstructure:"block_on_severity" json:"block_on_severity"`
|
||||
AllowedPackages []string `mapstructure:"allowed_packages" json:"allowed_packages"`
|
||||
IgnoredCVEs []string `mapstructure:"ignored_cves" json:"ignored_cves"`
|
||||
Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"`
|
||||
BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"`
|
||||
RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"`
|
||||
RescanActiveWindow time.Duration `mapstructure:"rescan_active_window" json:"rescan_active_window"` // rescan only packages accessed within this window; 0 = all
|
||||
RescanConcurrency int `mapstructure:"rescan_concurrency" json:"rescan_concurrency"` // scans run in parallel per rescan cycle; <1 = 1
|
||||
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
|
||||
ScanWaitTimeout time.Duration `mapstructure:"scan_wait_timeout" json:"scan_wait_timeout"` // how long a first download waits for its scan; 0 = 30s
|
||||
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
|
||||
RescanOnAccess bool `mapstructure:"rescan_on_access" json:"rescan_on_access"` // rescan a stale cache hit before serving it; needs rescan_interval
|
||||
UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"`
|
||||
}
|
||||
|
||||
// VulnerabilityThresholds defines max allowed vulnerabilities per severity
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package prewarming
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/proxy/pypi"
|
||||
)
|
||||
|
||||
const (
|
||||
registryNPM = "npm"
|
||||
registryPyPI = "pypi"
|
||||
registryGo = "go"
|
||||
|
||||
// proxyHost is only a placeholder: the handlers are called in-process and never dial it.
|
||||
proxyHost = "gohoarder.invalid"
|
||||
maxMetadataBytes = 64 << 20
|
||||
)
|
||||
|
||||
var (
|
||||
hrefPattern = regexp.MustCompile(`href="([^"]+)"`)
|
||||
numericSemVer = regexp.MustCompile(`^\d+(\.\d+)*$`)
|
||||
distSuffixes = []string{".whl", ".tar.gz", ".zip", ".egg"}
|
||||
)
|
||||
|
||||
// ProxyFetcher pre-warms through the registry handlers in-process, so artifacts are cached,
|
||||
// scanned and policy-checked exactly like a client request.
|
||||
type ProxyFetcher struct {
|
||||
handlers map[string]http.Handler
|
||||
}
|
||||
|
||||
// NewProxyFetcher returns a fetcher with no registries mounted.
|
||||
func NewProxyFetcher() *ProxyFetcher {
|
||||
return &ProxyFetcher{handlers: make(map[string]http.Handler)}
|
||||
}
|
||||
|
||||
// Mount registers the handler serving a registry; it must already strip the "/<registry>" prefix
|
||||
// the way the HTTP server mounts it. Mount before the worker starts.
|
||||
func (f *ProxyFetcher) Mount(registry string, h http.Handler) {
|
||||
f.handlers[registry] = h
|
||||
}
|
||||
|
||||
// Fetch resolves the version when it is empty or LatestVersion, then downloads the artifact.
|
||||
func (f *ProxyFetcher) Fetch(ctx context.Context, pkg PackageInfo) error {
|
||||
h, ok := f.handlers[pkg.Registry]
|
||||
if !ok {
|
||||
return fmt.Errorf("registry %q is not mounted", pkg.Registry)
|
||||
}
|
||||
if !safeName(pkg.Name) {
|
||||
return fmt.Errorf("unsafe package name %q", pkg.Name)
|
||||
}
|
||||
latest := pkg.Version == "" || pkg.Version == LatestVersion
|
||||
switch pkg.Registry {
|
||||
case registryNPM:
|
||||
return f.fetchNPM(ctx, h, pkg.Name, pkg.Version, latest)
|
||||
case registryGo:
|
||||
return f.fetchGo(ctx, h, pkg.Name, pkg.Version, latest)
|
||||
case registryPyPI:
|
||||
return f.fetchPyPI(ctx, h, pkg.Name, pkg.Version, latest)
|
||||
default:
|
||||
return fmt.Errorf("unsupported registry %q", pkg.Registry)
|
||||
}
|
||||
}
|
||||
|
||||
func safeName(name string) bool {
|
||||
return name != "" && !strings.ContainsAny(name, "?#\\") && !strings.Contains(name, "..") && !strings.HasPrefix(name, "/")
|
||||
}
|
||||
|
||||
func (f *ProxyFetcher) fetchNPM(ctx context.Context, h http.Handler, name, version string, latest bool) error {
|
||||
if latest {
|
||||
body, err := call(ctx, h, "/npm/"+name, "", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("npm metadata: %w", err)
|
||||
}
|
||||
var meta struct {
|
||||
DistTags map[string]string `json:"dist-tags"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &meta); err != nil {
|
||||
return fmt.Errorf("npm metadata: %w", err)
|
||||
}
|
||||
if version = meta.DistTags["latest"]; version == "" {
|
||||
return fmt.Errorf("npm %s has no latest dist-tag", name)
|
||||
}
|
||||
}
|
||||
bare := name[strings.LastIndex(name, "/")+1:]
|
||||
_, err := call(ctx, h, "/npm/"+name+"/-/"+bare+"-"+version+".tgz", "", false)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *ProxyFetcher) fetchGo(ctx context.Context, h http.Handler, name, version string, latest bool) error {
|
||||
if latest {
|
||||
body, err := call(ctx, h, "/go/"+name+"/@latest", "", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("go latest: %w", err)
|
||||
}
|
||||
var info struct{ Version string }
|
||||
if err := json.Unmarshal(body, &info); err != nil {
|
||||
return fmt.Errorf("go latest: %w", err)
|
||||
}
|
||||
if version = info.Version; version == "" {
|
||||
return fmt.Errorf("go %s has no latest version", name)
|
||||
}
|
||||
}
|
||||
_, err := call(ctx, h, "/go/"+name+"/@v/"+version+".zip", "", false)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *ProxyFetcher) fetchPyPI(ctx context.Context, h http.Handler, name, version string, latest bool) error {
|
||||
page, err := call(ctx, h, "/pypi/simple/"+name+"/", "text/html", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("pypi package page: %w", err)
|
||||
}
|
||||
link, err := pickPyPIFile(page, version, latest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("pypi %s: %w", name, err)
|
||||
}
|
||||
if !strings.HasPrefix(link.Path, "/pypi/") {
|
||||
return fmt.Errorf("pypi %s: link %q is not a proxy path", name, link.Path)
|
||||
}
|
||||
_, err = call(ctx, h, link.Path, "", false, link.RawQuery)
|
||||
return err
|
||||
}
|
||||
|
||||
type distFile struct {
|
||||
link *url.URL
|
||||
version string
|
||||
}
|
||||
|
||||
// pickPyPIFile chooses one distribution: the wanted version or the highest plain release,
|
||||
// preferring a wheel over an sdist.
|
||||
func pickPyPIFile(page []byte, version string, latest bool) (*url.URL, error) {
|
||||
var wheel, sdist *distFile
|
||||
for _, m := range hrefPattern.FindAllSubmatch(page, -1) {
|
||||
u, err := url.Parse(html.UnescapeString(string(m[1])))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
file := path.Base(u.Path)
|
||||
if !hasDistSuffix(file) {
|
||||
continue
|
||||
}
|
||||
cand := &distFile{link: u, version: pypi.ReleaseVersion(file)}
|
||||
if latest {
|
||||
if !numericSemVer.MatchString(cand.version) {
|
||||
continue
|
||||
}
|
||||
} else if cand.version != version {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(file, ".whl") {
|
||||
wheel = better(wheel, cand, latest)
|
||||
} else {
|
||||
sdist = better(sdist, cand, latest)
|
||||
}
|
||||
}
|
||||
for _, c := range []*distFile{wheel, sdist} {
|
||||
if c != nil {
|
||||
return c.link, nil
|
||||
}
|
||||
}
|
||||
if latest {
|
||||
return nil, fmt.Errorf("no plain release file listed")
|
||||
}
|
||||
return nil, fmt.Errorf("no file listed for version %q", version)
|
||||
}
|
||||
|
||||
func better(cur, cand *distFile, latest bool) *distFile {
|
||||
if cur == nil || (latest && compareVersions(cand.version, cur.version) > 0) {
|
||||
return cand
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
func hasDistSuffix(file string) bool {
|
||||
for _, s := range distSuffixes {
|
||||
if strings.HasSuffix(file, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func compareVersions(a, b string) int {
|
||||
as, bs := strings.Split(a, "."), strings.Split(b, ".")
|
||||
for i := 0; i < len(as) || i < len(bs); i++ {
|
||||
var x, y int
|
||||
if i < len(as) {
|
||||
x, _ = strconv.Atoi(as[i])
|
||||
}
|
||||
if i < len(bs) {
|
||||
y, _ = strconv.Atoi(bs[i])
|
||||
}
|
||||
if x != y {
|
||||
if x > y {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// call serves a GET through h. It keeps the body only when capture is set and fails on non-200.
|
||||
func call(ctx context.Context, h http.Handler, p, accept string, capture bool, rawQuery ...string) ([]byte, error) {
|
||||
u := url.URL{Scheme: "http", Host: proxyHost, Path: p}
|
||||
if len(rawQuery) > 0 {
|
||||
u.RawQuery = rawQuery[0]
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if accept != "" {
|
||||
req.Header.Set("Accept", accept)
|
||||
}
|
||||
w := &sink{header: make(http.Header), capture: capture}
|
||||
h.ServeHTTP(w, req)
|
||||
if w.status == 0 {
|
||||
w.status = http.StatusOK
|
||||
}
|
||||
if w.status != http.StatusOK {
|
||||
return nil, fmt.Errorf("GET %s: status %d", p, w.status)
|
||||
}
|
||||
if w.overflow {
|
||||
return nil, fmt.Errorf("GET %s: response over %d bytes", p, maxMetadataBytes)
|
||||
}
|
||||
return w.buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// sink is a ResponseWriter that discards artifact bytes so a pre-warm never holds one in memory.
|
||||
type sink struct {
|
||||
header http.Header
|
||||
buf bytes.Buffer
|
||||
status int
|
||||
capture bool
|
||||
overflow bool
|
||||
}
|
||||
|
||||
func (s *sink) Header() http.Header { return s.header }
|
||||
|
||||
func (s *sink) WriteHeader(code int) {
|
||||
if s.status == 0 {
|
||||
s.status = code
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sink) Write(b []byte) (int, error) {
|
||||
s.WriteHeader(http.StatusOK)
|
||||
if s.capture {
|
||||
if s.buf.Len()+len(b) > maxMetadataBytes {
|
||||
s.overflow = true
|
||||
} else {
|
||||
s.buf.Write(b)
|
||||
}
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package prewarming
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type routes struct {
|
||||
resp map[string]string
|
||||
hits []string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (r *routes) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
key := req.URL.RequestURI()
|
||||
r.mu.Lock()
|
||||
r.hits = append(r.hits, key)
|
||||
r.mu.Unlock()
|
||||
body, ok := r.resp[key]
|
||||
if !ok {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(body))
|
||||
}
|
||||
|
||||
func fetcherFor(registry string, resp map[string]string) (*ProxyFetcher, *routes) {
|
||||
rt := &routes{resp: resp}
|
||||
f := NewProxyFetcher()
|
||||
f.Mount(registry, rt)
|
||||
return f, rt
|
||||
}
|
||||
|
||||
func TestFetchNPMLatestDownloadsTheTarball(t *testing.T) {
|
||||
f, rt := fetcherFor("npm", map[string]string{
|
||||
"/npm/@scope/pkg": `{"dist-tags":{"latest":"2.1.0"}}`,
|
||||
"/npm/@scope/pkg/-/pkg-2.1.0.tgz": "tarball",
|
||||
})
|
||||
|
||||
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "@scope/pkg", Version: LatestVersion}))
|
||||
|
||||
assert.Equal(t, []string{"/npm/@scope/pkg", "/npm/@scope/pkg/-/pkg-2.1.0.tgz"}, rt.hits)
|
||||
}
|
||||
|
||||
func TestFetchNPMExplicitVersionSkipsMetadata(t *testing.T) {
|
||||
f, rt := fetcherFor("npm", map[string]string{"/npm/lodash/-/lodash-4.17.21.tgz": "x"})
|
||||
|
||||
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "lodash", Version: "4.17.21"}))
|
||||
|
||||
assert.Equal(t, []string{"/npm/lodash/-/lodash-4.17.21.tgz"}, rt.hits)
|
||||
}
|
||||
|
||||
func TestFetchGoLatestDownloadsTheZip(t *testing.T) {
|
||||
f, rt := fetcherFor("go", map[string]string{
|
||||
"/go/example.com/m/@latest": `{"Version":"v1.2.3","Time":"2026-01-01T00:00:00Z"}`,
|
||||
"/go/example.com/m/@v/v1.2.3.zip": "zip",
|
||||
})
|
||||
|
||||
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "go", Name: "example.com/m", Version: LatestVersion}))
|
||||
|
||||
assert.Equal(t, []string{"/go/example.com/m/@latest", "/go/example.com/m/@v/v1.2.3.zip"}, rt.hits)
|
||||
}
|
||||
|
||||
const pypiPage = `<html><body>
|
||||
<a href="http://h/pypi/req/req-2.9.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fa">a</a>
|
||||
<a href="http://h/pypi/req/req-2.31.0.tar.gz?original_url=https%3A%2F%2Ffiles%2Fb">b</a>
|
||||
<a href="http://h/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1">c</a>
|
||||
<a href="http://h/pypi/req/req-3.0.0rc1-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fd">d</a>
|
||||
<a href="http://h/pypi/req/req-2.31.0-py3-none-any.whl.metadata?original_url=m">m</a>
|
||||
</body></html>`
|
||||
|
||||
func TestFetchPyPILatestPicksHighestPlainReleaseWheel(t *testing.T) {
|
||||
f, rt := fetcherFor("pypi", map[string]string{
|
||||
"/pypi/simple/req/": pypiPage,
|
||||
"/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1": "whl",
|
||||
})
|
||||
|
||||
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: LatestVersion}))
|
||||
|
||||
require.Len(t, rt.hits, 2)
|
||||
assert.Equal(t, "/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1", rt.hits[1])
|
||||
}
|
||||
|
||||
func TestFetchPyPIExplicitVersionAndMissingVersion(t *testing.T) {
|
||||
f, rt := fetcherFor("pypi", map[string]string{
|
||||
"/pypi/simple/req/": pypiPage,
|
||||
"/pypi/req/req-2.9.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fa": "whl",
|
||||
})
|
||||
|
||||
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: "2.9.0"}))
|
||||
assert.Contains(t, rt.hits[1], "req-2.9.0")
|
||||
require.ErrorContains(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: "9.9.9"}), "no file listed")
|
||||
}
|
||||
|
||||
func TestFetchRejectsBadInput(t *testing.T) {
|
||||
f, rt := fetcherFor("npm", map[string]string{})
|
||||
ctx := context.Background()
|
||||
|
||||
require.ErrorContains(t, f.Fetch(ctx, PackageInfo{Registry: "cargo", Name: "x"}), "not mounted")
|
||||
for _, name := range []string{"", "../etc", "a?b", "/abs", "a#b"} {
|
||||
assert.ErrorContains(t, f.Fetch(ctx, PackageInfo{Registry: "npm", Name: name}), "unsafe package name", name)
|
||||
}
|
||||
assert.Empty(t, rt.hits)
|
||||
}
|
||||
|
||||
func TestFetchReportsUpstreamFailure(t *testing.T) {
|
||||
f, _ := fetcherFor("npm", map[string]string{})
|
||||
|
||||
err := f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "ghost", Version: LatestVersion})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "404")
|
||||
}
|
||||
|
||||
func TestSinkDiscardsArtifactBytes(t *testing.T) {
|
||||
big := strings.Repeat("a", 1<<20)
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(big)) })
|
||||
|
||||
body, err := call(context.Background(), h, "/x", "", false)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, body)
|
||||
}
|
||||
+70
-81
@@ -8,11 +8,28 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/network"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// LatestVersion asks the Fetcher to resolve the newest release itself.
|
||||
const LatestVersion = "latest"
|
||||
|
||||
const (
|
||||
fetchTimeout = 5 * time.Minute
|
||||
trendingPackages = 50
|
||||
)
|
||||
|
||||
// Fetcher pulls an artifact through the proxy path, so it is cached and scanned like a client request.
|
||||
type Fetcher interface {
|
||||
Fetch(ctx context.Context, pkg PackageInfo) error
|
||||
}
|
||||
|
||||
// Popularity ranks packages by recent demand.
|
||||
type Popularity interface {
|
||||
GetTopPackages(limit int) []analytics.PopularPackage
|
||||
GetTrendingPackages(limit int) []analytics.PopularPackage
|
||||
}
|
||||
|
||||
// PackageInfo represents a package to pre-warm
|
||||
type PackageInfo struct {
|
||||
Registry string
|
||||
@@ -23,21 +40,21 @@ type PackageInfo struct {
|
||||
|
||||
// Worker handles background pre-warming of popular packages
|
||||
type Worker struct {
|
||||
cache *cache.Manager
|
||||
analytics *analytics.Engine
|
||||
client *network.Client
|
||||
stopChan chan struct{}
|
||||
popularity Popularity
|
||||
fetcher Fetcher
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
interval time.Duration
|
||||
maxConcurrent int
|
||||
topPackages int
|
||||
enabled bool
|
||||
}
|
||||
|
||||
// Config holds pre-warming worker configuration
|
||||
type Config struct {
|
||||
CacheManager *cache.Manager
|
||||
Analytics *analytics.Engine
|
||||
NetworkClient *network.Client
|
||||
Popularity Popularity
|
||||
Fetcher Fetcher
|
||||
Interval time.Duration
|
||||
MaxConcurrent int
|
||||
TopPackages int
|
||||
@@ -57,13 +74,12 @@ func NewWorker(cfg Config) *Worker {
|
||||
}
|
||||
|
||||
worker := &Worker{
|
||||
cache: cfg.CacheManager,
|
||||
analytics: cfg.Analytics,
|
||||
client: cfg.NetworkClient,
|
||||
popularity: cfg.Popularity,
|
||||
fetcher: cfg.Fetcher,
|
||||
interval: cfg.Interval,
|
||||
maxConcurrent: cfg.MaxConcurrent,
|
||||
topPackages: cfg.TopPackages,
|
||||
enabled: cfg.Enabled,
|
||||
stopChan: make(chan struct{}),
|
||||
}
|
||||
|
||||
if cfg.Enabled {
|
||||
@@ -78,15 +94,26 @@ func NewWorker(cfg Config) *Worker {
|
||||
return worker
|
||||
}
|
||||
|
||||
// Start begins the pre-warming worker
|
||||
// Start begins the pre-warming worker; it is a no-op when disabled or already started.
|
||||
func (w *Worker) Start(ctx context.Context) {
|
||||
if !w.enabled {
|
||||
log.Debug().Msg("Pre-warming worker is disabled, not starting")
|
||||
return
|
||||
}
|
||||
if w.fetcher == nil || w.popularity == nil {
|
||||
log.Warn().Msg("Pre-warming worker has no fetcher or popularity source, not starting")
|
||||
return
|
||||
}
|
||||
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.cancel != nil {
|
||||
return
|
||||
}
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
w.cancel = cancel
|
||||
w.wg.Add(1)
|
||||
go w.run(ctx)
|
||||
go w.run(runCtx)
|
||||
log.Info().Msg("Pre-warming worker started")
|
||||
}
|
||||
|
||||
@@ -97,15 +124,11 @@ func (w *Worker) run(ctx context.Context) {
|
||||
ticker := time.NewTicker(w.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Run immediately on start
|
||||
w.prewarmPopularPackages(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Info().Msg("Pre-warming worker stopping due to context cancellation")
|
||||
return
|
||||
case <-w.stopChan:
|
||||
log.Info().Msg("Pre-warming worker stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
@@ -119,14 +142,14 @@ func (w *Worker) prewarmPopularPackages(ctx context.Context) {
|
||||
log.Info().Msg("Starting pre-warming cycle")
|
||||
|
||||
// Get popular packages from analytics
|
||||
popularPackages := w.analytics.GetTopPackages(100)
|
||||
popularPackages := w.popularity.GetTopPackages(w.topPackages)
|
||||
if len(popularPackages) == 0 {
|
||||
log.Debug().Msg("No popular packages found for pre-warming")
|
||||
return
|
||||
}
|
||||
|
||||
// Get trending packages for additional candidates
|
||||
trendingPackages := w.analytics.GetTrendingPackages(50)
|
||||
trendingPackages := w.popularity.GetTrendingPackages(trendingPackages)
|
||||
|
||||
// Combine and deduplicate
|
||||
packages := w.combinePackages(popularPackages, trendingPackages)
|
||||
@@ -141,7 +164,7 @@ func (w *Worker) prewarmPopularPackages(ctx context.Context) {
|
||||
workChan <- PackageInfo{
|
||||
Registry: pkg.Registry,
|
||||
Name: pkg.Name,
|
||||
Version: "latest", // Pre-warm latest version
|
||||
Version: LatestVersion,
|
||||
Priority: int(pkg.Downloads),
|
||||
}
|
||||
}
|
||||
@@ -168,13 +191,13 @@ func (w *Worker) processPackages(ctx context.Context, workerID int, workChan <-c
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
w.prewarmPackage(ctx, pkg, workerID)
|
||||
_ = w.prewarmPackage(ctx, pkg, workerID) // logged inside
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prewarmPackage fetches and caches a single package
|
||||
func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID int) {
|
||||
// prewarmPackage fetches a single package through the proxy path
|
||||
func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID int) error {
|
||||
log.Debug().
|
||||
Int("worker", workerID).
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -182,60 +205,24 @@ func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID i
|
||||
Str("version", pkg.Version).
|
||||
Msg("Pre-warming package")
|
||||
|
||||
// Build URL based on registry
|
||||
url := w.buildPackageURL(pkg)
|
||||
if url == "" {
|
||||
log.Warn().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Msg("Cannot build URL for registry")
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch package from upstream
|
||||
reqCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
reqCtx, cancel := context.WithTimeout(ctx, fetchTimeout)
|
||||
defer cancel()
|
||||
|
||||
body, statusCode, err := w.client.Get(reqCtx, url, nil)
|
||||
if err != nil {
|
||||
if err := w.fetcher.Fetch(reqCtx, pkg); err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Msg("Failed to fetch package for pre-warming")
|
||||
return
|
||||
}
|
||||
defer func() { _ = body.Close() }() // #nosec G104 -- Cleanup, error not critical
|
||||
|
||||
if statusCode != 200 {
|
||||
log.Warn().
|
||||
Int("status", statusCode).
|
||||
Str("package", pkg.Name).
|
||||
Msg("Non-200 response for package")
|
||||
return
|
||||
Msg("Failed to pre-warm package")
|
||||
return err
|
||||
}
|
||||
|
||||
// Cache the package
|
||||
// In a real implementation, this would read the response body and store it
|
||||
log.Info().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Successfully pre-warmed package")
|
||||
}
|
||||
|
||||
// buildPackageURL builds the upstream URL for a package
|
||||
func (w *Worker) buildPackageURL(pkg PackageInfo) string {
|
||||
// This is simplified - in reality, each registry has different URL patterns
|
||||
switch pkg.Registry {
|
||||
case "npm":
|
||||
return "https://registry.npmjs.org/" + pkg.Name
|
||||
case "pypi":
|
||||
return "https://pypi.org/simple/" + pkg.Name + "/"
|
||||
case "go":
|
||||
// Go modules use different URL patterns
|
||||
return "https://proxy.golang.org/" + pkg.Name + "/@latest"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
Msg("Pre-warmed package")
|
||||
return nil
|
||||
}
|
||||
|
||||
// combinePackages merges popular and trending packages, removing duplicates
|
||||
@@ -262,22 +249,25 @@ func (w *Worker) combinePackages(popular, trending []analytics.PopularPackage) [
|
||||
return result
|
||||
}
|
||||
|
||||
// Stop gracefully stops the pre-warming worker
|
||||
// Stop stops the worker and waits for it; it is safe on a nil, disabled or never-started worker.
|
||||
func (w *Worker) Stop() {
|
||||
if !w.enabled {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
|
||||
log.Info().Msg("Stopping pre-warming worker")
|
||||
close(w.stopChan)
|
||||
w.mu.Lock()
|
||||
cancel := w.cancel
|
||||
w.mu.Unlock()
|
||||
if cancel != nil {
|
||||
log.Info().Msg("Stopping pre-warming worker")
|
||||
cancel()
|
||||
}
|
||||
w.wg.Wait()
|
||||
log.Info().Msg("Pre-warming worker stopped")
|
||||
}
|
||||
|
||||
// TriggerPrewarm manually triggers a pre-warming cycle
|
||||
func (w *Worker) TriggerPrewarm(ctx context.Context) {
|
||||
if !w.enabled {
|
||||
log.Warn().Msg("Cannot trigger pre-warm: worker is disabled")
|
||||
if !w.enabled || w.fetcher == nil || w.popularity == nil {
|
||||
log.Warn().Msg("Cannot trigger pre-warm: worker is disabled or unconfigured")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -287,8 +277,8 @@ func (w *Worker) TriggerPrewarm(ctx context.Context) {
|
||||
|
||||
// PrewarmPackage pre-warms a specific package
|
||||
func (w *Worker) PrewarmPackage(ctx context.Context, registry, name, version string) error {
|
||||
if !w.enabled {
|
||||
log.Warn().Msg("Pre-warming worker is disabled")
|
||||
if !w.enabled || w.fetcher == nil {
|
||||
log.Warn().Msg("Pre-warming worker is disabled or unconfigured")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -299,8 +289,7 @@ func (w *Worker) PrewarmPackage(ctx context.Context, registry, name, version str
|
||||
Priority: 100,
|
||||
}
|
||||
|
||||
w.prewarmPackage(ctx, pkg, 0)
|
||||
return nil
|
||||
return w.prewarmPackage(ctx, pkg, 0)
|
||||
}
|
||||
|
||||
// GetStatus returns the current status of the pre-warming worker
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package prewarming
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fakeFetcher struct {
|
||||
err error
|
||||
got map[string]PackageInfo
|
||||
calls chan PackageInfo
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newFakeFetcher() *fakeFetcher {
|
||||
return &fakeFetcher{got: map[string]PackageInfo{}, calls: make(chan PackageInfo, 64)}
|
||||
}
|
||||
|
||||
func (f *fakeFetcher) Fetch(_ context.Context, pkg PackageInfo) error {
|
||||
f.mu.Lock()
|
||||
f.got[pkg.Registry+":"+pkg.Name] = pkg
|
||||
f.mu.Unlock()
|
||||
f.calls <- pkg
|
||||
return f.err
|
||||
}
|
||||
|
||||
type fakePopularity struct {
|
||||
top, trending []analytics.PopularPackage
|
||||
topLimit int
|
||||
}
|
||||
|
||||
func (p *fakePopularity) GetTopPackages(limit int) []analytics.PopularPackage {
|
||||
p.topLimit = limit
|
||||
return p.top
|
||||
}
|
||||
|
||||
func (p *fakePopularity) GetTrendingPackages(int) []analytics.PopularPackage { return p.trending }
|
||||
|
||||
func samplePopularity() *fakePopularity {
|
||||
return &fakePopularity{
|
||||
top: []analytics.PopularPackage{{Registry: "npm", Name: "lodash", Downloads: 9}, {Registry: "go", Name: "example.com/m", Downloads: 3}},
|
||||
trending: []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}, {Registry: "pypi", Name: "requests"}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCycleFetchesEachPopularPackageOnceAsLatest(t *testing.T) {
|
||||
f, pop := newFakeFetcher(), samplePopularity()
|
||||
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: pop, MaxConcurrent: 2, TopPackages: 7})
|
||||
|
||||
w.prewarmPopularPackages(context.Background())
|
||||
|
||||
assert.Len(t, f.got, 3, "lodash appears in both lists and must be fetched once")
|
||||
for _, p := range f.got {
|
||||
assert.Equal(t, LatestVersion, p.Version)
|
||||
}
|
||||
assert.Equal(t, 7, pop.topLimit)
|
||||
}
|
||||
|
||||
func TestFetchFailureDoesNotStopTheCycle(t *testing.T) {
|
||||
f := newFakeFetcher()
|
||||
f.err = errors.New("upstream down")
|
||||
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity(), MaxConcurrent: 1})
|
||||
|
||||
w.prewarmPopularPackages(context.Background())
|
||||
|
||||
assert.Len(t, f.got, 3)
|
||||
}
|
||||
|
||||
func TestStartRunsACycleAndStopEndsIt(t *testing.T) {
|
||||
f := newFakeFetcher()
|
||||
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity(), Interval: time.Hour})
|
||||
|
||||
w.Start(context.Background())
|
||||
w.Start(context.Background()) // second start must not spawn a second loop
|
||||
|
||||
select {
|
||||
case <-f.calls:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Start never ran a pre-warm cycle")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { w.Stop(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Stop did not return")
|
||||
}
|
||||
w.Stop() // idempotent
|
||||
}
|
||||
|
||||
func TestDisabledWorkerNeverFetches(t *testing.T) {
|
||||
f := newFakeFetcher()
|
||||
w := NewWorker(Config{Enabled: false, Fetcher: f, Popularity: samplePopularity()})
|
||||
|
||||
w.Start(context.Background())
|
||||
w.TriggerPrewarm(context.Background())
|
||||
require.NoError(t, w.PrewarmPackage(context.Background(), "npm", "lodash", "4.17.21"))
|
||||
w.Stop()
|
||||
|
||||
assert.Empty(t, f.calls)
|
||||
}
|
||||
|
||||
func TestStopIsSafeWithoutStart(t *testing.T) {
|
||||
assert.NotPanics(t, func() {
|
||||
NewWorker(Config{Enabled: true, Fetcher: newFakeFetcher(), Popularity: samplePopularity()}).Stop()
|
||||
NewWorker(Config{}).Stop()
|
||||
(*Worker)(nil).Stop()
|
||||
})
|
||||
}
|
||||
|
||||
func TestStartWithoutFetcherDoesNotRun(t *testing.T) {
|
||||
w := NewWorker(Config{Enabled: true, Popularity: samplePopularity()})
|
||||
w.Start(context.Background())
|
||||
w.Stop()
|
||||
assert.Nil(t, w.cancel)
|
||||
}
|
||||
|
||||
func TestPrewarmPackagePassesExplicitVersionAndReturnsError(t *testing.T) {
|
||||
f := newFakeFetcher()
|
||||
f.err = errors.New("boom")
|
||||
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity()})
|
||||
|
||||
err := w.PrewarmPackage(context.Background(), "npm", "lodash", "4.17.21")
|
||||
|
||||
require.ErrorContains(t, err, "boom")
|
||||
assert.Equal(t, "4.17.21", f.got["npm:lodash"].Version)
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func New(cacheManager *cache.Manager, client *network.Client, config Config) *Ha
|
||||
// ServeHTTP handles NPM registry requests
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
path := strings.TrimPrefix(r.URL.Path, "/npm")
|
||||
path := r.URL.Path
|
||||
|
||||
log.Debug().Str("path", path).Str("method", r.Method).Msg("NPM proxy request")
|
||||
|
||||
|
||||
@@ -111,9 +111,11 @@ func New(cacheManager *cache.Manager, client *network.Client, config Config) *Ha
|
||||
// ServeHTTP handles PyPI Simple API requests
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
path := strings.TrimPrefix(r.URL.Path, "/pypi")
|
||||
// Also trim /simple prefix since upstream already includes it
|
||||
path = strings.TrimPrefix(path, "/simple")
|
||||
path := r.URL.Path
|
||||
// Upstream already includes /simple; trim it only as a whole segment so a package such as simple-x keeps its name.
|
||||
if path == "/simple" || strings.HasPrefix(path, "/simple/") {
|
||||
path = path[len("/simple"):]
|
||||
}
|
||||
|
||||
log.Debug().Str("path", path).Str("method", r.Method).Msg("PyPI proxy request")
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // govulncheck -json exits 0 whether or not it finds anything
|
||||
|
||||
vulns, err := parseFindings(output)
|
||||
vulns, err := parseFindings(output, module)
|
||||
if err != nil {
|
||||
return s.errorResult(ctx, registry, packageName, version,
|
||||
fmt.Sprintf("govulncheck failed: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
|
||||
@@ -175,8 +175,10 @@ func hasPathElement(importPath, element string) bool {
|
||||
}
|
||||
|
||||
// parseFindings reads govulncheck's stream of JSON messages. An output without the config
|
||||
// message did not come from a completed run.
|
||||
func parseFindings(output []byte) ([]GovulncheckVuln, error) {
|
||||
// message did not come from a completed run. Only findings in the scanned module count:
|
||||
// dependency findings come from the minimum versions in its go.mod, which a consuming build
|
||||
// replaces with its own, and stdlib findings describe the scanner's toolchain.
|
||||
func parseFindings(output []byte, module string) ([]GovulncheckVuln, error) {
|
||||
summaries := make(map[string]string)
|
||||
var vulns []GovulncheckVuln
|
||||
seen := make(map[string]bool)
|
||||
@@ -194,14 +196,15 @@ func parseFindings(output []byte) ([]GovulncheckVuln, error) {
|
||||
sawConfig = true
|
||||
case msg.OSV != nil:
|
||||
summaries[msg.OSV.ID] = msg.OSV.Summary
|
||||
case msg.Finding != nil && msg.Finding.OSV != "" && !seen[msg.Finding.OSV]:
|
||||
case msg.Finding != nil && msg.Finding.OSV != "" && !seen[msg.Finding.OSV] &&
|
||||
len(msg.Finding.Trace) > 0 && msg.Finding.Trace[0].Module == module:
|
||||
seen[msg.Finding.OSV] = true
|
||||
v := GovulncheckVuln{OSV: msg.Finding.OSV, FixedVersion: msg.Finding.FixedVersion}
|
||||
if len(msg.Finding.Trace) > 0 {
|
||||
v.Module = msg.Finding.Trace[0].Module
|
||||
v.ModuleVersion = msg.Finding.Trace[0].Version
|
||||
}
|
||||
vulns = append(vulns, v)
|
||||
vulns = append(vulns, GovulncheckVuln{
|
||||
OSV: msg.Finding.OSV,
|
||||
FixedVersion: msg.Finding.FixedVersion,
|
||||
Module: msg.Finding.Trace[0].Module,
|
||||
ModuleVersion: msg.Finding.Trace[0].Version,
|
||||
})
|
||||
}
|
||||
}
|
||||
if !sawConfig {
|
||||
|
||||
@@ -86,16 +86,28 @@ func ids(res *metadata.ScanResult) map[string]string {
|
||||
func TestScanReadsPrettyPrintedFindings(t *testing.T) {
|
||||
// govulncheck -json prints indented objects, not one object per line.
|
||||
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
|
||||
fakeGovulncheck(t, abs(t, "gin-v1.6.0-source-scan.stream"), 0, "")
|
||||
fakeGovulncheck(t, abs(t, "gin-v1.6.0.stream"), 0, "")
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/gin-gonic/gin/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GO-2022-0493": "v0.0.0-20220412211240-33da011f77ad",
|
||||
"GO-2026-5024": "v0.44.0",
|
||||
}, ids(res), "one entry per advisory, with the fixed version")
|
||||
"GO-2021-0052": "v1.7.7",
|
||||
"GO-2023-1737": "v1.9.1",
|
||||
}, ids(res), "one entry per advisory against gin, with the fixed version; the x/sys findings belong to a dependency")
|
||||
}
|
||||
|
||||
func TestScanIgnoresFindingsInDependencies(t *testing.T) {
|
||||
// gin's go.mod requires an old x/sys; a build that uses gin resolves its own x/sys version.
|
||||
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
|
||||
fakeGovulncheck(t, abs(t, "gin-v1.6.0-source-scan.stream"), 0, "")
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/gin-gonic/gin/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
assert.Empty(t, res.Vulnerabilities)
|
||||
}
|
||||
|
||||
func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
type healthProbe struct {
|
||||
err error
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *healthProbe) Name() string { return "counting" }
|
||||
|
||||
func (s *healthProbe) Scan(context.Context, string, string, string, string) (*metadata.ScanResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *healthProbe) Health(context.Context) error {
|
||||
s.calls.Add(1)
|
||||
return s.err
|
||||
}
|
||||
|
||||
// Health runs each scanner's version command; under scan load that took over a second, so
|
||||
// repeated probes must reuse a recent result.
|
||||
func TestHealthReusesRecentResult(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
name string
|
||||
}{
|
||||
{name: "healthy", err: nil},
|
||||
{name: "unhealthy", err: errors.New("grype missing")},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := &healthProbe{err: tt.err}
|
||||
m := &Manager{enabled: true, scanners: []Scanner{s}}
|
||||
for range 3 {
|
||||
if err := m.Health(context.Background()); (err != nil) != (tt.err != nil) {
|
||||
t.Fatalf("Health() error = %v, want error %v", err, tt.err != nil)
|
||||
}
|
||||
}
|
||||
if got := s.calls.Load(); got != 1 {
|
||||
t.Fatalf("scanner health ran %d times, want 1", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A probe whose context was cancelled must not pin its failure for the cache period.
|
||||
func TestHealthDoesNotCacheCancelledProbe(t *testing.T) {
|
||||
s := &healthProbe{err: context.Canceled}
|
||||
m := &Manager{enabled: true, scanners: []Scanner{s}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_ = m.Health(ctx)
|
||||
s.err = nil
|
||||
if err := m.Health(context.Background()); err != nil {
|
||||
t.Fatalf("Health() after cancelled probe = %v, want nil", err)
|
||||
}
|
||||
if got := s.calls.Load(); got != 2 {
|
||||
t.Fatalf("scanner health ran %d times, want 2", got)
|
||||
}
|
||||
}
|
||||
+25
-8
@@ -264,6 +264,7 @@ func (s *Scanner) cleanGoModuleName(packageName, version, ecosystem string) (str
|
||||
func (s *Scanner) convertOSVResult(osvResp *OSVResponse, registry, packageName, version string) *metadata.ScanResult {
|
||||
vulnerabilities := make([]metadata.Vulnerability, 0, len(osvResp.Vulns))
|
||||
severityCounts := make(map[string]int)
|
||||
queryName, _ := s.cleanGoModuleName(packageName, version, s.registryToEcosystem(registry))
|
||||
|
||||
for _, vuln := range osvResp.Vulns {
|
||||
// Determine severity from various sources
|
||||
@@ -277,7 +278,7 @@ func (s *Scanner) convertOSVResult(osvResp *OSVResponse, registry, packageName,
|
||||
}
|
||||
|
||||
// Find fixed version
|
||||
fixedVersion := s.findFixedVersion(&vuln, version)
|
||||
fixedVersion := s.findFixedVersion(&vuln, queryName)
|
||||
|
||||
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
|
||||
ID: vuln.ID,
|
||||
@@ -352,14 +353,30 @@ func (s *Scanner) determineSeverity(vuln *OSVVulnerability) string {
|
||||
return metadata.NormalizeSeverity(rawSeverity)
|
||||
}
|
||||
|
||||
// findFixedVersion extracts the fixed version from OSV affected ranges
|
||||
func (s *Scanner) findFixedVersion(vuln *OSVVulnerability, currentVersion string) string {
|
||||
// findFixedVersion returns the first fixed version in the ranges for the queried package; an
|
||||
// advisory can cover several packages (stdlib and golang.org/x/net) with different fixes.
|
||||
func (s *Scanner) findFixedVersion(vuln *OSVVulnerability, name string) string {
|
||||
fallback := ""
|
||||
for _, affected := range vuln.Affected {
|
||||
for _, r := range affected.Ranges {
|
||||
for _, event := range r.Events {
|
||||
if event.Fixed != "" {
|
||||
return event.Fixed
|
||||
}
|
||||
fixed := firstFixed(affected.Ranges)
|
||||
if fixed == "" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(affected.Package.Name, name) {
|
||||
return fixed
|
||||
}
|
||||
if fallback == "" {
|
||||
fallback = fixed
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func firstFixed(ranges []OSVRange) string {
|
||||
for _, r := range ranges {
|
||||
for _, event := range r.Events {
|
||||
if event.Fixed != "" {
|
||||
return event.Fixed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,3 +44,22 @@ func TestScan_FullQueryURLIsKept(t *testing.T) {
|
||||
t.Errorf("request path = %q, want /v1/query", gotPath)
|
||||
}
|
||||
}
|
||||
|
||||
// An advisory that covers the stdlib and x/net lists the stdlib range first; the fixed version
|
||||
// shown for x/net must come from the x/net range.
|
||||
func TestScan_FixedVersionComesFromTheQueriedPackage(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"vulns":[{"id":"GO-2026-6612","summary":"s","affected":[
|
||||
{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.26.9"}]}]},
|
||||
{"package":{"name":"golang.org/x/net","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"0.60.0"}]}]}]}]}`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
res, err := New(config.OSVConfig{APIURL: srv.URL}).Scan(context.Background(), "go", "golang.org/x/net/@v/v0.56.0.zip", "v0.56.0", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Scan: %v", err)
|
||||
}
|
||||
if len(res.Vulnerabilities) != 1 || res.Vulnerabilities[0].FixedIn != "0.60.0" {
|
||||
t.Fatalf("vulnerabilities = %+v, want one fixed in 0.60.0", res.Vulnerabilities)
|
||||
}
|
||||
}
|
||||
|
||||
+166
-94
@@ -3,6 +3,7 @@ package scanner
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
@@ -16,16 +17,41 @@ type RescanWorker struct {
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
interval time.Duration
|
||||
activeWindow time.Duration
|
||||
concurrency int
|
||||
}
|
||||
|
||||
// RescanOption tunes a RescanWorker.
|
||||
type RescanOption func(*RescanWorker)
|
||||
|
||||
// WithActiveWindow skips packages not accessed within window (0 = scan all).
|
||||
func WithActiveWindow(window time.Duration) RescanOption {
|
||||
return func(w *RescanWorker) { w.activeWindow = window }
|
||||
}
|
||||
|
||||
// WithConcurrency sets the scans run in parallel within a cycle; values below 1 mean 1.
|
||||
func WithConcurrency(n int) RescanOption {
|
||||
return func(w *RescanWorker) {
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
w.concurrency = n
|
||||
}
|
||||
}
|
||||
|
||||
// NewRescanWorker creates a new rescan worker
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
|
||||
return &RescanWorker{
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration, opts ...RescanOption) *RescanWorker {
|
||||
w := &RescanWorker{
|
||||
manager: manager,
|
||||
metadataStore: metadataStore,
|
||||
interval: interval,
|
||||
concurrency: 1,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(w)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// Start begins the periodic re-scanning process
|
||||
@@ -70,115 +96,161 @@ func (w *RescanWorker) Stop() {
|
||||
})
|
||||
}
|
||||
|
||||
// rescanCounts tallies one rescan cycle; workers update it concurrently.
|
||||
type rescanCounts struct {
|
||||
scanned atomic.Int64
|
||||
failed atomic.Int64
|
||||
skipMetadata atomic.Int64
|
||||
skipIdle atomic.Int64
|
||||
skipFresh atomic.Int64
|
||||
skipNoSource atomic.Int64
|
||||
}
|
||||
|
||||
// rescanPackages re-scans packages that need updating
|
||||
func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
log.Info().Msg("Starting package rescan cycle - checking all packages for scan status")
|
||||
|
||||
// Get all packages
|
||||
packages, err := w.metadataStore.ListPackages(ctx, &metadata.ListOptions{})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages for rescan")
|
||||
return
|
||||
}
|
||||
|
||||
scanned := 0
|
||||
skipped := 0
|
||||
failed := 0
|
||||
|
||||
for _, pkg := range packages {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if package needs rescanning
|
||||
needsRescan, err := w.needsRescan(ctx, pkg)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Failed to check rescan status")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
if !needsRescan {
|
||||
log.Debug().
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Bool("security_scanned", pkg.SecurityScanned).
|
||||
Msg("Package does not need rescanning, skipping")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package needs rescanning")
|
||||
|
||||
if pkg.StorageKey == "" {
|
||||
log.Warn().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package has no storage key, skipping rescan")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
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).
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("storage_key", pkg.StorageKey).
|
||||
Msg("Failed to read package file, skipping rescan")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
// Perform the actual scan
|
||||
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
|
||||
cleanup()
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Failed to rescan package")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
scanned++
|
||||
var counts rescanCounts
|
||||
jobs := make(chan *metadata.Package)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < w.concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for pkg := range jobs {
|
||||
w.rescanOne(ctx, pkg, &counts)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
dispatch:
|
||||
for _, pkg := range packages {
|
||||
if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) {
|
||||
counts.skipMetadata.Add(1)
|
||||
continue
|
||||
}
|
||||
if w.idle(pkg) {
|
||||
counts.skipIdle.Add(1)
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case jobs <- pkg:
|
||||
case <-ctx.Done():
|
||||
break dispatch
|
||||
case <-w.stopCh:
|
||||
break dispatch
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
|
||||
log.Info().
|
||||
Int("total", len(packages)).
|
||||
Int("scanned", scanned).
|
||||
Int("skipped", skipped).
|
||||
Int("failed", failed).
|
||||
Int64("scanned", counts.scanned.Load()).
|
||||
Int64("failed", counts.failed.Load()).
|
||||
Int64("skipped_metadata", counts.skipMetadata.Load()).
|
||||
Int64("skipped_idle", counts.skipIdle.Load()).
|
||||
Int64("skipped_fresh", counts.skipFresh.Load()).
|
||||
Int64("skipped_no_source", counts.skipNoSource.Load()).
|
||||
Int("concurrency", w.concurrency).
|
||||
Dur("active_window", w.activeWindow).
|
||||
Msg("Rescan cycle completed")
|
||||
}
|
||||
|
||||
// idle reports whether a package was last served longer ago than the active window.
|
||||
// A zero LastAccessed is unknown, so the package is scanned.
|
||||
func (w *RescanWorker) idle(pkg *metadata.Package) bool {
|
||||
if w.activeWindow <= 0 || pkg.LastAccessed.IsZero() {
|
||||
return false
|
||||
}
|
||||
return time.Since(pkg.LastAccessed) > w.activeWindow
|
||||
}
|
||||
|
||||
// rescanOne scans a single package when its result is missing or stale.
|
||||
func (w *RescanWorker) rescanOne(ctx context.Context, pkg *metadata.Package, counts *rescanCounts) {
|
||||
needsRescan, err := w.needsRescan(ctx, pkg)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Failed to check rescan status")
|
||||
counts.failed.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
if !needsRescan {
|
||||
log.Debug().
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Bool("security_scanned", pkg.SecurityScanned).
|
||||
Msg("Package does not need rescanning, skipping")
|
||||
counts.skipFresh.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package needs rescanning")
|
||||
|
||||
if pkg.StorageKey == "" {
|
||||
log.Warn().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package has no storage key, skipping rescan")
|
||||
counts.failed.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
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")
|
||||
counts.skipNoSource.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if err != nil {
|
||||
log.Warn().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("storage_key", pkg.StorageKey).
|
||||
Msg("Failed to read package file, skipping rescan")
|
||||
counts.failed.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
|
||||
cleanup()
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("Failed to rescan package")
|
||||
counts.failed.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
counts.scanned.Add(1)
|
||||
}
|
||||
|
||||
// needsRescan checks if a package needs to be rescanned
|
||||
func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (bool, error) {
|
||||
// Get latest scan result
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// rescanStore serves a fixed package list and keeps saved scan results.
|
||||
type rescanStore struct {
|
||||
results map[string]*metadata.ScanResult
|
||||
packages []*metadata.Package
|
||||
stubMetadataStore
|
||||
rmu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *rescanStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return s.packages, nil
|
||||
}
|
||||
|
||||
func (s *rescanStore) GetScanResult(_ context.Context, registry, name, version string) (*metadata.ScanResult, error) {
|
||||
s.rmu.Lock()
|
||||
defer s.rmu.Unlock()
|
||||
if r, ok := s.results[scanKey(registry, name, version)]; ok {
|
||||
return r, nil
|
||||
}
|
||||
return nil, hoardererrors.NotFound("no scan result")
|
||||
}
|
||||
|
||||
func (s *rescanStore) SaveScanResult(ctx context.Context, r *metadata.ScanResult) error {
|
||||
s.rmu.Lock()
|
||||
s.results[scanKey(r.Registry, r.PackageName, r.PackageVersion)] = r
|
||||
s.rmu.Unlock()
|
||||
return s.stubMetadataStore.SaveScanResult(ctx, r)
|
||||
}
|
||||
|
||||
// countingScanner records how often each package is scanned.
|
||||
type countingScanner struct {
|
||||
calls map[string]int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (c *countingScanner) Name() string { return "counting" }
|
||||
|
||||
func (c *countingScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
c.mu.Lock()
|
||||
c.calls[scanKey(registry, name, version)]++
|
||||
c.mu.Unlock()
|
||||
return &metadata.ScanResult{
|
||||
Registry: registry, PackageName: name, PackageVersion: version,
|
||||
Scanner: "counting", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *countingScanner) Health(context.Context) error { return nil }
|
||||
|
||||
func (c *countingScanner) snapshot() map[string]int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
out := make(map[string]int, len(c.calls))
|
||||
for k, v := range c.calls {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func pkgRow(registry, name, version string, lastAccessed time.Time) *metadata.Package {
|
||||
return &metadata.Package{
|
||||
Registry: registry, Name: name, Version: version,
|
||||
StorageKey: registry + "/" + name + "/" + version, LastAccessed: lastAccessed,
|
||||
}
|
||||
}
|
||||
|
||||
func runRescan(t *testing.T, pkgs []*metadata.Package, opts ...RescanOption) map[string]int {
|
||||
t.Helper()
|
||||
store := &rescanStore{results: map[string]*metadata.ScanResult{}, packages: pkgs}
|
||||
mgr := newTestManager(t, store)
|
||||
cs := &countingScanner{calls: map[string]int{}}
|
||||
mgr.RegisterScanner(cs)
|
||||
mgr.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
NewRescanWorker(mgr, store, time.Hour, opts...).rescanPackages(context.Background())
|
||||
return cs.snapshot()
|
||||
}
|
||||
|
||||
func TestRescanSkipsMetadataEntries(t *testing.T) {
|
||||
now := time.Now()
|
||||
pkgs := []*metadata.Package{
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", now),
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.info", "v1.0.0", now),
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", now),
|
||||
pkgRow("npm", "left-pad", "list", now),
|
||||
pkgRow("npm", "left-pad", "1.3.0", now),
|
||||
pkgRow("npm", "weird.mod", "1.0.0", now),
|
||||
}
|
||||
got := runRescan(t, pkgs)
|
||||
assert.Equal(t, map[string]int{
|
||||
scanKey("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0"): 1,
|
||||
scanKey("npm", "left-pad", "1.3.0"): 1,
|
||||
scanKey("npm", "weird.mod", "1.0.0"): 1,
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestRescanActiveWindow(t *testing.T) {
|
||||
now := time.Now()
|
||||
pkgs := []*metadata.Package{
|
||||
pkgRow("npm", "hot", "1.0.0", now.Add(-time.Hour)),
|
||||
pkgRow("npm", "cold", "1.0.0", now.Add(-72*time.Hour)),
|
||||
pkgRow("npm", "unknown", "1.0.0", time.Time{}),
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
want []string
|
||||
window time.Duration
|
||||
}{
|
||||
{"window off scans everything", []string{"hot", "cold", "unknown"}, 0},
|
||||
{"window skips idle only", []string{"hot", "unknown"}, 24 * time.Hour},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := runRescan(t, pkgs, WithActiveWindow(tt.window))
|
||||
want := map[string]int{}
|
||||
for _, n := range tt.want {
|
||||
want[scanKey("npm", n, "1.0.0")] = 1
|
||||
}
|
||||
assert.Equal(t, want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRescanConcurrencyScansEachOnce(t *testing.T) {
|
||||
now := time.Now()
|
||||
var pkgs []*metadata.Package
|
||||
want := map[string]int{}
|
||||
for i := 0; i < 40; i++ {
|
||||
name := string(rune('a'+i%26)) + string(rune('a'+i/26))
|
||||
pkgs = append(pkgs, pkgRow("npm", name, "1.0.0", now))
|
||||
want[scanKey("npm", name, "1.0.0")] = 1
|
||||
}
|
||||
pkgs = append(pkgs, pkgRow("go", "m/@v/v1.mod", "v1", now))
|
||||
|
||||
for _, n := range []int{-2, 0, 1, 3, 8} {
|
||||
got := runRescan(t, pkgs, WithConcurrency(n))
|
||||
require.Equal(t, want, got, "concurrency %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRescanConcurrencyFloor(t *testing.T) {
|
||||
for _, n := range []int{-1, 0} {
|
||||
w := NewRescanWorker(nil, nil, time.Hour, WithConcurrency(n))
|
||||
assert.Equal(t, 1, w.concurrency)
|
||||
}
|
||||
assert.Equal(t, 1, NewRescanWorker(nil, nil, time.Hour).concurrency)
|
||||
}
|
||||
@@ -71,8 +71,18 @@ func (m *Manager) currentFileSource() FileSource {
|
||||
return m.fileSource
|
||||
}
|
||||
|
||||
// healthTTL bounds how often /health forks each scanner's version command; under scan load one round took over a second.
|
||||
const healthTTL = 30 * time.Second
|
||||
|
||||
type healthCache struct {
|
||||
at time.Time
|
||||
err error
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
health healthCache
|
||||
metadataStore metadata.MetadataStore
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
@@ -913,6 +923,20 @@ func (m *Manager) Health(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.health.mu.Lock()
|
||||
defer m.health.mu.Unlock()
|
||||
if !m.health.at.IsZero() && time.Since(m.health.at) < healthTTL {
|
||||
return m.health.err
|
||||
}
|
||||
err := m.checkScanners(ctx)
|
||||
if ctx.Err() != nil {
|
||||
return err
|
||||
}
|
||||
m.health.at, m.health.err = time.Now(), err
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Manager) checkScanners(ctx context.Context) error {
|
||||
for _, scanner := range m.scanners {
|
||||
if err := scanner.Health(ctx); err != nil {
|
||||
return fmt.Errorf("scanner %s health check failed: %w", scanner.Name(), err)
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package trivy
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// maxExtractBytes caps the unpacked size so a compressed bomb cannot fill the disk.
|
||||
const maxExtractBytes int64 = 512 << 20
|
||||
|
||||
var errTooLarge = errors.New("archive exceeds the extraction size limit")
|
||||
|
||||
// unpackNPM extracts an npm tarball into root/node_modules/<name>, the layout trivy's node-pkg
|
||||
// analyzer reads. It returns root, which the caller must remove.
|
||||
func unpackNPM(archive, name string) (root string, err error) {
|
||||
if !validPackageName(name) {
|
||||
return "", fmt.Errorf("unsafe package name %q", name)
|
||||
}
|
||||
root, err = os.MkdirTemp("", "trivy-npm-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = os.RemoveAll(root)
|
||||
root = ""
|
||||
}
|
||||
}()
|
||||
dest := filepath.Join(root, "node_modules", filepath.FromSlash(name))
|
||||
if err = os.MkdirAll(dest, 0o750); err != nil {
|
||||
return root, err
|
||||
}
|
||||
err = extractTarball(archive, dest)
|
||||
return root, err
|
||||
}
|
||||
|
||||
func validPackageName(name string) bool {
|
||||
if name == "" || strings.Contains(name, "\\") || !filepath.IsLocal(name) {
|
||||
return false
|
||||
}
|
||||
for _, seg := range strings.Split(name, "/") {
|
||||
if seg == ".." || seg == "." || seg == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// extractTarball unpacks a .tgz into dest, dropping the top-level directory. Links are never
|
||||
// created; escaping ones are rejected outright.
|
||||
func extractTarball(archive, dest string) error {
|
||||
f, err := os.Open(archive) // #nosec G304 -- path from the cache, not user input
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open gzip: %w", err)
|
||||
}
|
||||
defer func() { _ = gz.Close() }()
|
||||
|
||||
tr := tar.NewReader(gz)
|
||||
var total int64
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read tar: %w", err)
|
||||
}
|
||||
rel, err := entryPath(hdr.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch hdr.Typeflag {
|
||||
case tar.TypeDir:
|
||||
if rel == "" {
|
||||
continue
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(dest, rel), 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
case tar.TypeReg:
|
||||
if rel == "" {
|
||||
continue
|
||||
}
|
||||
n, err := writeEntry(filepath.Join(dest, rel), tr, maxExtractBytes-total)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total += n
|
||||
case tar.TypeSymlink, tar.TypeLink:
|
||||
if err := checkLink(hdr); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// entryPath validates a tar entry name and strips its first segment.
|
||||
func entryPath(name string) (string, error) {
|
||||
clean := strings.ReplaceAll(name, "\\", "/")
|
||||
if strings.HasPrefix(clean, "/") {
|
||||
return "", fmt.Errorf("absolute path in archive: %q", name)
|
||||
}
|
||||
for _, seg := range strings.Split(clean, "/") {
|
||||
if seg == ".." {
|
||||
return "", fmt.Errorf("path traversal in archive: %q", name)
|
||||
}
|
||||
}
|
||||
segs := strings.Split(path.Clean(clean), "/")
|
||||
if len(segs) < 2 {
|
||||
return "", nil
|
||||
}
|
||||
rel := filepath.FromSlash(strings.Join(segs[1:], "/"))
|
||||
if !filepath.IsLocal(rel) {
|
||||
return "", fmt.Errorf("unsafe path in archive: %q", name)
|
||||
}
|
||||
return rel, nil
|
||||
}
|
||||
|
||||
func checkLink(hdr *tar.Header) error {
|
||||
target := strings.ReplaceAll(hdr.Linkname, "\\", "/")
|
||||
if strings.HasPrefix(target, "/") {
|
||||
return fmt.Errorf("absolute link target in archive: %q -> %q", hdr.Name, hdr.Linkname)
|
||||
}
|
||||
base := path.Dir(hdr.Name)
|
||||
if hdr.Typeflag == tar.TypeLink {
|
||||
base = "."
|
||||
}
|
||||
joined := path.Join(base, target)
|
||||
if joined == ".." || strings.HasPrefix(joined, "../") {
|
||||
return fmt.Errorf("link escapes the archive: %q -> %q", hdr.Name, hdr.Linkname)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeEntry copies at most limit bytes and fails when the entry is larger.
|
||||
func writeEntry(dst string, r io.Reader, limit int64) (int64, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) // #nosec G304 -- dst validated by entryPath
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, err := io.Copy(out, io.LimitReader(r, limit+1))
|
||||
if cerr := out.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil && n > limit {
|
||||
err = errTooLarge
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
@@ -110,15 +110,23 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
// Determine scan type based on registry
|
||||
scanType := s.determineScanType(registry, filePath)
|
||||
target := filePath
|
||||
if registry == "npm" {
|
||||
// trivy does not unpack archives; the node-pkg analyzer needs an installed tree.
|
||||
root, err := unpackNPM(filePath, packageName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare npm package for trivy: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(root) }()
|
||||
target = root
|
||||
}
|
||||
|
||||
// Build Trivy command
|
||||
args := []string{
|
||||
scanType,
|
||||
"--format", "json",
|
||||
"--quiet",
|
||||
filePath,
|
||||
target,
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
|
||||
@@ -166,7 +174,7 @@ func (s *Scanner) determineScanType(registry, filePath string) string {
|
||||
|
||||
switch registry {
|
||||
case "npm":
|
||||
return "fs" // Filesystem scan for npm packages
|
||||
return "rootfs" // rootfs enables the node-pkg analyzer; fs reads lockfiles only
|
||||
case "pypi":
|
||||
return "fs" // Filesystem scan for Python packages
|
||||
case "go":
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
package trivy
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -16,9 +23,129 @@ import (
|
||||
func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) {
|
||||
scannertest.Script(t, "trivy", "exec sleep 5")
|
||||
|
||||
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "npm", "p", "1", "/x")
|
||||
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "pypi", "p", "1", "/x")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
||||
assert.Equal(t, true, res.Details[scanerr.DetailInfrastructure])
|
||||
}
|
||||
|
||||
type entry struct {
|
||||
name, body, link string
|
||||
typeflag byte
|
||||
}
|
||||
|
||||
func tgz(t *testing.T, entries ...entry) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
for _, e := range entries {
|
||||
tf := e.typeflag
|
||||
if tf == 0 {
|
||||
tf = tar.TypeReg
|
||||
}
|
||||
hdr := &tar.Header{Name: e.name, Typeflag: tf, Mode: 0o644, Linkname: e.link}
|
||||
if tf == tar.TypeReg {
|
||||
hdr.Size = int64(len(e.body))
|
||||
}
|
||||
require.NoError(t, tw.WriteHeader(hdr))
|
||||
if tf == tar.TypeReg {
|
||||
_, err := tw.Write([]byte(e.body))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
require.NoError(t, tw.Close())
|
||||
require.NoError(t, gz.Close())
|
||||
p := filepath.Join(t.TempDir(), "p.tgz")
|
||||
require.NoError(t, os.WriteFile(p, buf.Bytes(), 0o600))
|
||||
return p
|
||||
}
|
||||
|
||||
func TestNPMScanRunsRootfsOnUnpackedTree(t *testing.T) {
|
||||
rec := t.TempDir()
|
||||
scannertest.Script(t, "trivy", fmt.Sprintf(`
|
||||
printf '%%s\n' "$@" > %[1]q/args
|
||||
for last; do :; done
|
||||
cp "$last/node_modules/@scope/pkg/package.json" %[1]q/package.json
|
||||
echo "$last" > %[1]q/root
|
||||
echo '{"Results":[]}'`, rec))
|
||||
archive := tgz(t,
|
||||
entry{name: "package/", typeflag: tar.TypeDir},
|
||||
entry{name: "package/package.json", body: `{"name":"@scope/pkg"}`},
|
||||
entry{name: "package/lib/index.js", body: "x"},
|
||||
)
|
||||
|
||||
res, err := New(config.TrivyConfig{}).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
args, err := os.ReadFile(filepath.Join(rec, "args")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
root, err := os.ReadFile(filepath.Join(rec, "root")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
lines := strings.Split(strings.TrimSpace(string(args)), "\n")
|
||||
assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", strings.TrimSpace(string(root))}, lines)
|
||||
pkg, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{"name":"@scope/pkg"}`, string(pkg))
|
||||
_, err = os.Stat(strings.TrimSpace(string(root))) // #nosec G304 G703 -- path from the test fake
|
||||
assert.True(t, os.IsNotExist(err), "temp tree must be removed")
|
||||
}
|
||||
|
||||
func TestNonNPMScansTheFileWithFS(t *testing.T) {
|
||||
argsFile := scannertest.Fake(t, "trivy", "", "", 0)
|
||||
_, err := New(config.TrivyConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
|
||||
require.Error(t, err) // empty output is not JSON
|
||||
assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "/x/p.whl"}, scannertest.Args(t, argsFile))
|
||||
}
|
||||
|
||||
func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
entries []entry
|
||||
}{
|
||||
{"parent traversal", []entry{{name: "package/../../evil", body: "x"}}},
|
||||
{"leading traversal", []entry{{name: "../evil", body: "x"}}},
|
||||
{"absolute path", []entry{{name: "/etc/evil", body: "x"}}},
|
||||
{"symlink to absolute", []entry{{name: "package/l", typeflag: tar.TypeSymlink, link: "/etc/passwd"}}},
|
||||
{"symlink out of tree", []entry{{name: "package/l", typeflag: tar.TypeSymlink, link: "../../x"}}},
|
||||
{"hardlink out of tree", []entry{{name: "package/l", typeflag: tar.TypeLink, link: "../x"}}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
root, err := unpackNPM(tgz(t, tt.entries...), "pkg")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, root)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
|
||||
root, err := unpackNPM(tgz(t,
|
||||
entry{name: "package/real.js", body: "x"},
|
||||
entry{name: "package/l", typeflag: tar.TypeSymlink, link: "real.js"},
|
||||
), "pkg")
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = os.RemoveAll(root) }()
|
||||
_, err = os.Lstat(filepath.Join(root, "node_modules", "pkg", "l"))
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
assert.FileExists(t, filepath.Join(root, "node_modules", "pkg", "real.js"))
|
||||
}
|
||||
|
||||
func TestUnpackRejectsUnsafePackageNames(t *testing.T) {
|
||||
archive := tgz(t, entry{name: "package/package.json", body: "{}"})
|
||||
for _, name := range []string{"", "..", "../x", "/abs", "a/../../b", `a\b`} {
|
||||
_, err := unpackNPM(archive, name)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractEnforcesSizeCap(t *testing.T) {
|
||||
dest := t.TempDir()
|
||||
_, err := writeEntry(filepath.Join(dest, "big"), strings.NewReader(strings.Repeat("a", 11)), 10)
|
||||
require.ErrorIs(t, err, errTooLarge)
|
||||
n, err := writeEntry(filepath.Join(dest, "ok"), strings.NewReader(strings.Repeat("a", 10)), 10)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 10, n)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user