Compare commits

...
15 Commits
Author SHA1 Message Date
lukaszraczylo e6d8ed0f2e fix(scanner): reuse a recent scanner health result
Each /health request ran the version command of every scanner. Under rescan load one round took about 1.4 seconds, which exceeds the client probes that use /health to choose the cache. The result is now reused for 30 seconds. A probe that ends with a cancelled context is not stored.
2026-11-23 19:47:16 +00:00
lukaszraczylo 40ed8f8213 docs(lean): model rescan skip and on-access freshness as GH-26
The rescan worker skip predicate matches the serve path. A hit whose scan is
older than the interval is judged on a fresh scan, or on the previous result
when the rescan times out.
2026-11-23 19:30:16 +00:00
lukaszraczylo ecf750adbb feat(cache): rescan stale cache hits before serving
With security.rescan_on_access and rescan_interval set, a hit whose scan
result is missing or older than the interval is rescanned before it is
served. Concurrent hits share one scan, and the scan runs under the
manager context so a client disconnect does not abort it. The wait is
bounded by scan_wait_timeout. On a timeout the previous result decides,
or the first-download rule applies when none exists.
2026-11-23 19:27:49 +00:00
lukaszraczylo 41f8369c43 feat(rescan): limit rescans to active packages and run them in parallel
security.rescan_active_window skips packages not requested within the
window. security.rescan_concurrency runs a bounded pool of scans per
cycle. The cycle summary reports skips by reason. Both options default
to the previous behaviour.
2026-11-23 19:26:10 +00:00
lukaszraczylo d6044cdd2e fix(rescan): skip Go .mod and .info rows in the rescan worker
The worker kept its own list of metadata versions and scanned Go module
metadata rows that the serve path never scans. It now uses
metadata.IsMetadataEntry like the cache layer.
2026-11-23 19:25:28 +00:00
lukaszraczylo 1baa6b8e26 docs(lean): model the merge of error results as GH-25
Add the merge model for error-status results and the ledger row. One
error result with one clean result reads clean, all errors read error,
and an error never hides a finding.
2026-11-23 18:07:30 +00:00
lukaszraczylo 3d6bda3a5f fix(pip-audit): audit the release from a pinned requirement
pip-audit takes a project directory as its positional argument and has
no --pyproject option, so every wheel and sdist scan failed. The scanner
now audits name==version from a requirements file with --no-deps and
--disable-pip.

It reads stdout only, lists each advisory once, and treats a skip_reason
as an error because pip-audit exits 0 for a package it could not audit.
2026-11-23 18:07:27 +00:00
lukaszraczylo e37c797602 fix(govulncheck): scan the module as a dependency and read the stream
govulncheck prints indented JSON objects. The line parser read none of
them, so every module read clean.

govulncheck also never reports advisories against the main module of the
tree it scans. A scan of the x/text 0.3.5 source found nothing. The
module is now a dependency of a wrapper module that imports its
packages, and the scan runs at module level.
2026-11-23 18:07:21 +00:00
lukaszraczylo 157814cf08 fix(npm-audit): audit the package through a wrapper project
npm 11 prints via as an array and metadata.dependencies as an object, so
the parser failed on every report. It now reads both shapes of via and
lists each advisory once.

The lockfile step resolved devDependencies, which took 28 seconds for
dayjs and reported 142 findings in its development tree. The tarball is
now the only dependency of a wrapper project, audited with --omit=dev.
This also audits the package itself, which npm audit skips for a root.
2026-11-23 18:07:00 +00:00
lukaszraczylo 65aa2e25dc fix(grype): parse file sources and scan packages by purl
grype 0.121 prints source.target as a string for file, directory and
purl sources. The parser expected an object and failed every scan.

A bare npm, PyPI or Go archive holds nothing grype can catalog, so a
scan of the archive read minimist 0.0.8 as clean. The scanner now passes
a purl for these registries and falls back to the file for others.
2026-11-23 18:06:57 +00:00
lukaszraczylo 3731ca05ce fix(scanner): leave failed scanner results out of the merge
A scanner that returns a result with status error now counts as a failed
scanner, like one that returns an error. Its result no longer joins the
merge, and the manager counts it as an infrastructure failure or another
failure by its cause.

The merged status is error only when every applicable scanner failed.
The fail_closed setting then decides that case as before. One scanner
failing while another returns clean now reads clean.
2026-11-23 18:06:54 +00:00
lukaszraczylo 8adb1e0c87 build: pin the scanner image tool versions
The scanner image installed trivy and grype from install scripts on the main branch, govulncheck at latest and pip-audit unpinned, so every build could pull different tools. They are now pinned: trivy v0.76.2, grype v0.121.2, govulncheck v1.9.0 and pip-audit 2.10.1, each released at least two weeks ago.
2026-11-23 17:37:51 +00:00
lukaszraczylo 16fb52ed3e feat(config): make the first-download scan wait configurable
The cache waited a fixed 30 seconds for a first download's scan, and the app never set the wait. Scanners run one after another, so a deployment with several scanners and fail_closed refused most first downloads. security.scan_wait_timeout now sets the wait; 0 keeps 30 seconds.
2026-11-23 17:37:45 +00:00
lukaszraczylo 13abb140d7 docs(lean): record the GH-24 fix commit 2026-11-23 17:24:58 +00:00
lukaszraczylo 378b8731fc fix(app): start the rescan worker
The app created the rescan worker when security.rescan_interval was set but never started it; only Shutdown called Stop. A scan lost to a restart therefore left its package unscanned for good, and old results were never refreshed with new CVEs. startWorkers now starts the worker. The ledger records it as GH-24.
2026-11-23 17:24:55 +00:00
52 changed files with 5154 additions and 504 deletions
+4 -4
View File
@@ -23,17 +23,17 @@ RUN apk add --no-cache \
&& update-ca-certificates
# Install Trivy for container scanning
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/v0.76.2/contrib/install.sh | sh -s -- -b /usr/local/bin v0.76.2
# Install Grype for vulnerability scanning
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/v0.121.2/install.sh | sh -s -- -b /usr/local/bin v0.121.2
# Install govulncheck for Go vulnerability scanning
RUN go install golang.org/x/vuln/cmd/govulncheck@latest && \
RUN go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 && \
mv /root/go/bin/govulncheck /usr/local/bin/
# Install pip-audit for Python package vulnerability scanning
RUN pip3 install --no-cache-dir pip-audit --break-system-packages
RUN pip3 install --no-cache-dir pip-audit==2.10.1 --break-system-packages
# Create non-root user
RUN addgroup -g 1000 scanner && \
+5
View File
@@ -110,9 +110,14 @@ 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
# How long a first download waits for its scan before it is served (or refused with fail_closed). Default 30s.
scan_wait_timeout: "30s"
scan_retry_interval: "5m"
update_db_on_startup: false # Update vulnerability databases on startup
allowed_packages: [] # Packages that bypass security checks (format: "registry/name@version")
+23 -1
View File
@@ -28,6 +28,9 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | 536f35a |
| 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 |
### Exploit paths and reach
@@ -66,8 +69,27 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
- **GH-25.** `scan` treats an error-status result like a returned error: it is left out of the merge and counted as an
infrastructure failure (`infrastructure_error` in its details, set on a deadline or an unreachable network) or another failure.
Before, one such result made the merged row an error and `evaluateScan` blocked the package even with `fail_closed: false`.
Defects found by running the published scanner image (grype 0.121.2, npm 11.12.1, govulncheck 1.9.0, pip-audit 2.10.1,
go 1.26), each with a fixture of real output under the scanner's `testdata/`:
grype: `source.target` is a string for file and purl sources, and a bare archive has nothing to catalog, so minimist 0.0.8 read clean;
the scanner now passes a purl. npm audit: `via` is an array and `metadata.dependencies` an object in npm 11; the lockfile
step resolved devDependencies (dayjs: 1567 packages, 142 findings, 28s) and `npm audit` cannot report the root package itself;
the tarball is now installed into a wrapper project and audited with `--omit=dev` (under 1s). govulncheck: the JSON stream is
indented, so the line parser read nothing, and govulncheck never reports the main module of the tree it scans (x/text 0.3.5
read clean); the module is now a dependency of a wrapper module and scanned at module level. pip-audit: its positional
argument is a project directory and `--pyproject` does not exist, so every scan failed; the release is audited from a pinned
requirement, an advisory is listed once, and `skip_reason` is an error. trivy is not covered: it reads a bare npm archive
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
@@ -77,7 +99,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-11 | cache hit | the stored SHA-256 is not re-verified on read | by-design | `Put` verifies the stream it just hashed; no doc promises read-side integrity. A check reads up to 2 GB per hit. Disk corruption is outside the proxy's threat model. |
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.error_and_clean_reads_clean` (a returned error and, since GH-25, an error-status result). `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. |
### Decision: `fail_closed: false` with recurring infrastructure errors
+12
View File
@@ -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
+151 -5
View File
@@ -3,7 +3,7 @@ import Mathlib
/-!
# Security decision logic
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `scheduleRetry`,
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `succeeded`, `scheduleRetry`,
`pkg/metadata/gormstore/gormstore_v2.go` `GetActiveCVEBypasses`, and the scan gate in
`pkg/cache/cache.go` `getOrFetch`. Severities are ranks (low 1 .. critical 4). Omits: the
scanners themselves, threshold counters (`block_thresholds`), network.
@@ -193,7 +193,7 @@ theorem npm_scan_keeps_cache_version (cacheVersion : String) :
theorem file_name_is_not_release_version :
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
/-! ### Merge: worst status wins, but a failed scanner leaves no trace -/
/-! ### Merge: worst status wins among scanners that ran; a failed scanner leaves no trace -/
/-- ranks: clean 0, pending 1, error 2, vulnerable 3 (`mergeResults`). -/
def mergeRank (xs : List ℕ) : ℕ := xs.foldr max 0
@@ -207,8 +207,154 @@ theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRa
· exact le_max_left _ _
· exact le_trans (ih h) (le_max_right _ _)
/-- Results exist only for scanners that returned; with one scanner failing and one clean, the
merged status is clean and no retry is scheduled (`scan`: retry only when no scanner succeeded). -/
theorem partial_failure_reads_clean : mergeRank [0] = 0 := by decide
def errorRank : ℕ := 2
/-- Before GH-25 a scanner's error-status result took part in the merge, as the rank `errorRank`. -/
def oldMerge (xs : List ℕ) : ℕ := mergeRank xs
/-- `scan` after GH-25: a scanner that returns an error-status result failed, like one that returns
an error. Only results of scanners that ran are merged; with none left every scanner failed. -/
def newMerge (xs : List ℕ) : ℕ :=
if (xs.filter (· ≠ errorRank)).isEmpty then errorRank else mergeRank (xs.filter (· ≠ errorRank))
/-- GH-25: one scanner's error result turned a clean package into an error row. -/
theorem old_error_poisons_clean : oldMerge [0, errorRank] = errorRank := by decide
theorem error_and_clean_reads_clean : newMerge [0, errorRank] = 0 := by decide
theorem error_never_hides_vulnerable : newMerge [errorRank, 3] = 3 := by decide
theorem all_error_reads_error (xs : List ℕ) (h : ∀ x ∈ xs, x = errorRank) : newMerge xs = errorRank := by
have : xs.filter (· ≠ errorRank) = [] := by
rw [List.filter_eq_nil_iff]
intro x hx
simp [h x hx]
unfold newMerge
rw [this]
rfl
theorem error_result_ignored (xs : List ℕ) : newMerge (errorRank :: xs) = newMerge xs := by
simp [newMerge]
theorem mergeRank_not_error (ys : List ℕ) (h : ∀ y ∈ ys, y ≠ errorRank) : mergeRank ys ≠ errorRank := by
induction ys with
| nil => simp [mergeRank, errorRank]
| cons y ys ih =>
simp only [mergeRank, List.foldr_cons]
have hy : y ≠ errorRank := h y (List.mem_cons_self ..)
have hys : mergeRank ys ≠ errorRank := ih (fun z hz => h z (List.mem_cons_of_mem _ hz))
rcases max_choice y (ys.foldr max 0) with e | e
· rw [e]; exact hy
· rw [e]; exact hys
/-- With any scanner that ran, the merged status is not an error, so `fail_closed` never decides it. -/
theorem merged_not_error_when_one_ran (xs : List ℕ) (h : ∃ x ∈ xs, x ≠ errorRank) :
newMerge xs ≠ errorRank := by
obtain ⟨x, hx, hne⟩ := h
have hmem : x ∈ xs.filter (· ≠ errorRank) := List.mem_filter.mpr ⟨hx, by simpa using hne⟩
unfold newMerge
have hne' : ¬ (xs.filter (· ≠ errorRank)).isEmpty = true := by
intro hempty
rw [List.isEmpty_iff] at hempty
rw [hempty] at hmem
simp at hmem
simp only [hne']
apply mergeRank_not_error
intro y hy
simpa using (List.mem_filter.mp hy).2
/-- The retry is for infrastructure only: `scan` counts each failure by cause and the row is an
infrastructure error only when there was a failure and every failure was infrastructure. -/
def infraOnly (failures : List Bool) : Bool := decide (failures ≠ []) && failures.all id
theorem one_package_failure_is_not_infra : infraOnly [true, false] = false := by decide
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
+15 -1
View File
@@ -234,7 +234,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,
@@ -242,6 +247,7 @@ func (a *App) initializeComponents() error {
DeletedRetention: a.config.Cache.DeletedRetention,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
ScanWaitTimeout: a.config.Security.ScanWaitTimeout,
})
if err != nil {
return fmt.Errorf("failed to initialize cache: %w", err)
@@ -319,7 +325,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
@@ -617,6 +626,11 @@ func (a *App) startWorkers(ctx context.Context) {
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
// Re-scans artifacts whose scan was lost to a restart and refreshes old results.
if a.rescanWorker != nil {
go a.rescanWorker.Start(ctx)
}
}
func (a *App) Run() error {
+56
View File
@@ -0,0 +1,56 @@
package app
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// A cached artifact whose scan never completed (lost to a restart) is scanned once the
// workers start, when security.rescan_interval is set.
func TestWorkersStartTheRescanWorker(t *testing.T) {
osv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"vulns":[]}`))
}))
defer osv.Close()
a := newTestApp(t, func(c *config.Config) {
c.Security.Enabled = true
c.Security.RescanInterval = time.Hour
c.Security.Scanners.OSV.Enabled = true
c.Security.Scanners.OSV.APIURL = osv.URL
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const key = "npm/left-pad/1.3.0"
if err := a.storage.Put(ctx, key, strings.NewReader("tarball"), nil); err != nil {
t.Fatalf("storage.Put: %v", err)
}
now := time.Now()
err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: key,
Size: 7, CachedAt: now, LastAccessed: now,
})
if err != nil {
t.Fatalf("SavePackage: %v", err)
}
a.startWorkers(ctx)
deadline := time.Now().Add(20 * time.Second)
for time.Now().Before(deadline) {
if _, err := a.metadata.GetScanResult(ctx, "npm", "left-pad", "1.3.0"); err == nil {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatal("no scan result after the workers started; the rescan worker never ran")
}
+58
View File
@@ -0,0 +1,58 @@
package app
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
)
// security.scan_wait_timeout bounds how long a first download waits for its scan; with
// fail_closed a slow scan is refused at that bound instead of the 30s default.
func TestScanWaitTimeoutComesFromConfig(t *testing.T) {
release := make(chan struct{})
osv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
<-release
_, _ = w.Write([]byte(`{"vulns":[]}`))
}))
defer osv.Close()
defer close(release)
a := newTestApp(t, func(c *config.Config) {
c.Security.Enabled = true
c.Security.FailClosed = true
c.Security.ScanWaitTimeout = 150 * time.Millisecond
c.Security.Scanners.OSV.Enabled = true
c.Security.Scanners.OSV.APIURL = osv.URL
})
fetch := func(context.Context) (*cache.FetchResult, error) {
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
}
start := time.Now()
_, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", fetch)
elapsed := time.Since(start)
var ghErr *errors.Error
if err == nil || !asError(err, &ghErr) || ghErr.Code != errors.ErrCodeServiceUnavailable {
t.Fatalf("Get = %v, want a service-unavailable refusal", err)
}
if elapsed > 5*time.Second {
t.Fatalf("refusal took %s; the configured 150ms wait was not applied", elapsed)
}
}
func asError(err error, target **errors.Error) bool {
e, ok := err.(*errors.Error)
if ok {
*target = e
}
return ok
}
+5
View File
@@ -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")
+71
View File
@@ -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)
}
+176
View File
@@ -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 -11
View File
@@ -174,17 +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
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
+118
View File
@@ -0,0 +1,118 @@
package scanner
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func stubResult(name string, status metadata.ScanStatus, details map[string]interface{}, vulns ...metadata.Vulnerability) *stubScanner {
return &stubScanner{name: name, result: &metadata.ScanResult{
ID: name, Scanner: name, ScannedAt: time.Now(), Status: status, Details: details,
Vulnerabilities: vulns, VulnerabilityCount: len(vulns),
}}
}
func scanWith(t *testing.T, cfg config.SecurityConfig, scanners ...Scanner) *metadata.ScanResult {
t.Helper()
store := &stubMetadataStore{}
mgr, err := New(cfg, store)
require.NoError(t, err)
t.Cleanup(mgr.Stop)
for _, s := range scanners {
mgr.RegisterScanner(s)
}
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
require.Len(t, store.savedResults, 1)
return store.savedResults[0]
}
func TestScanPackage_ErrorResultPlusCleanReadsClean(t *testing.T) {
for _, failClosed := range []bool{false, true} {
saved := scanWith(t, config.SecurityConfig{Enabled: true, FailClosed: failClosed},
stubResult("npm-audit", metadata.ScanStatusError, map[string]interface{}{"error": "parse"}),
stubResult("osv", metadata.ScanStatusClean, nil))
assert.Equal(t, metadata.ScanStatusClean, saved.Status, "fail_closed=%v", failClosed)
assert.Equal(t, "osv", saved.Scanner, "a failed scanner is not part of the merge")
assert.NotContains(t, saved.Details, "npm-audit")
}
}
func TestScanPackage_ErrorResultDoesNotHideFindings(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, nil),
stubResult("osv", metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "HIGH")))
assert.Equal(t, metadata.ScanStatusVulnerable, saved.Status)
assert.Len(t, saved.Vulnerabilities, 1)
}
func TestScanPackage_AllErrorResultsReadError(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, map[string]interface{}{"error": "parse"}),
stubResult("grype", metadata.ScanStatusError, nil))
assert.Equal(t, metadata.ScanStatusError, saved.Status)
assert.NotEqual(t, true, saved.Details[DetailInfrastructureError], "no failure was infrastructure")
}
func TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure(t *testing.T) {
infra := map[string]interface{}{DetailInfrastructureError: true}
t.Run("all infrastructure", func(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, infra),
stubResult("trivy", metadata.ScanStatusError, infra))
assert.Equal(t, metadata.ScanStatusError, saved.Status)
assert.Equal(t, true, saved.Details[DetailInfrastructureError])
})
t.Run("one other failure makes it a package failure", func(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, infra),
stubResult("grype", metadata.ScanStatusError, nil))
assert.NotEqual(t, true, saved.Details[DetailInfrastructureError])
})
}
func TestScanPackage_ErrorPlusCleanIsServedEvenWhenFailClosed(t *testing.T) {
cfg := config.SecurityConfig{Enabled: true, FailClosed: true}
saved := scanWith(t, cfg,
stubResult("npm-audit", metadata.ScanStatusError, nil),
stubResult("osv", metadata.ScanStatusClean, nil))
mgr, err := New(cfg, &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: saved})
require.NoError(t, err)
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.False(t, blocked, "reason %q", reason)
}
func TestScanPackage_BlockingStillAppliesToRealFindings(t *testing.T) {
cfg := config.SecurityConfig{Enabled: true, BlockOnSeverity: "high",
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}}
saved := scanWith(t, cfg,
stubResult("npm-audit", metadata.ScanStatusError, nil),
stubResult("osv", metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "HIGH")))
mgr, err := New(cfg, &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: saved})
require.NoError(t, err)
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.True(t, blocked)
}
func TestMergeResults_IgnoresErrorResults(t *testing.T) {
mgr := newTestManager(t, &stubMetadataStore{})
ok := stubResult("osv", metadata.ScanStatusClean, nil).result
bad := stubResult("grype", metadata.ScanStatusError, nil).result
assert.Equal(t, metadata.ScanStatusClean, mgr.mergeResults([]*metadata.ScanResult{bad, ok}, []string{"grype", "osv"}).Status)
assert.Equal(t, metadata.ScanStatusError, mgr.mergeResults([]*metadata.ScanResult{bad, bad}, []string{"a", "b"}).Status)
}
+20
View File
@@ -0,0 +1,20 @@
// Package gomodule maps a Go cache key to a module path.
package gomodule
import "strings"
// Path returns the module path of a cache key "module/@v/version.zip", with the module proxy's
// case encoding ("!a" is "A") reversed. A name without "/@v/" is taken as the module path.
func Path(cacheKey string) string {
module, _, _ := strings.Cut(cacheKey, "/@v/")
var b strings.Builder
for i := 0; i < len(module); i++ {
if module[i] == '!' && i+1 < len(module) {
i++
b.WriteString(strings.ToUpper(string(module[i])))
continue
}
b.WriteByte(module[i])
}
return b.String()
}
+13
View File
@@ -0,0 +1,13 @@
package gomodule
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestPath(t *testing.T) {
assert.Equal(t, "golang.org/x/text", Path("golang.org/x/text/@v/v0.3.5.zip"))
assert.Equal(t, "github.com/Azure/go-x", Path("github.com/!azure/go-x/@v/v1.2.3.zip"))
assert.Equal(t, "github.com/a/b/v2", Path("github.com/a/b/v2"))
}
+177 -88
View File
@@ -3,17 +3,24 @@
package govulncheck
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -64,62 +71,67 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting govulncheck scan")
// Create a temporary directory for extraction
module := gomodule.Path(packageName)
if !validModule.MatchString(module) || !validVersion.MatchString(version) {
return s.errorResult(ctx, registry, packageName, version,
fmt.Sprintf("not a module path and version: %q %q", module, version), ""), nil
}
tmpDir, err := os.MkdirTemp("", "govulncheck-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Extract the .zip file
if extractErr := s.extractZip(filePath, tmpDir); extractErr != nil {
return nil, fmt.Errorf("failed to extract zip: %w", extractErr)
// govulncheck never reports advisories against the main module of the tree it scans, so
// scanning the module's own source reports a vulnerable module clean. The module is
// scanned as a dependency of a wrapper module instead, and the wrapper imports its
// packages because module-mode scanning only considers modules that provide an import.
// Resolving the module reaches the module proxy.
env := append(os.Environ(), "GOFLAGS=-mod=mod", "GOTOOLCHAIN=local", "GOWORK=off")
goMod := fmt.Sprintf("module gohoarder.audit\n\nrequire %s %s\n", module, version)
if err = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte(goMod), 0o600); err != nil {
return nil, fmt.Errorf("failed to write go.mod: %w", err)
}
// Locate the Go module root (directory containing go.mod). Go modules
// in the proxy zip layout are nested under <module>@<version>/.
moduleDir, err := findGoModDir(tmpDir)
listCmd := exec.CommandContext(ctx, "go", "list", "-e", "-f", listFormat, module+"/...") // #nosec G204 -- module path is validated
listCmd.Dir = tmpDir
listCmd.Env = env
var listErr bytes.Buffer
listCmd.Stderr = &listErr
listOut, err := listCmd.Output()
if err != nil {
log.Warn().
Err(err).
Str("package", packageName).
Str("version", version).
Msg("Could not locate go.mod in extracted module, skipping govulncheck")
return s.skippedResult(registry, packageName, version, "no go.mod in extracted module"), nil
return s.errorResult(ctx, registry, packageName, version,
fmt.Sprintf("go list failed: %v: %s", err, strings.TrimSpace(listErr.String())), listErr.String()), nil
}
// Run govulncheck in source mode against the module's package set.
// -mode=binary requires a compiled binary which we do not have; the
// default (source) mode wants a Go source tree with a go.mod.
cmd := exec.CommandContext(ctx, "govulncheck", "-json", "./...") // #nosec G204 -- fixed args, cwd is controlled temp dir
cmd.Dir = moduleDir
output, _ := cmd.CombinedOutput()
imports := importable(string(listOut))
if len(imports) == 0 {
return s.skippedResult(registry, packageName, version, "no importable package in module"), nil
}
var mainSrc strings.Builder
mainSrc.WriteString("package main\n\nimport (\n")
for _, pkg := range imports {
fmt.Fprintf(&mainSrc, "\t_ %q\n", pkg)
}
mainSrc.WriteString(")\n\nfunc main() {}\n")
if err = os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte(mainSrc.String()), 0o600); err != nil {
return nil, fmt.Errorf("failed to write main.go: %w", err)
}
// govulncheck returns non-zero when vulnerabilities are found
// Parse output regardless of error
var vulns []GovulncheckVuln
if len(output) > 0 {
// Parse line-delimited JSON
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
var entry GovulncheckEntry
if err := json.Unmarshal([]byte(line), &entry); err != nil {
log.Warn().Err(err).Str("line", line).Msg("Failed to parse govulncheck line")
continue
}
if entry.Finding != nil && entry.Finding.OSV != "" {
vulns = append(vulns, GovulncheckVuln{
OSV: entry.Finding.OSV,
FixedVersion: entry.Finding.FixedVersion,
})
}
}
cmd := exec.CommandContext(ctx, "govulncheck", "-json", "-scan", "module") // #nosec G204 -- fixed args, cwd is controlled temp dir
cmd.Dir = tmpDir
cmd.Env = env
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // govulncheck -json exits 0 whether or not it finds anything
vulns, err := parseFindings(output)
if err != nil {
return s.errorResult(ctx, registry, packageName, version,
fmt.Sprintf("govulncheck failed: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
}
// Convert to our format
result := s.convertResult(vulns, registry, packageName, version)
log.Info().
@@ -131,6 +143,76 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
// listFormat prints "import-path name go-files cgo-files [ERR]" per package.
const listFormat = "{{.ImportPath}} {{.Name}} {{len .GoFiles}} {{len .CgoFiles}} {{if .Error}}ERR{{end}}"
var (
validModule = regexp.MustCompile(`^[A-Za-z0-9._~/-]+$`)
validVersion = regexp.MustCompile(`^v[0-9A-Za-z.+_-]+$`)
)
// importable lists the packages of `go list` output that another module can import.
func importable(listOut string) []string {
var pkgs []string
for _, line := range strings.Split(listOut, "\n") {
f := strings.Fields(line)
if len(f) < 4 || f[1] == "main" || (len(f) > 4 && f[4] == "ERR") {
continue
}
if f[2] == "0" && f[3] == "0" {
continue
}
if hasPathElement(f[0], "internal") || hasPathElement(f[0], "testdata") || hasPathElement(f[0], "vendor") {
continue
}
pkgs = append(pkgs, f[0])
}
return pkgs
}
func hasPathElement(importPath, element string) bool {
return slices.Contains(strings.Split(importPath, "/"), element)
}
// 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) {
summaries := make(map[string]string)
var vulns []GovulncheckVuln
seen := make(map[string]bool)
sawConfig := false
dec := json.NewDecoder(bytes.NewReader(output))
for {
var msg GovulncheckEntry
if err := dec.Decode(&msg); err == io.EOF {
break
} else if err != nil {
return nil, fmt.Errorf("parse govulncheck output: %w", err)
}
switch {
case msg.Config != nil:
sawConfig = true
case msg.OSV != nil:
summaries[msg.OSV.ID] = msg.OSV.Summary
case msg.Finding != nil && msg.Finding.OSV != "" && !seen[msg.Finding.OSV]:
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)
}
}
if !sawConfig {
return nil, errors.New("no config message in output")
}
for i := range vulns {
vulns[i].Summary = summaries[vulns[i].OSV]
}
return vulns, nil
}
// Health checks if govulncheck is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "govulncheck", "-version")
@@ -140,48 +222,26 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// extractZip extracts a zip file to destination
func (s *Scanner) extractZip(zipPath, destDir string) error {
cmd := exec.Command("unzip", "-q", zipPath, "-d", destDir)
return cmd.Run()
// errorResult returns a scan-error result. The manager leaves it out of the merge and counts it as
// an infrastructure failure when the context ended or the tool output shows the network was unreachable.
func (s *Scanner) errorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
return &metadata.ScanResult{
ID: uuid.New().String(),
Registry: registry,
PackageName: packageName,
PackageVersion: version,
Scanner: ScannerName,
ScannedAt: time.Now(),
Status: metadata.ScanStatusError,
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: scanerr.ErrorDetails(reason, infra),
}
}
// findGoModDir walks the directory tree under root looking for a directory
// that contains a go.mod file. The Go module proxy ships zips with layout
// "<module>@<version>/...", so the module root is typically one or two
// levels below the extraction directory. Returns an error if none is found.
func findGoModDir(root string) (string, error) {
// Quick check: does the root itself contain go.mod?
if _, err := os.Stat(filepath.Join(root, "go.mod")); err == nil {
return root, nil
}
var found string
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil // keep searching
}
if d.IsDir() {
return nil
}
if d.Name() == "go.mod" {
found = filepath.Dir(path)
return filepath.SkipAll
}
return nil
})
if err != nil {
return "", err
}
if found == "" {
return "", fmt.Errorf("go.mod not found under %s", root)
}
return found, nil
}
// skippedResult returns a clean ScanResult marked as skipped with an
// explanation. Using clean (not error) here because the package is simply
// not a Go module we can analyse — not a scanner failure.
// skippedResult returns a clean ScanResult marked as skipped with an explanation: the module has
// nothing another module can import, so there is nothing to audit.
func (s *Scanner) skippedResult(registry, packageName, version, reason string) *metadata.ScanResult {
return &metadata.ScanResult{
ID: uuid.New().String(),
@@ -221,7 +281,7 @@ func (s *Scanner) convertResult(vulns []GovulncheckVuln, registry, packageName,
ID: vuln.OSV,
Severity: severity,
Title: vuln.OSV,
Description: fmt.Sprintf("Vulnerability %s found by govulncheck", vuln.OSV),
Description: describe(vuln),
References: []string{fmt.Sprintf("https://pkg.go.dev/vuln/%s", vuln.OSV)},
FixedIn: vuln.FixedVersion,
})
@@ -249,17 +309,46 @@ func (s *Scanner) convertResult(vulns []GovulncheckVuln, registry, packageName,
}
}
// GovulncheckEntry represents a single line of govulncheck JSON output
func describe(v GovulncheckVuln) string {
desc := v.Summary
if desc == "" {
desc = "Vulnerability " + v.OSV
}
if v.Module != "" {
desc += fmt.Sprintf(" (%s@%s)", v.Module, v.ModuleVersion)
}
return desc
}
// GovulncheckEntry is one message of govulncheck's JSON stream; exactly one field is set.
type GovulncheckEntry struct {
Config *struct{} `json:"config,omitempty"`
OSV *GovulncheckOSV `json:"osv,omitempty"`
Finding *GovulncheckFinding `json:"finding,omitempty"`
}
// GovulncheckOSV is the advisory a finding refers to.
type GovulncheckOSV struct {
ID string `json:"id"`
Summary string `json:"summary"`
}
type GovulncheckFinding struct {
OSV string `json:"osv"`
FixedVersion string `json:"fixed_version,omitempty"`
OSV string `json:"osv"`
FixedVersion string `json:"fixed_version,omitempty"`
Trace []GovulncheckModule `json:"trace"`
}
// GovulncheckModule is the module a finding is in.
type GovulncheckModule struct {
Module string `json:"module"`
Version string `json:"version"`
}
type GovulncheckVuln struct {
OSV string
FixedVersion string
OSV string
FixedVersion string
Module string
ModuleVersion string
Summary string
}
+194
View File
@@ -0,0 +1,194 @@
package govulncheck
import (
"archive/zip"
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The .stream fixtures are real govulncheck 1.9.0 `-json` output, cut down to the config, finding and
// referenced osv messages, and real `go list` output (see FINDINGS GH-25).
func abs(t *testing.T, name string) string {
t.Helper()
p, err := filepath.Abs(filepath.Join("testdata", name))
require.NoError(t, err)
return p
}
// module is a zip as the module proxy serves it; the scanner audits the module by path and version.
func module(t *testing.T) string {
t.Helper()
p := filepath.Join(t.TempDir(), "m.zip")
f, err := os.Create(p) // #nosec G304 -- test temp dir
require.NoError(t, err)
zw := zip.NewWriter(f)
w, err := zw.Create("example.com/[email protected]/go.mod")
require.NoError(t, err)
_, err = w.Write([]byte("module example.com/m\n"))
require.NoError(t, err)
require.NoError(t, zw.Close())
require.NoError(t, f.Close())
return p
}
// fakeGo fakes `go list`, recording the working directory's go.mod and main.go for the audit.
func fakeGo(t *testing.T, listFixture string, exit int, stderr string) (rec string) {
t.Helper()
rec = t.TempDir()
body := fmt.Sprintf(`
case "$1" in
list) cp go.mod %[1]q/go.mod; echo "$GOFLAGS|$GOTOOLCHAIN" > %[1]q/env; %[2]s; printf '%%s' %[3]q >&2; exit %[4]d ;;
esac`, rec, catOrNothing(listFixture), stderr, exit)
scannertest.Script(t, "go", body)
return rec
}
func catOrNothing(path string) string {
if path == "" {
return "true"
}
return "cat " + fmt.Sprintf("%q", path)
}
// fakeGovulncheck fakes govulncheck: it records main.go and the arguments, prints fixture.
func fakeGovulncheck(t *testing.T, fixture string, exit int, stderr string) (argsFile, mainCopy string) {
t.Helper()
dir := t.TempDir()
argsFile = filepath.Join(dir, "args")
mainCopy = filepath.Join(dir, "main.go")
scannertest.Script(t, "govulncheck", fmt.Sprintf(`
cp main.go %[2]q
for a in "$@"; do echo "$a" >> %[1]q; done
%[3]s
printf '%%s' %[4]q >&2
exit %[5]d`, argsFile, mainCopy, catOrNothing(fixture), stderr, exit))
return argsFile, mainCopy
}
func ids(res *metadata.ScanResult) map[string]string {
out := map[string]string{}
for _, v := range res.Vulnerabilities {
out[v.ID] = v.FixedIn
}
return out
}
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, "")
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")
}
func TestScanAuditsTheModuleItself(t *testing.T) {
rec := fakeGo(t, abs(t, "golist-x-text-v0.3.5.txt"), 0, "")
args, mainCopy := fakeGovulncheck(t, abs(t, "x-text-v0.3.5.stream"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "golang.org/x/text/@v/v0.3.5.zip", "v0.3.5", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.Equal(t, map[string]string{
"GO-2021-0113": "v0.3.7", "GO-2022-1059": "v0.3.8", "GO-2026-5970": "v0.39.0", "GO-2026-6629": "v0.41.0",
}, ids(res), "advisories against the scanned module, which a scan of its own source never reports")
for _, v := range res.Vulnerabilities {
assert.Equal(t, "HIGH", v.Severity)
assert.Equal(t, []string{"https://pkg.go.dev/vuln/" + v.ID}, v.References)
}
gomod, err := os.ReadFile(filepath.Join(rec, "go.mod")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Contains(t, string(gomod), "require golang.org/x/text v0.3.5")
env, err := os.ReadFile(filepath.Join(rec, "env")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Equal(t, "-mod=mod|local\n", string(env))
assert.Equal(t, []string{"-json", "-scan", "module"}, scannertest.Args(t, args))
src, err := os.ReadFile(mainCopy) // #nosec G304 -- test temp dir
require.NoError(t, err)
imports := string(src)
assert.Contains(t, imports, `_ "golang.org/x/text/language"`)
assert.NotContains(t, imports, "/cmd/gotext\"", "package main cannot be imported")
assert.NotContains(t, imports, "/internal", "internal packages cannot be imported")
}
func TestScanCleanModule(t *testing.T) {
scannertest.Script(t, "go", `echo "github.com/google/uuid uuid 12 0 "`)
_, _ = fakeGovulncheck(t, abs(t, "google-uuid-v1.6.0.stream"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
func TestScanModuleWithoutImportablePackagesIsSkipped(t *testing.T) {
scannertest.Script(t, "go", `echo "example.com/m/cmd/tool main 1 0 "`)
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
assert.Contains(t, res.Details["skipped"], "no importable package")
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
setup func(t *testing.T)
name string
infra bool
}{
{name: "module download fails on the network", setup: func(t *testing.T) { fakeGo(t, "", 1, "dial tcp: lookup proxy.golang.org: no such host") }, infra: true},
{name: "module is not in the proxy", setup: func(t *testing.T) { fakeGo(t, "", 1, "reading example.com/m/@v/v1.0.0.mod: 404 Not Found") }, infra: false},
{name: "govulncheck prints nothing", setup: func(t *testing.T) {
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
fakeGovulncheck(t, "", 1, "govulncheck: loading packages: boom")
}, infra: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
tc.setup(t)
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanRefusesModuleCoordinatesThatCouldInjectGoMod(t *testing.T) {
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "example.com/m/@v/v1.0.0\nreplace x => y.zip", "v1.0.0\nreplace a => b", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "npm", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
@@ -0,0 +1,338 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "symbol",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-5024",
"modified": "2026-05-22T18:28:47Z",
"published": "2026-05-22T18:28:47Z",
"aliases": [
"CVE-2026-39824"
],
"summary": "Invoking integer overflow in NewNTUnicodeString in golang.org/x/sys/windows",
"details": "NewNTUnicodeString does not check for string length overflow. When provided with a string that overflows the maximum size of a NTUnicodeString (a 16-bit number of bytes), it returns a truncated string rather than an error.",
"affected": [
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.44.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/windows",
"goos": [
"windows"
],
"symbols": [
"NewNTUnicodeString"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/78916"
},
{
"type": "FIX",
"url": "https://go.dev/cl/770080"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/6MMI8Lj-Atg"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-5024",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
{
"finding": {
"osv": "GO-2022-0493",
"fixed_version": "v0.0.0-20220412211240-33da011f77ad",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
{
"finding": {
"osv": "GO-2026-5024",
"fixed_version": "v0.44.0",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
{
"finding": {
"osv": "GO-2022-0493",
"fixed_version": "v0.0.0-20220412211240-33da011f77ad",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42",
"package": "golang.org/x/sys/unix"
}
]
}
}
+522
View File
@@ -0,0 +1,522 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "module",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2021-0052",
"modified": "2024-05-20T16:03:47Z",
"published": "2021-04-14T20:04:52Z",
"aliases": [
"CVE-2020-28483",
"GHSA-h395-qcrw-5vmq"
],
"summary": "Inconsistent interpretation of HTTP Requests in github.com/gin-gonic/gin",
"details": "Due to improper HTTP header sanitization, a malicious user can spoof their source IP address by setting the X-Forwarded-For header. This may allow a user to bypass IP based restrictions, or obfuscate their true source.",
"affected": [
{
"package": {
"name": "github.com/gin-gonic/gin",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.7.7"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "github.com/gin-gonic/gin",
"symbols": [
"Context.ClientIP",
"Context.Next",
"Context.RemoteIP",
"Engine.HandleContext",
"Engine.Run",
"Engine.RunFd",
"Engine.RunListener",
"Engine.RunTLS",
"Engine.RunUnix",
"Engine.ServeHTTP"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/2862"
},
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/2473"
},
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/2232"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/2844"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/commit/5929d521715610c9dd14898ebbe1d188d5de8937"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/2632"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/commit/bfc8ca285eb46dad60e037d57c545cd260636711"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/2675"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/commit/03e5e05ae089bc989f1ca41841f05504d29e3fd9"
},
{
"type": "WEB",
"url": "https://github.com/gin-gonic/gin/pull/2474"
}
],
"credits": [
{
"name": "@sorenisanerd"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2021-0052",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2023-1737",
"modified": "2024-05-20T16:03:47Z",
"published": "2023-05-11T18:59:56Z",
"aliases": [
"CVE-2023-29401",
"GHSA-2c4m-59x9-fr2g"
],
"summary": "Improper handling of filenames in Content-Disposition HTTP header in github.com/gin-gonic/gin",
"details": "The filename parameter of the Context.FileAttachment function is not properly sanitized. A maliciously crafted filename can cause the Content-Disposition header to be sent with an unexpected filename value or otherwise modify the Content-Disposition header. For example, a filename of \"setup.bat&quot;;x=.txt\" will be sent as a file named \"setup.bat\".\n\nIf the FileAttachment function is called with names provided by an untrusted source, this may permit an attacker to cause a file to be served with a name different than provided. Maliciously crafted attachment file name can modify the Content-Disposition header.",
"affected": [
{
"package": {
"name": "github.com/gin-gonic/gin",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "1.3.1-0.20190301021747-ccb9e902956d"
},
{
"fixed": "1.9.1"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "github.com/gin-gonic/gin",
"symbols": [
"Context.FileAttachment"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/3555"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/3556"
},
{
"type": "WEB",
"url": "https://github.com/gin-gonic/gin/releases/tag/v1.9.1"
}
],
"credits": [
{
"name": "motoyasu-saburi"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2023-1737",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-5024",
"modified": "2026-05-22T18:28:47Z",
"published": "2026-05-22T18:28:47Z",
"aliases": [
"CVE-2026-39824"
],
"summary": "Invoking integer overflow in NewNTUnicodeString in golang.org/x/sys/windows",
"details": "NewNTUnicodeString does not check for string length overflow. When provided with a string that overflows the maximum size of a NTUnicodeString (a 16-bit number of bytes), it returns a truncated string rather than an error.",
"affected": [
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.44.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/windows",
"goos": [
"windows"
],
"symbols": [
"NewNTUnicodeString"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/78916"
},
{
"type": "FIX",
"url": "https://go.dev/cl/770080"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/6MMI8Lj-Atg"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-5024",
"review_status": "REVIEWED"
}
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
{
"finding": {
"osv": "GO-2021-0052",
"fixed_version": "v1.7.7",
"trace": [
{
"module": "github.com/gin-gonic/gin",
"version": "v1.6.0"
}
]
}
}
{
"finding": {
"osv": "GO-2023-1737",
"fixed_version": "v1.9.1",
"trace": [
{
"module": "github.com/gin-gonic/gin",
"version": "v1.6.0"
}
]
}
}
{
"finding": {
"osv": "GO-2022-0493",
"fixed_version": "v0.0.0-20220412211240-33da011f77ad",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
{
"finding": {
"osv": "GO-2026-5024",
"fixed_version": "v0.44.0",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
@@ -0,0 +1,6 @@
github.com/gin-gonic/gin gin 18 0
github.com/gin-gonic/gin/binding binding 13 0
github.com/gin-gonic/gin/ginS ginS 1 0
github.com/gin-gonic/gin/internal/bytesconv bytesconv 1 0
github.com/gin-gonic/gin/internal/json json 1 0
github.com/gin-gonic/gin/render render 11 0
@@ -0,0 +1,63 @@
golang.org/x/text text 1 0
golang.org/x/text/cases cases 7 0
golang.org/x/text/cmd/gotext main 7 0
golang.org/x/text/cmd/gotext/examples/extract main 2 0
golang.org/x/text/cmd/gotext/examples/extract_http main 2 0
golang.org/x/text/cmd/gotext/examples/extract_http/pkg pkg 1 0
golang.org/x/text/cmd/gotext/examples/rewrite main 1 0
golang.org/x/text/collate collate 5 0
golang.org/x/text/collate/build build 6 0
golang.org/x/text/collate/tools/colcmp main 4 0
golang.org/x/text/currency currency 5 0
golang.org/x/text/date date 1 0
golang.org/x/text/encoding encoding 1 0
golang.org/x/text/encoding/charmap charmap 2 0
golang.org/x/text/encoding/htmlindex htmlindex 3 0
golang.org/x/text/encoding/ianaindex ianaindex 3 0
golang.org/x/text/encoding/internal internal 1 0
golang.org/x/text/encoding/internal/enctest enctest 1 0
golang.org/x/text/encoding/internal/identifier identifier 2 0
golang.org/x/text/encoding/japanese japanese 5 0
golang.org/x/text/encoding/korean korean 2 0
golang.org/x/text/encoding/simplifiedchinese simplifiedchinese 4 0
golang.org/x/text/encoding/traditionalchinese traditionalchinese 2 0
golang.org/x/text/encoding/unicode unicode 2 0
golang.org/x/text/encoding/unicode/utf32 utf32 1 0
golang.org/x/text/feature/plural plural 4 0
golang.org/x/text/internal internal 2 0
golang.org/x/text/internal/catmsg catmsg 3 0
golang.org/x/text/internal/cldrtree cldrtree 5 0
golang.org/x/text/internal/colltab colltab 8 0
golang.org/x/text/internal/export/idna idna 5 0
golang.org/x/text/internal/export/unicode unicode 1 0
golang.org/x/text/internal/format format 2 0
golang.org/x/text/internal/gen gen 2 0
golang.org/x/text/internal/gen/bitfield bitfield 1 0
golang.org/x/text/internal/language language 10 0
golang.org/x/text/internal/language/compact compact 5 0
golang.org/x/text/internal/number number 7 0
golang.org/x/text/internal/stringset stringset 1 0
golang.org/x/text/internal/tag tag 1 0
golang.org/x/text/internal/testtext testtext 5 0
golang.org/x/text/internal/triegen triegen 3 0
golang.org/x/text/internal/ucd ucd 1 0
golang.org/x/text/internal/utf8internal utf8internal 1 0
golang.org/x/text/language language 8 0
golang.org/x/text/language/display display 4 0
golang.org/x/text/message message 5 0
golang.org/x/text/message/catalog catalog 3 0
golang.org/x/text/message/pipeline pipeline 5 0
golang.org/x/text/number number 4 0
golang.org/x/text/runes runes 2 0
golang.org/x/text/search search 4 0
golang.org/x/text/secure secure 1 0
golang.org/x/text/secure/bidirule bidirule 2 0
golang.org/x/text/secure/precis precis 10 0
golang.org/x/text/transform transform 1 0
golang.org/x/text/unicode unicode 1 0
golang.org/x/text/unicode/bidi bidi 6 0
golang.org/x/text/unicode/cldr cldr 7 0
golang.org/x/text/unicode/norm norm 9 0
golang.org/x/text/unicode/rangetable rangetable 3 0
golang.org/x/text/unicode/runenames runenames 2 0
golang.org/x/text/width width 5 0
@@ -0,0 +1,22 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "module",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
+369
View File
@@ -0,0 +1,369 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "module",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2021-0113",
"modified": "2024-05-20T16:03:47Z",
"published": "2021-10-06T17:51:21Z",
"aliases": [
"CVE-2021-38561",
"GHSA-ppp9-7jff-5vj2"
],
"summary": "Out-of-bounds read in golang.org/x/text/language",
"details": "Due to improper index calculation, an incorrectly formatted language tag can cause Parse to panic via an out of bounds read. If Parse is used to process untrusted user inputs, this may be used as a vector for a denial of service attack.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.3.7"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/language",
"symbols": [
"MatchStrings",
"MustParse",
"Parse",
"ParseAcceptLanguage"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/340830"
},
{
"type": "FIX",
"url": "https://go.googlesource.com/text/+/383b2e75a7a4198c42f8f87833eefb772868a56f"
}
],
"credits": [
{
"name": "Guido Vranken"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2021-0113",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-1059",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-10-11T18:16:24Z",
"aliases": [
"CVE-2022-32149",
"GHSA-69ch-w2m2-3vjp"
],
"summary": "Denial of service via crafted Accept-Language header in golang.org/x/text/language",
"details": "An attacker may cause a denial of service by crafting an Accept-Language header which ParseAcceptLanguage will take significant time to parse.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.3.8"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/language",
"symbols": [
"MatchStrings",
"ParseAcceptLanguage"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/56152"
},
{
"type": "FIX",
"url": "https://go.dev/cl/442235"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/-hjNw559_tE/m/KlGTfid5CAAJ"
}
],
"credits": [
{
"name": "Adam Korczynski (ADA Logics)"
},
{
"name": "OSS-Fuzz"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-1059",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-5970",
"modified": "2026-08-10T22:42:36Z",
"published": "2026-07-14T17:29:56Z",
"aliases": [
"CVE-2026-56852"
],
"summary": "Infinite loop on invalid input in golang.org/x/text",
"details": "A norm.Iter can enter an infinite loop when handling input containing invalid UTF-8 bytes.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.39.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/unicode/norm",
"symbols": [
"Form.Append",
"Form.AppendString",
"Form.Bytes",
"Form.FirstBoundary",
"Form.FirstBoundaryInString",
"Form.IsNormal",
"Form.IsNormalString",
"Form.LastBoundary",
"Form.NextBoundary",
"Form.NextBoundaryInString",
"Form.Properties",
"Form.PropertiesString",
"Form.QuickSpan",
"Form.QuickSpanString",
"Form.Span",
"Form.SpanString",
"Form.String",
"Form.Transform",
"Iter.Init",
"Iter.InitString",
"Iter.Next",
"Iter.Seek",
"nextComposed",
"normReader.Read",
"normWriter.Write"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/80142"
},
{
"type": "FIX",
"url": "https://go.dev/cl/794100"
}
],
"credits": [
{
"name": "Viky Choi (\"vikychoi\" on GitHub)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-5970",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-6629",
"modified": "2026-10-07T14:09:43Z",
"published": "2026-10-07T14:09:43Z",
"aliases": [
"CVE-2026-56851"
],
"summary": "Panic parsing crafted input in x/text/secure/precis in golang.org/x/text",
"details": "The Nickname profile can panic with an out-of-bounds slice error when transforming crafted input into a short destination buffer.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.41.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/secure/precis",
"symbols": [
"Profile.Append",
"Profile.AppendCompareKey",
"Profile.Bytes",
"Profile.Compare",
"Profile.CompareKey",
"Profile.NewTransformer",
"Profile.String",
"Transformer.Bytes",
"Transformer.String",
"Transformer.Transform",
"nickAdditionalMapping.Transform"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/793360"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/80112"
}
],
"credits": [
{
"name": "Omkhar Arasaratnam (GitHub: omkhar)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-6629",
"review_status": "REVIEWED"
}
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
{
"finding": {
"osv": "GO-2021-0113",
"fixed_version": "v0.3.7",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
{
"finding": {
"osv": "GO-2022-1059",
"fixed_version": "v0.3.8",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
{
"finding": {
"osv": "GO-2026-5970",
"fixed_version": "v0.39.0",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
{
"finding": {
"osv": "GO-2026-6629",
"fixed_version": "v0.41.0",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
+46 -16
View File
@@ -3,14 +3,17 @@
package grype
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os/exec"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -44,25 +47,25 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("file", filePath).
Msg("Starting Grype scan")
// Run grype scan
cmd := exec.CommandContext(ctx, "grype", filePath, "-o", "json", "-q")
output, err := cmd.CombinedOutput()
if err != nil {
// Grype returns non-zero exit code when vulnerabilities are found
// Only treat it as error if we got no output
if len(output) == 0 {
return nil, fmt.Errorf("grype scan failed: %w (output: %s)", err, string(output))
}
target := purl(registry, packageName, version)
if target == "" {
target = filePath
}
cmd := exec.CommandContext(ctx, "grype", target, "-o", "json", "-q") // #nosec G204 -- target is a purl or the stored artifact path
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil && len(output) == 0 {
return nil, fmt.Errorf("grype scan failed: %w (stderr: %s)", err, strings.TrimSpace(stderr.String()))
}
// Parse Grype JSON output
var grypeResult GrypeResult
if err := json.Unmarshal(output, &grypeResult); err != nil {
return nil, fmt.Errorf("failed to parse grype output: %w", err)
grypeResult, err := parse(output)
if err != nil {
return nil, err
}
// Convert to our format
result := s.convertGrypeResult(&grypeResult, registry, packageName, version)
result := s.convertGrypeResult(grypeResult, registry, packageName, version)
log.Info().
Str("scanner", ScannerName).
@@ -73,6 +76,33 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
// purl names the package for grype. A bare npm, PyPI or Go archive has no lockfile or installed
// metadata, so grype catalogs nothing in it and reports clean; a purl is matched against the
// database directly. Empty means no purl can be built.
func purl(registry, name, version string) string {
if name == "" || version == "" {
return ""
}
version = strings.ReplaceAll(version, "+", "%2B")
switch registry {
case "npm":
return "pkg:npm/" + strings.Replace(name, "@", "%40", 1) + "@" + version
case "go":
return "pkg:golang/" + gomodule.Path(name) + "@" + version
case "pypi":
return "pkg:pypi/" + strings.ToLower(strings.NewReplacer("_", "-", ".", "-").Replace(name)) + "@" + version
}
return ""
}
func parse(output []byte) (*GrypeResult, error) {
var res GrypeResult
if err := json.Unmarshal(output, &res); err != nil {
return nil, fmt.Errorf("failed to parse grype output: %w", err)
}
return &res, nil
}
// Health checks if Grype is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "grype", "version")
@@ -166,8 +196,8 @@ type GrypeDescriptor struct {
}
type GrypeSource struct {
Target map[string]interface{} `json:"target"`
Type string `json:"type"`
Type string `json:"type"`
Target json.RawMessage `json:"target"` // a string for file, directory and purl sources, an object for images
}
type GrypeMatch struct {
+126
View File
@@ -0,0 +1,126 @@
package grype
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The fixtures are real `grype -o json -q` output from grype 0.121.2 (see FINDINGS GH-25).
func fixture(name string) string { return filepath.Join("testdata", name) }
func TestParseFileScanTargetIsAString(t *testing.T) {
data, err := os.ReadFile(fixture("file-minimist-0.0.8.json"))
require.NoError(t, err)
res, err := parse(data)
require.NoError(t, err)
assert.Equal(t, "file", res.Source.Type)
}
func TestScanMapsRealOutput(t *testing.T) {
cases := []struct {
wantSeverities map[string]string
wantFixedIn map[string]string
name, fixture, registry, pkg, version string
wantPurl string
wantStatus metadata.ScanStatus
}{
{
name: "npm vulnerable", fixture: "purl-minimist-0.0.8.json", registry: "npm", pkg: "minimist", version: "0.0.8",
wantPurl: "pkg:npm/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
wantSeverities: map[string]string{"GHSA-xvch-5gv4-984h": "CRITICAL", "GHSA-vh95-rmgr-6w4m": "MODERATE"},
wantFixedIn: map[string]string{"GHSA-xvch-5gv4-984h": "0.2.4"},
},
{
name: "npm clean", fixture: "purl-dayjs-1.11.13.json", registry: "npm", pkg: "dayjs", version: "1.11.13",
wantPurl: "pkg:npm/[email protected]", wantStatus: metadata.ScanStatusClean,
},
{
name: "go vulnerable", fixture: "purl-go-text-0.3.5.json", registry: "go", pkg: "golang.org/x/text/@v/v0.3.5.zip", version: "v0.3.5",
wantPurl: "pkg:golang/golang.org/x/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
wantSeverities: map[string]string{"GHSA-69ch-w2m2-3vjp": "HIGH", "GO-2026-6629": "HIGH"},
},
{
name: "pypi vulnerable", fixture: "purl-pypi-requests-2.19.0.json", registry: "pypi", pkg: "requests", version: "2.19.0",
wantPurl: "pkg:pypi/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
wantSeverities: map[string]string{"GHSA-x84v-xcm2-53pg": "HIGH", "GHSA-j8r2-6x86-q33q": "MODERATE"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
args := scannertest.Fake(t, "grype", fixture(tc.fixture), "", 0)
res, err := New(config.GrypeConfig{}).Scan(context.Background(), tc.registry, tc.pkg, tc.version, "/tmp/artifact")
require.NoError(t, err)
assert.Equal(t, tc.wantStatus, res.Status)
assert.Equal(t, tc.wantPurl, scannertest.Args(t, args)[0], "the package is scanned by purl, not by its archive")
got := map[string]string{}
fixed := map[string]string{}
for _, v := range res.Vulnerabilities {
got[v.ID] = v.Severity
fixed[v.ID] = v.FixedIn
}
for id, sev := range tc.wantSeverities {
assert.Equal(t, sev, got[id], id)
}
for id, f := range tc.wantFixedIn {
assert.Equal(t, f, fixed[id], id)
}
assert.Equal(t, len(res.Vulnerabilities), res.VulnerabilityCount)
})
}
}
func TestScanFallsBackToFileForUnknownRegistry(t *testing.T) {
args := scannertest.Fake(t, "grype", fixture("file-minimist-0.0.8.json"), "", 0)
res, err := New(config.GrypeConfig{}).Scan(context.Background(), "docker", "x", "1", "/tmp/artifact.tar")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
assert.Equal(t, "/tmp/artifact.tar", scannertest.Args(t, args)[0])
}
func TestScanIgnoresStderrNoise(t *testing.T) {
scannertest.Fake(t, "grype", fixture("purl-dayjs-1.11.13.json"), "[0000] WARN something\n", 0)
res, err := New(config.GrypeConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", "/tmp/a.tgz")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
func TestScanFailureWithoutOutputIsAnError(t *testing.T) {
scannertest.Fake(t, "grype", "", "failed to load vulnerability db", 1)
_, err := New(config.GrypeConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", "/tmp/a.tgz")
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to load vulnerability db")
}
func TestPurl(t *testing.T) {
cases := []struct{ registry, name, version, want string }{
{"npm", "left-pad", "1.3.0", "pkg:npm/[email protected]"},
{"npm", "@babel/traverse", "7.0.0", "pkg:npm/%40babel/[email protected]"},
{"go", "github.com/!azure/go-x/@v/v1.2.3.zip", "v1.2.3", "pkg:golang/github.com/Azure/[email protected]"},
{"go", "github.com/a/b/v2/@v/v2.0.0+incompatible.zip", "v2.0.0+incompatible", "pkg:golang/github.com/a/b/[email protected]%2Bincompatible"},
{"pypi", "Zope.Interface_x", "5.0", "pkg:pypi/[email protected]"},
{"npm", "", "1", ""},
{"npm", "x", "", ""},
{"docker", "x", "1", ""},
}
for _, tc := range cases {
assert.Equal(t, tc.want, purl(tc.registry, tc.name, tc.version), "%s %s", tc.registry, tc.name)
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+68
View File
@@ -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)
}
}
+151 -107
View File
@@ -3,16 +3,20 @@
package npmaudit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -63,71 +67,60 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting npm audit scan")
// Create a temporary directory
tmpDir, err := os.MkdirTemp("", "npm-audit-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Extract the .tgz file
if err := s.extractTgz(filePath, tmpDir); err != nil {
return nil, fmt.Errorf("failed to extract tgz: %w", err)
if err = writeWrapper(tmpDir, packageName, filePath); err != nil {
return s.scanErrorResult(ctx, registry, packageName, version, fmt.Sprintf("prepare audit project: %v", err), ""), nil
}
// Find the package directory (usually "package/")
packageDir := filepath.Join(tmpDir, "package")
if _, err := os.Stat(packageDir); os.IsNotExist(err) {
// Try the tmpDir itself
packageDir = tmpDir
}
// npm tarballs ship only package.json — there is no lockfile. We must
// generate one before `npm audit` can resolve the dependency tree.
// NOTE: this performs network egress (npm registry lookups for
// transitive deps). Acceptable here because the scanner runs server-
// side and the operator already trusts upstream resolution to cache
// the package; we use --ignore-scripts to avoid running install hooks.
// npm audit needs a lockfile and a tarball ships none. The tarball is installed into a
// wrapper project, so its own advisories are audited with its production dependencies, and
// its devDependencies are never resolved. This step reaches the npm registry.
log.Info().
Str("scanner", ScannerName).
Str("package", packageName).
Msg("Generating package-lock.json for npm audit (network egress)")
installCmd := exec.CommandContext(ctx, "npm", "install",
installCmd := exec.CommandContext(ctx, "npm", "install", // #nosec G204 -- fixed args
"--package-lock-only",
"--omit=dev",
"--ignore-scripts",
"--no-audit",
"--no-fund",
)
installCmd.Dir = packageDir
if installOut, err := installCmd.CombinedOutput(); err != nil {
installCmd.Dir = tmpDir
if installOut, installErr := installCmd.CombinedOutput(); installErr != nil {
log.Warn().
Err(err).
Err(installErr).
Str("package", packageName).
Str("output", string(installOut)).
Msg("npm install --package-lock-only failed; returning scan-error")
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("npm install --package-lock-only failed: %v", err)), nil
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("npm install --package-lock-only failed: %v", installErr), string(installOut)), nil
}
// Run npm audit against the freshly generated lockfile.
cmd := exec.CommandContext(ctx, "npm", "audit", "--json")
cmd.Dir = packageDir
output, _ := cmd.CombinedOutput() // npm audit returns non-zero when vulns found
cmd := exec.CommandContext(ctx, "npm", "audit", "--omit=dev", "--json") // #nosec G204 -- fixed args
cmd.Dir = tmpDir
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // npm audit exits non-zero when it finds vulnerabilities
// Parse npm audit output
var auditResult NpmAuditResult
if len(output) > 0 {
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Msg("Failed to parse npm audit output")
// Parse failure means we couldn't determine vulnerability state — fail closed.
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("failed to parse npm audit output: %v", err)), nil
}
auditResult, err := parse(output)
if err != nil {
log.Warn().Err(err).Msg("Failed to parse npm audit output")
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("failed to parse npm audit output: %v", err), stderr.String()), nil
}
if auditResult.Error != nil {
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("npm audit failed: %s %s", auditResult.Error.Code, auditResult.Error.Summary), stderr.String()), nil
}
// Convert to our format
result := s.convertResult(&auditResult, registry, packageName, version)
result := s.convertResult(auditResult, registry, packageName, version)
log.Info().
Str("scanner", ScannerName).
@@ -138,6 +131,44 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
// wrapperTarball is the archive's name inside the wrapper project.
const wrapperTarball = "artifact.tgz"
// writeWrapper makes dir a project whose only dependency is the archive.
func writeWrapper(dir, packageName, archive string) error {
src, err := os.Open(archive) // #nosec G304 -- path from the cache, not user input
if err != nil {
return err
}
defer func() { _ = src.Close() }()
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
dst, err := root.Create(wrapperTarball)
if err != nil {
return err
}
if _, err = io.Copy(dst, src); err != nil {
_ = dst.Close()
return err
}
if err = dst.Close(); err != nil {
return err
}
manifest, err := json.Marshal(map[string]interface{}{
"name": "gohoarder-audit",
"version": "1.0.0",
"private": true,
"dependencies": map[string]string{packageName: "file:./" + wrapperTarball},
})
if err != nil {
return err
}
return root.WriteFile("package.json", manifest, 0o600)
}
// Health checks if npm is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "npm", "--version")
@@ -147,18 +178,11 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// extractTgz extracts a .tgz file
func (s *Scanner) extractTgz(tgzPath, destDir string) error {
cmd := exec.Command("tar", "-xzf", tgzPath, "-C", destDir)
return cmd.Run()
}
// emptyResult returns an empty scan result
// scanErrorResult returns a result marked as scan-error so the manager merge
// and CheckVulnerabilities can fail closed. Use this when the scan could not
// complete and we therefore have no signal about vulnerabilities.
func (s *Scanner) scanErrorResult(registry, packageName, version, reason string) *metadata.ScanResult {
// scanErrorResult returns a result marked scan-error. The manager leaves it out of the merge
// and counts it as an infrastructure failure when the context ended or the tool output shows
// the network was unreachable.
func (s *Scanner) scanErrorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
return &metadata.ScanResult{
ID: uuid.New().String(),
Registry: registry,
@@ -169,9 +193,7 @@ func (s *Scanner) scanErrorResult(registry, packageName, version, reason string)
Status: metadata.ScanStatusError,
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: map[string]interface{}{
"error": reason,
},
Details: scanerr.ErrorDetails(reason, infra),
}
}
@@ -180,37 +202,35 @@ func (s *Scanner) convertResult(auditResult *NpmAuditResult, registry, packageNa
vulnerabilities := make([]metadata.Vulnerability, 0)
severityCounts := make(map[string]int)
// Process vulnerabilities from the audit result
for _, vuln := range auditResult.Vulnerabilities {
// Normalize severity
normalizedSeverity := metadata.NormalizeSeverity(vuln.Severity)
severityCounts[normalizedSeverity]++
// Get references
refs := make([]string, 0)
if vuln.URL != "" {
refs = append(refs, vuln.URL)
}
for _, ref := range vuln.References {
if ref.URL != "" {
refs = append(refs, ref.URL)
// Each advisory is listed once, under the package it affects. A string in `via` only says
// that the package is affected through another one, whose own entry lists the advisory.
seen := make(map[int]bool)
names := make([]string, 0, len(auditResult.Vulnerabilities))
for name := range auditResult.Vulnerabilities {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
for _, via := range auditResult.Vulnerabilities[name].Via {
adv := via.Advisory
if adv == nil || seen[adv.Source] {
continue
}
seen[adv.Source] = true
normalizedSeverity := metadata.NormalizeSeverity(adv.Severity)
severityCounts[normalizedSeverity]++
refs := make([]string, 0, 1)
if adv.URL != "" {
refs = append(refs, adv.URL)
}
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
ID: advisoryID(adv),
Severity: normalizedSeverity,
Title: adv.Title,
Description: fmt.Sprintf("%s: %s (affected %s)", adv.Name, adv.Title, adv.Range),
References: refs,
})
}
// Get fixed version
fixedIn := ""
if vuln.FixAvailable != nil {
fixedIn = fmt.Sprintf("%v", vuln.FixAvailable)
}
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
ID: vuln.Via,
Severity: normalizedSeverity,
Title: vuln.Name,
Description: vuln.Name,
References: refs,
FixedIn: fixedIn,
})
}
status := metadata.ScanStatusClean
@@ -234,38 +254,62 @@ func (s *Scanner) convertResult(auditResult *NpmAuditResult, registry, packageNa
}
}
// NpmAuditResult represents npm audit JSON output
// advisoryID is the GHSA id from the advisory URL, or the npm advisory number.
func advisoryID(adv *NpmAdvisory) string {
if i := strings.LastIndex(adv.URL, "/"); i >= 0 && i+1 < len(adv.URL) {
return adv.URL[i+1:]
}
return fmt.Sprintf("npm:%d", adv.Source)
}
func parse(output []byte) (*NpmAuditResult, error) {
var res NpmAuditResult
if err := json.Unmarshal(output, &res); err != nil {
return nil, err
}
return &res, nil
}
// NpmAuditResult represents `npm audit --json` output (auditReportVersion 2), or its error document.
type NpmAuditResult struct {
Vulnerabilities map[string]NpmVulnerability `json:"vulnerabilities"`
Metadata NpmAuditMetadata `json:"metadata"`
AuditReportVersion int `json:"auditReportVersion"`
Vulnerabilities map[string]NpmVulnerability `json:"vulnerabilities"`
Error *NpmAuditError `json:"error"`
}
// NpmAuditError is the document npm prints in place of a report, e.g. ENOLOCK.
type NpmAuditError struct {
Code string `json:"code"`
Summary string `json:"summary"`
}
// NpmVulnerability is one affected package.
type NpmVulnerability struct {
Name string `json:"name"`
Severity string `json:"severity"`
Via string `json:"via"`
Effects []string `json:"effects"`
Range string `json:"range"`
FixAvailable interface{} `json:"fixAvailable"`
URL string `json:"url"`
References []NpmReference `json:"references"`
Name string `json:"name"`
Severity string `json:"severity"`
Via []NpmVia `json:"via"`
}
type NpmReference struct {
URL string `json:"url"`
// NpmVia is a package name (affected through that package) or an advisory.
type NpmVia struct {
Advisory *NpmAdvisory
Package string
}
type NpmAuditMetadata struct {
Vulnerabilities NpmVulnCounts `json:"vulnerabilities"`
Dependencies int `json:"dependencies"`
// UnmarshalJSON accepts both shapes of an element of `via`.
func (v *NpmVia) UnmarshalJSON(data []byte) error {
if len(data) > 0 && data[0] == '"' {
return json.Unmarshal(data, &v.Package)
}
v.Advisory = &NpmAdvisory{}
return json.Unmarshal(data, v.Advisory)
}
type NpmVulnCounts struct {
Info int `json:"info"`
Low int `json:"low"`
Moderate int `json:"moderate"`
High int `json:"high"`
Critical int `json:"critical"`
Total int `json:"total"`
// NpmAdvisory is a security advisory attached to a package.
type NpmAdvisory struct {
Name string `json:"name"`
Title string `json:"title"`
URL string `json:"url"`
Severity string `json:"severity"`
Range string `json:"range"`
Source int `json:"source"`
}
+204
View File
@@ -0,0 +1,204 @@
package npmaudit
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The fixtures are real `npm audit --json` output from npm 11.12.1 (see FINDINGS GH-25).
func fixture(name string) string { return filepath.Join("testdata", name) }
func readFixture(t *testing.T, name string) []byte {
t.Helper()
data, err := os.ReadFile(fixture(name))
require.NoError(t, err)
return data
}
func severities(res *metadata.ScanResult) map[string]string {
out := map[string]string{}
for _, v := range res.Vulnerabilities {
out[v.ID] = v.Severity
}
return out
}
func TestParseKeepsBothViaShapes(t *testing.T) {
// `via` is an array of package names for a transitive finding and an array of advisory
// objects for a direct one; mkdirp-0.5.1.json has both, the dev-tree file many of each.
for _, name := range []string{"dayjs-1.11.13.json", "minimist-0.0.8.json", "mkdirp-0.5.1.json", "request-2.88.2.json", "mkdirp-0.5.1-dev-tree.json"} {
t.Run(name, func(t *testing.T) {
_, err := parse(readFixture(t, name))
require.NoError(t, err)
})
}
}
func TestConvertMapsAdvisories(t *testing.T) {
cases := []struct {
want map[string]string
fixture string
}{
{fixture: "dayjs-1.11.13.json", want: map[string]string{}},
{fixture: "minimist-0.0.8.json", want: map[string]string{"GHSA-vh95-rmgr-6w4m": "MODERATE", "GHSA-xvch-5gv4-984h": "CRITICAL"}},
// mkdirp has no advisory of its own: its entry only points at minimist.
{fixture: "mkdirp-0.5.1.json", want: map[string]string{"GHSA-vh95-rmgr-6w4m": "MODERATE", "GHSA-xvch-5gv4-984h": "CRITICAL"}},
{fixture: "request-2.88.2.json", want: map[string]string{
"GHSA-fjxv-7rqg-78g4": "CRITICAL", "GHSA-hmw2-7cc7-3qxx": "HIGH", "GHSA-6rw7-vpxm-498p": "MODERATE",
"GHSA-4mjr-xmp4-gh2g": "MODERATE", "GHSA-p8p7-x288-28g6": "MODERATE", "GHSA-72xf-g2v4-qvf3": "MODERATE",
"GHSA-w5hq-g745-h8pq": "MODERATE",
}},
}
for _, tc := range cases {
t.Run(tc.fixture, func(t *testing.T) {
audit, err := parse(readFixture(t, tc.fixture))
require.NoError(t, err)
res := New(config.NpmAuditConfig{}).convertResult(audit, "npm", "p", "1")
assert.Equal(t, tc.want, severities(res))
assert.Equal(t, len(tc.want), res.VulnerabilityCount)
if len(tc.want) == 0 {
assert.Equal(t, metadata.ScanStatusClean, res.Status)
} else {
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
}
})
}
}
func TestConvertCarriesTitleAndReference(t *testing.T) {
audit, err := parse(readFixture(t, "minimist-0.0.8.json"))
require.NoError(t, err)
res := New(config.NpmAuditConfig{}).convertResult(audit, "npm", "minimist", "0.0.8")
ids := make([]string, 0)
for _, v := range res.Vulnerabilities {
ids = append(ids, v.ID)
assert.Equal(t, "Prototype Pollution in minimist", v.Title)
assert.Equal(t, []string{"https://github.com/advisories/" + v.ID}, v.References)
}
sort.Strings(ids)
assert.Equal(t, []string{"GHSA-vh95-rmgr-6w4m", "GHSA-xvch-5gv4-984h"}, ids)
}
// npmScript fakes npm: `install` exits installExit, `audit` prints stdout and exits 1.
func npmScript(t *testing.T, auditFixture string, installExit int, installStderr string) (recDir string) {
t.Helper()
recDir = t.TempDir()
audit := "cat " + fmt.Sprintf("%q", mustAbs(t, auditFixture))
if auditFixture == "" {
audit = "printf '%s' 'not json'"
}
scannertest.Script(t, "npm", fmt.Sprintf(`
case "$1" in
install) cat package.json > %[1]q/package.json; echo "$@" > %[1]q/install; printf '%%s' %[2]q >&2; exit %[3]d ;;
audit) echo "$@" > %[1]q/audit; %[4]s; exit 1 ;;
esac`, recDir, installStderr, installExit, audit))
return recDir
}
func mustAbs(t *testing.T, name string) string {
t.Helper()
if name == "" {
return ""
}
abs, err := filepath.Abs(fixture(name))
require.NoError(t, err)
return abs
}
func artifact(t *testing.T) string {
t.Helper()
p := filepath.Join(t.TempDir(), "pkg.tgz")
require.NoError(t, os.WriteFile(p, []byte("tgz"), 0o600))
return p
}
func TestScanAuditsThePackageItselfWithoutItsDevTree(t *testing.T) {
rec := npmScript(t, "minimist-0.0.8.json", 0, "")
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "minimist", "0.0.8", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.Len(t, res.Vulnerabilities, 2)
pkgJSON, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
require.NoError(t, err)
var wrapper struct {
Dependencies map[string]string `json:"dependencies"`
}
require.NoError(t, json.Unmarshal(pkgJSON, &wrapper))
assert.Equal(t, map[string]string{"minimist": "file:./artifact.tgz"}, wrapper.Dependencies,
"the tarball is a dependency of a wrapper project, so its own advisories are audited and its devDependencies are never resolved")
audit, err := os.ReadFile(filepath.Join(rec, "audit")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Contains(t, string(audit), "--omit=dev")
}
func TestScanCleanPackage(t *testing.T) {
npmScript(t, "dayjs-1.11.13.json", 0, "")
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
name string
fixture string
installOut string
installRC int
infra bool
}{
{"network down", "", "npm error code ENOTFOUND", 1, true},
{"unresolvable tree", "", "npm error code ERESOLVE", 1, false},
{"unparseable audit", "", "", 0, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
npmScript(t, tc.fixture, tc.installRC, tc.installOut)
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "p", "1", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanAuditErrorDocumentIsAnErrorResult(t *testing.T) {
doc := filepath.Join(t.TempDir(), "enolock.json")
require.NoError(t, os.WriteFile(doc, []byte(`{"error":{"code":"ENOLOCK","summary":"This command requires an existing lockfile.","detail":""}}`), 0o600))
scannertest.Script(t, "npm", fmt.Sprintf(`case "$1" in audit) cat %q; exit 1 ;; esac`, doc))
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "p", "1", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Contains(t, res.Details["error"], "ENOLOCK")
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
+22
View File
@@ -0,0 +1,22 @@
{
"auditReportVersion": 2,
"vulnerabilities": {},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
},
"dependencies": {
"prod": 2,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 1
}
}
}
+68
View File
@@ -0,0 +1,68 @@
{
"auditReportVersion": 2,
"vulnerabilities": {
"minimist": {
"name": "minimist",
"severity": "critical",
"isDirect": true,
"via": [
{
"source": 1096466,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-vh95-rmgr-6w4m",
"severity": "moderate",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 5.6,
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L"
},
"range": "<0.2.1"
},
{
"source": 1097677,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-xvch-5gv4-984h",
"severity": "critical",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 9.8,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
},
"range": "<0.2.4"
}
],
"effects": [],
"range": "<=0.2.3",
"nodes": [
"node_modules/minimist"
],
"fixAvailable": false
}
},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 1,
"total": 1
},
"dependencies": {
"prod": 2,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 1
}
}
}
File diff suppressed because it is too large Load Diff
+84
View File
@@ -0,0 +1,84 @@
{
"auditReportVersion": 2,
"vulnerabilities": {
"minimist": {
"name": "minimist",
"severity": "critical",
"isDirect": false,
"via": [
{
"source": 1096466,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-vh95-rmgr-6w4m",
"severity": "moderate",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 5.6,
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L"
},
"range": "<0.2.1"
},
{
"source": 1097677,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-xvch-5gv4-984h",
"severity": "critical",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 9.8,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
},
"range": "<0.2.4"
}
],
"effects": [
"mkdirp"
],
"range": "<=0.2.3",
"nodes": [
"node_modules/minimist"
],
"fixAvailable": false
},
"mkdirp": {
"name": "mkdirp",
"severity": "critical",
"isDirect": true,
"via": [
"minimist"
],
"effects": [],
"range": "0.4.1 - 0.5.1",
"nodes": [
"node_modules/mkdirp"
],
"fixAvailable": false
}
},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 2,
"total": 2
},
"dependencies": {
"prod": 3,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 2
}
}
}
+214
View File
@@ -0,0 +1,214 @@
{
"auditReportVersion": 2,
"vulnerabilities": {
"form-data": {
"name": "form-data",
"severity": "critical",
"isDirect": false,
"via": [
{
"source": 1109540,
"name": "form-data",
"dependency": "form-data",
"title": "form-data uses unsafe random function in form-data for choosing boundary",
"url": "https://github.com/advisories/GHSA-fjxv-7rqg-78g4",
"severity": "critical",
"cwe": [
"CWE-330"
],
"cvss": {
"score": 0,
"vectorString": null
},
"range": "<2.5.4"
},
{
"source": 1120745,
"name": "form-data",
"dependency": "form-data",
"title": "form-data: CRLF injection in form-data via unescaped multipart field names and filenames",
"url": "https://github.com/advisories/GHSA-hmw2-7cc7-3qxx",
"severity": "high",
"cwe": [
"CWE-93"
],
"cvss": {
"score": 7.5,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N"
},
"range": "<2.5.6"
}
],
"effects": [
"request"
],
"range": "<=2.5.5",
"nodes": [
"node_modules/form-data"
],
"fixAvailable": false
},
"qs": {
"name": "qs",
"severity": "moderate",
"isDirect": false,
"via": [
{
"source": 1113719,
"name": "qs",
"dependency": "qs",
"title": "qs's arrayLimit bypass in its bracket notation allows DoS via memory exhaustion",
"url": "https://github.com/advisories/GHSA-6rw7-vpxm-498p",
"severity": "moderate",
"cwe": [
"CWE-20"
],
"cvss": {
"score": 3.7,
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L"
},
"range": "<6.14.1"
},
{
"source": 1158507,
"name": "qs",
"dependency": "qs",
"title": "qs: Denial of Service via Attacker Controlled isBuffer",
"url": "https://github.com/advisories/GHSA-4mjr-xmp4-gh2g",
"severity": "moderate",
"cwe": [
"CWE-248",
"CWE-703"
],
"cvss": {
"score": 5.3,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L"
},
"range": ">=2.2.5 <6.16.0"
}
],
"effects": [
"request"
],
"range": "<=6.15.4",
"nodes": [
"node_modules/qs"
],
"fixAvailable": false
},
"request": {
"name": "request",
"severity": "critical",
"isDirect": true,
"via": [
{
"source": 1096727,
"name": "request",
"dependency": "request",
"title": "Server-Side Request Forgery in Request",
"url": "https://github.com/advisories/GHSA-p8p7-x288-28g6",
"severity": "moderate",
"cwe": [
"CWE-918"
],
"cvss": {
"score": 6.1,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"
},
"range": "<=2.88.2"
},
"form-data",
"qs",
"tough-cookie",
"uuid"
],
"effects": [],
"range": "*",
"nodes": [
"node_modules/request"
],
"fixAvailable": false
},
"tough-cookie": {
"name": "tough-cookie",
"severity": "moderate",
"isDirect": false,
"via": [
{
"source": 1097682,
"name": "tough-cookie",
"dependency": "tough-cookie",
"title": "tough-cookie Prototype Pollution vulnerability",
"url": "https://github.com/advisories/GHSA-72xf-g2v4-qvf3",
"severity": "moderate",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 6.5,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N"
},
"range": "<4.1.3"
}
],
"effects": [
"request"
],
"range": "<4.1.3",
"nodes": [
"node_modules/tough-cookie"
],
"fixAvailable": false
},
"uuid": {
"name": "uuid",
"severity": "moderate",
"isDirect": false,
"via": [
{
"source": 1119441,
"name": "uuid",
"dependency": "uuid",
"title": "uuid: Missing buffer bounds check in v3/v5/v6 when buf is provided",
"url": "https://github.com/advisories/GHSA-w5hq-g745-h8pq",
"severity": "moderate",
"cwe": [
"CWE-787",
"CWE-1285"
],
"cvss": {
"score": 7.5,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N"
},
"range": "<11.1.1"
}
],
"effects": [
"request"
],
"range": "<11.1.1",
"nodes": [
"node_modules/uuid"
],
"fixAvailable": false
}
},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 3,
"high": 0,
"critical": 2,
"total": 5
},
"dependencies": {
"prod": 48,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 47
}
}
}
-35
View File
@@ -1,35 +0,0 @@
package pipaudit
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyInto(t *testing.T) {
s := &Scanner{}
src := filepath.Join(t.TempDir(), "pkg.whl")
require.NoError(t, os.WriteFile(src, []byte("wheel"), 0600))
t.Run("copies inside dir", func(t *testing.T) {
dir := t.TempDir()
require.NoError(t, s.copyInto(src, dir, "pkg.whl"))
got, err := os.ReadFile(filepath.Join(dir, "pkg.whl"))
require.NoError(t, err)
require.Equal(t, "wheel", string(got))
})
t.Run("refuses name escaping dir", func(t *testing.T) {
parent := t.TempDir()
dir := filepath.Join(parent, "sub")
require.NoError(t, os.Mkdir(dir, 0750))
require.Error(t, s.copyInto(src, dir, "../escape.whl"))
require.NoFileExists(t, filepath.Join(parent, "escape.whl"))
})
t.Run("missing source", func(t *testing.T) {
require.Error(t, s.copyInto(filepath.Join(t.TempDir(), "none"), t.TempDir(), "x"))
})
}
+47 -128
View File
@@ -3,17 +3,20 @@
package pipaudit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -64,47 +67,43 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting pip-audit scan")
// Create a temporary directory
if !validName.MatchString(packageName) || !validVersion.MatchString(version) {
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("not a project name and version: %q %q", packageName, version), ""), nil
}
tmpDir, err := os.MkdirTemp("", "pip-audit-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Copy the wheel/tar.gz file to temp directory
tmpFile := filepath.Join(tmpDir, filepath.Base(filePath))
if err := s.copyInto(filePath, tmpDir, filepath.Base(tmpFile)); err != nil {
return nil, fmt.Errorf("failed to copy file: %w", err)
// pip-audit has no wheel or sdist input: its positional argument is a project directory. The
// release is audited by its pinned name and version. --no-deps and --disable-pip keep it to
// that release, with no resolution of its dependencies.
reqFile := filepath.Join(tmpDir, "requirements.txt")
if err := os.WriteFile(reqFile, []byte(packageName+"=="+version+"\n"), 0o600); err != nil {
return nil, fmt.Errorf("failed to write requirements: %w", err)
}
// Build the appropriate pip-audit invocation based on artifact type.
// `-r` expects requirements.txt — passing a wheel/tarball there is wrong.
// Wheels can be scanned directly via positional arg. Source distributions
// (tarballs) need to be extracted; if they contain a pyproject.toml we
// can scan that, otherwise we fail closed.
cmd, prepErr := s.buildAuditCmd(ctx, tmpDir, tmpFile)
if prepErr != nil {
log.Warn().
Err(prepErr).
Str("package", packageName).
Str("version", version).
Msg("pip-audit could not prepare input artifact, returning scan-error")
return s.scanErrorResult(registry, packageName, version, prepErr.Error()), nil
}
output, _ := cmd.CombinedOutput() // pip-audit returns non-zero when vulns found
cmd := exec.CommandContext(ctx, "pip-audit", "-r", reqFile, "--no-deps", "--disable-pip", "-f", "json") // #nosec G204 -- name and version are validated, file is in a controlled temp dir
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // pip-audit exits non-zero when it finds vulnerabilities
// Parse pip-audit output
var auditResult PipAuditResult
if len(output) > 0 {
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Msg("Failed to parse pip-audit output")
// Parse failure → no signal → fail closed.
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("failed to parse pip-audit output: %v", err)), nil
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Str("stderr", stderr.String()).Msg("Failed to parse pip-audit output")
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("failed to parse pip-audit output: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
}
for _, dep := range auditResult.Dependencies {
if dep.SkipReason != "" {
// pip-audit exits 0 for a package it could not audit; that is no verdict.
return s.scanErrorResult(ctx, registry, packageName, version, dep.SkipReason, ""), nil
}
}
// Convert to our format
result := s.convertResult(&auditResult, registry, packageName, version)
log.Info().
@@ -116,6 +115,11 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
var (
validName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
validVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.+!_-]*$`)
)
// Health checks if pip-audit is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "pip-audit", "--version")
@@ -125,98 +129,10 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// copyInto copies src to name inside dir; name cannot escape dir.
func (s *Scanner) copyInto(src, dir, name string) error {
input, err := os.ReadFile(src) // #nosec G304 -- Source path is from scanner, controlled
if err != nil {
return err
}
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
return root.WriteFile(name, input, 0600)
}
// buildAuditCmd constructs the right pip-audit command for the input artifact.
//
// - .whl -> pip-audit <wheel> --format json
// - .tar.gz / .tgz / .zip (sdist) -> extract; if pyproject.toml exists
// run `pip-audit --pyproject <pyproject> --format json`; otherwise error.
//
// extractDir is used as a workspace for sdist extraction.
func (s *Scanner) buildAuditCmd(ctx context.Context, extractDir, artifact string) (*exec.Cmd, error) {
lower := strings.ToLower(artifact)
switch {
case strings.HasSuffix(lower, ".whl"):
// pip-audit can scan a wheel directly via positional argument.
return exec.CommandContext(ctx, "pip-audit", artifact, "--format", "json"), nil // #nosec G204 -- artifact path is in controlled tmp dir
case strings.HasSuffix(lower, ".tar.gz"),
strings.HasSuffix(lower, ".tgz"),
strings.HasSuffix(lower, ".zip"):
// Source distributions must be unpacked first.
sdistDir := filepath.Join(extractDir, "sdist")
if err := os.MkdirAll(sdistDir, 0o750); err != nil {
return nil, fmt.Errorf("create sdist dir: %w", err)
}
if err := s.extractSdist(artifact, sdistDir); err != nil {
return nil, fmt.Errorf("extract sdist: %w", err)
}
pyproject, err := findPyProject(sdistDir)
if err != nil {
return nil, fmt.Errorf("no pyproject.toml in sdist: %w", err)
}
return exec.CommandContext(ctx, "pip-audit", "--pyproject", pyproject, "--format", "json"), nil // #nosec G204 -- pyproject path under controlled tmp dir
default:
return nil, fmt.Errorf("unsupported pip artifact extension: %s", filepath.Base(artifact))
}
}
// extractSdist unpacks a Python source distribution into destDir.
func (s *Scanner) extractSdist(archive, destDir string) error {
lower := strings.ToLower(archive)
switch {
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
return exec.Command("tar", "-xzf", archive, "-C", destDir).Run()
case strings.HasSuffix(lower, ".zip"):
return exec.Command("unzip", "-q", archive, "-d", destDir).Run()
default:
return fmt.Errorf("unknown archive type: %s", archive)
}
}
// findPyProject returns the path to a pyproject.toml within root, walking
// one level deep (sdists typically extract to <pkg>-<ver>/).
func findPyProject(root string) (string, error) {
var found string
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
if d.Name() == "pyproject.toml" {
found = path
return filepath.SkipAll
}
return nil
})
if err != nil {
return "", err
}
if found == "" {
return "", fmt.Errorf("pyproject.toml not found under %s", root)
}
return found, nil
}
// scanErrorResult returns a result marked scan-error so manager merge and
// CheckVulnerabilities can fail closed when this scanner could not run.
func (s *Scanner) scanErrorResult(registry, packageName, version, reason string) *metadata.ScanResult {
// scanErrorResult returns a scan-error result. The manager leaves it out of the merge and counts it
// as an infrastructure failure when the context ended or the tool output shows the network was unreachable.
func (s *Scanner) scanErrorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
return &metadata.ScanResult{
ID: uuid.New().String(),
Registry: registry,
@@ -227,21 +143,23 @@ func (s *Scanner) scanErrorResult(registry, packageName, version, reason string)
Status: metadata.ScanStatusError,
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: map[string]interface{}{
"error": reason,
},
Details: scanerr.ErrorDetails(reason, infra),
}
}
// emptyResult returns an empty scan result
// convertResult converts pip-audit output to our ScanResult format
func (s *Scanner) convertResult(auditResult *PipAuditResult, registry, packageName, version string) *metadata.ScanResult {
vulnerabilities := make([]metadata.Vulnerability, 0)
severityCounts := make(map[string]int)
seen := make(map[string]bool)
for _, dep := range auditResult.Dependencies {
for _, vuln := range dep.Vulns {
// pip-audit lists an advisory once per alias.
if seen[vuln.ID] {
continue
}
seen[vuln.ID] = true
// Map pip-audit severity to our standard
severity := s.mapSeverity(vuln.ID)
normalizedSeverity := metadata.NormalizeSeverity(severity)
@@ -298,9 +216,10 @@ type PipAuditResult struct {
}
type PipDependency struct {
Name string `json:"name"`
Version string `json:"version"`
Vulns []PipVuln `json:"vulns"`
Name string `json:"name"`
Version string `json:"version"`
SkipReason string `json:"skip_reason"`
Vulns []PipVuln `json:"vulns"`
}
type PipVuln struct {
+142
View File
@@ -0,0 +1,142 @@
package pipaudit
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The fixtures are real `pip-audit -f json` output from pip-audit 2.10.1 (see FINDINGS GH-25); the
// example proxy credential in the requests 2.19.0 advisory text is replaced by a placeholder.
func fixture(name string) string { return filepath.Join("testdata", name) }
func ids(res *metadata.ScanResult) []string {
out := make([]string, 0, len(res.Vulnerabilities))
for _, v := range res.Vulnerabilities {
out = append(out, v.ID)
}
return out
}
// artifactNamed is a stand-in for the cached file: the scanner audits the release by name and version.
func artifactNamed(t *testing.T, name string) string {
t.Helper()
p := filepath.Join(t.TempDir(), name)
require.NoError(t, os.WriteFile(p, []byte("x"), 0o600))
return p
}
func TestScanAuditsTheReleaseFromARequirement(t *testing.T) {
// pip-audit has no wheel argument: its positional argument is a project directory, and it
// has no --pyproject flag. A wheel or sdist is audited by name and version.
for _, file := range []string{"requests-2.19.0-py2.py3-none-any.whl", "requests-2.19.0.tar.gz"} {
t.Run(file, func(t *testing.T) {
args := scannertest.Fake(t, "pip-audit", fixture("requests-2.19.0.json"), "WARNING:pip_audit._cli:--no-deps is supported\n", 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "requests", "2.19.0", artifactNamed(t, file))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.ElementsMatch(t, []string{"PYSEC-2018-28", "PYSEC-2023-74", "PYSEC-2026-1872", "PYSEC-2026-1873", "PYSEC-2026-2275"}, ids(res),
"pip-audit lists an advisory once per alias; the result lists it once")
assert.Equal(t, 5, res.VulnerabilityCount)
got := scannertest.Args(t, args)
assert.Equal(t, []string{"-r"}, got[:1])
assert.Equal(t, []string{"--no-deps", "--disable-pip", "-f", "json"}, got[2:])
})
}
}
func TestScanWritesAPinnedRequirement(t *testing.T) {
dir := t.TempDir()
scannertest.Script(t, "pip-audit", `cat "$2" > `+filepath.Join(dir, "req")+`; cat `+mustAbs(t, "six-1.16.0.json"))
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "six", "1.16.0", artifactNamed(t, "six-1.16.0-py2.py3-none-any.whl"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
req, err := os.ReadFile(filepath.Join(dir, "req")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Equal(t, "six==1.16.0\n", string(req))
}
func mustAbs(t *testing.T, name string) string {
t.Helper()
p, err := filepath.Abs(fixture(name))
require.NoError(t, err)
return p
}
func TestScanSeverityAndFix(t *testing.T) {
scannertest.Fake(t, "pip-audit", fixture("requests-2.32.0.json"), "", 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "requests", "2.32.0", artifactNamed(t, "requests-2.32.0.tar.gz"))
require.NoError(t, err)
fixed := map[string]string{}
for _, v := range res.Vulnerabilities {
fixed[v.ID] = v.FixedIn
assert.Equal(t, "MODERATE", v.Severity, "pip-audit reports no severity")
}
assert.Equal(t, map[string]string{"PYSEC-2026-1872": "2.32.4", "PYSEC-2026-2275": "2.33.0"}, fixed)
}
func TestScanPackageUnknownToPyPIIsAnError(t *testing.T) {
// pip-audit exits 0 with a skip_reason; reading that as clean would pass an unaudited package.
scannertest.Fake(t, "pip-audit", fixture("not-on-pypi.json"), "", 0)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "nopkg-zzz", "1.0", artifactNamed(t, "nopkg_zzz-1.0.tar.gz"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Contains(t, res.Details["error"], "not found on PyPI")
assert.Equal(t, false, res.Details[scanerr.DetailInfrastructure])
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
name, stderr string
infra bool
}{
{"network", "ERROR: HTTPSConnectionPool: Max retries exceeded: ConnectionError ECONNREFUSED", true},
{"other", "ERROR:pip_audit._cli:boom", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
scannertest.Fake(t, "pip-audit", "", tc.stderr, 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "six", "1.16.0", artifactNamed(t, "six-1.16.0.tar.gz"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanRefusesNameAndVersionThatCouldBeOptions(t *testing.T) {
args := scannertest.Fake(t, "pip-audit", fixture("six-1.16.0.json"), "", 0)
for _, c := range [][2]string{{"--index-url=http://evil", "1.0"}, {"six", "1.0\n--index-url=x"}, {"", "1.0"}, {"six", ""}} {
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", c[0], c[1], artifactNamed(t, "x.whl"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status, "%q %q", c[0], c[1])
}
_, statErr := os.Stat(args)
assert.True(t, os.IsNotExist(statErr), "pip-audit never ran")
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "npm", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "nopkg-zzz", "skip_reason": "Dependency not found on PyPI and could not be audited: nopkg-zzz (1.0)"}], "fixes": []}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "requests", "version": "2.32.0", "vulns": [{"id": "PYSEC-2026-1872", "fix_versions": ["2.32.4"], "aliases": ["CVE-2024-47081", "GHSA-9hjg-9r4m-mvj7"], "description": "### Impact Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak .netrc credentials to third parties for specific maliciously-crafted URLs. ### Workarounds For older versions of Requests, use of the .netrc file can be disabled with `trust_env=False` on your Requests Session ([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)). ### References https://github.com/psf/requests/pull/6965 https://seclists.org/fulldisclosure/2025/Jun/2"}, {"id": "PYSEC-2026-2275", "fix_versions": ["2.33.0"], "aliases": ["CVE-2026-25645", "GHSA-gc5v-m9x4-r6x2"], "description": "### Impact The `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting files from zip archives into the system temporary directory. If the target file already exists, it is reused without validation. A local attacker with write access to the temp directory could pre-create a malicious file that would be loaded in place of the legitimate one. ### Affected usages **Standard usage of the Requests library is not affected by this vulnerability.** Only applications that call `extract_zipped_paths()` directly are impacted. ### Remediation Upgrade to at least Requests 2.33.0, where the library now extracts files to a non-deterministic location. If developers are unable to upgrade, they can set `TMPDIR` in their environment to a directory with restricted write access."}, {"id": "PYSEC-2026-1872", "fix_versions": ["2.32.4"], "aliases": ["CVE-2024-47081", "GHSA-9hjg-9r4m-mvj7"], "description": "### Impact Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak .netrc credentials to third parties for specific maliciously-crafted URLs. ### Workarounds For older versions of Requests, use of the .netrc file can be disabled with `trust_env=False` on your Requests Session ([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)). ### References https://github.com/psf/requests/pull/6965 https://seclists.org/fulldisclosure/2025/Jun/2"}, {"id": "PYSEC-2026-2275", "fix_versions": ["2.33.0"], "aliases": ["CVE-2026-25645", "GHSA-gc5v-m9x4-r6x2"], "description": "Requests is a HTTP library. Prior to version 2.33.0, the `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting files from zip archives into the system temporary directory. If the target file already exists, it is reused without validation. A local attacker with write access to the temp directory could pre-create a malicious file that would be loaded in place of the legitimate one. Standard usage of the Requests library is not affected by this vulnerability. Only applications that call `extract_zipped_paths()` directly are impacted. Starting in version 2.33.0, the library extracts files to a non-deterministic location. If developers are unable to upgrade, they can set `TMPDIR` in their environment to a directory with restricted write access."}]}], "fixes": []}
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "six", "version": "1.16.0", "vulns": []}], "fixes": []}
+166 -94
View File
@@ -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
+161
View File
@@ -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)
}
+21
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"net"
"net/http"
"strings"
)
// ErrInfrastructure marks a failure of the scanning machinery (timeout,
@@ -44,3 +45,23 @@ func IsInfrastructure(err error) bool {
}
return false
}
// DetailInfrastructure is the scan-result detail key that marks an error result as infrastructure.
const DetailInfrastructure = "infrastructure_error"
// ErrorDetails builds the Details of a scan-error result.
func ErrorDetails(reason string, infra bool) map[string]interface{} {
return map[string]interface{}{"error": reason, DetailInfrastructure: infra}
}
var networkMarkers = []string{"ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED", "ECONNRESET", "EAI_AGAIN", "i/o timeout", "no such host", "connection refused"}
// NetworkFailure reports whether a tool's output shows it could not reach the network.
func NetworkFailure(output string) bool {
for _, m := range networkMarkers {
if strings.Contains(output, m) {
return true
}
}
return false
}
+68 -11
View File
@@ -48,7 +48,7 @@ type DatabaseUpdater interface {
const (
// DetailInfrastructureError marks a stored scan-error result as caused by
// scanner infrastructure (timeout, upstream 5xx) rather than by the package.
DetailInfrastructureError = "infrastructure_error"
DetailInfrastructureError = scanerr.DetailInfrastructure
defaultScanRetryInterval = 5 * time.Minute
maxScanRetries = 6
@@ -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
@@ -326,6 +336,22 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
continue
}
// A scanner that returns an error-status result failed exactly like one
// that returns an error: another scanner's verdict still stands.
if result.Status == metadata.ScanStatusError {
log.Error().
Str("scanner", scanner.Name()).
Str("package", packageName).
Interface("details", result.Details).
Msg("Scanner returned an error result")
if infra, _ := result.Details[DetailInfrastructureError].(bool); infra {
infraFailures++
} else {
otherFailures++
}
continue
}
scanResults = append(scanResults, result)
scannerNames = append(scannerNames, scanner.Name())
@@ -430,13 +456,36 @@ func (m *Manager) scanVersion(ctx context.Context, registry, packageName, versio
return pkg.ReleaseVersion
}
// succeeded drops error-status results; a failed scanner leaves no trace in the merge.
func succeeded(results []*metadata.ScanResult, names []string) ([]*metadata.ScanResult, []string) {
okResults := make([]*metadata.ScanResult, 0, len(results))
okNames := make([]string, 0, len(results))
for i, r := range results {
if r.Status == metadata.ScanStatusError {
continue
}
okResults = append(okResults, r)
okNames = append(okNames, names[i])
}
return okResults, okNames
}
// mergeResults merges and deduplicates scan results from multiple scanners
func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []string) *metadata.ScanResult {
if len(results) == 0 {
return nil
}
// Use first result as base
results, scannerNames = succeeded(results, scannerNames)
// Use first result as base, or the failure itself when none succeeded
if len(results) == 0 {
return &metadata.ScanResult{
Status: metadata.ScanStatusError,
Vulnerabilities: make([]metadata.Vulnerability, 0),
Details: map[string]interface{}{"error": "all scanners failed"},
}
}
merged := &metadata.ScanResult{
ID: results[0].ID,
Registry: results[0].Registry,
@@ -506,19 +555,13 @@ func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []st
}
}
// Update status to worst case.
// Order: vulnerable > error > pending > clean. Vulnerable wins because
// the cache layer must surface the actual vulns. Otherwise, if any
// scanner errored, propagate so CheckVulnerabilities can fail closed.
// Update status to worst case: vulnerable > pending > clean.
// Error results never reach this loop (see succeeded).
switch result.Status {
case metadata.ScanStatusVulnerable:
merged.Status = metadata.ScanStatusVulnerable
case metadata.ScanStatusError:
if merged.Status != metadata.ScanStatusVulnerable {
merged.Status = metadata.ScanStatusError
}
case metadata.ScanStatusPending:
if merged.Status != metadata.ScanStatusVulnerable && merged.Status != metadata.ScanStatusError {
if merged.Status != metadata.ScanStatusVulnerable {
merged.Status = metadata.ScanStatusPending
}
}
@@ -880,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)
+65
View File
@@ -0,0 +1,65 @@
// Package scannertest supplies fake scanner binaries for tests of the CLI wrappers.
package scannertest
import (
"os"
"path/filepath"
"strconv"
"testing"
)
// Fake puts an executable called name first on PATH. It records its arguments, one per line, in
// the returned file, writes stdoutFile to stdout and stderr to stderr, and exits with code.
func Fake(t *testing.T, name, stdoutFile, stderr string, code int) (argsFile string) {
t.Helper()
dir := t.TempDir()
argsFile = filepath.Join(dir, "args")
script := "#!/bin/sh\n" +
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> '" + argsFile + "'; done\n" +
"pwd > '" + filepath.Join(dir, "cwd") + "'\n"
if stdoutFile != "" {
abs, err := filepath.Abs(stdoutFile)
if err != nil {
t.Fatal(err)
}
script += "cat '" + abs + "'\n"
}
if stderr != "" {
script += "printf '%s' '" + stderr + "' >&2\n"
}
script += "exit " + strconv.Itoa(code) + "\n"
install(t, dir, name, script)
return argsFile
}
// Script puts a shell executable called name, with the given body, first on PATH.
func Script(t *testing.T, name, body string) {
t.Helper()
install(t, t.TempDir(), name, "#!/bin/sh\n"+body+"\n")
}
func install(t *testing.T, dir, name, script string) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil { // #nosec G306 -- test helper must be executable
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
}
// Args returns the arguments the fake was called with.
func Args(t *testing.T, argsFile string) []string {
t.Helper()
data, err := os.ReadFile(argsFile) // #nosec G304 -- test temp file
if err != nil {
t.Fatal(err)
}
var out []string
start := 0
for i, b := range data {
if b == '\n' {
out = append(out, string(data[start:i]))
start = i + 1
}
}
return out
}
+2 -3
View File
@@ -13,6 +13,7 @@ import (
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -140,9 +141,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Scanner: s.Name(),
ScannedAt: time.Now(),
Status: metadata.ScanStatusError,
Details: map[string]interface{}{
"error": "scan timeout",
},
Details: scanerr.ErrorDetails("scan timeout", true),
}, nil
}
+24
View File
@@ -0,0 +1,24 @@
package trivy
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
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")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, true, res.Details[scanerr.DetailInfrastructure])
}