Compare commits

...
63 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
lukaszraczylo a83cc20058 docs(lean): record the GH-23 fix commit 2026-11-23 17:08:24 +00:00
lukaszraczylo 501bf1aec8 fix(pypi): serve pip's PEP 658 metadata requests
pip builds the PEP 658 URL by appending .metadata to the whole link, so the suffix lands on original_url, not the path. The filename binding from GH-01 then rejected the request with 400, and every pip install through the proxy failed. The handler now treats that form as the requested wheel's sidecar and streams it without storing it. A sidecar of another file is still refused. The Lean model and the ledger cover the new form (GH-23).
2026-11-23 17:08:20 +00:00
lukaszraczylo 527c1759f9 fix(frontend): revalidate index.html on every load
nginx sent index.html without Cache-Control, so browsers cached it heuristically. After a deploy, a browser kept loading the previous hashed bundle until the cache expired, and fixes did not appear. The SPA location now sends Cache-Control: no-cache. Hashed assets stay immutable. scripts/check_frontend_html_cache.sh checks both.
2026-11-23 16:36:10 +00:00
lukaszraczylo 933b5a75c0 fix(ui): read nested stats from stats_update events
The server sends stats_update as {stats, timestamp}, but the realtime store read the counters from the top level of the payload. About 30 seconds after load, the first broadcast replaced the polled stats with undefined values, and the dashboard tiles showed 0. The store now unwraps the nested stats object.
2026-11-23 16:30:22 +00:00
lukaszraczylo f4cf96e1e8 fix(api): resolve Go module paths to cache keys for vulnerability details
The dashboard links Go packages by module path, but Go rows are stored under cache keys (module/@v/version.zip, .mod, .info). The vulnerability details lookup used the module path, so every Go details page returned 404 "package not found". The handler now falls back to the .zip key, then .mod and .info.
2026-11-23 15:49:33 +00:00
lukaszraczylo aa8487ad87 build: pull pinned base images from mirror.gcr.io
Docker Hub rate-limited the v0.1.328 release build, so goreleaser kept retrying the base image pulls. The Dockerfiles now pull alpine 3.24.4 and nginx 1.31.9-alpine from mirror.gcr.io, pinned by digest. Those digests are what alpine:latest and nginx:alpine resolved to, so the images are unchanged, and a release no longer moves silently with a floating tag.
2026-11-23 15:28:01 +00:00
lukaszraczylo 2ada975065 fix(ui): name trend series by the packages they count
The severity series now read "Packages with <severity> vulnerabilities",
which matches the severity tiles and the snapshot counts.
2026-11-23 15:12:15 +00:00
lukaszraczylo b98e761c90 fix(stats): count a package under every severity it holds
The trend snapshot counted each vulnerable package once, under its
highest severity. The Vulnerable packages tiles and the severity
filter count a package under every severity its latest scan holds.
The two views disagreed, for example low 0 against 8 packages.

The snapshot and the backfill now use the filter definition, so a
package with high and low findings counts under both. A test compares
the snapshot with the filter result on one fixture.
2026-11-23 15:12:12 +00:00
lukaszraczylo a457e3d2e8 test(metadata): stop the aggregation worker before counting statements 2026-11-23 14:58:44 +00:00
lukaszraczylo ba8bc392ec feat(cache): purge soft-deleted package rows after a retention period
The cleanup worker now hard-deletes package rows whose deleted_at is
older than cache.deleted_retention. The default is 30 days. A value of
0 keeps the rows. The purge runs in bounded batches, with at most 100
batches per cleanup pass, and removes child rows with the package.

History tables have no foreign key to packages, and stats_snapshots
holds its own counts, so the purge leaves both untouched. The cleanup
log line now reports purged_deleted and deleted_retention.
2026-11-23 14:55:26 +00:00
lukaszraczylo 1512230ab3 feat(stats): record daily snapshots and serve a trend API
The aggregation worker now writes one row per UTC day to
stats_snapshots. The row holds package count, total size, vulnerable
package count, the four severity counts and the blocked count. The
write is an idempotent upsert per day.

A migration backfills package counts from cached_at and deleted_at as
the number of packages alive at the end of each day. Vulnerability
fields backfill from scan_results timestamps and stay empty before the
first scan. GET /api/stats/trend returns daily points for 30day, 90day
or 1year with a constant number of queries.

The Stats page shows a chart of cached and vulnerable packages with a
period selector and severity toggles. The Dashboard shows a compact
version. The Lean model gains theorems for the backfill and upsert.
2026-11-23 14:55:19 +00:00
lukaszraczylo bd9d686383 feat(vulnerable): filter vulnerable packages by severity
The four severity tiles on the vulnerable packages page are now toggle
buttons with aria-pressed. Each tile shows "Filter on" while active.
A tile selects packages with at least one vulnerability of that
severity. Several tiles combine with OR. A second click clears the
tile, and a Clear filters control clears all of them.

The selection lives in the URL (?severity=critical,high), so it
survives a reload and works as a link. An empty result shows the
library empty state with a clear action.

GET /api/packages accepts a severity list. The page uses it to load
only vulnerable packages instead of the whole cache. The filter is a
subquery on the latest scan result, so the statement count does not
grow with the number of rows. An unknown severity returns 400.
2026-11-23 14:54:44 +00:00
lukaszraczylo 4d31e535ff test(app): pace broadcast bursts to remove a race flake 2026-11-23 14:31:49 +00:00
lukaszraczylo fe2d9f8b3a fix(metadata): wait for the aggregation worker before closing the store 2026-11-23 14:26:35 +00:00
lukaszraczylo a84f080b79 fix(scanner): rescan packages on remote storage via ScanFile 2026-11-23 14:26:35 +00:00
lukaszraczylo 9b4659218c feat(cache): wire cache.ttl_overrides to metadata freshness 2026-11-23 14:26:29 +00:00
lukaszraczylo 1256756057 fix(api): drop dead per-handler CORS headers 2026-11-23 14:26:17 +00:00
lukaszraczylo 262771d224 fix(api): return 404 when deleting a package that does not exist 2026-11-23 14:26:09 +00:00
lukaszraczylo 536f35ab55 fix(server): stop 431 on /api for browsers with large session cookies 2026-11-23 14:14:28 +00:00
lukaszraczylo 5a9d104b37 chore(lean): model redirects, key lookup, upserts, retries, CORS, TTL 2026-11-23 13:39:03 +00:00
lukaszraczylo f2049383cb fix(api): restrict CORS to allowed origins, refuse cross-origin writes 2026-11-23 13:38:38 +00:00
lukaszraczylo 549d56e0a1 fix(cache): default metadata freshness to 24h, under the age gate 2026-11-23 13:38:37 +00:00
lukaszraczylo 31db940014 fix(scanner): re-read the blob when a scan retry finds its file gone 2026-11-23 13:38:37 +00:00
lukaszraczylo f46e079cee fix(stats): upsert hourly and daily stats on SQLite as PostgreSQL does 2026-11-23 13:38:37 +00:00
lukaszraczylo ae5167ffa9 fix(auth): look up API keys by id, one bcrypt compare per request 2026-11-23 13:38:37 +00:00
lukaszraczylo 787c757827 fix(network): vet every redirect hop against the upstream allowlist 2026-11-23 13:38:36 +00:00
lukaszraczylo ac4f39322c feat(ui): page, search and filter packages on the server
The package list loaded every package, then grouped and paged in the
browser. The dashboard did the same to show ten recent rows.

- PackageList asks the server for one page of 25 groups. The registry
  filter and a debounced search box (300 ms) change the request. A newer
  request replaces the answer of an older one.
- Dashboard loads a page of 10 groups sorted by cached_at, newest first,
  and runs its stats, recent list and chart requests in parallel.
- Stats already used /api/stats only and does not change.
- The store keeps the loading flag on until the last overlapping request
  settles. Deleting a package no longer reloads the full list, and the
  list reloads its own page instead.
- VulnerablePackages keeps the unpaginated call because it filters on
  scan results in the browser.
2026-11-23 13:26:50 +00:00
lukaszraczylo db5ca2539f perf(api): serve package lists and stats in constant queries
The dashboard waited seconds for /api/packages and /api/stats. Both
handlers ran queries per package, so the cost grew with the cache.

Baseline, measured live through a port-forward (median of 5):
- /api/packages: 3033 ms, 594 items, limit ignored
- /api/packages?limit=50&offset=0: 2813 ms
- /api/stats: 3813 ms
- /api/stats/timeseries?period=1day: 12 ms

Baseline queries per request, counted on SQLite with 20 and 120 rows:
- /api/packages: 141 and 841 queries (7 per package)
- /api/stats: 103 and 603 queries (5 per package)

Both handlers now run a constant number of queries: 4 for the full list,
6 for a page, 6 for stats. The query-count tests fail on the old code.

- /api/packages pages (registry, name) groups with page, page_size,
  registry, q, sort and order, and returns total_groups. Without page
  and page_size it returns every package, so old clients keep working.
- A batched scan lookup replaces the per-package GetScanResult and
  CheckVulnerabilities calls. ScanDecisions returns the same verdicts as
  CheckVulnerabilities, proven by a policy and bypass matrix test.
- The silent 1000-row cap is gone from the list and the Go delete.
- /api/stats sums per registry with GROUP BY and judges blocked
  packages in one batch.
- Migration 202611240001 adds scan_results (package_id, scanned_at) on
  SQLite, PostgreSQL and MySQL. The existing (registry_id, name, version)
  index already serves the group lookups.
2026-11-23 13:26:50 +00:00
lukaszraczylo a7b9917696 chore(lean): model cache, keys, scan policy, access, release age and stats
Six Lean 4 + Mathlib modules prove or refute the audited properties and cite the Go files they model. FINDINGS.md records each verdict with its Lean theorem, Go test and fix commit. The axiom audit and the currency check live in lean4/scripts.
2026-11-23 13:16:52 +00:00
lukaszraczylo 3143de3a3f fix(scanner): scan PyPI artifacts by release version, not file name
PyPI artifacts are cached under their file name, and the scanners received that name as the version. OSV parsed it as a version below every range, so it missed vulnerabilities that affect the real release (for requests 2.19.0, PYSEC-2023-74 and GHSA-j8r2-6x86-q33q) and reported others that do not. Scanners now receive the release version stored on the package row. The saved result stays keyed by the cache version.
2026-11-23 13:15:34 +00:00
lukaszraczylo f0b37ea719 fix(cache): scan npm and PyPI packages named like Go metadata
IsMetadataEntry treated any name ending in .mod or .info as metadata. An npm or PyPI package with such a name skipped the vulnerability scan and was never blocked. The suffix rule now applies to the go registry only.
2026-11-23 13:15:34 +00:00
lukaszraczylo 7192e4ff3e fix(stats): keep downloads that a daily rollup has not counted yet
The time series let a day's rollup replace the hourly rows and events for that day. A download aggregated after the rollup ran vanished from the chart until the next pass. The chart now takes the larger of the two figures.
2026-11-23 13:15:34 +00:00
lukaszraczylo ad4e848e2b fix(stats): roll up every completed day still held hourly
The daily pass rolled up only yesterday, once a day at hour 0. A pass that ran before its last hour was aggregated, or that a restart skipped, left that day short or empty, and the hourly rows were deleted after seven days. Each pass now recomputes the six completed days before today.
2026-11-23 13:15:33 +00:00
lukaszraczylo 990a1d3409 fix(cache): retry once when a purge removes the blob during a hit
Get probed the blob in getOrFetch and opened it again after the singleflight. A purge between the two returned a storage error to the client. Get now resolves the entry a second time, which sees the miss and fetches again.
2026-11-23 13:15:33 +00:00
lukaszraczylo 440279aa50 fix(cache): stop LRU eviction spinning and failing overlapping stores
evict re-listed the same 100 rows forever when every delete failed, and an
overlapping store received a quota error because a flag rejected the second
eviction. Eviction now returns when a pass deletes nothing, and a second
caller waits for the running eviction.
2026-11-23 13:15:33 +00:00
lukaszraczylo 1f31256769 fix(storage): release replaced bytes when a key is overwritten
Put added the new size to the usage counter without subtracting the file it
replaced. Each overwrite inflated usage until restart and could trip the
quota on a cache that was not full.
2026-11-23 13:15:33 +00:00
lukaszraczylo 4713524778 fix(scanner): honour CVE bypasses under block_on_severity LOW
The LOW policy counted every vulnerability, including bypassed ones, so an
active bypass never unblocked a package. It now counts only the remaining
vulnerabilities.
2026-11-23 13:15:33 +00:00
lukaszraczylo 5c9f7e6af3 fix(pypi): bind original_url to the requested file name
The cache key is built from the request path, but the upstream fetch used
the original_url query value. Any file on an allowed host could be stored
under another package's key. The handler now rejects an original_url whose
file name differs from the requested file.
2026-11-23 13:15:32 +00:00
lukaszraczylo 6f604367da fix(websocket): start the event loop and throttle drop warnings
The app built the websocket server but never called Start, so nothing read the 256-slot broadcast channel. After the first 256 events every event was dropped with a warning, and dashboard clients blocked forever on the unbuffered register channel, leaking a goroutine per connection and never receiving events. Run now starts the loop with the other workers. Dropped events are counted in gohoarder_websocket_events_dropped_total and warned about at most once a minute.
2026-11-23 12:56:32 +00:00
lukaszraczylo c98720c02e docs: describe cache.idle_ttl and the cleanup run
Document the new idle_ttl key in the example config and the README.
Explain that artifacts never expire by age and that metadata entries
refresh after default_ttl.
2026-11-23 12:50:01 +00:00
lukaszraczylo 9a44683fbd feat(ui): note the idle eviction window on the stats page
The stats page now reads idle_ttl from the stats API. It shows
"Cached items not requested for 7 days are removed." in an info alert.
The note stays hidden when idle eviction is off.
2026-11-23 12:50:00 +00:00
lukaszraczylo d6edd40d79 feat(cache): evict items idle past cache.idle_ttl
Every cached item got a 7-day expiry at store time. A popular tarball
left the cache seven days after it was cached, however often clients
requested it.

Artifacts now get no age-based expiry. Cleanup removes any item whose
last_accessed is older than cache.idle_ttl (default 168h, 0 disables).
It reads the items in bounded batches of 500 through the indexed
last_accessed column and deletes them through deletePackage. Metadata
entries keep the freshness expiry from default_ttl.

Startup and each cleanup run clear the expiry that earlier versions set
on artifact rows. Cleanup records the idle and ttl eviction reasons and
logs the count and bytes freed. The stats API reports idle_ttl in
seconds. Package deletes are soft deletes and no history table has a
foreign key to packages, so download history stays intact.
2026-11-23 12:49:47 +00:00
lukaszraczylo 99c885cd88 fix(ui): stack package rows on phones and drop pager edge buttons
At 320px the package name shared a row with the registry badge, size and downloads, so it had about 90px and scoped names broke mid-word. Below sm the name now takes the full width with the meta row underneath. The pager's first and last buttons wrapped onto a second line inside the card; the page list already reaches the first and last pages, so the edge buttons are off.
2026-11-23 12:29:40 +00:00
lukaszraczylo c022824d2b fix(ui): swap native key prompt for a dialog; add favicon 2026-11-23 03:18:43 +00:00
lukaszraczylo 5420480ef8 fix(metadata): keep created_at on CVE bypass edit; repair MySQL suite 2026-11-23 03:18:42 +00:00
lukaszraczylo bde9eebf3d fix(ui): show the PyPI release version in every version display 2026-11-23 03:18:42 +00:00
github-actions[bot]andGitHub f65c0cc1f3 chore(deps): update dependencies
Automated dependency update. All tests passed.
2026-11-23 03:17:22 +00:00
lukaszraczylo 947b264d94 fix(pypi): send the release version in the scanned package list
The package list builds its own payload when scanning is on, and that payload left out release_version, so the dashboard still showed file names. A helper now builds the summary and a test covers it.
2026-11-23 02:47:34 +00:00
187 changed files with 16137 additions and 1339 deletions
+2
View File
@@ -72,6 +72,7 @@ tests/fixtures/temp/
# Markdown files (except README.md)
*.md
!README.md
!lean4/FINDINGS.md
/gohoarder
*.log
@@ -83,3 +84,4 @@ data/storage
# Local worktrees
.worktrees/
lean4/.lake
+6 -1
View File
@@ -2,7 +2,7 @@
# Combines frontend serving and backend proxy (previously separate gateway)
# EXPECTS: Pre-built frontend files in frontend/dist/ directory
FROM nginx:alpine
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
# Install envsubst for runtime configuration
RUN apk add --no-cache gettext
@@ -85,6 +85,8 @@ server {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header Connection "";
# The backend authenticates by API-key header; browser session cookies only bloat the request.
proxy_set_header Cookie "";
# Timeouts for long-running operations
proxy_connect_timeout 60s;
@@ -122,6 +124,7 @@ server {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Cookie "";
# WebSocket timeouts
proxy_connect_timeout 7d;
@@ -144,6 +147,8 @@ server {
# Frontend SPA - serve index.html for all other routes
location / {
# index.html names the hashed bundles; a cached copy keeps serving the previous release.
add_header Cache-Control "no-cache" always;
try_files $uri $uri/ /index.html;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM alpine:latest
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
+5 -5
View File
@@ -2,7 +2,7 @@
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM alpine:latest
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
@@ -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 && \
+1 -1
View File
@@ -2,7 +2,7 @@
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM alpine:latest
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
+43 -4
View File
@@ -193,6 +193,7 @@ server:
host: "0.0.0.0"
read_timeout: "5m"
write_timeout: "5m"
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
storage:
backend: "filesystem" # Options: filesystem, s3, smb
@@ -233,7 +234,12 @@ security:
enabled: true
cache:
default_ttl: 86400 # 24 hours in seconds
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
pypi: 12h
cleanup_interval: 1h
logging:
level: "info" # debug, info, warn, error
@@ -245,6 +251,17 @@ upstream:
go: "https://proxy.golang.org"
```
#### Cache cleanup
Every `cleanup_interval` the cleanup run removes:
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
### Environment Variables
All configuration values can be overridden with environment variables:
@@ -876,10 +893,29 @@ Access the web dashboard at **http://localhost:8080**
**List Packages:**
```bash
GET /api/packages
GET /api/packages?registry=npm
GET /api/packages?status=vulnerable
GET /api/packages?page=1&page_size=25
GET /api/packages?registry=npm&q=axios&page_size=25
GET /api/packages?sort=cached_at&order=desc&page_size=10
```
The dashboard groups versions under a package, so paging counts packages (a
registry and name pair), not rows. Without `page` and `page_size` the call
returns every package in one response, with no row cap.
| Parameter | Meaning |
|---|---|
| `page` | 1-based page of groups. Default 1. |
| `page_size` | Groups per page. Default 25 when `page` is set, at most 200. |
| `registry` | Only this registry, for example `npm`, `pypi` or `go`. |
| `q` | Case-insensitive search in name, version and release version. |
| `sort` | `name` (default, ascending), `cached_at`, `downloads` or `size` (both descending). |
| `order` | `asc` or `desc`, to override the default direction of `sort`. |
`packages` holds every version row of each group on the page, in group order
and newest first within a group. `total` is the number of rows returned.
`total_groups` is the number of groups that match the filters across all pages.
A paged response also echoes `page` and `page_size`.
**Package Details:**
```bash
GET /api/packages/:registry/:name/:version
@@ -909,7 +945,10 @@ GET /api/packages/:registry/:name/:version
}
}
],
"total": 42
"total": 1,
"total_groups": 42,
"page": 1,
"page_size": 25
}
```
+17 -5
View File
@@ -10,8 +10,13 @@ server:
host: "0.0.0.0"
port: 8080 # Backend API server port
read_timeout: "5m"
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
write_timeout: "5m"
idle_timeout: "2m"
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
allowed_origins: []
tls:
enabled: false
cert_file: ""
@@ -89,23 +94,30 @@ metadata:
log_level: "warn" # GORM log level: silent, error, warn, info
cache:
default_ttl: "168h" # 7 days
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
cleanup_interval: "1h"
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
max_size_bytes: 536870912000 # 500GB
per_project_quota: 53687091200 # 50GB
ttl_overrides:
npm: "168h"
pip: "168h"
go: "168h"
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
npm: "24h"
pypi: "24h"
go: "24h"
security:
enabled: false
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")
+3
View File
@@ -5,3 +5,6 @@ VITE_BACKEND_URL=http://localhost:8080
# Frontend dev server port
# The Vite development server will run on this port
VITE_PORT=5173
# Origin sent on the dev WebSocket proxy, for a backend with an allowed-origins list
# VITE_WS_ORIGIN=https://gohoarder.example.com
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="data:," />
<title>GoHoarder dashboard</title>
</head>
<body>
+144 -87
View File
@@ -24,19 +24,19 @@ importers:
version: 7.3.1
'@perfect-design/ui':
specifier: 0.3.10
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))
axios:
specifier: ^1.20.0
version: 1.21.1
version: 1.21.1([email protected]([email protected]))([email protected])
pinia:
specifier: ^4.0.0
version: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
version: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
vue:
specifier: ^3.5.26
version: 3.5.45([email protected])
version: 3.5.46([email protected])
vue-router:
specifier: ^5.3.1
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected]))
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected]))
devDependencies:
'@tailwindcss/vite':
specifier: ^4.3.3
@@ -46,13 +46,13 @@ importers:
version: 7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
'@testing-library/vue':
specifier: ^8.1.0
version: 8.1.0(@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))
version: 8.1.0(@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))
'@vitejs/plugin-vue':
specifier: ^6.0.3
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]5([email protected]))
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]6([email protected]))
'@vue/test-utils':
specifier: ^2.4.6
version: 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
version: 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
jsdom:
specifier: ^31.0.0
version: 31.0.1
@@ -654,18 +654,30 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==}
'@vue/[email protected]':
resolution: {integrity: sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==}
'@vue/[email protected]':
resolution: {integrity: sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==}
'@vue/[email protected]':
resolution: {integrity: sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==}
'@vue/[email protected]':
resolution: {integrity: sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==}
'@vue/[email protected]':
resolution: {integrity: sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==}
'@vue/[email protected]':
resolution: {integrity: sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==}
'@vue/[email protected]':
resolution: {integrity: sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-6u4vXBlIBAC1wMplIZgpyPn7uh/s4Bf6F5bMzvLv+EdJ0aHs/+4B7Ygv864EStQSjRbsRzTko/kUG1A1IejQ3A==}
@@ -678,17 +690,17 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==}
'@vue/[email protected]5':
resolution: {integrity: sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==}
'@vue/[email protected]6':
resolution: {integrity: sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==}
'@vue/[email protected]5':
resolution: {integrity: sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==}
'@vue/[email protected]6':
resolution: {integrity: sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==}
'@vue/[email protected]5':
resolution: {integrity: sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==}
'@vue/[email protected]6':
resolution: {integrity: sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==}
'@vue/[email protected]5':
resolution: {integrity: sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==}
'@vue/[email protected]6':
resolution: {integrity: sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==}
@@ -696,6 +708,9 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==}
'@vue/[email protected]':
resolution: {integrity: sha512-kTB6s2p34cA/xXSpt17G0enU9A3F3pdm+o5GZgE3WGXXXpXJ5SVBsRhgCJNCc+ekGAzY0T7Hjyo5yEfwencBlg==}
peerDependencies:
@@ -855,8 +870,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
[email protected].3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
[email protected].4:
resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==}
[email protected]:
resolution: {integrity: sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==}
@@ -1476,6 +1491,10 @@ packages:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
[email protected]:
resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==}
engines: {node: '>=6.0.0'}
[email protected]:
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
@@ -1710,8 +1729,8 @@ packages:
peerDependencies:
typescript: '>=5.0.0'
[email protected]5:
resolution: {integrity: sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==}
[email protected]6:
resolution: {integrity: sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==}
peerDependencies:
typescript: '*'
peerDependenciesMeta:
@@ -1901,11 +1920,11 @@ snapshots:
'@floating-ui/[email protected]': {}
'@floating-ui/[email protected]([email protected]5([email protected]))':
'@floating-ui/[email protected]([email protected]6([email protected]))':
dependencies:
'@floating-ui/dom': 1.8.0
'@floating-ui/utils': 0.2.12
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@fontsource/[email protected]': {}
@@ -1948,13 +1967,13 @@ snapshots:
'@oxc-project/[email protected]': {}
'@perfect-design/[email protected]([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))':
'@perfect-design/[email protected]([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))':
dependencies:
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
reka-ui: 2.11.0([email protected]5([email protected]))
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
reka-ui: 2.11.0([email protected]6([email protected]))
tailwind-merge: 3.7.1
tailwindcss: 4.3.5
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@rolldown/[email protected]':
optional: true
@@ -2077,10 +2096,10 @@ snapshots:
'@tanstack/[email protected]': {}
'@tanstack/[email protected]([email protected]5([email protected]))':
'@tanstack/[email protected]([email protected]6([email protected]))':
dependencies:
'@tanstack/virtual-core': 3.13.14
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@testing-library/[email protected]':
dependencies:
@@ -2116,12 +2135,12 @@ snapshots:
optionalDependencies:
vitest: 5.1.1([email protected])([email protected]([email protected])([email protected]))
'@testing-library/[email protected](@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))':
'@testing-library/[email protected](@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))':
dependencies:
'@babel/runtime': 7.28.4
'@testing-library/dom': 9.3.4
'@vue/test-utils': 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
vue: 3.5.45([email protected])
'@vue/test-utils': 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
vue: 3.5.46([email protected])
optionalDependencies:
'@vue/compiler-sfc': 3.5.45
transitivePeerDependencies:
@@ -2141,11 +2160,11 @@ snapshots:
'@types/[email protected]': {}
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]5([email protected]))':
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]6([email protected]))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.8([email protected])([email protected])
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@vitest/[email protected]([email protected]([email protected])([email protected]))':
dependencies:
@@ -2182,7 +2201,7 @@ snapshots:
optionalDependencies:
typescript: 6.0.3
'@vue-macros/[email protected]([email protected]5([email protected]))':
'@vue-macros/[email protected]([email protected]6([email protected]))':
dependencies:
'@vue/compiler-sfc': 3.5.45
ast-kit: 2.2.0
@@ -2190,7 +2209,7 @@ snapshots:
magic-string-ast: 1.0.3
unplugin-utils: 0.3.2
optionalDependencies:
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@vue/[email protected]':
dependencies:
@@ -2208,6 +2227,14 @@ snapshots:
estree-walker: 2.0.2
source-map-js: 1.2.2
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
'@vue/shared': 3.5.46
entities: 7.0.1
estree-walker: 2.0.2
source-map-js: 1.2.4
'@vue/[email protected]':
dependencies:
'@vue/compiler-core': 3.5.44
@@ -2218,6 +2245,11 @@ snapshots:
'@vue/compiler-core': 3.5.45
'@vue/shared': 3.5.45
'@vue/[email protected]':
dependencies:
'@vue/compiler-core': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
@@ -2230,11 +2262,28 @@ snapshots:
postcss: 8.5.32
source-map-js: 1.2.2
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
'@vue/compiler-core': 3.5.46
'@vue/compiler-dom': 3.5.46
'@vue/compiler-ssr': 3.5.46
'@vue/shared': 3.5.46
estree-walker: 2.0.2
magic-string: 0.30.21
postcss: 8.5.32
source-map-js: 1.2.4
'@vue/[email protected]':
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/shared': 3.5.45
'@vue/[email protected]':
dependencies:
'@vue/compiler-dom': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]':
dependencies:
'@vue/devtools-kit': 8.2.1
@@ -2258,61 +2307,63 @@ snapshots:
path-browserify: 1.0.1
picomatch: 4.0.7
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/shared': 3.5.45
'@vue/shared': 3.5.46
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/reactivity': 3.5.45
'@vue/shared': 3.5.45
'@vue/reactivity': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/reactivity': 3.5.45
'@vue/runtime-core': 3.5.45
'@vue/shared': 3.5.45
csstype: 3.2.3
'@vue/reactivity': 3.5.46
'@vue/runtime-core': 3.5.46
'@vue/shared': 3.5.46
csstype: 3.2.4
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/compiler-ssr': 3.5.45
'@vue/runtime-dom': 3.5.45
'@vue/shared': 3.5.45
'@vue/compiler-ssr': 3.5.46
'@vue/runtime-dom': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]': {}
'@vue/[email protected]': {}
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
'@vue/[email protected]': {}
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/compiler-dom': 3.5.46
js-beautify: 2.0.3
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
vue-component-type-helpers: 3.3.12
optionalDependencies:
'@vue/server-renderer': 3.5.45
'@vue/server-renderer': 3.5.46
'@vueuse/[email protected]([email protected]5([email protected]))':
'@vueuse/[email protected]([email protected]6([email protected]))':
dependencies:
'@types/web-bluetooth': 0.0.21
'@vueuse/metadata': 14.4.0
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
vue: 3.5.45([email protected])
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
vue: 3.5.46([email protected])
'@vueuse/[email protected]': {}
'@vueuse/[email protected]([email protected]5([email protected]))':
'@vueuse/[email protected]([email protected]6([email protected]))':
dependencies:
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
[email protected]: {}
[email protected]: {}
[email protected]:
[email protected]([email protected]):
dependencies:
debug: 4.4.3
debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2368,11 +2419,11 @@ snapshots:
dependencies:
possible-typed-array-names: 1.1.0
[email protected]:
[email protected]([email protected]([email protected]))([email protected]):
dependencies:
follow-redirects: 1.16.3
follow-redirects: 1.16.3([email protected]([email protected]))
form-data: 4.0.6
https-proxy-agent: 5.0.1
https-proxy-agent: 5.0.1([email protected])
proxy-from-env: 2.1.0
transitivePeerDependencies:
- debug
@@ -2445,7 +2496,7 @@ snapshots:
[email protected]: {}
[email protected].3: {}
[email protected].4: {}
[email protected]:
dependencies:
@@ -2454,9 +2505,11 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
[email protected]:
[email protected]([email protected]):
dependencies:
ms: 2.1.3
optionalDependencies:
supports-color: 7.2.0
[email protected]: {}
@@ -2600,7 +2653,9 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
[email protected]: {}
[email protected]([email protected]([email protected])):
optionalDependencies:
debug: 4.4.3([email protected])
[email protected]:
dependencies:
@@ -2675,10 +2730,10 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
[email protected]:
[email protected]([email protected]):
dependencies:
agent-base: 6.0.2
debug: 4.4.3
agent-base: 6.0.2([email protected])
debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2968,11 +3023,11 @@ snapshots:
[email protected]: {}
[email protected](@vue/[email protected])([email protected])([email protected]5([email protected])):
[email protected](@vue/[email protected])([email protected])([email protected]6([email protected])):
dependencies:
'@vue/devtools-api': 8.2.1
nostics: 1.3.0
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
optionalDependencies:
typescript: 6.0.3
@@ -3030,18 +3085,18 @@ snapshots:
gopd: 1.2.0
set-function-name: 2.0.2
[email protected]([email protected]5([email protected])):
[email protected]([email protected]6([email protected])):
dependencies:
'@floating-ui/vue': 2.0.1([email protected]5([email protected]))
'@floating-ui/vue': 2.0.1([email protected]6([email protected]))
'@internationalized/date': 3.10.1
'@internationalized/number': 3.6.5
'@tanstack/vue-virtual': 3.13.14([email protected]5([email protected]))
'@vueuse/core': 14.4.0([email protected]5([email protected]))
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
'@tanstack/vue-virtual': 3.13.14([email protected]6([email protected]))
'@vueuse/core': 14.4.0([email protected]6([email protected]))
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
aria-hidden: 1.2.6
defu: 6.1.7
ohash: 2.0.11
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
[email protected]:
dependencies:
@@ -3124,6 +3179,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
@@ -3240,9 +3297,9 @@ snapshots:
[email protected]: {}
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected])):
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected])):
dependencies:
'@vue-macros/common': 3.1.4([email protected]5([email protected]))
'@vue-macros/common': 3.1.4([email protected]6([email protected]))
'@vue/devtools-api': 8.2.1
ast-walker-scope: 0.10.0
chokidar: 6.0.0
@@ -3258,10 +3315,10 @@ snapshots:
tinyglobby: 0.2.17
unplugin: 3.7.0([email protected])([email protected])([email protected]([email protected])([email protected]))
unplugin-utils: 0.3.2
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
optionalDependencies:
'@vue/compiler-sfc': 3.5.45
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
vite: 8.3.8([email protected])([email protected])
transitivePeerDependencies:
- '@farmfe/core'
@@ -3280,13 +3337,13 @@ snapshots:
'@vue/language-core': 3.3.14
typescript: 6.0.3
[email protected]5([email protected]):
[email protected]6([email protected]):
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/compiler-sfc': 3.5.45
'@vue/runtime-dom': 3.5.45
'@vue/server-renderer': 3.5.45
'@vue/shared': 3.5.45
'@vue/compiler-dom': 3.5.46
'@vue/compiler-sfc': 3.5.46
'@vue/runtime-dom': 3.5.46
'@vue/server-renderer': 3.5.46
'@vue/shared': 3.5.46
optionalDependencies:
typescript: 6.0.3
@@ -85,7 +85,7 @@
:hint="
bypassForm.type === 'cve'
? 'Enter the CVE ID, for example CVE-2021-23337.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
"
required
>
@@ -137,6 +137,24 @@
</DialogContent>
</Dialog>
<Dialog v-model:open="showKeyDialog">
<DialogContent size="sm">
<DialogHeader>
<DialogTitle>Admin API key</DialogTitle>
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
</DialogHeader>
<form class="flex flex-col gap-4" @submit.prevent="submitApiKey">
<Field label="API key" required>
<Input v-model="keyInput" type="password" autocomplete="off" />
</Field>
<DialogFooter>
<Button variant="outline" @click="showKeyDialog = false">Cancel</Button>
<Button type="submit" :disabled="keyInput.trim() === ''">Continue</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<ConfirmDialog
v-model:open="showDeleteModal"
title="Delete bypass?"
@@ -222,6 +240,8 @@ const bypassForm = ref({ ...EMPTY_FORM })
// Get API key from localStorage or prompt user
const apiKey = ref<string>('')
const keyInput = ref('')
const showKeyDialog = ref(false)
const filteredBypasses = computed(() => {
let filtered = bypasses.value
@@ -264,16 +284,23 @@ onMounted(() => {
})
function promptForApiKey() {
const key = prompt('Enter your admin API key:')
if (key) {
apiKey.value = key
localStorage.setItem('admin_api_key', key)
fetchBypasses()
} else {
error.value = 'Admin API key required to manage bypasses'
}
keyInput.value = ''
showKeyDialog.value = true
}
function submitApiKey() {
const key = keyInput.value.trim()
if (!key) return
apiKey.value = key
localStorage.setItem('admin_api_key', key)
showKeyDialog.value = false
fetchBypasses()
}
watch(showKeyDialog, (open) => {
if (!open && !apiKey.value) error.value = 'Admin API key required to manage bypasses'
})
async function fetchBypasses() {
if (!apiKey.value) {
promptForApiKey()
+23 -41
View File
@@ -1,18 +1,23 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { mount as mountWith } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import Dashboard from './Dashboard.vue'
import { usePackageStore } from '../stores/packages'
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
import { createTestRouter } from '@/test/router'
describe('Dashboard.vue', () => {
beforeEach(() => {
let router: Awaited<ReturnType<typeof createTestRouter>>
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
beforeEach(async () => {
router = await createTestRouter('/')
setActivePinia(createPinia())
__resetRealtimeSingleton()
// Mock the fetch functions to prevent actual API calls
const store = usePackageStore()
vi.spyOn(store, 'fetchStats').mockResolvedValue()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
})
it('renders dashboard component', () => {
@@ -127,7 +132,7 @@ describe('Dashboard.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
store.recentPackages = [
{
id: '1',
registry: 'npm',
@@ -144,22 +149,12 @@ describe('Dashboard.vue', () => {
expect(wrapper.text()).toContain('Recent packages')
})
it('shows recent packages sorted by cached_at', async () => {
it('lists recent packages in the order the store holds them, newest first', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'old-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
store.recentPackages = [
{
id: '2',
registry: 'npm',
@@ -170,46 +165,33 @@ describe('Dashboard.vue', () => {
last_accessed: '2025-01-02T00:00:00Z',
download_count: 5,
},
{
id: '1',
registry: 'npm',
name: 'old-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
await wrapper.vm.$nextTick()
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
// new-package should appear before old-package since it's more recent
// The store sorts by cached_at; the view keeps that order
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
recentPackagesSection.indexOf('old-package')
)
})
it('limits recent packages to 10 items', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = Array.from({ length: 15 }, (_, i) => ({
id: `${i}`,
registry: 'npm',
name: `package${i}`,
version: '1.0.0',
size: 1024,
cached_at: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
last_accessed: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
download_count: i,
}))
await wrapper.vm.$nextTick()
const recentSection = wrapper.text().split('Recent packages')[1]
// Count how many "package" strings appear (each package has the word "package" in its name)
const packageCount = (recentSection.match(/package\d+/g) || []).length
expect(packageCount).toBeLessThanOrEqual(10)
})
it('handles empty packages array', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = []
store.recentPackages = []
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('0')
+41 -46
View File
@@ -39,35 +39,38 @@
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Download activity</CardTitle>
<CardAction>
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
</CardAction>
</CardHeader>
<CardContent>
<LoadingState
v-if="chartLoading && chartData.length === 0"
layout="inline"
label="Loading chart data..."
/>
<ErrorState
v-else-if="chartError"
variant="inline"
title="Could not load download activity"
:message="chartError"
@retry="fetchTimeSeriesData"
/>
<BarChart
v-else
:labels="chartLabels"
:series="[{ name: 'Downloads', data: chartData }]"
label="Downloads over the selected period"
empty-text="No download activity in this period"
/>
</CardContent>
</Card>
<div class="grid gap-6 lg:grid-cols-2">
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Download activity</CardTitle>
<CardAction>
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
</CardAction>
</CardHeader>
<CardContent>
<LoadingState
v-if="chartLoading && chartData.length === 0"
layout="inline"
label="Loading chart data..."
/>
<ErrorState
v-else-if="chartError"
variant="inline"
title="Could not load download activity"
:message="chartError"
@retry="fetchTimeSeriesData"
/>
<BarChart
v-else
:labels="chartLabels"
:series="[{ name: 'Downloads', data: chartData }]"
label="Downloads over the selected period"
empty-text="No download activity in this period"
/>
</CardContent>
</Card>
<TrendChart compact class="min-w-0" />
</div>
<Card>
<CardHeader>
@@ -75,7 +78,7 @@
</CardHeader>
<CardContent>
<EmptyState
v-if="packages.length === 0"
v-if="recentPackages.length === 0"
size="sm"
:icon="faBoxOpen"
title="No packages cached yet"
@@ -124,10 +127,11 @@ import {
type DataTableColumn,
} from '@perfect-design/ui'
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
import TrendChart from './TrendChart.vue'
import { usePackageStore, type Package } from '../stores/packages'
import { useRealtimeStore } from '../stores/realtime'
import type { EventType, RealtimeEvent } from '@/lib/ws'
import { formatBytes, formatNumber } from '@/lib/format'
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
import {
faBox,
faBoxOpen,
@@ -140,7 +144,7 @@ import {
} from '@/lib/icons'
const store = usePackageStore()
const { packages, stats, loading, error } = storeToRefs(store)
const { recentPackages, stats, loading, error } = storeToRefs(store)
const rt = useRealtimeStore()
const { lastStats, events: rtEvents } = storeToRefs(rt)
@@ -190,7 +194,8 @@ function labelForEvent(type: EventType): string {
function describeEvent(evt: RealtimeEvent): string {
const p = evt.payload
const name = typeof p.name === 'string' ? p.name : ''
const version = typeof p.version === 'string' ? `@${p.version}` : ''
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
const version = typeof shown === 'string' ? `@${shown}` : ''
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
if (evt.type === 'stats_update') return ''
if (name) return `${registry}${name}${version}`
@@ -250,7 +255,7 @@ const chartLabels = computed(() => chartData.value.map((_, index) => getChartLab
const packageColumns: DataTableColumn<Package>[] = [
{ key: 'name', header: 'Package', rowHeader: true },
{ key: 'version', header: 'Version' },
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
{ key: 'registry', header: 'Registry' },
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
@@ -258,7 +263,7 @@ const packageColumns: DataTableColumn<Package>[] = [
function refresh() {
void store.fetchStats()
void store.fetchPackages()
void store.fetchRecentPackages()
}
function getChartLabel(index: number): string {
@@ -290,14 +295,6 @@ function getChartLabel(index: number): string {
return labels[selectedPeriod.value]?.(index) || `${index}`
}
// API returns clean, deduplicated data - just sort and limit
const recentPackages = computed(() => {
return packages.value
.slice()
.sort((a, b) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
.slice(0, 10)
})
// Watch for period changes and fetch new data
watch(selectedPeriod, () => {
fetchTimeSeriesData()
@@ -308,9 +305,7 @@ onMounted(async () => {
// initial polling resolves. Singleton survives navigation, so we
// intentionally do not disconnect on unmount.
rt.connect()
await store.fetchStats()
await store.fetchPackages()
await fetchTimeSeriesData()
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), fetchTimeSeriesData()])
})
</script>
+4 -2
View File
@@ -7,7 +7,7 @@
<template #description>
<span class="flex flex-wrap items-center gap-2">
<Badge variant="outline">{{ registry }}</Badge>
<Badge variant="outline" class="font-mono">v{{ version }}</Badge>
<Badge variant="outline" class="font-mono">{{ withVersionPrefix(shownVersion) }}</Badge>
</span>
</template>
</PageHeader>
@@ -184,7 +184,7 @@ import {
TableRow,
} from '@perfect-design/ui'
import SeveritySummary from './SeveritySummary.vue'
import { formatDate } from '@/lib/format'
import { formatDate, withVersionPrefix } from '@/lib/format'
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
@@ -201,6 +201,7 @@ const packageName = computed(() => {
return nameParam as string
})
const version = computed(() => route.params.version as string)
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
interface BypassInfo {
id: string
@@ -221,6 +222,7 @@ interface Vulnerability {
}
interface VulnerabilityResponse {
package?: { release_version?: string }
scanned: boolean
scanner: string
scanned_at: string
+105 -26
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
@@ -6,6 +6,14 @@ import { defineComponent, h } from 'vue'
import PackageList from './PackageList.vue'
import { usePackageStore } from '../stores/packages'
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
// A page as the server sends it: whole groups, flattened to rows.
function setRows(store: ReturnType<typeof usePackageStore>, packages: Row[]) {
const groups = new Set(packages.map((p) => `${p.registry}:${p.name}`))
store.packagePage = { packages, totalGroups: groups.size, page: 1, pageSize: 25 }
}
const Stub = defineComponent({ render: () => h('div') })
function createTestRouter(): Router {
@@ -41,7 +49,7 @@ describe('PackageList.vue', () => {
setActivePinia(createPinia())
// Prevent real network calls from store actions on mount
const store = usePackageStore()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
})
it('renders package list component', async () => {
@@ -74,7 +82,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = []
setRows(store, [])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('No packages cached yet')
@@ -85,7 +93,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '1',
registry: 'npm',
@@ -96,17 +104,17 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('test-package')
expect(wrapper.text()).toContain('1 version')
})
it('calls fetchPackages on mount', async () => {
it('asks the server for the first page on mount', async () => {
const store = usePackageStore()
// beforeEach already spied with mockResolvedValue; reuse that spy
const fetchSpy = store.fetchPackages as ReturnType<typeof vi.spyOn>
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
await mountWithRouter()
@@ -119,7 +127,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '1',
registry: 'npm',
@@ -140,7 +148,7 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-02T00:00:00Z',
download_count: 20,
},
]
])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('test-package')
@@ -152,7 +160,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '1',
registry: 'npm',
@@ -163,7 +171,7 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('1 MB')
@@ -174,7 +182,17 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '3',
registry: 'go',
name: 'go-module',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 3,
},
{
id: '1',
registry: 'npm',
@@ -195,21 +213,11 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-01T00:00:00Z',
download_count: 5,
},
{
id: '3',
registry: 'go',
name: 'go-module',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 3,
},
]
])
await wrapper.vm.$nextTick()
// Verify that all registry badges are displayed
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
// The server sends groups in name order: go-module, npm-package, python-package
expect(wrapper.text()).toContain('npm')
expect(wrapper.text()).toContain('pypi')
expect(wrapper.text()).toContain('go')
@@ -223,7 +231,7 @@ describe('PackageList.vue', () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.packages = [
setRows(store, [
{
id: '1',
registry: 'pypi',
@@ -235,7 +243,7 @@ describe('PackageList.vue', () => {
last_accessed: '2026-11-23T00:00:00Z',
download_count: 0,
},
]
])
await wrapper.vm.$nextTick()
await wrapper.find('button[aria-expanded]').trigger('click')
await wrapper.vm.$nextTick()
@@ -243,4 +251,75 @@ describe('PackageList.vue', () => {
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
describe('server-side paging, search and registry filter', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('debounces the search box into one request with q and page 1', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
const input = wrapper.find('input[type="search"], input')
await input.setValue('l')
await input.setValue('le')
await input.setValue('left')
expect(fetchSpy).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(300)
expect(fetchSpy).toHaveBeenCalledTimes(1)
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'all', q: 'left' })
})
it('sends the registry of the route with every request', async () => {
const router = createTestRouter()
router.push('/packages/pypi')
await router.isReady()
const store = usePackageStore()
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
mount(PackageList, { props: { registry: 'pypi' }, global: { plugins: [router] } })
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'pypi', q: '' })
})
it('pages through the server, not the loaded rows', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packagePage = {
packages: [
{ id: '1', registry: 'npm', name: 'a', version: '1', size: 1, cached_at: '2025-01-01T00:00:00Z', last_accessed: '2025-01-01T00:00:00Z', download_count: 0 },
],
totalGroups: 60,
page: 1,
pageSize: 25,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Page 1 of 3 (60 total packages)')
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
const next = wrapper.findAll('button').find((b) => /next/i.test(b.attributes('aria-label') ?? b.text()))
await next!.trigger('click')
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, pageSize: 25, registry: 'all', q: '' })
})
it('says no packages match when a filter empties the page', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
setRows(store, [])
await wrapper.find('input').setValue('zzz')
await vi.advanceTimersByTimeAsync(300)
expect(wrapper.text()).toContain('No packages match')
expect(wrapper.text()).not.toContain('No packages cached yet')
})
})
})
+70 -71
View File
@@ -2,7 +2,7 @@
<div class="flex flex-col gap-6">
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
<template #actions>
<Button variant="outline" :icon-start="faRotateRight" @click="store.fetchPackages()">Refresh</Button>
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
</template>
</PageHeader>
@@ -23,32 +23,33 @@
variant="card"
title="Could not load packages"
:message="error"
@retry="store.fetchPackages()"
@retry="load()"
/>
<Card v-else>
<CardContent>
<EmptyState
v-if="packages.length === 0"
v-if="totalGroups === 0 && !filtersActive"
:icon="faBoxOpen"
title="No packages cached yet"
description="Packages will appear here once they are downloaded through the proxy."
/>
<EmptyState
v-else-if="groupedPackages.length === 0"
v-else-if="groups.length === 0"
:icon="faMagnifyingGlass"
title="No packages match"
description="Change the registry filter or the search text."
/>
<Accordion v-else type="multiple" class="w-full">
<AccordionItem
v-for="group in groupedPackages"
v-for="group in groups"
:key="`${group.registry}:${group.name}`"
:value="`${group.registry}:${group.name}`"
>
<AccordionTrigger :heading-level="2">
<span class="flex w-full min-w-0 items-center justify-between gap-4">
<span class="min-w-0 text-start">
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<span class="w-full min-w-0 text-start sm:w-auto">
<span class="block break-words font-semibold">{{ group.name }}</span>
<span class="block text-sm text-muted-foreground">
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
@@ -109,12 +110,13 @@
<div v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
<p class="m-0 text-sm text-muted-foreground">
Page {{ currentPage }} of {{ totalPages }} ({{ allGroupedPackages.length }} total packages)
Page {{ currentPage }} of {{ totalPages }} ({{ totalGroups }} total packages)
</p>
<Pagination
:page="currentPage"
:total="allGroupedPackages.length"
:page-size="itemsPerPage"
:total="totalGroups"
:page-size="PAGE_SIZE"
:show-edges="false"
@update:page="changePage"
/>
</div>
@@ -134,7 +136,7 @@
</template>
<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { onBeforeUnmount, onMounted, ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
@@ -177,7 +179,7 @@ const route = useRoute()
const router = useRouter()
const store = usePackageStore()
const toasts = useToastStore()
const { packages, loading, error } = storeToRefs(store)
const { packagePage, loading, error } = storeToRefs(store)
const showDeleteModal = ref(false)
const packageToDelete = ref<Package | null>(null)
@@ -188,88 +190,77 @@ const REGISTRY_OPTIONS = [
{ value: 'go', label: 'Go' },
]
const PAGE_SIZE = 25
const SEARCH_DEBOUNCE_MS = 300
const selectedRegistry = ref<string>(props.registry || 'all')
const searchTerm = ref<string>('')
// What the server was last asked: the search text lags the input by the debounce.
const activeQuery = ref<string>('')
const currentPage = ref<number>(1)
const itemsPerPage = ref<number>(10)
// Group packages by name
const allGroupedPackages = computed(() => {
const groups = new Map<string, Package[]>()
const totalGroups = computed(() => packagePage.value.totalGroups)
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
// Filter packages by selected registry and search term
let filteredPackages = selectedRegistry.value === 'all'
? packages.value
: packages.value.filter(pkg => pkg.registry === selectedRegistry.value)
// Apply search filter if search term exists
if (searchTerm.value.trim()) {
const searchLower = searchTerm.value.toLowerCase()
filteredPackages = filteredPackages.filter(pkg =>
pkg.name.toLowerCase().includes(searchLower) ||
displayVersion(pkg).toLowerCase().includes(searchLower) ||
pkg.version.toLowerCase().includes(searchLower)
)
// The server pages whole (registry, name) groups and sends every version row of each.
const groups = computed(() => {
const byKey = new Map<string, { registry: string; name: string; versions: Package[] }>()
for (const pkg of packagePage.value.packages) {
const key = `${pkg.registry}\u0000${pkg.name}`
let group = byKey.get(key)
if (!group) {
group = { registry: pkg.registry, name: pkg.name, versions: [] }
byKey.set(key, group)
}
group.versions.push(pkg)
}
return Array.from(byKey.values()).map((group) => ({
...group,
totalSize: group.versions.reduce((sum, v) => sum + v.size, 0),
totalDownloads: group.versions.reduce((sum, v) => sum + v.download_count, 0),
}))
})
filteredPackages.forEach(pkg => {
const key = `${pkg.registry}:${pkg.name}`
if (!groups.has(key)) {
groups.set(key, [])
}
groups.get(key)!.push(pkg)
async function load() {
await store.fetchPackagePage({
page: currentPage.value,
pageSize: PAGE_SIZE,
registry: selectedRegistry.value,
q: activeQuery.value,
})
// Convert to array and sort versions within each group
return Array.from(groups.entries()).map(([key, versions]) => {
const [registry, name] = key.split(':')
return {
registry,
name,
versions: versions.sort((a, b) =>
new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime()
),
totalSize: versions.reduce((sum, v) => sum + v.size, 0),
totalDownloads: versions.reduce((sum, v) => sum + v.download_count, 0),
}
}).sort((a, b) => a.name.localeCompare(b.name))
})
// Pagination
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
const groupedPackages = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage.value
const end = start + itemsPerPage.value
return allGroupedPackages.value.slice(start, end)
})
}
function changePage(page: number) {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page
void load()
// Scroll to top of packages list
window.scrollTo({ top: 0, behavior: 'smooth' })
}
}
// Reset to page 1 when filters change
function resetPagination() {
currentPage.value = 1
}
// Watch for filter/search changes and reset pagination
watch([selectedRegistry, searchTerm], () => {
resetPagination()
// A burst of keystrokes asks the server once.
let searchTimer: ReturnType<typeof setTimeout> | undefined
watch(searchTerm, (term) => {
clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
if (term === activeQuery.value) return
activeQuery.value = term
currentPage.value = 1
void load()
}, SEARCH_DEBOUNCE_MS)
})
onBeforeUnmount(() => clearTimeout(searchTimer))
// Watch for route parameter changes to update filter
watch(() => route.params.registry, (newRegistry) => {
selectedRegistry.value = (newRegistry as string) || 'all'
currentPage.value = 1
void load()
})
onMounted(async () => {
await store.fetchPackages()
})
onMounted(load)
function confirmDelete(pkg: Package) {
packageToDelete.value = pkg
@@ -287,7 +278,15 @@ async function deletePackage() {
toasts.error('Could not delete package', `${label}: ${store.error}`)
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
store.error = null
} else toasts.success('Package deleted', label)
} else {
toasts.success('Package deleted', label)
await load()
// Deleting the last group of the last page leaves that page empty.
if (packagePage.value.packages.length === 0 && totalGroups.value > 0 && currentPage.value > 1) {
currentPage.value = Math.max(totalPages.value, 1)
await load()
}
}
}
function showVulnerabilityDetails(registry: string, name: string, version: string) {
+52 -5
View File
@@ -1,18 +1,65 @@
<template>
<StatGroup :columns="4" :aria-label="label">
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
</KpiTile>
<template v-if="selectable">
<KpiTile
v-for="level in SEVERITY_LEVELS"
:key="level"
as="button"
type="button"
variant="interactive"
:label="formatSeverityName(level)"
:value="counts[level]"
:aria-pressed="isSelected(level)"
:class="isSelected(level) && 'ring-2 ring-primary'"
:data-severity="level"
@click="toggle(level)"
>
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
<template #hint>
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
{{ packageCounts ? ' · ' : '' }}Filter on
</span>
</template>
</KpiTile>
</template>
<template v-else>
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
</KpiTile>
</template>
</StatGroup>
</template>
<script setup lang="ts">
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
import type { VulnerabilityCounts } from '../stores/packages'
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
defineProps<{
const props = defineProps<{
counts: VulnerabilityCounts
label: string
/** Tiles become toggle buttons that edit `modelValue`. */
selectable?: boolean
/** Selected severities; several are allowed. */
modelValue?: readonly SeverityLevel[]
/** Packages per severity, shown on each tile in selectable mode. */
packageCounts?: VulnerabilityCounts
}>()
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
function isSelected(level: SeverityLevel): boolean {
return props.modelValue?.includes(level) ?? false
}
function toggle(level: SeverityLevel) {
const current = props.modelValue ?? []
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
}
function formatPackageCount(n: number): string {
return `${n} package${n === 1 ? '' : 's'}`
}
</script>
+42
View File
@@ -207,4 +207,46 @@ describe('Stats.vue', () => {
expect(wrapper.findAll('tbody th')).toHaveLength(0)
expect(wrapper.text()).toContain('No registries reported')
})
describe('idle eviction note', () => {
const baseStats = {
registry: '',
total_packages: 100,
total_size: 1073741824,
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
async function render(idleTtl?: number) {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
await wrapper.vm.$nextTick()
return wrapper
}
it.each([
[604800, 'Cached items not requested for 7 days are removed.'],
[86400, 'Cached items not requested for 1 day are removed.'],
[129600, 'Cached items not requested for 36 hours are removed.'],
[5400, 'Cached items not requested for 90 minutes are removed.'],
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
const wrapper = await render(seconds)
expect(wrapper.text()).toContain(sentence)
})
it('hides the note when idle eviction is off', async () => {
const wrapper = await render(0)
expect(wrapper.text()).not.toContain('not requested')
})
it('hides the note when the API sends no idle_ttl', async () => {
const wrapper = await render()
expect(wrapper.text()).not.toContain('not requested')
})
})
})
+12 -1
View File
@@ -13,6 +13,10 @@
/>
<template v-else>
<Alert v-if="idleTtl > 0" variant="info">
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
</Alert>
<Card>
<CardHeader>
<CardTitle as="h2">Overall statistics</CardTitle>
@@ -66,6 +70,8 @@
</CardContent>
</Card>
<TrendChart />
<Card>
<CardHeader>
<CardTitle as="h2">Registry breakdown</CardTitle>
@@ -91,6 +97,8 @@ import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { usePackageStore } from '../stores/packages'
import {
Alert,
AlertDescription,
Card,
CardContent,
CardHeader,
@@ -103,7 +111,8 @@ import {
StatGroup,
type DataTableColumn,
} from '@perfect-design/ui'
import { formatBytes, formatNumber } from '@/lib/format'
import TrendChart from './TrendChart.vue'
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
const store = usePackageStore()
@@ -162,6 +171,8 @@ const registries = computed(() => {
}))
})
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
const storagePercentage = computed(() => {
const totalSize = stats.value?.total_size || 0
const maxSize = stats.value?.max_cache_size || 1
+213
View File
@@ -0,0 +1,213 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import TrendChart from './TrendChart.vue'
import { TREND } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
import { formatTrendDate, trendValues } from '@/lib/trend'
vi.mock('axios')
let restore: (() => void) | undefined
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockReset()
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
})
afterEach(() => {
restore?.()
restore = undefined
vi.restoreAllMocks()
})
async function open(props: Record<string, unknown> = {}) {
const router = await createTestRouter('/stats')
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
restore = mounted.restore
await flushPromises()
return mounted
}
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
describe('TrendChart', () => {
it('requests the 30 day trend and draws both charts with accessible names', async () => {
const { wrapper, problems } = await open()
expect(problems).toEqual([])
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
expect(labels).toHaveLength(2)
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
})
it('offers every value as text through the chart data table', async () => {
const { wrapper } = await open()
const tables = wrapper.findAll('table')
expect(tables.length).toBeGreaterThanOrEqual(2)
expect(tables[0]!.text()).toContain('Cached packages')
expect(tables[0]!.text()).toContain('4')
})
it('refetches when the period changes', async () => {
const { wrapper } = await open()
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
await ninety.trigger('click')
await flushPromises()
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
})
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
const { wrapper } = await open()
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
expect(vulnerable()).not.toContain('lines for')
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
expect(critical.attributes('aria-pressed')).toBe('false')
await critical.trigger('click')
await flushPromises()
expect(critical.attributes('aria-pressed')).toBe('true')
expect(vulnerable()).toContain('with lines for critical')
expect(wrapper.text()).toContain('Packages with critical vulnerabilities')
await critical.trigger('click')
await flushPromises()
expect(vulnerable()).not.toContain('lines for')
})
it('offers all four severities as toggle buttons', async () => {
const { wrapper } = await open()
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
})
it('says plainly when vulnerability history starts after the first day', async () => {
const { wrapper } = await open()
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
})
it('shows no note when every day has vulnerability data', async () => {
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
vi.mocked(axios.get).mockResolvedValue({ data: full })
const { wrapper } = await open()
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
})
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
const noScans = {
...TREND,
vulnerability_history_start: null,
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
}
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
const { wrapper, problems } = await open()
expect(problems).toEqual([])
expect(charts(wrapper)).toHaveLength(1)
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
})
it('shows an empty state when the server holds no snapshots', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
const { wrapper } = await open()
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
expect(charts(wrapper)).toHaveLength(0)
})
it('shows a loading state until the first answer arrives', async () => {
let resolve!: (value: unknown) => void
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
const { wrapper } = await open()
expect(wrapper.text()).toContain('Loading package history...')
resolve({ data: TREND })
await flushPromises()
expect(wrapper.text()).not.toContain('Loading package history...')
expect(charts(wrapper)).toHaveLength(2)
})
it('shows the error with a retry that fetches again', async () => {
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
const { wrapper, problems } = await open()
expect(problems).toEqual([])
const state = wrapper.get('[data-slot="error-state"]')
expect(state.text()).toContain('502')
expect(charts(wrapper)).toHaveLength(0)
await state.get('button').trigger('click')
await flushPromises()
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
expect(charts(wrapper)).toHaveLength(2)
expect(requested()).toHaveLength(2)
})
it('rejects a body without points as an error, not an empty chart', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
const { wrapper } = await open()
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
})
it('ignores an answer that a newer request has replaced', async () => {
const answers: Array<(v: unknown) => void> = []
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
const { wrapper } = await open()
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
await flushPromises()
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
await flushPromises()
answers[0]!({ data: TREND })
await flushPromises()
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
})
describe('compact', () => {
it('always asks for 30 days, draws one chart and links to the full history', async () => {
const { wrapper, problems } = await open({ compact: true })
expect(problems).toEqual([])
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
expect(charts(wrapper)).toHaveLength(1)
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
})
it('says so when the latest day has no vulnerability data', async () => {
const last = { ...TREND.points[2]!, vulnerable_packages: null }
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
const { wrapper } = await open({ compact: true })
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
})
})
})
describe('trend helpers', () => {
it('formats a UTC date without shifting it with the viewer zone', () => {
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
})
it('turns unknown counts into gaps, never zeros', () => {
const values = trendValues(TREND.points, 'vulnerable_packages')
expect(values[0]).toBeNaN()
expect(values.slice(1)).toEqual([1, 2])
})
})
+196
View File
@@ -0,0 +1,196 @@
<template>
<Card data-testid="trend-card">
<CardHeader>
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
<CardDescription>
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
</CardDescription>
<CardAction>
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
<Button v-else as-child variant="link" size="sm">
<RouterLink to="/stats">Open the full history</RouterLink>
</Button>
</CardAction>
</CardHeader>
<CardContent class="flex flex-col gap-8">
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
<ErrorState
v-else-if="error"
variant="inline"
title="Could not load the package history"
:message="error"
@retry="load"
/>
<EmptyState
v-else-if="points.length === 0"
title="No history yet"
description="The server records the first daily snapshot when it starts, then one more each day."
/>
<template v-else>
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
<LineChart
variant="area"
:size="compact ? 'sm' : 'md'"
:y-min="0"
:labels="labels"
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
:label="packagesLabel"
/>
</section>
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
{{ compactVulnerable }}
</p>
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
<ToggleGroup
v-model="severities"
type="multiple"
variant="outline"
size="sm"
aria-label="Add a line per severity"
>
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
{{ formatSeverityName(level) }}
</ToggleGroupItem>
</ToggleGroup>
</div>
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
{{ vulnerabilityNote }}
</p>
<LineChart
v-if="data?.vulnerability_history_start"
:y-min="0"
:labels="labels"
:series="vulnerableSeries"
:label="vulnerableLabel"
/>
<EmptyState
v-else
size="sm"
title="Vulnerability history has not started"
description="Scan results are counted from the first daily snapshot that includes them."
/>
</section>
</template>
</CardContent>
</Card>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { RouterLink } from 'vue-router'
import {
Button,
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
LineChart,
LoadingState,
SegmentedControl,
ToggleGroup,
ToggleGroupItem,
} from '@perfect-design/ui'
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
import {
DEFAULT_TREND_PERIOD,
SEVERITY_LINE_TONES,
TREND_PERIODS,
formatTrendDate,
trendValues,
type TrendPeriod,
type TrendPoint,
type TrendResponse,
} from '@/lib/trend'
const props = defineProps<{
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
compact?: boolean
}>()
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
const severities = ref<SeverityLevel[]>([])
const data = ref<TrendResponse | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
let request = 0
async function load() {
const current = ++request
loading.value = true
error.value = null
try {
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
if (current !== request) return
const body = response.data as TrendResponse | undefined
if (!body || !Array.isArray(body.points)) {
data.value = null
error.value = 'Unexpected response format from server'
return
}
data.value = body
} catch (err) {
if (current !== request) return
data.value = null
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
} finally {
if (current === request) loading.value = false
}
}
onMounted(load)
watch(period, load)
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
function span(key: keyof Omit<TrendPoint, 'date'>): string {
const known = points.value.filter((p) => p[key] !== null)
const first = known[0]
const last = known[known.length - 1]
if (!first || !last) return ''
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
}
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
const vulnerableLabel = computed(() => {
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
})
const vulnerableSeries = computed(() => [
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
name: `Packages with ${level} vulnerabilities`,
data: values(level),
tone: SEVERITY_LINE_TONES[level],
})),
])
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
const vulnerabilityNote = computed(() => {
const start = data.value?.vulnerability_history_start
const first = points.value[0]
if (!start) return 'Vulnerability history has not started in this period.'
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
return ''
})
const compactVulnerable = computed(() => {
const last = points.value[points.value.length - 1]
const n = last?.vulnerable_packages
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
return `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
})
</script>
@@ -0,0 +1,226 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import VulnerablePackages from './VulnerablePackages.vue'
import type { Package, VulnerabilityCounts } from '@/stores/packages'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
vi.mock('axios')
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
return {
id: name,
registry: 'npm',
name,
version: '1.0.0',
size: 1024,
cached_at: '2026-01-03T10:00:00Z',
last_accessed: '2026-01-03T10:00:00Z',
download_count: 1,
vulnerabilities: {
scanned: true,
status: 'vulnerable',
counts: full,
total: full.critical + full.high + full.moderate + full.low,
scannedAt: '2026-01-03T10:05:00Z',
isBlocked: false,
},
}
}
const ALL_SEVERITIES = 'critical,high,moderate,low'
const FIXTURE: Package[] = [
vulnerable('alpha-critical', { critical: 1 }),
vulnerable('bravo-high', { high: 2 }),
vulnerable('charlie-moderate', { moderate: 1 }),
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
]
const NAMES = FIXTURE.map((p) => p.name)
let restore: (() => void) | undefined
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
})
afterEach(() => {
restore?.()
restore = undefined
vi.restoreAllMocks()
})
async function open(path = '/vulnerable-packages') {
const router = await createTestRouter(path)
const pinia = createPinia()
setActivePinia(pinia)
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
restore = mounted.restore
await flushPromises()
return { ...mounted, router }
}
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
const pressed = (wrapper: Wrapper) =>
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
describe('VulnerablePackages severity filter', () => {
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
const { wrapper, problems, router } = await open()
expect(problems).toEqual([])
expect(shown(wrapper)).toEqual(NAMES)
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
expect(wrapper.text()).not.toContain('Filter on')
expect(clearButtons(wrapper)).toHaveLength(0)
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('asks the server for vulnerable packages only', async () => {
await open()
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
})
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
const { wrapper } = await open()
const tiles = wrapper.findAll('button[data-severity]')
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
for (const t of tiles) {
expect(t.element.tagName).toBe('BUTTON')
expect(t.attributes('type')).toBe('button')
expect(t.attributes('tabindex')).not.toBe('-1')
expect(t.attributes('aria-pressed')).toBeDefined()
}
})
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'high').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['bravo-high'])
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
expect(tile(wrapper, 'high').text()).toContain('Filter on')
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
expect(clearButtons(wrapper)).toHaveLength(1)
expect(router.currentRoute.value.query.severity).toBe('high')
})
it('keeps the tile counts of the whole list while a filter is on', async () => {
const { wrapper } = await open()
const before = tile(wrapper, 'critical').text()
await tile(wrapper, 'high').trigger('click')
await flushPromises()
expect(tile(wrapper, 'critical').text()).toBe(before)
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
})
it('selects several severities with OR semantics', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'critical').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
await tile(wrapper, 'high').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
expect(router.currentRoute.value.query.severity).toBe('critical,high')
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
})
it('a second click toggles the filter off and removes the query', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'moderate').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
await tile(wrapper, 'moderate').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(NAMES)
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
expect(clearButtons(wrapper)).toHaveLength(0)
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('Clear filters resets every selected severity at once', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'critical').trigger('click')
await tile(wrapper, 'high').trigger('click')
await flushPromises()
await clearButtons(wrapper)[0]!.trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(NAMES)
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('restores the filter from the URL, as after a reload or a shared link', async () => {
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
expect(clearButtons(wrapper)).toHaveLength(1)
})
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
expect(shown(wrapper)).toEqual(NAMES)
expect(clearButtons(wrapper)).toHaveLength(0)
await tile(wrapper, 'low').trigger('click')
await flushPromises()
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
})
it('shows a library empty state with a clear control when no package matches', async () => {
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
const empty = wrapper.get('[data-slot="empty-state"]')
expect(empty.text()).toContain('No packages match the filter')
expect(shown(wrapper)).toEqual([])
// The tiles stay so the filter can be changed without leaving the page.
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(NAMES)
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
const { wrapper } = await open('/vulnerable-packages?severity=critical')
expect(wrapper.text()).toContain('No vulnerable packages')
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
})
it('still narrows to blocked packages on the blocked route', async () => {
const blocked = vulnerable('echo-blocked', { critical: 1 })
blocked.vulnerabilities!.isBlocked = true
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
const { wrapper } = await open('/blocked-packages?severity=critical')
expect(wrapper.text()).toContain('echo-blocked')
expect(wrapper.text()).not.toContain('alpha-critical')
})
})
+79 -8
View File
@@ -23,7 +23,7 @@
@retry="fetchVulnerablePackages"
/>
<Card v-else-if="sortedVulnerablePackages.length === 0">
<Card v-else-if="vulnerablePackages.length === 0">
<CardContent>
<EmptyState
tone="success"
@@ -35,9 +35,34 @@
</Card>
<template v-else>
<SeveritySummary :counts="totalCounts" label="Vulnerabilities by severity" />
<SeveritySummary
v-model="selectedSeverities"
selectable
:counts="totalCounts"
:package-counts="packageCounts"
label="Vulnerabilities by severity. Select a severity to filter the packages."
/>
<Card>
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
</div>
<Card v-if="sortedVulnerablePackages.length === 0">
<CardContent>
<EmptyState
:icon="faCircleCheck"
title="No packages match the filter"
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
>
<template #action>
<Button variant="outline" @click="clearFilters">Clear filters</Button>
</template>
</EmptyState>
</CardContent>
</Card>
<Card v-else>
<CardHeader>
<CardTitle as="h2">
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
@@ -104,7 +129,7 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
import {
Accordion,
AccordionContent,
@@ -128,12 +153,38 @@ import VulnerabilityBadge from './VulnerabilityBadge.vue'
import SeveritySummary from './SeveritySummary.vue'
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
import { NO_VULNERABILITIES } from '@/lib/severity'
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
const store = usePackageStore()
const router = useRouter()
const route = useRoute()
const SEVERITY_QUERY = 'severity'
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
}
// The URL is the source of truth, so a reload or a shared link restores the filter.
const selectedSeverities = computed<SeverityLevel[]>({
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
set: (levels) => {
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
},
})
const hasFilter = computed(() => selectedSeverities.value.length > 0)
const filterSummary = computed(() =>
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
)
function clearFilters() {
selectedSeverities.value = []
}
const loading = ref(false)
const error = ref<string | null>(null)
const vulnerablePackages = ref<Package[]>([])
@@ -150,7 +201,8 @@ async function fetchVulnerablePackages() {
error.value = null
try {
await store.fetchPackages()
// The server drops clean packages; the toggles below narrow the rest without another request.
await store.fetchPackages({ severity: SEVERITY_LEVELS })
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
if (store.error) {
error.value = store.error
@@ -171,9 +223,17 @@ async function fetchVulnerablePackages() {
}
}
// A package passes when it has at least one vulnerability of any selected severity.
const filteredPackages = computed(() => {
if (!hasFilter.value) return vulnerablePackages.value
return vulnerablePackages.value.filter((pkg) =>
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
)
})
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
const sortedVulnerablePackages = computed(() => {
return [...vulnerablePackages.value].sort((a, b) => {
return [...filteredPackages.value].sort((a, b) => {
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
@@ -227,7 +287,18 @@ const groupedPackages = computed(() => {
return Array.from(groups.values())
})
// Calculate total counts across all packages
// Packages holding at least one vulnerability of each severity, before any filter.
const packageCounts = computed<VulnerabilityCounts>(() => {
const counts = { ...NO_VULNERABILITIES }
for (const pkg of vulnerablePackages.value) {
for (const level of SEVERITY_LEVELS) {
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
}
}
return counts
})
// Calculate total counts across all packages, before any filter
const totalCounts = computed(() =>
vulnerablePackages.value.reduce(
(sum, pkg) => {
+120 -2
View File
@@ -12,7 +12,7 @@ import Stats from './Stats.vue'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
import { usePackageStore } from '@/stores/packages'
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
@@ -22,6 +22,7 @@ const API_KEY_STORAGE = 'admin_api_key'
function respond(url: string) {
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
if (url.startsWith('/api/stats/trend')) return { data: TREND }
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
@@ -140,6 +141,31 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(document.body.querySelector('textarea')).not.toBeNull()
})
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
localStorage.clear()
const prompt = vi.spyOn(window, 'prompt')
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
await flushPromises()
expect(problems).toEqual([])
expect(prompt).not.toHaveBeenCalled()
expect(document.body.textContent).toContain('Enter your admin API key to manage bypasses.')
const input = document.body.querySelector<HTMLInputElement>('input[type="password"]')
expect(input).not.toBeNull()
input!.value = 'secret-key'
input!.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
document.body.querySelector<HTMLFormElement>('input[type="password"]')!.form!.requestSubmit()
await flushPromises()
expect(localStorage.getItem('admin_api_key')).toBe('secret-key')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(
expect.stringContaining('/api/admin/bypasses'),
expect.objectContaining({ headers: { Authorization: 'Bearer secret-key' } }),
)
expect(wrapper.text()).toContain('CVE-2026-0002')
})
it('Stats renders totals, the storage tile and the registry table', async () => {
const { wrapper, problems } = await smoke(Stats, '/stats')
expect(problems).toEqual([])
@@ -183,6 +209,98 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
it('PackageList still fetches through the store on mount', async () => {
await smoke(PackageList, '/packages')
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
expect(usePackageStore().packagePage.packages.length).toBe(PACKAGES.length)
})
})
describe('PyPI rows show the release version, not the file name', () => {
const FILE = 'six-1.17.0-py2.py3-none-any.whl'
const SIX = {
id: 'pypi-six',
registry: 'pypi',
name: 'six',
version: FILE,
release_version: '1.17.0',
size: 1,
cached_at: '2026-02-01T10:00:00Z',
last_accessed: '2026-02-01T10:00:00Z',
download_count: 1,
vulnerabilities: {
scanned: true,
status: 'vulnerable',
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
total: 1,
scannedAt: '2026-02-01T10:05:00Z',
isBlocked: false,
},
}
beforeEach(() => {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.endsWith('/vulnerabilities')) {
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
}
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
return respond(url) as never
})
})
it('Dashboard recent packages', async () => {
const { wrapper } = await smoke(Dashboard, '/')
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('Dashboard activity feed', async () => {
const router = await createTestRouter('/')
const pinia = createPinia()
setActivePinia(pinia)
const rt = useRealtimeStore()
vi.spyOn(rt, 'connect').mockImplementation(() => {})
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
const { wrapper, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
restore = r
await flushPromises()
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
expect(feed).toContain('[email protected]')
expect(feed).not.toContain('whl')
})
it('VulnerablePackages version column', async () => {
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
await flushPromises()
await wrapper.find('button[aria-expanded]').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('PackageDetails header badge', async () => {
const { wrapper } = await smoke(PackageDetails, `/package/pypi/six/${FILE}`)
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
await router.push(`/package/pypi/six/${FILE}`)
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('PackageDetails falls back to the route version without a release version', async () => {
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
const { wrapper } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
await router.push('/package/npm/left-pad/1.3.0')
await flushPromises()
expect(wrapper.text()).toContain('v1.3.0')
})
it('bypass form tells PyPI users to use the release version', async () => {
const { wrapper } = await smoke(BypassManagementPanel, '/admin/bypasses')
await wrapper.findAll('button').find((b) => b.text() === 'Create bypass')!.trigger('click')
await flushPromises()
const pkg = Array.from(document.body.querySelectorAll<HTMLElement>('button, [role="radio"]')).find((e) => e.textContent?.trim() === 'Package bypass')
pkg!.click()
await flushPromises()
expect(document.body.textContent).toContain('pypi/[email protected]')
})
})
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest'
import { formatDuration } from './format'
describe('formatDuration', () => {
it.each([
[604800, '7 days'],
[86400, '1 day'],
[129600, '36 hours'],
[3600, '1 hour'],
[5400, '90 minutes'],
[60, '1 minute'],
])('formats %i seconds as %s', (seconds, expected) => {
expect(formatDuration(seconds)).toBe(expected)
})
})
+15
View File
@@ -11,6 +11,21 @@ export function formatBytes(bytes: number): string {
return Math.round((bytes / Math.pow(BYTES_PER_UNIT, i)) * 100) / 100 + ' ' + BYTE_UNITS[i]
}
const SECONDS_PER_DAY = 86400
const SECONDS_PER_HOUR = 3600
const SECONDS_PER_MINUTE = 60
function plural(n: number, unit: string): string {
return `${n} ${unit}${n === 1 ? '' : 's'}`
}
/** Whole days, hours or minutes, using the largest unit that divides the span evenly. */
export function formatDuration(seconds: number): string {
if (seconds % SECONDS_PER_DAY === 0) return plural(seconds / SECONDS_PER_DAY, 'day')
if (seconds % SECONDS_PER_HOUR === 0) return plural(seconds / SECONDS_PER_HOUR, 'hour')
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
}
export function formatDate(date: string): string {
if (!date) return 'N/A'
const parsed = new Date(date)
+63
View File
@@ -0,0 +1,63 @@
import type { SeverityLevel } from '@/lib/severity'
export type TrendPeriod = '30day' | '90day' | '1year'
export const TREND_PERIODS: { value: TrendPeriod; label: string }[] = [
{ value: '30day', label: '30 days' },
{ value: '90day', label: '90 days' },
{ value: '1year', label: '1 year' },
]
export const DEFAULT_TREND_PERIOD: TrendPeriod = '30day'
/** One UTC day. A null count is unknown (no scan history yet), not zero. */
export interface TrendPoint {
date: string
total_packages: number
total_size: number
vulnerable_packages: number | null
critical: number | null
high: number | null
moderate: number | null
low: number | null
blocked: number | null
}
export interface TrendResponse {
period: TrendPeriod
from: string
to: string
/** First day in the window with vulnerability data; null when the window has none. */
vulnerability_history_start: string | null
points: TrendPoint[]
}
/** Chart tone of each severity line, from the LineChart tone set. */
export const SEVERITY_LINE_TONES: Record<SeverityLevel, 'danger' | 'warning' | 'info' | 'muted'> = {
critical: 'danger',
high: 'warning',
moderate: 'info',
low: 'muted',
}
/** "2026-11-23" as "23 Nov", read in UTC so the label never shifts a day with the viewer's zone. */
export function formatTrendDate(iso: string, withYear = false): string {
const date = new Date(`${iso}T00:00:00Z`)
if (Number.isNaN(date.getTime())) return iso
return date.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short',
year: withYear ? 'numeric' : undefined,
timeZone: 'UTC',
})
}
/** Chart values of one count; unknown days become NaN, which breaks the line instead of drawing zero. */
export function trendValues(points: readonly TrendPoint[], key: keyof Omit<TrendPoint, 'date'>): number[] {
return points.map((p) => p[key] ?? Number.NaN)
}
/** True when some day in the window has no vulnerability data. */
export function hasUnknownVulnerabilityDays(points: readonly TrendPoint[]): boolean {
return points.some((p) => p.vulnerable_packages === null)
}
+135
View File
@@ -0,0 +1,135 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { usePackageStore, RECENT_PACKAGES, type Package } from './packages'
vi.mock('axios')
function pkg(id: number, cachedAt: string, over: Partial<Package> = {}): Package {
return {
id: String(id),
registry: 'npm',
name: `p${id}`,
version: '1.0.0',
size: 1,
cached_at: cachedAt,
last_accessed: cachedAt,
download_count: 0,
...over,
}
}
describe('package store paging', () => {
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockReset()
})
afterEach(() => vi.restoreAllMocks())
it('sends page, page_size, registry and q; skips the all-registries and empty values', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [], total_groups: 0 } })
const store = usePackageStore()
await store.fetchPackagePage({ page: 2, pageSize: 25, registry: 'pypi', q: ' six ' })
await store.fetchPackagePage({ page: 1, pageSize: 25, registry: 'all', q: '' })
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
'/api/packages?page=2&page_size=25&registry=pypi&q=six',
'/api/packages?page=1&page_size=25',
])
})
it('fetchPackages asks for the listed severities only, and for everything without them', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
const store = usePackageStore()
await store.fetchPackages()
await store.fetchPackages({ severity: [] })
await store.fetchPackages({ severity: ['critical', 'high'] })
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
'/api/packages',
'/api/packages',
'/api/packages?severity=critical,high',
])
})
it('keeps the server group count, and counts groups itself when the server sends none', async () => {
const store = usePackageStore()
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 80 } })
await store.fetchPackagePage({ page: 3, pageSize: 25 })
expect(store.packagePage).toMatchObject({ totalGroups: 80, page: 3, pageSize: 25 })
vi.mocked(axios.get).mockResolvedValueOnce({
data: { packages: [pkg(1, '2026-01-01T00:00:00Z'), pkg(1, '2026-01-02T00:00:00Z', { version: '2.0.0' })] },
})
await store.fetchPackagePage({ page: 1, pageSize: 25 })
expect(store.packagePage.totalGroups).toBe(1)
})
it('drops the answer of a request a newer one has replaced', async () => {
const store = usePackageStore()
let release: (v: unknown) => void = () => {}
vi.mocked(axios.get)
.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
.mockResolvedValueOnce({ data: { packages: [pkg(2, '2026-01-01T00:00:00Z')], total_groups: 1 } })
const slow = store.fetchPackagePage({ page: 1, pageSize: 25, q: 'old' })
await store.fetchPackagePage({ page: 1, pageSize: 25, q: 'new' })
release({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
await slow
expect(store.packagePage.packages.map((p) => p.id)).toEqual(['2'])
expect(store.loading).toBe(false)
})
it('reports a failed page request and leaves the last page in place', async () => {
const store = usePackageStore()
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
await store.fetchPackagePage({ page: 1, pageSize: 25 })
vi.mocked(axios.get).mockRejectedValueOnce(new Error('502'))
await store.fetchPackagePage({ page: 1, pageSize: 25 })
expect(store.error).toBe('502')
expect(store.packagePage.packages).toHaveLength(1)
expect(store.loading).toBe(false)
})
it('recent packages: small page sorted by cached_at, newest ten rows, newest first', async () => {
const rows = Array.from({ length: 14 }, (_, i) => pkg(i, `2026-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`))
vi.mocked(axios.get).mockResolvedValue({ data: { packages: rows, total_groups: 14 } })
const store = usePackageStore()
await store.fetchRecentPackages()
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(`/api/packages?page=1&page_size=${RECENT_PACKAGES}&sort=cached_at&order=desc`)
expect(store.recentPackages).toHaveLength(RECENT_PACKAGES)
expect(store.recentPackages[0].id).toBe('13')
expect(store.recentPackages[9].id).toBe('4')
})
it('loading stays on until the last overlapping request settles', async () => {
const store = usePackageStore()
const releases: Array<(v: unknown) => void> = []
vi.mocked(axios.get).mockImplementation(() => new Promise((resolve) => releases.push(resolve)))
const stats = store.fetchStats()
const recent = store.fetchRecentPackages()
expect(store.loading).toBe(true)
releases[0]({ data: { stats: { total_packages: 1 }, registries: {} } })
await stats
expect(store.loading).toBe(true)
releases[1]({ data: { packages: [] } })
await recent
expect(store.loading).toBe(false)
})
it('delete removes one version and leaves reloading to the caller', async () => {
vi.mocked(axios.delete).mockResolvedValue({})
const store = usePackageStore()
await store.deletePackage('npm', 'left-pad', '1.0.0')
expect(vi.mocked(axios.delete)).toHaveBeenCalledWith('/api/packages/npm/left-pad/1.0.0')
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
})
})
+118 -10
View File
@@ -40,20 +40,70 @@ export interface Stats {
scanned_packages: number
vulnerable_packages: number
blocked_packages: number
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
idle_ttl?: number
}
export type PackageSort = 'name' | 'cached_at' | 'downloads' | 'size'
export interface PackagePageParams {
page: number
pageSize: number
/** Empty or 'all' means every registry. */
registry?: string
/** Case-insensitive match on name, version or release version. */
q?: string
sort?: PackageSort
order?: 'asc' | 'desc'
}
/** One page of package groups: every version row of each group, in group order. */
export interface PackagePage {
packages: Package[]
totalGroups: number
page: number
pageSize: number
}
/** Rows shown under "Recent packages". */
export const RECENT_PACKAGES = 10
function distinctGroups(rows: Package[]): number {
return new Set(rows.map((p) => `${p.registry}\u0000${p.name}`)).size
}
export const usePackageStore = defineStore('packages', () => {
const packages = ref<Package[]>([])
const packagePage = ref<PackagePage>({ packages: [], totalGroups: 0, page: 1, pageSize: 25 })
const recentPackages = ref<Package[]>([])
const stats = ref<Stats | null>(null)
const registries = ref<Record<string, any>>({})
const loading = ref(false)
const error = ref<string | null>(null)
async function fetchPackages() {
// Requests overlap (stats next to the recent list, a new search before the last answer),
// so loading stays on until the last one settles.
let inFlight = 0
function begin() {
inFlight++
loading.value = true
error.value = null
}
function settle() {
inFlight = Math.max(inFlight - 1, 0)
if (inFlight === 0) loading.value = false
}
let pageRequest = 0
/**
* Every package, unpaginated. Only views that filter on scan results need it.
* `severity` keeps the packages whose latest scan has a vulnerability of any listed severity.
*/
async function fetchPackages(options: { severity?: readonly string[] } = {}) {
begin()
try {
const response = await axios.get('/api/packages')
const query = options.severity?.length ? `?severity=${options.severity.join(',')}` : ''
const response = await axios.get(`/api/packages${query}`)
// Only update packages if we got valid data
if (response.data && Array.isArray(response.data.packages)) {
packages.value = response.data.packages
@@ -66,13 +116,68 @@ export const usePackageStore = defineStore('packages', () => {
error.value = err.message
// Don't clear packages on error - keep showing the cached data
} finally {
loading.value = false
settle()
}
}
async function fetchPackagePage(params: PackagePageParams) {
const request = ++pageRequest
begin()
try {
const query = new URLSearchParams({ page: String(params.page), page_size: String(params.pageSize) })
if (params.registry && params.registry !== 'all') query.set('registry', params.registry)
if (params.q?.trim()) query.set('q', params.q.trim())
if (params.sort) query.set('sort', params.sort)
if (params.order) query.set('order', params.order)
const response = await axios.get(`/api/packages?${query.toString()}`)
// A newer request is on its way; its answer must win.
if (request !== pageRequest) return
const data = response.data
if (data && Array.isArray(data.packages)) {
packagePage.value = {
packages: data.packages,
totalGroups: Number.isFinite(data.total_groups) ? data.total_groups : distinctGroups(data.packages),
page: params.page,
pageSize: params.pageSize,
}
} else {
console.warn('Unexpected API response format:', data)
error.value = 'Unexpected response format from server'
}
} catch (err: any) {
if (request !== pageRequest) return
console.error('Failed to fetch packages:', err)
error.value = err.message
} finally {
settle()
}
}
async function fetchRecentPackages() {
begin()
try {
const response = await axios.get(
`/api/packages?page=1&page_size=${RECENT_PACKAGES}&sort=cached_at&order=desc`,
)
if (response.data && Array.isArray(response.data.packages)) {
// The page holds whole groups, so the newest rows are in there but not in order.
recentPackages.value = [...response.data.packages]
.sort((a: Package, b: Package) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
.slice(0, RECENT_PACKAGES)
} else {
console.warn('Unexpected API response format:', response.data)
error.value = 'Unexpected response format from server'
}
} catch (err: any) {
console.error('Failed to fetch recent packages:', err)
error.value = err.message
} finally {
settle()
}
}
async function fetchStats(registry = '') {
loading.value = true
error.value = null
begin()
try {
const url = registry ? `/api/stats?registry=${registry}` : '/api/stats'
const response = await axios.get(url)
@@ -89,30 +194,33 @@ export const usePackageStore = defineStore('packages', () => {
error.value = err.message
// Don't clear stats on error - keep showing the cached data
} finally {
loading.value = false
settle()
}
}
/** Deletes one version; the caller reloads whichever list it shows. */
async function deletePackage(registry: string, name: string, version: string) {
loading.value = true
error.value = null
begin()
try {
await axios.delete(`/api/packages/${registry}/${name}/${version}`)
await fetchPackages()
} catch (err: any) {
error.value = err.message
} finally {
loading.value = false
settle()
}
}
return {
packages,
packagePage,
recentPackages,
stats,
registries,
loading,
error,
fetchPackages,
fetchPackagePage,
fetchRecentPackages,
fetchStats,
deletePackage,
}
+16
View File
@@ -53,6 +53,22 @@ describe('useRealtimeStore', () => {
expect(store.lastStats).toMatchObject({ total_packages: 42, total_size: 1024 })
})
it('unwraps the server stats_update shape {stats, timestamp}', () => {
const store = useRealtimeStore()
store.ingest(
makeEvent('stats_update', {
stats: { total_packages: 1454, total_size: 980870617, total_downloads: 5376, scanned_packages: 1451 },
timestamp: '2026-11-23T16:00:00Z',
}),
)
expect(store.lastStats).toMatchObject({
total_packages: 1454,
total_size: 980870617,
total_downloads: 5376,
scanned_packages: 1451,
})
})
it('exposes filtered computed slices', () => {
const store = useRealtimeStore()
store.ingest(makeEvent('package_cached'))
+3 -1
View File
@@ -55,7 +55,9 @@ export const useRealtimeStore = defineStore('realtime', () => {
events.value.splice(0, events.value.length - EVENTS_CAP)
}
if (event.type === 'stats_update') {
lastStats.value = event.payload as RealtimeStats
// The server nests the counters under `stats`; reading the payload flat shows zeros.
const nested = event.payload.stats
lastStats.value = (nested && typeof nested === 'object' ? nested : event.payload) as RealtimeStats
}
}
+3
View File
@@ -10,6 +10,7 @@
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
@@ -59,6 +60,8 @@
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
+16
View File
@@ -158,3 +158,19 @@ export const BYPASSES = [
active: false,
},
]
function trendDay(offset: number): string {
return new Date(Date.UTC(2026, 0, 4 + offset)).toISOString().slice(0, 10)
}
export const TREND = {
period: '30day',
from: trendDay(-2),
to: trendDay(0),
vulnerability_history_start: trendDay(-1),
points: [
{ date: trendDay(-2), total_packages: 3, total_size: 3072, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null, blocked: null },
{ date: trendDay(-1), total_packages: 4, total_size: 7168, vulnerable_packages: 1, critical: 0, high: 1, moderate: 0, low: 0, blocked: null },
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
],
}
+3
View File
@@ -5,6 +5,7 @@ import { themeBootScript } from '@perfect-design/ui/stores/theme-boot'
// Get backend URL from environment or use default
const BACKEND_URL = process.env.VITE_BACKEND_URL || 'http://localhost:8080'
const WS_ORIGIN = process.env.VITE_WS_ORIGIN
const FRONTEND_PORT = parseInt(process.env.VITE_PORT || '5173')
// Applies the saved colour mode before first paint so a dark system never flashes light.
@@ -33,6 +34,8 @@ export default defineConfig({
target: BACKEND_URL.replace('http', 'ws'),
ws: true,
changeOrigin: true,
// A backend with an origin allowlist refuses the dev server origin; set this to an allowed one.
...(WS_ORIGIN ? { headers: { Origin: WS_ORIGIN } } : {}),
},
},
},
+3 -3
View File
@@ -15,6 +15,7 @@ require (
github.com/gorilla/websocket v1.5.3
github.com/lib/pq v1.12.3
github.com/prometheus/client_golang v1.25.0
github.com/prometheus/client_model v0.6.3
github.com/rs/zerolog v1.35.1
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
@@ -87,7 +88,7 @@ require (
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/klauspost/compress v1.20.5 // indirect
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 // indirect
github.com/magiconair/properties v1.18.13 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
@@ -110,7 +111,6 @@ require (
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/philhofer/fwd v1.2.1 // indirect
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
@@ -127,7 +127,7 @@ require (
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.79.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
+6 -6
View File
@@ -149,8 +149,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -218,8 +218,8 @@ github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/n
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@@ -278,8 +278,8 @@ github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcY
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE=
go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
+4
View File
@@ -10,8 +10,10 @@ data:
host: {{ .Values.server.host | quote }}
port: {{ .Values.server.port }}
read_timeout: {{ .Values.server.readTimeout | quote }}
read_buffer_size: {{ .Values.server.readBufferSize }}
write_timeout: {{ .Values.server.writeTimeout | quote }}
idle_timeout: {{ .Values.server.idleTimeout | quote }}
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
tls:
enabled: false
@@ -73,6 +75,8 @@ data:
cache:
default_ttl: {{ .Values.cache.defaultTTL | quote }}
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
idle_ttl: {{ .Values.cache.idleTTL | quote }}
deleted_retention: {{ .Values.cache.deletedRetention | default "720h" | quote }}
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
per_project_quota: {{ .Values.cache.perProjectQuota }}
ttl_overrides:
+10 -5
View File
@@ -91,8 +91,11 @@ server:
host: "0.0.0.0"
port: 8080
readTimeout: "5m"
readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431
writeTimeout: "5m"
idleTimeout: "2m"
# Browser origins allowed to use /api and /ws; empty = same-origin only
allowedOrigins: []
# Additional environment variables for server container
# Use this to override config via environment variables
@@ -375,14 +378,16 @@ migration:
# Cache configuration
cache:
defaultTTL: "168h" # 7 days
defaultTTL: "24h" # Freshness window for metadata pages; keep below the 72h client release-age gate
cleanupInterval: "1h"
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
deletedRetention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
maxSizeBytes: 536870912000 # 500GB
perProjectQuota: 53687091200 # 50GB
ttlOverrides:
npm: "168h"
pip: "168h"
go: "168h"
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
npm: "24h"
pypi: "24h"
go: "24h"
# Security scanning configuration
security:
+42
View File
@@ -0,0 +1,42 @@
// Package dbcount counts the SQL statements a GORM handle runs, for query-count tests.
package dbcount
import (
"context"
"sync/atomic"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Counter holds the number of statements seen since the last Reset.
type Counter struct {
n atomic.Int64
}
// Attach returns a session of db that counts every statement it executes. It
// swaps the logger instead of registering callbacks, because callback
// registration is not safe while other goroutines already run queries.
// GORM runs a subquery as a dry run with a discarded logger, so subqueries do not count.
func Attach(db *gorm.DB) (*gorm.DB, *Counter) {
c := &Counter{}
return db.Session(&gorm.Session{Logger: &countingLogger{Interface: logger.Discard, c: c}}), c
}
// Reset zeroes the count.
func (c *Counter) Reset() { c.n.Store(0) }
// Count returns the statements counted since the last Reset.
func (c *Counter) Count() int { return int(c.n.Load()) }
type countingLogger struct {
logger.Interface
c *Counter
}
func (l *countingLogger) LogMode(logger.LogLevel) logger.Interface { return l }
func (l *countingLogger) Trace(context.Context, time.Time, func() (string, int64), error) {
l.c.n.Add(1)
}
+1
View File
@@ -0,0 +1 @@
.lake/
+124
View File
@@ -0,0 +1,124 @@
# Lean audit findings
Audit of GoHoarder at c98720c (v0.1.303) with Lean 4 + Mathlib v4.36.0. Models live in
`lean4/Gohoarder/*.lean`; each cites the Go files it models. Statements are "proved about the model".
A Lean counterexample is never the evidence alone: every fixed row has a Go test that failed first.
Build: `cd lean4 && lake exe cache get && lake build && lake env lean scripts/Axioms.lean`.
Currency: `sh lean4/scripts/check_currency.sh origin/main`.
## Fixed
| id | area | claim | class | severity | evidence (Lean / Go test) | fix commit |
|----|------|-------|-------|----------|---------------------------|------------|
| GH-01 | PyPI fetch | the file fetched from `original_url` is the file the cache key names | security, CWE-345 | high | `Access.old_guard_allows_key_poisoning`, `fixed_guard_binds_key` / `TestHandlePackageFile_OriginalURLFilenameBound` | 5c9f7e6 |
| GH-02 | scan decision | a bypassed CVE never blocks, under any `block_on_severity` | correctness (over-block) | low | `Security.old_low_ignores_bypass`, `fully_bypassed_never_blocks` / `TestCheckVulnerabilities_BypassedCVENeverBlocks` | 4713524 |
| GH-03 | PyPI scan | scanners are asked about the release version, not the file name | security, CWE-693 | high when a block policy is set | `Security.scan_asks_release_version`, `file_name_is_not_release_version` / `TestScanAsksScannersForReleaseVersion` | 3143de3 |
| GH-04 | scan gate | an npm or PyPI package named `*.info` or `*.mod` is scanned | security, CWE-693 | medium | `Cache.npm_named_like_go_metadata_is_scanned`, `old_exempted_npm_package` / `TestCacheHitScansPackagesNamedLikeGoMetadata`, `TestIsMetadataEntry` | f0b37ea |
| GH-05 | storage quota | `used` equals bytes on disk after an overwrite | correctness | low | `Cache.put_keeps_usage_exact`, `old_put_inflates_usage` / `TestPutOverwriteKeepsUsageExact`, `TestPutOverwriteWithinQuota` | 1f31256 |
| GH-06 | LRU eviction | eviction terminates; an overlapping store waits instead of failing | correctness | medium | `Cache.old_evict_is_stuck`, `fixed_evict_measure_falls` / `TestEvictTerminatesWhenDeletesFail`, `TestEvictWaitsForRunningEviction` | 440279a |
| GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 |
| GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 |
| GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f |
| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e |
| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 |
| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f |
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | 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
- **GH-01.** A client requests `/pypi/<victim>/<victim-file>?original_url=https://files.pythonhosted.org/.../<attacker-file>`.
The host is on the allowlist, the key is `pypi/<victim>/<victim-file>`, and an uncached key stores the attacker's
file. Every later client gets it; OSV judges the victim's name and version. The attacker publishes the file on PyPI
and needs no credentials. Reach: any network client of `/pypi`, unauthenticated when `auth.enabled` is false (production).
- **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name
returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong
scan results rather than serving blocked packages; any deployment with a block policy served such packages.
- **GH-17.** A page at any origin issued `DELETE /api/packages/<registry>/<name>/<version>` from a visitor's browser, and
`Access-Control-Allow-Origin: *` let it read every `/api` response. Reach: any visitor to a hostile page when
`auth.enabled` is false (production); impact is cache eviction. Fixed by `apiOriginGuard` against `server.allowed_origins`;
with none set, only same-origin passes.
- **GH-19.** An allowed host that answered 302 reached any target (`169.254.169.254`, `127.0.0.1`, `10.x`), by name or by
DNS rebinding. No allowed host redirects today; the fix removes the dependency on that. Hops are capped at 10, limited to
http(s), vetted against the allowlist, and a hop to another host dials through a guard that refuses private, loopback,
link-local and carrier-grade addresses after resolution. A redirect inside one host is left alone: a private index is
operator-trusted.
- **GH-04.** The publisher of an npm or PyPI package named `x.info` skipped the scan and the block policy. Reach: any package
publisher; needs a block policy to matter.
### Notes on the fixed rows
- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry
(`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no
age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown
registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`,
`TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`.
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
legacy path. Production holds none.
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
- **GH-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
| id | area | claim | verdict | why |
|----|------|-------|---------|-----|
| GH-10 | key path | `keyToPath` rewrites `..` instead of rejecting; distinct keys share a path | hardening, unreachable | `Keys.keyToPath_not_injective`. A probe through the full app showed the HTTP layer resolves literal `..` and answers 404 to encoded slashes (`/npm/lodash/-/lodash-1.0.0/../../x.tgz` reached upstream as `/lodash/-/lodash-x.tgz`). No key with `..` reaches storage. |
| GH-11 | cache hit | the stored SHA-256 is not re-verified on read | by-design | `Put` verifies the stream it just hashed; no doc promises read-side integrity. A check reads up to 2 GB per hit. Disk corruption is outside the proxy's threat model. |
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.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
Served: a package with no scan row while a scan is in flight, and a package whose every scanner failed on infrastructure
(`Security.unscanned_served_iff`, `infra_error_served_forever`). Retries: at most 6 at 5 minute spacing, 7 scans, 30
minutes (`retry_terminates`, `retry_window_minutes`); after that the error row stays and the package stays served until
the rescan worker runs (needs `rescan_interval`). Quoted intent: `pkg/cache/cache.go` "A wait that times out serves the
package unless FailClosed is set"; `scanner.go` "Scan failed on infrastructure, serving package; scan will be retried";
production config "A scan that fails on infrastructure is retried and the package is served (fail_closed false)".
Verdict: acceptable for production, whose only scanner is OSV, a remote service that cannot be made to time out by package
content. Residual risk: with file-based scanners (trivy, grype, pip-audit) a crafted package that makes the scanner time out
is served unscanned, because a deadline counts as infrastructure. Run those with `fail_closed: true`. No code change.
## Negative matrices (do not re-run)
| surface | runs | a leak would look like | verdict |
|---------|------|------------------------|---------|
| frontend nginx blocklist (`Dockerfile.frontend` template on nginx:alpine, stub backend) | 30 raw paths: `//npm`, `/./npm`, `%6Epm`, `/api/../npm`, `/api/..%2fnpm`, `/health/..%2fnpm`, `/ws/..%2fnpm`, `/api/..\npm`, `/api/..;/npm`, `/api/%5c..%5cnpm`, `/api/..%252fnpm`, `/npm?x=1`, `/metrics/` and more | 200 from the backend for `/npm`, `/pypi`, `/go` or `/metrics` | all 404 or SPA. `/NPM/x` returns the SPA page, not the proxy. |
| backend re-interpretation of the six paths nginx forwarded raw | `/api/..\npm/x`, `/api/..;/npm/x`, `/api/%5c..%5cnpm/x`, `/api/%2e%2e%5cnpm/x`, `/api/..%252fnpm/x`, `/api/;/../npm/x` against the full app | 200 from the npm handler | all 404 |
| WebSocket origin check | `Access.default_port_equivalent`, `scheme_mismatch_rejected`, `port_mismatch_rejected`, `glob_rejects_label_prefix`, `glob_rejects_suffix_trick` | an origin outside the allowlist accepted | clean. Same-origin mode compares host only; documented: "the Origin host must match the Host header". |
| history totals under eviction | existing `TestPostgresHistoryTablesHaveNoPackageForeignKey`, `checkDeleteKeepsDownloadHistory` | totals fall after a package delete | clean: history tables carry no foreign key to packages. |
+6
View File
@@ -0,0 +1,6 @@
import Gohoarder.Cache
import Gohoarder.Keys
import Gohoarder.Security
import Gohoarder.Access
import Gohoarder.Release
import Gohoarder.Stats
+224
View File
@@ -0,0 +1,224 @@
import Mathlib
/-!
# Access control and upstream fetch guards
Models `pkg/app/app.go` `buildCheckOrigin` / `normalizeOriginHost`, `pkg/app/handlers_admin.go`
`requireAdmin`, `pkg/auth/auth.go` (`getPermissionsForRole`, `ValidateAPIKey` expiry),
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards, `get`), `pkg/network/client.go` (`send`), `pkg/auth/auth.go` (`ValidateAPIKey` cost), `pkg/app/cors.go` (`apiOriginGuard`), `Dockerfile.frontend`.
Omits: the TLS layer, bcrypt internals, DNS.
-/
namespace Gohoarder.Access
/-! ### WebSocket origin -/
inductive Scheme | http | https
deriving DecidableEq
def defaultPort : Scheme → ℕ
| Scheme.http => 80
| Scheme.https => 443
/-- An origin after `strings.ToLower`: host labels plus an optional explicit port. -/
structure Origin where
scheme : Scheme
host : List Char
port : Option ℕ
/-- `normalizeOriginHost`: a port equal to the scheme default is dropped; compare on the effective port. -/
def effPort (o : Origin) : ℕ := o.port.getD (defaultPort o.scheme)
/-- An exact allowlist rule matches iff scheme, host and effective port agree (`buildCheckOrigin`). -/
def matchesExact (rule o : Origin) : Bool :=
decide (rule.scheme = o.scheme) && decide (rule.host = o.host) && decide (effPort rule = effPort o)
theorem default_port_equivalent (s : Scheme) (h : List Char) :
matchesExact ⟨s, h, none⟩ ⟨s, h, some (defaultPort s)⟩ = true := by
simp [matchesExact, effPort]
theorem scheme_mismatch_rejected (rule o : Origin) (h : rule.scheme ≠ o.scheme) :
matchesExact rule o = false := by
simp [matchesExact, h]
theorem port_mismatch_rejected (s : Scheme) (h : List Char) (p q : ℕ) (hp : p ≠ q) :
matchesExact ⟨s, h, some p⟩ ⟨s, h, some q⟩ = false := by
simp [matchesExact, effPort, hp]
/-- Wildcard rule `https://*.d`: `strings.HasSuffix(host, ".d")` or host = `d`. -/
def matchesGlob (d host : List Char) : Bool :=
decide (host = d) || decide (('.' :: d) <:+ host)
/-- The leading dot pins the match to a label boundary: `evilexample.com` is not under `example.com`. -/
theorem glob_rejects_label_prefix :
matchesGlob "example.com".toList "evilexample.com".toList = false := by decide
theorem glob_accepts_subdomain :
matchesGlob "example.com".toList "app.example.com".toList = true := by decide
theorem glob_rejects_suffix_trick :
matchesGlob "example.com".toList "example.com.evil.net".toList = false := by decide
/-! ### Admin gate -/
inductive Role | readonly | readwrite | admin
deriving DecidableEq
/-- `getPermissionsForRole`, restricted to the bypass-management and key-management permissions. -/
def canManageBypasses : Role → Bool
| Role.admin => true
| _ => false
def canManageKeys : Role → Bool
| Role.admin => true
| _ => false
/-- `requireAdmin` admits a key with the admin role or the `bypasses:manage` permission; it also
guards `/api/admin/keys`. No other role holds that permission, so no escalation to key minting. -/
def requireAdminPasses (r : Role) : Bool := decide (r = Role.admin) || canManageBypasses r
theorem admin_gate_implies_key_manager (r : Role) (h : requireAdminPasses r = true) :
canManageKeys r = true := by
cases r <;> simp_all [requireAdminPasses, canManageBypasses, canManageKeys]
/-- `ValidateAPIKey`: a key is a candidate iff it has no expiry or `now <= expiresAt`. -/
def keyLive (now : ℤ) (exp : Option ℤ) : Bool :=
match exp with
| none => true
| some e => decide (now ≤ e)
theorem expired_key_rejected (now e : ℤ) (h : e < now) : keyLive now (some e) = false := by
simp [keyLive, not_le.mpr h]
/-! ### PyPI `original_url` guards -/
/-- A fetch the handler would perform: host and file name of `original_url`. -/
structure Fetch where
host : String
file : String
def allowedHosts : List String := ["pypi.org", "files.pythonhosted.org", "pythonhosted.org"]
/-- `isAllowedPyPIHost`: listed hosts, or a subdomain of pythonhosted.org (suffix on characters). -/
def hostAllowed (h : String) : Bool :=
decide (h ∈ allowedHosts) || decide (".pythonhosted.org".toList <:+ h.toList)
/-- Before the fix: host allowlist only. The cache key is `pypi/<name>/<requested file>`. -/
def acceptsOld (f : Fetch) : Bool := hostAllowed f.host
/-- After the fix: the fetched file must be the requested one. -/
def acceptsNew (requested : String) (f : Fetch) : Bool := hostAllowed f.host && decide (f.file = requested)
/-- Integrity of the cache key: what is stored under a key is the file the key names. -/
theorem fixed_guard_binds_key (requested : String) (f : Fetch) (h : acceptsNew requested f = true) :
f.file = requested := by
simp only [acceptsNew, Bool.and_eq_true, decide_eq_true_eq] at h
exact h.2
/-- Before the fix any file on an allowed host was stored under any requested name. -/
theorem old_guard_allows_key_poisoning :
∃ requested f, acceptsOld f = true ∧ f.file ≠ requested := by
exact ⟨"requests-2.31.0-py3-none-any.whl", ⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl"⟩,
by decide, by decide⟩
/-- pip requests the PEP 658 sidecar as `<link>.metadata`, so the suffix lands on `original_url` and the
request names the sidecar of the requested file. `handlePackageFile` streams it and never stores it. -/
def pipSidecar (requested : String) (f : Fetch) : Bool := decide (f.file = requested ++ ".metadata")
/-- The guard with the pip form: the requested file, or its own sidecar. -/
def acceptsPip (requested : String) (f : Fetch) : Bool :=
hostAllowed f.host && (decide (f.file = requested) || pipSidecar requested f)
/-- What the pip form stores still names the key: only the sidecar escapes, and it is not stored. -/
theorem pip_form_keeps_key_binding (requested : String) (f : Fetch)
(h : acceptsPip requested f = true) (hs : pipSidecar requested f = false) : f.file = requested := by
simp only [acceptsPip, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at h
rcases h.2 with h2 | h2
· exact h2
· rw [h2] at hs; exact absurd hs (by simp)
theorem pip_sidecar_of_other_file_rejected :
acceptsPip "example-1.0.0-py3-none-any.whl"
⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl.metadata"⟩ = false := by decide
theorem pip_sidecar_of_same_file_accepted :
acceptsPip "example-1.0.0-py3-none-any.whl"
⟨"files.pythonhosted.org", "example-1.0.0-py3-none-any.whl.metadata"⟩ = true := by decide
theorem internal_hosts_rejected :
hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧
hostAllowed "metadata.google.internal" = false := by decide
/-- Before the fix the allowlist was checked once, on the first hop. `network.Client` followed
redirects without re-checking, so an allowed host that answers 302 reached any target. -/
def hopAllowedOld (hops : List String) : Bool := hops.head?.any hostAllowed
/-- After the fix (`network.Client.send`, `pypi.Handler.get`) every hop must pass the allowlist. -/
def hopAllowed (hops : List String) : Bool := hops.all hostAllowed
theorem redirect_escapes_allowlist :
hopAllowedOld ["files.pythonhosted.org", "169.254.169.254"] = true ∧
hostAllowed "169.254.169.254" = false := by decide
theorem fixed_redirect_stays_allowlisted :
hopAllowed ["pypi.org", "files.pythonhosted.org"] = true ∧
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = false := by decide
/-- A hop is accepted only if every hop is on the allowlist. -/
theorem hopAllowed_implies_each (hops : List String) (h : hopAllowed hops = true) :
∀ x ∈ hops, hostAllowed x = true := by
simpa [hopAllowed] using h
/-! ### API key validation cost (`pkg/auth/auth.go` `ValidateAPIKey`) -/
/-- bcrypt compares for one request when every stored key is a candidate (before the fix). -/
def compareCostOld (storedKeys : ℕ) : ℕ := storedKeys
/-- A key carrying its id selects one stored key: one compare, hit or miss (a miss compares a dummy hash). -/
def compareCostNew (_storedKeys : ℕ) : ℕ := 1
theorem old_cost_grows_with_keys : compareCostOld 1000 = 1000 := rfl
theorem new_cost_independent_of_keys (n m : ℕ) : compareCostNew n = compareCostNew m := rfl
/-! ### Cross-origin writes on `/api` (`pkg/app/cors.go` `apiOriginGuard`) -/
/-- Before the fix every handler answered `Access-Control-Allow-Origin: *`, so any page could call them. -/
def corsOld (_ : Origin) : Bool := true
/-- After the fix a state-changing request passes iff it names no origin (non-browser client) or an
allowed one; the same rule as the WebSocket origin check. -/
def writeAllowed (rules : List Origin) : Option Origin → Bool
| none => true
| some o => rules.any (fun r => matchesExact r o)
def dashboard : Origin := ⟨Scheme.https, "gohoarder.example.com".toList, none⟩
def attacker : Origin := ⟨Scheme.https, "evil.example.net".toList, none⟩
theorem old_cors_admits_any_page : corsOld attacker = true := rfl
theorem fixed_refuses_foreign_origin : writeAllowed [dashboard] (some attacker) = false := by decide
theorem fixed_admits_dashboard_and_cli :
writeAllowed [dashboard] (some dashboard) = true ∧ writeAllowed [dashboard] none = true := by decide
/-- With nothing configured only a request with no origin passes the allowlist step; browsers fall to the
same-origin host comparison in the handler. -/
theorem empty_allowlist_refuses_any_origin (o : Origin) : writeAllowed [] (some o) = false := by
simp [writeAllowed]
/-! ### Frontend blocklist (`Dockerfile.frontend`) -/
/-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/
def blocked (first : String) (rest : String) : Bool :=
decide (first ∈ ["npm", "pypi", "go", "metrics"]) && (decide (rest.toList = []) || decide (rest.toList.head? = some '/'))
theorem blocklist_covers_registries :
blocked "npm" "/x" = true ∧ blocked "pypi" "" = true ∧ blocked "go" "/@v/list" = true ∧
blocked "metrics" "" = true := by decide
/-- A prefix that merely starts with a registry name is not blocked, and is not proxied either: the
`/health` and `/api/` locations are the only ones with a backend. -/
theorem blocklist_is_segment_exact : blocked "npmx" "" = false := by decide
end Gohoarder.Access
+223
View File
@@ -0,0 +1,223 @@
import Mathlib
/-!
# Cache lifecycle
Models `pkg/cache/cache.go`: `store` (expiry), `getOrFetch` and `Get` (hit path,
retry), `purge` and `cleanup` (idle eviction), `evict` (LRU).
What it omits: wall-clock skew, the storage backend, byte-level I/O.
-/
namespace Gohoarder.Cache
/-! ### Expiry: artifacts never expire by age, metadata pages do -/
/-- `pkg/cache/cache.go` `store`: only metadata entries get `now + DefaultTTL`. -/
def expiryFor (isMeta : Bool) (now ttl : ℤ) : Option ℤ :=
if isMeta then some (now + ttl) else none
/-- `pkg/cache/cache.go` `getOrFetch`: `pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt)`. -/
def expired (e : Option ℤ) (now : ℤ) : Prop := ∃ x, e = some x ∧ x < now
theorem artifact_never_expires (now ttl t : ℤ) : ¬ expired (expiryFor false now ttl) t := by
simp [expiryFor, expired]
theorem metadata_expires_after_ttl (now ttl t : ℤ) (h : now + ttl < t) :
expired (expiryFor true now ttl) t :=
⟨now + ttl, by simp [expiryFor], h⟩
theorem metadata_fresh_within_ttl (now ttl t : ℤ) (h : t ≤ now + ttl) :
¬ expired (expiryFor true now ttl) t := by
simp only [expired, expiryFor, ite_true, Option.some.injEq, exists_eq_left']
omega
/-! ### Idle eviction -/
/-- `pkg/cache/cache.go` `cleanup`: cutoff = now - IdleTTL; due iff `LastAccessed.Before(cutoff)`. -/
def idleDue (now idleTTL lastAccessed : ℤ) : Prop := lastAccessed < now - idleTTL
theorem idle_keeps_recent (now idleTTL la : ℤ) (h : now - la ≤ idleTTL) :
¬ idleDue now idleTTL la := by
unfold idleDue; omega
theorem idle_removes_stale (now idleTTL la : ℤ) (h : idleTTL < now - la) :
idleDue now idleTTL la := by
unfold idleDue; omega
/-- A request refreshes `LastAccessed` (`UpdateDownloadCount`), so a hit is never idle-due at that instant. -/
theorem touch_defers_idle (now idleTTL : ℤ) (h : 0 ≤ idleTTL) : ¬ idleDue now idleTTL now := by
unfold idleDue; omega
/-! ### Interleavings of a hit and a purge -/
/-- One step of the concurrent schedule on a single entry. -/
inductive Step
| touch (t : ℤ) -- a request refreshes LastAccessed
| check -- purge's `stillDue` re-read
| del -- purge's `deletePackage`
deriving DecidableEq
structure World where
last : ℤ
present : Bool
checked : Bool -- the last `check` found the entry due
deriving DecidableEq
def run (cutoff : ℤ) : World → List Step → World
| w, [] => w
| w, Step.touch t :: s => run cutoff { w with last := t } s
| w, Step.check :: s => run cutoff { w with checked := decide (w.last < cutoff) } s
| w, Step.del :: s => run cutoff { w with present := if w.checked then false else w.present } s
/-- Check and delete are two steps (`purge`: `stillDue(current)` then `deletePackage`), so a
request between them is lost: the entry is deleted although `LastAccessed >= cutoff`. This is
the window `Get` now covers with its retry. -/
theorem purge_window_deletes_fresh_entry :
let w := run 10 ⟨0, true, false⟩ [Step.check, Step.touch 20, Step.del]
w.present = false ∧ 10 ≤ w.last := by
decide
/-- With no request inside the window the purge honours `stillDue`. -/
theorem purge_without_window_keeps_fresh (cutoff t : ℤ) (h : cutoff ≤ t) :
(run cutoff ⟨0, true, false⟩ [Step.touch t, Step.check, Step.del]).present = true := by
simp [run, not_lt.mpr h]
/-! ### `Get`: probe, then open -/
inductive Outcome | served | refetched | error
deriving DecidableEq
/-- Before the fix: probe in `getOrFetch`, open after the singleflight; `purgedBetween` is a delete
between the two. -/
def getOnce (present purgedBetween : Bool) : Outcome :=
if present then (if purgedBetween then Outcome.error else Outcome.served) else Outcome.refetched
/-- `Get` with `getAttempts = 2`: the second pass re-probes the (now missing) blob and fetches. -/
def getRetry (present d1 d2 : Bool) : Outcome :=
match getOnce present d1 with
| Outcome.error => if d2 then Outcome.error else Outcome.refetched
| o => o
theorem getOnce_errors_on_purge : getOnce true true = Outcome.error := rfl
/-- At most one purge per `Get` never reaches the client as an error. -/
theorem getRetry_survives_one_purge (present d1 d2 : Bool) (h : ¬ (d1 = true ∧ d2 = true)) :
getRetry present d1 d2 ≠ Outcome.error := by
cases present <;> cases d1 <;> cases d2 <;> simp_all [getRetry, getOnce]
/-! ### LRU eviction -/
/-- `evict`: delete oldest first until `freed >= needed`; `sizes` is the oldest-first listing. -/
def evictFreed : List ℕ → ℕ → ℕ
| [], _ => 0
| s :: rest, needed => if needed = 0 then 0 else s + evictFreed rest (needed - s)
theorem evictFreed_le_total (sizes : List ℕ) (needed : ℕ) : evictFreed sizes needed ≤ sizes.sum := by
induction sizes generalizing needed with
| nil => simp [evictFreed]
| cons s rest ih =>
unfold evictFreed
split_ifs
· simp
· simp only [List.sum_cons]; have := ih (needed - s); omega
theorem evictFreed_ge (sizes : List ℕ) (needed : ℕ) (h : needed ≤ sizes.sum) :
needed ≤ evictFreed sizes needed := by
induction sizes generalizing needed with
| nil => simpa [evictFreed] using h
| cons s rest ih =>
unfold evictFreed
split_ifs with h0
· omega
· simp only [List.sum_cons] at h
have := ih (needed - s) (by omega)
omega
/-- After `store` evicts for `needed = used + size - limit` and the listing held enough bytes,
usage including the new entry is within the cap. -/
theorem lru_keeps_cap (used size limit : ℕ) (sizes : List ℕ)
(hroom : used + size - limit ≤ sizes.sum) :
used + size - evictFreed sizes (used + size - limit) ≤ limit := by
have h1 := evictFreed_ge sizes (used + size - limit) hroom
omega
/-- When the listing cannot free enough (`freed < needed`) `evict` still returns nil, so the cap
rests on the backend's `Put` quota check (`filesystem.go` `Put`). The hypothesis of `lru_keeps_cap`
fails here, and the result exceeds the cap. -/
theorem lru_cap_needs_enough_evictable :
∃ used size limit : ℕ, ∃ sizes : List ℕ,
used + size - evictFreed sizes (used + size - limit) > limit := by
exact ⟨100, 10, 100, [5], by decide⟩
/-- The entry being stored is not in the metadata listing (`SavePackage` runs after `Put`), so
eviction never deletes it. -/
theorem evict_spares_unlisted (listed : List String) (new : String) (h : new ∉ listed) :
∀ victim ∈ listed.take 100, victim ≠ new := by
intro v hv hv'
exact h (hv' ▸ List.mem_of_mem_take hv)
/-- One eviction pass: `n` listed rows of which `d` can be deleted; the rest are listed again. -/
def passRemaining (n d : ℕ) : ℕ := n - d
/-- Before the fix the loop continued on `n >= limit` only; a pass that deletes nothing re-lists
the same rows and never ends. -/
theorem old_evict_is_stuck (n : ℕ) : passRemaining n 0 = n := by simp [passRemaining]
/-- After the fix a pass continues only if it deleted a row, so the row count strictly falls. -/
theorem fixed_evict_measure_falls (n d : ℕ) (hd : 0 < d) (hdn : d ≤ n) : passRemaining n d < n := by
unfold passRemaining; omega
/-! ### Quota accounting: overwriting a key
`pkg/storage/filesystem/filesystem.go` `Put`: `fs.used` tracks bytes on disk. -/
/-- After the fix: an overwrite releases the bytes of the file it replaces. -/
def usedAfterPut (used replaced written : ℕ) : ℕ := used - replaced + written
/-- Before the fix: the replaced bytes stayed counted. -/
def usedAfterPutOld (used written : ℕ) : ℕ := used + written
/-- If `used` is the sum of the stored sizes, `other + replaced`, the counter stays exact. -/
theorem put_keeps_usage_exact (other replaced written : ℕ) :
usedAfterPut (other + replaced) replaced written = other + written := by
unfold usedAfterPut; omega
/-- Two writes of one key (400 then 300 bytes) leave 700 counted, 300 on disk. -/
theorem old_put_inflates_usage : usedAfterPutOld (usedAfterPutOld 0 400) 300 = 700 ∧
usedAfterPut (usedAfterPut 0 0 400) 400 300 = 300 := by decide
/-! ### Which entries skip the scan
`pkg/metadata/interface.go` `IsMetadataEntry`; the scan gate in `getOrFetch` and `store`. -/
def metaVersions : List String := ["list", "page", "latest", "metadata"]
/-- After the fix the `.mod` / `.info` name suffix exempts Go entries only. -/
def scanExempt (registry : String) (nameSuffixMeta : Bool) (version : String) : Bool :=
decide (version ∈ metaVersions) || (decide (registry = "go") && nameSuffixMeta)
/-- Before the fix the suffix exempted any registry. -/
def scanExemptOld (nameSuffixMeta : Bool) (version : String) : Bool :=
decide (version ∈ metaVersions) || nameSuffixMeta
theorem npm_named_like_go_metadata_is_scanned (v : String) (hv : v ∉ metaVersions) :
scanExempt "npm" true v = false := by
simp [scanExempt, hv]
theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decide
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
/-- `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
+146
View File
@@ -0,0 +1,146 @@
import Mathlib
/-!
# Storage keys, path safety, canonicalisation
Models `pkg/cache/cache.go` `generateStorageKey`, `pkg/storage/filesystem/filesystem.go`
`keyToPath`, `pkg/proxy/npm/npm.go` `CanonicalPath`, and `pkg/proxy/pypi/pypi.go`
`extractVersionFromFilename`. Omits: symlinks (the store writes through `os.Root`), Unicode.
-/
namespace Gohoarder.Keys
/-! ### `keyToPath`: segment normalisation -/
/-- `filepath.Clean` plus the strip loop in `keyToPath`: `.` and empty segments vanish, `..` pops
a segment and is dropped at the root. Segments are kept in reverse order. -/
def cleanRev : List String → List String → List String
| acc, [] => acc
| acc, seg :: rest =>
if seg = "." ∨ seg = "" then cleanRev acc rest
else if seg = ".." then cleanRev acc.tail rest
else cleanRev (seg :: acc) rest
def clean (segs : List String) : List String := (cleanRev [] segs).reverse
theorem cleanRev_no_dotdot (segs acc : List String) (h : ".." ∉ acc) : ".." ∉ cleanRev acc segs := by
induction segs generalizing acc with
| nil => simpa [cleanRev] using h
| cons seg rest ih =>
unfold cleanRev
split_ifs with h1 h2
· exact ih acc h
· exact ih acc.tail (fun hm => h (List.mem_of_mem_tail hm))
· apply ih
simp only [List.mem_cons, not_or]
exact ⟨fun e => h2 e.symm, h⟩
/-- No cleaned key contains a `..` segment, so the joined path stays under the store root. -/
theorem clean_stays_in_root (segs : List String) : ".." ∉ clean segs := by
unfold clean
simpa using cleanRev_no_dotdot segs [] (by simp)
/-- The sanitiser rewrites; it does not reject. Distinct keys collapse onto one path. -/
theorem keyToPath_not_injective :
clean ["npm", "pkg", "..", "other", "1.0.0"] = clean ["npm", "other", "1.0.0"] ∧
["npm", "pkg", "..", "other", "1.0.0"] ≠ ["npm", "other", "1.0.0"] := by
decide
theorem keyToPath_traversal_is_clamped :
clean ["..", "..", "etc", "passwd"] = ["etc", "passwd"] := by decide
/-! ### Key injectivity: `registry/name/version` -/
/-- `generateStorageKey`: join with `/`. -/
def key (registry name version : String) : List String := [registry, name, version]
/-- Over segment lists the tuple is recoverable; `String.intercalate "/"` is injective exactly
when the parts contain no `/`. -/
theorem key_injective (r n v r' n' v' : String) (h : key r n v = key r' n' v') :
r = r' ∧ n = n' ∧ v = v' := by
simp only [key, List.cons.injEq, and_true] at h
exact ⟨h.1, h.2.1, h.2.2⟩
/-- With `/` inside a part the joined string collides: npm `@x/y` + `b` and `@x` + `y/b`. The
second tuple needs an upstream 200 at a path npm never serves, so the proxy cannot store it. -/
theorem joined_key_collides_with_slash :
String.intercalate "/" ["npm", "@x/y", "b"] = String.intercalate "/" ["npm", "@x", "y/b"] := by
decide
/-! ### `npm.CanonicalPath`: escaped scope separator -/
inductive Tok | scope | esc | sl | other
deriving DecidableEq
/-- Rewrites the first escaped `/` of the first segment (`CanonicalPath`'s `strings.Cut`). -/
def rewriteFirst : List Tok → List Tok
| [] => []
| Tok.sl :: r => Tok.sl :: r
| Tok.esc :: r => Tok.sl :: r
| Tok.scope :: r => Tok.scope :: rewriteFirst r
| Tok.other :: r => Tok.other :: rewriteFirst r
/-- `CanonicalPath` acts only on a segment starting with `@`. -/
def canon : List Tok → List Tok
| Tok.scope :: r => Tok.scope :: rewriteFirst r
| p => p
theorem rewriteFirst_idem (r : List Tok) : rewriteFirst (rewriteFirst r) = rewriteFirst r := by
induction r with
| nil => rfl
| cons t rest ih => cases t <;> simp [rewriteFirst, ih]
/-- Canonicalisation is idempotent: a second pass finds the separator the first one wrote. -/
theorem canon_idem (p : List Tok) : canon (canon p) = canon p := by
cases p with
| nil => rfl
| cons t r => cases t <;> simp [canon, rewriteFirst_idem]
/-- The rewrite adds at most one separator, so a name cannot smuggle extra path segments. -/
theorem rewriteFirst_adds_one_sep (r : List Tok) :
(rewriteFirst r).count Tok.sl ≤ r.count Tok.sl + 1 := by
induction r with
| nil => simp [rewriteFirst]
| cons t rest ih =>
cases t <;> simp [rewriteFirst, List.count_cons] at * <;> omega
theorem canon_adds_one_sep (p : List Tok) : (canon p).count Tok.sl ≤ p.count Tok.sl + 1 := by
cases p with
| nil => simp [canon]
| cons t r =>
have := rewriteFirst_adds_one_sep r
cases t <;> simp [canon, List.count_cons] at * <;> omega
/-- The escape that survives in the name part (`@a%2fb%2fc` gives `@a/b%2fc`) is later rejected:
Fiber answers 404 to an escaped slash, which `TestNPMScopedNames` and the traversal probe
(`/npm/@s%2fn%2f..%2f..%2fx` returns 404) exercise. -/
theorem canon_keeps_later_escape :
canon [Tok.scope, Tok.esc, Tok.other, Tok.esc, Tok.other] =
[Tok.scope, Tok.sl, Tok.other, Tok.esc, Tok.other] := by decide
/-! ### PyPI version from a file name -/
/-- Wheel (PEP 427): the version is the second `-` segment when it starts with a digit. -/
def startsWithDigit (v : String) : Bool :=
match v.toList with
| c :: _ => c.isDigit
| [] => false
def wheelVersion (segs : List String) : Option String :=
match segs with
| _ :: v :: _ => if startsWithDigit v then some v else none
| _ => none
/-- A well-formed wheel name `dist-version-...` yields its version, whatever follows. -/
theorem wheelVersion_correct (d v : String) (rest : List String) (hv : startsWithDigit v = true) :
wheelVersion (d :: v :: rest) = some v := by
simp [wheelVersion, hv]
/-- The cache version for a PyPI file is the file name, which is unique per file, while the
release version is shared by all files of a release (`release_version`). Two files of one release
have different keys and one release key: bypasses by release cover both, by design. -/
theorem pypi_key_per_file_release_shared (name f1 f2 : String) (h : f1 ≠ f2) :
key "pypi" name f1 ≠ key "pypi" name f2 := by
intro e; exact h (key_injective _ _ _ _ _ _ e).2.2
end Gohoarder.Keys
+84
View File
@@ -0,0 +1,84 @@
import Mathlib
/-!
# Release-age passthrough
Models `pkg/proxy/npm/npm.go` `rewriteMetadataURLs`, `pkg/proxy/pypi/simple_json.go`
`rewriteJSONPage`, and the packument/index freshness TTL in `pkg/cache/cache.go`. A client gate
accepts a version when `now - publishedAt >= gate`. Omits: JSON parsing, number formatting.
-/
namespace Gohoarder.Release
/-- A JSON object as key/value pairs. -/
abbrev Obj := List (String × String)
/-- `rewriteJSONPage`: only the `url` value of a file entry changes. -/
def rewriteFile (proxy : String) (o : Obj) : Obj :=
o.map fun kv => if kv.1 = "url" then (kv.1, proxy) else kv
theorem rewrite_preserves_upload_time (proxy : String) (o : Obj) (t : String)
(h : ("upload-time", t) ∈ o) : ("upload-time", t) ∈ rewriteFile proxy o := by
unfold rewriteFile
exact List.mem_map.mpr ⟨("upload-time", t), h, by simp⟩
theorem rewrite_preserves_other_keys (proxy : String) (o : Obj) (k v : String) (hk : k ≠ "url")
(h : (k, v) ∈ o) : (k, v) ∈ rewriteFile proxy o := by
unfold rewriteFile
exact List.mem_map.mpr ⟨(k, v), h, by simp [hk]⟩
theorem rewrite_keeps_keys (proxy : String) (o : Obj) : (rewriteFile proxy o).map Prod.fst = o.map Prod.fst := by
unfold rewriteFile
simp only [List.map_map]
congr 1
funext kv
simp only [Function.comp]
split_ifs <;> simp
/-! ### Staleness against a minimum-age gate -/
/-- The gate accepts a version published at `t` when it is at least `gate` old. -/
def gateAccepts (gate now t : ℤ) : Prop := gate ≤ now - t
/-- A version missing from a snapshot taken at `s` was published after `s`. If the snapshot is at
most `ttl` old and `ttl <= gate`, the missing version is younger than the gate, so the gate would
have refused it anyway: staleness hides nothing the gate allows. -/
theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ ttl) (httl : ttl ≤ gate)
(hnew : s < t) : ¬ gateAccepts gate now t := by
unfold gateAccepts; omega
/-- Production and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/
theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but
absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/
theorem old_default_ttl_exceeded_gate :
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/
/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/
def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default
/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/
theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ)
(hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default)
(hnew : s < t) : ¬ gateAccepts gate now t :=
stale_hides_only_gated gate _ now s t hstale hcfg hnew
/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/
theorem override_replaces_default (default o : ℤ) :
effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩
/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/
theorem override_above_gate_breaks_bound :
∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧
gateAccepts gate now t ∧ gate = 72 := by
exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, rfl⟩
/-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/
theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t :=
Iff.rfl
end Gohoarder.Release
+360
View File
@@ -0,0 +1,360 @@
import Mathlib
/-!
# Security decision logic
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.
-/
namespace Gohoarder.Security
structure Vuln where
id : ℕ
sev : ℕ
structure Bypass where
cve : ℕ
covers : Bool -- `AppliesTo` empty or equal to this package
active : Bool
expiresAt : ℤ
/-- `GetActiveCVEBypasses`: `active = true AND expires_at > now`. -/
def activeAt (now : ℤ) (b : Bypass) : Bool := b.active && decide (now < b.expiresAt)
def bypassedIds (now : ℤ) (bs : List Bypass) : List ℕ :=
(bs.filter fun b => activeAt now b && b.covers).map (·.cve)
/-- The vulnerabilities no bypass covers (`severityCounts` loop). -/
def remaining (now : ℤ) (bs : List Bypass) (vs : List Vuln) : List Vuln :=
vs.filter fun v => decide (v.id ∉ bypassedIds now bs)
/-- `block_on_severity`: `none` for "none"/empty, else block when a remaining vulnerability has
rank at or above the threshold. -/
def blocksBySeverity (policy : Option ℕ) (vs : List Vuln) : Bool :=
match policy with
| none => false
| some t => vs.any fun v => decide (t ≤ v.sev)
def decideSev (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) : Bool :=
blocksBySeverity policy (remaining now bs vs)
/-- The LOW branch before the fix: `len(result.Vulnerabilities) > 0`, bypasses ignored. -/
def decideLowOld (vs : List Vuln) : Bool := decide (0 < vs.length)
theorem expired_bypass_inactive (now : ℤ) (b : Bypass) (h : b.expiresAt ≤ now) : activeAt now b = false := by
simp [activeAt, not_lt.mpr h]
theorem inactive_bypass_ignored (now : ℤ) (b : Bypass) (h : b.active = false) : activeAt now b = false := by
simp [activeAt, h]
/-- Every vulnerability bypassed by an active, covering bypass: nothing blocks, for any policy. -/
theorem fully_bypassed_never_blocks (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln)
(h : ∀ v ∈ vs, v.id ∈ bypassedIds now bs) : decideSev policy now bs vs = false := by
have : remaining now bs vs = [] := by
simp only [remaining, List.filter_eq_nil_iff, decide_eq_true_eq, not_not]
exact h
simp [decideSev, this, blocksBySeverity]
cases policy <;> simp
/-- A vulnerability at or above the policy that no active bypass covers blocks. -/
theorem uncovered_vuln_blocks (t : ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln)
(hv : v ∈ vs) (hsev : t ≤ v.sev) (hun : v.id ∉ bypassedIds now bs) :
decideSev (some t) now bs vs = true := by
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq]
refine ⟨v, ?_, hsev⟩
simp [remaining, hv, hun]
/-- Adding a bypass never turns an allow into a block. -/
theorem bypass_monotone (policy : Option ℕ) (now : ℤ) (b : Bypass) (bs : List Bypass) (vs : List Vuln)
(h : decideSev policy now (b :: bs) vs = true) : decideSev policy now bs vs = true := by
cases policy with
| none => simp [decideSev, blocksBySeverity] at h
| some t =>
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq, remaining,
List.mem_filter] at h ⊢
obtain ⟨v, ⟨hv, hn⟩, hs⟩ := h
refine ⟨v, ⟨hv, ?_⟩, hs⟩
intro hmem
apply hn
simp only [bypassedIds, List.filter_cons] at hmem ⊢
split_ifs <;> simp_all
/-- Before the fix, LOW blocked a package whose only vulnerability was bypassed. -/
theorem old_low_ignores_bypass :
let vs := [Vuln.mk 1 1]
let bs := [Bypass.mk 1 true true 100]
decideLowOld vs = true ∧ decideSev (some 1) 0 bs vs = false := by
decide
/-! ### Serve decision -/
inductive Scan
| missing (inflight : Bool) -- no result row; `isInflight` while a scan runs
| err (infra : Bool) -- every scanner failed
| ok (vs : List Vuln)
/-- `CheckVulnerabilities` and the gate: `true` means the package is served. -/
def serves (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
Scan → Bool
| s =>
if pkgBypass then true else
match s with
| Scan.missing inflight => !failClosed && inflight
| Scan.err infra => !failClosed && infra
| Scan.ok vs => !decideSev policy now bs vs
theorem fail_closed_blocks_without_verdict (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (s : Scan)
(hs : (∃ i, s = Scan.missing i) ∨ (∃ i, s = Scan.err i)) :
serves true false policy now bs s = false := by
rcases hs with ⟨i, rfl⟩ | ⟨i, rfl⟩ <;> simp [serves]
/-- A vulnerable package is not served when policy blocks, unless a package bypass covers it. -/
theorem vulnerable_not_served (policy : Option ℕ) (t : ℕ) (hp : policy = some t) (failClosed : Bool)
(now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
(hun : v.id ∉ bypassedIds now bs) :
serves failClosed false policy now bs (Scan.ok vs) = false := by
subst hp
simp [serves, uncovered_vuln_blocks t now bs vs v hv hsev hun]
/-- With `fail_closed = false`, exactly these states serve a package with no verdict: a scan in
flight, or every scanner failing on infrastructure. A package bypass serves in any state. -/
theorem unscanned_served_iff (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
(bs : List Bypass) (i : Bool) :
(serves failClosed pkgBypass policy now bs (Scan.missing i) = true ↔
pkgBypass = true ∨ (failClosed = false ∧ i = true)) ∧
(serves failClosed pkgBypass policy now bs (Scan.err i) = true ↔
pkgBypass = true ∨ (failClosed = false ∧ i = true)) := by
cases failClosed <;> cases pkgBypass <;> cases i <;> simp [serves]
/-- The infra-error record never changes with retries, so the package stays served. -/
theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
serves false false policy now bs (Scan.err true) = true := by
simp [serves]
/-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/
def servesDisabled : Bool := true
/-! ### Retry input (`pkg/cache/cache.go` `store`, `ScanFile`; `scheduleRetry`) -/
/-- Before the fix a retry reused the first scan's path. Remote storage scans a temp file removed
after the first attempt, so only local backends kept it. -/
def retryReadableOld (localBackend : Bool) : Bool := localBackend
/-- After the fix a retry whose file is gone re-reads the blob through the file source. -/
def retryReadableNew (localBackend fileSourceSet : Bool) : Bool := localBackend || fileSourceSet
theorem old_remote_retry_unreadable : retryReadableOld false = false := rfl
theorem fixed_retry_always_readable : retryReadableNew false true = true ∧ retryReadableNew true false = true := by
decide
/-! ### Retry budget -/
def maxRetries : ℕ := 6
def retryIntervalMin : ℕ := 5
/-- Scans run from `attempt`: `scan` schedules attempt+1 only when infra-only and `attempt < maxRetries`. -/
def scansFrom : ℕ → ℕ
| 0 => 1
| k + 1 => 1 + scansFrom k
theorem scansFrom_eq (k : ℕ) : scansFrom k = k + 1 := by
induction k with
| zero => rfl
| succ k ih => simp only [scansFrom, ih]; omega
theorem scans_total : scansFrom maxRetries = maxRetries + 1 := scansFrom_eq _
theorem retry_window_minutes : maxRetries * retryIntervalMin = 30 := by decide
/-- The attempt counter is bounded, so a package that keeps failing on infrastructure is scanned at most 7 times. -/
theorem retry_terminates (attempt : ℕ) : scansFrom (maxRetries - attempt) ≤ maxRetries + 1 := by
rw [scansFrom_eq]; omega
/-! ### Which version scanners are asked about
`pkg/scanner/scanner.go` `scanVersion`: PyPI artifacts are cached under their file name. -/
def scanVersion (release cacheVersion : String) : String :=
if release = "" then cacheVersion else release
theorem scan_asks_release_version (release cacheVersion : String) (h : release ≠ "") :
scanVersion release cacheVersion = release := by
simp [scanVersion, h]
theorem npm_scan_keeps_cache_version (cacheVersion : String) :
scanVersion "" cacheVersion = cacheVersion := by
simp [scanVersion]
/-- Before the fix scanners received the file name, which is never a release version. -/
theorem file_name_is_not_release_version :
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
/-! ### Merge: worst status wins 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
theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRank xs := by
induction xs with
| nil => simp at h
| cons y ys ih =>
simp only [mergeRank, List.foldr_cons]
rcases List.mem_cons.mp h with rfl | h
· exact le_max_left _ _
· exact le_trans (ih h) (le_max_right _ _)
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
+222
View File
@@ -0,0 +1,222 @@
import Mathlib
/-!
# Stats and time series
Models `pkg/metadata/gormstore/aggregation_worker.go` (`AggregateHourly`, `AggregateDaily`) and
`pkg/metadata/gormstore/gormstore_v2.go` `GetTimeSeriesStats`. Time is in whole minutes since the
epoch; an hour is 60 minutes and a day 24 hours. Omits: unique IPs, packages, registries.
The last three sections model the trend snapshots and backfill in `pkg/metadata/gormstore/snapshots.go`,
the soft-delete purge in `pkg/metadata/gormstore/purge.go` and `pkg/cache/cache.go` `purgeDeleted`,
and the severity filter in `pkg/metadata/gormstore/dashboard.go`.
-/
namespace Gohoarder.Stats
/-! ### Hourly pass: each event is counted once -/
/-- `AggregateHourly`: cutoff hour = floor((now - 5min) / 60); events in earlier hours move to
`hr` and are deleted, in one transaction. -/
def cutoffHour (nowMin : ℤ) : ℤ := (nowMin - 5) / 60
def moveEvents (c : ℤ) (ev hr : ℤ → ℕ) : (ℤ → ℕ) × (ℤ → ℕ) :=
(fun h => if h < c then 0 else ev h, fun h => hr h + if h < c then ev h else 0)
/-- Per hour, events plus hourly rows are unchanged by a pass: nothing is counted twice or dropped. -/
theorem hourly_pass_conserves (c : ℤ) (ev hr : ℤ → ℕ) (h : ℤ) :
(moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h = ev h + hr h := by
simp only [moveEvents]
split_ifs <;> omega
theorem hourly_pass_conserves_sum (c : ℤ) (ev hr : ℤ → ℕ) (S : Finset ℤ) :
∑ h ∈ S, ((moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h) = ∑ h ∈ S, (ev h + hr h) :=
Finset.sum_congr rfl fun h _ => hourly_pass_conserves c ev hr h
/-- Within five minutes after the hour the cutoff is still the previous hour, so the last hour of a
day is not aggregated by a pass at `hh:00`-`hh:04`. -/
theorem early_tick_leaves_last_hour (hourIdx m : ℤ) (hm0 : 0 ≤ m) (hm : m < 5) :
cutoffHour (60 * hourIdx + m) = hourIdx - 1 := by
unfold cutoffHour; omega
theorem late_tick_covers_last_hour (hourIdx m : ℤ) (hm0 : 5 ≤ m) (hm : m < 60) :
cutoffHour (60 * hourIdx + m) = hourIdx := by
unfold cutoffHour; omega
/-! ### Daily pass: which days are rolled up -/
def retentionDays : ℕ := 7
/-- Days recomputed by each pass (`rollupDays`). -/
def rollupDays : ℕ := 6
/-- A pass on day `t` rolls up day `d` (before: only yesterday). -/
def oldRolls (t d : ℕ) : Prop := d + 1 = t
def newRolls (t d : ℕ) : Prop := d + 1 ≤ t ∧ t ≤ d + rollupDays
theorem rollup_window_below_retention : rollupDays < retentionDays := by decide
/-- The pass on day `t` deletes hourly rows older than 7 days: hours of day `d` survive it
whenever `t < d + 7`. The new window ends at `d + 6`, inside that bound. -/
theorem new_window_inside_retention (t d : ℕ) (h : newRolls t d) : t < d + retentionDays := by
unfold newRolls at h; unfold retentionDays rollupDays at *; omega
/-- A day is rolled up if some pass day (hour-0 tick) falls in its window. -/
def covered (rolls : ℕ → ℕ → Prop) (passes : Set ℕ) (d : ℕ) : Prop := ∃ t ∈ passes, rolls t d
/-- Before: skipping the one pass on day d+1 (restart at midnight) loses day d for good. -/
theorem old_loses_day_on_one_skip (d : ℕ) :
¬ covered oldRolls {t | t ≠ d + 1} d := by
rintro ⟨t, ht, h⟩
unfold oldRolls at h
exact ht h.symm
/-- After: any single surviving pass in the next six days repairs it. -/
theorem new_repairs_after_skip (d : ℕ) : covered newRolls {t | t ≠ d + 1} d :=
⟨d + 2, by simp, by unfold newRolls rollupDays; omega⟩
/-! ### Chart: rollup against hourly rows and events -/
/-- Before: `counts[day] = rollup`. After: the larger of rollup and hourly+events. -/
def chartOld (rollup live : ℕ) : ℕ := rollup
def chartNew (rollup live : ℕ) : ℕ := max rollup live
/-- Rollup and live (hourly rows + events) each count a subset of the day's downloads, so the
larger is the better lower bound and never exceeds the truth. -/
theorem chartNew_sound (truth rollup live : ℕ) (hr : rollup ≤ truth) (hl : live ≤ truth) :
chartNew rollup live ≤ truth := max_le hr hl
theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ chartNew rollup live :=
le_max_left _ _
/-- A download aggregated after the rollup ran: the old chart shows 1 of 2. -/
theorem chartOld_drops_late_download : chartOld 1 2 < chartNew 1 2 := by decide
/-! ### SQLite upsert (`aggregation_worker.go`, `sqlite_stats.go`) -/
/-- A bucket is a list of stored rows; the chart sums them. Before the fix SQLite had no unique index,
so `INSERT OR REPLACE` appended a row per pass. -/
def chartTotal (rows : List ℕ) : ℕ := rows.sum
/-- Three passes over a bucket whose registry total is 3: three copies. -/
theorem old_sqlite_duplicates_rows : chartTotal [3, 3, 3] ≠ 3 := by decide
/-- `ON CONFLICT ... DO UPDATE` over the unique index keeps one row per bucket: a derived row is set,
a package row adds the new events, as on PostgreSQL. -/
def upsertDerived (_old new : ℕ) : List ℕ := [new]
def upsertAdditive (old new : ℕ) : List ℕ := [old + new]
theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
chartTotal (upsertDerived old new) = new := by simp [chartTotal, upsertDerived]
theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) :
chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive]
/-! ### Daily snapshots and backfill (`snapshots.go`) -/
/-- Minutes in a UTC day. -/
def dayLen : ℕ := 1440
/-- `stateAtDayEnd`: a package cached at `cached` and deleted at `x` (`none` = still cached) counts in
the snapshot of day `d` iff it was cached before the day ended and not deleted before it ended. -/
def aliveAtEnd (cached : ℕ) (deleted : Option ℕ) (d : ℕ) : Prop :=
cached < dayLen * (d + 1) ∧ ∀ x, deleted = some x → dayLen * (d + 1) ≤ x
/-- A package cached and deleted inside one day is in no snapshot. -/
theorem same_day_package_never_counted (cached x d : ℕ) (hx : x < dayLen * (d + 1)) :
¬ aliveAtEnd cached (some x) d := by
rintro ⟨_, h⟩
exact absurd (h x rfl) (by omega)
theorem undeleted_package_counts_from_its_day (cached d : ℕ) :
aliveAtEnd cached none d ↔ cached < dayLen * (d + 1) := by
simp [aliveAtEnd]
/-- The backfill adds only each day's change to a running total (`deltas`, then the cumulative loop). -/
def delta (s : ℕ → ℤ) (d : ℕ) : ℤ := s d - (if d = 0 then 0 else s (d - 1))
/-- The running total of the daily changes equals the end-of-day state: the sweep loses nothing. -/
theorem sweep_telescopes (s : ℕ → ℤ) (n : ℕ) :
∑ d ∈ Finset.range (n + 1), delta s d = s n := by
induction n with
| zero => simp [delta]
| succ n ih =>
rw [Finset.sum_range_succ, ih]
simp [delta]
/-- One snapshot row per day, `none` = no row. `upsertSnapshot` (`SnapshotStats`) replaces the day's row. -/
def upsertSnapshot (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ := Function.update rows day (some v)
/-- Running the snapshot twice in a day leaves the last write only. -/
theorem snapshot_last_write_wins (rows : ℕ → Option ℕ) (day a b : ℕ) :
upsertSnapshot (upsertSnapshot rows day a) day b = upsertSnapshot rows day b :=
Function.update_idem _ _ _
theorem snapshot_leaves_other_days (rows : ℕ → Option ℕ) (day other v : ℕ) (h : other ≠ day) :
upsertSnapshot rows day v other = rows other :=
Function.update_of_ne h _ _
/-- The backfill insert (`ON CONFLICT DO NOTHING`) never replaces an existing row. -/
def insertMissing (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ :=
fun d => if d = day then (rows d).or (some v) else rows d
theorem backfill_keeps_existing (rows : ℕ → Option ℕ) (day a v : ℕ) (h : rows day = some a) :
insertMissing rows day v day = some a := by
simp [insertMissing, h]
/-- The backfill runs only while no past-day snapshot exists, so it cannot rewrite history. -/
def backfillRuns (pastRows : ℕ) : Bool := pastRows == 0
theorem backfill_idle_once_history_exists (n : ℕ) : backfillRuns (n + 1) = false := by
simp [backfillRuns]
/-! ### Soft-delete purge (`purge.go`, `cache.go` `purgeDeleted`) -/
/-- Cutoff = now - retention; a row is purged iff it was deleted before the cutoff. A row that is
not deleted (`none`) is never purged. -/
def purgeable (now retention : ℕ) (deleted : Option ℕ) : Prop :=
∃ x, deleted = some x ∧ x + retention < now
theorem active_row_never_purged (now retention : ℕ) : ¬ purgeable now retention none := by
rintro ⟨x, h, _⟩
cases h
theorem recent_delete_kept (now retention x : ℕ) (h : now ≤ x + retention) :
¬ purgeable now retention (some x) := by
rintro ⟨y, hy, hlt⟩
cases hy
omega
/-- The purge touches package rows only; the snapshot rows come out as they went in. -/
def purgeStep {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
List P × (ℕ → Option ℕ) := (pkgs.filter keep, snaps)
theorem purge_keeps_snapshots {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
(purgeStep pkgs keep snaps).2 = snaps := rfl
/-- One pass purges at most `maxPurgeBatches` batches of `limit` rows. -/
def maxPurgeBatches : ℕ := 100
theorem purge_pass_bounded (batches limit : ℕ) (h : batches ≤ maxPurgeBatches) :
batches * limit ≤ maxPurgeBatches * limit :=
Nat.mul_le_mul_right limit h
/-! ### Severity filter (`dashboard.go` `severityFilter`, `latestScanWith`) -/
/-- A package passes when no severity is selected, or its latest scan counts one of them. -/
def passes (selected : List ℕ) (counts : ℕ → ℕ) : Prop := selected = [] ∨ ∃ s ∈ selected, 0 < counts s
/-- OR semantics: selecting one more severity never hides a package. -/
theorem passes_monotone (sel sel' : List ℕ) (counts : ℕ → ℕ) (h : ∀ s ∈ sel, s ∈ sel')
(hne : sel ≠ []) (hp : passes sel counts) : passes sel' counts := by
right
rcases hp with hp | ⟨s, hs, hc⟩
· exact absurd hp hne
· exact ⟨s, h s hs, hc⟩
/-- A package with no finding of any selected severity is filtered out. -/
theorem clean_package_filtered (sel : List ℕ) (hne : sel ≠ []) : ¬ passes sel (fun _ => 0) := by
rintro (h | ⟨s, _, hc⟩)
· exact hne h
· exact absurd hc (by simp)
end Gohoarder.Stats
+96
View File
@@ -0,0 +1,96 @@
{"version": "1.3.0",
"packagesDir": ".lake/packages",
"packages":
[{"url": "https://github.com/leanprover-community/mathlib4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
"name": "mathlib",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": false,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/plausible",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "054b228ce0ac61d767c6e71ba73a24728f191b72",
"name": "plausible",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/LeanSearchClient",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9",
"name": "LeanSearchClient",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/import-graph",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0",
"name": "importGraph",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/ProofWidgets4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "2f0f3520daeac2d9310ff25b7a877a0e5cdaa203",
"name": "proofwidgets",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/aesop",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "66ff77cf0c4c898799e4b94d14db55f7a02d0c5a",
"name": "aesop",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/quote4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "ff055a2fcc835935e0ae607339b455a5f5896b4b",
"name": "Qq",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/batteries",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "b4b25a3886a16daacaf6615c2eea7170a6e8f458",
"name": "batteries",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover/lean4-cli",
"type": "git",
"subDir": null,
"scope": "leanprover",
"rev": "50810f72af7618bee62fe9800dc26e806c188703",
"name": "Cli",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": true,
"configFile": "lakefile.toml"}],
"name": "gohoarder",
"lakeDir": ".lake",
"fixedToolchain": false}
+10
View File
@@ -0,0 +1,10 @@
name = "gohoarder"
defaultTargets = ["Gohoarder"]
[[require]]
name = "mathlib"
scope = "leanprover-community"
rev = "v4.36.0"
[[lean_lib]]
name = "Gohoarder"
+1
View File
@@ -0,0 +1 @@
leanprover/lean4:v4.36.0
+27
View File
@@ -0,0 +1,27 @@
import Gohoarder
import Lean
/-! Fails unless every theorem under `Gohoarder` depends only on `propext`, `Classical.choice` and
`Quot.sound`. Run from `lean4/`: `lake env lean scripts/Axioms.lean`. -/
open Lean Elab Command
elab "#audit_axioms" : command => do
let env ← getEnv
let allowed : List Name := [``propext, ``Classical.choice, ``Quot.sound]
let mut audited : Nat := 0
let mut bad : Array String := #[]
for (n, ci) in env.constants.map₁.toList do
if `Gohoarder |>.isPrefixOf n then
if let .thmInfo _ := ci then
audited := audited + 1
let axs ← liftCoreM (collectAxioms n)
for a in axs do
if !allowed.contains a then
bad := bad.push s!"{n} uses {a}"
if bad.isEmpty then
logInfo m!"{audited} theorems audited, axioms within {allowed}"
else
throwError "unexpected axioms:\n{"\n".intercalate bad.toList}"
#audit_axioms
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# Fails when a Go file cited by the Lean model changed in the range with no change under lean4/.
# Usage: lean4/scripts/check_currency.sh [base-ref] (default origin/main)
set -eu
base="${1:-origin/main}"
root="$(git rev-parse --show-toplevel)"
cd "$root"
changed="$(git diff --name-only "$base"...HEAD)"
cited="$(grep -rhoE '(pkg|cmd)/[A-Za-z0-9_./-]+\.go|Dockerfile\.frontend' lean4/Gohoarder | sort -u)"
if printf '%s\n' "$changed" | grep -q '^lean4/'; then
lean_changed=yes
else
lean_changed=no
fi
status=0
for file in $cited; do
if [ ! -f "$file" ]; then
echo "MISSING: $file is cited by the Lean model but does not exist"
status=1
continue
fi
if printf '%s\n' "$changed" | grep -qx "$file" && [ "$lean_changed" = no ]; then
echo "REVIEW: $file is cited by the Lean model and changed with no lean4/ change"
status=1
fi
done
[ "$status" -eq 0 ] && echo "currency: every cited file exists and none changed without a model change"
exit "$status"
@@ -181,6 +181,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
FOREIGN KEY (package_id) REFERENCES packages(id) ON DELETE CASCADE ON UPDATE CASCADE,
INDEX idx_scan_package_scanner (package_id, scanner, deleted_at),
INDEX idx_scan_package_scanned_at (package_id, scanned_at),
INDEX idx_scan_scanned_at (scanned_at DESC),
INDEX idx_scan_status (status),
INDEX idx_scan_vuln_count (vuln_count)
@@ -190,6 +190,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
);
CREATE INDEX idx_scan_package_scanner ON scan_results(package_id, scanner) WHERE deleted_at IS NULL;
CREATE INDEX idx_scan_package_scanned_at ON scan_results(package_id, scanned_at) WHERE deleted_at IS NULL;
CREATE INDEX idx_scan_scanned_at ON scan_results(scanned_at DESC);
CREATE INDEX idx_scan_status ON scan_results(status);
CREATE INDEX idx_scan_vuln_count ON scan_results(vuln_count) WHERE vuln_count > 0;
+54 -18
View File
@@ -215,6 +215,10 @@ func (a *App) initializeComponents() error {
return fmt.Errorf("failed to initialize scanner: %w", err)
}
if setter, ok := a.metadata.(blockedCounterSetter); ok {
setter.SetBlockedCounter(a.countBlocked)
}
// Initialize analytics engine first (needed by cache)
log.Info().Msg("Initializing analytics engine")
a.analyticsEngine = analytics.NewEngine(analytics.Config{
@@ -230,11 +234,20 @@ 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{
DefaultTTL: a.config.Cache.DefaultTTL,
CleanupInterval: cleanupInterval,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
RescanAfter: rescanAfter,
DefaultTTL: a.config.Cache.DefaultTTL,
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
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)
@@ -307,10 +320,15 @@ func (a *App) initializeComponents() error {
}
bootCancel()
a.scanManager.SetFileSource(a.cache.ScanFile)
// Initialize rescan worker if enabled
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
scanner.WithConcurrency(a.config.Security.RescanConcurrency),
)
}
// Initialize WebSocket server
@@ -388,10 +406,11 @@ func (a *App) initializeComponents() error {
func (a *App) setupServer() error {
// Create Fiber app
a.app = fiber.New(fiber.Config{
ReadTimeout: a.config.Server.ReadTimeout,
WriteTimeout: a.config.Server.WriteTimeout,
ServerHeader: "GoHoarder",
AppName: "GoHoarder v1.0",
ReadTimeout: a.config.Server.ReadTimeout,
WriteTimeout: a.config.Server.WriteTimeout,
ReadBufferSize: a.config.Server.ReadBufferSize,
ServerHeader: "GoHoarder",
AppName: "GoHoarder v1.0",
})
// Auth middleware factories. Built once, reused on every gated route.
@@ -410,6 +429,8 @@ func (a *App) setupServer() error {
_ = mwOptional // reserved for future endpoints with anonymous fallback
}
a.app.Use("/api", apiOriginGuard(a.config.Server.AllowedOrigins))
// Health endpoints — ALWAYS public (k8s liveness/readiness probes).
a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler()))
a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler()))
@@ -439,6 +460,7 @@ func (a *App) setupServer() error {
a.app.All("/api/packages/*", mwAuth, a.handlePackages) // OPTIONS, preflight, vulnerabilities
a.app.Get("/api/stats", mwAuth, a.handleStats)
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
a.app.Get("/api/info", mwAuth, a.handleInfo)
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
@@ -453,6 +475,7 @@ func (a *App) setupServer() error {
a.app.All("/api/packages/*", a.handlePackages)
a.app.Get("/api/stats", a.handleStats)
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
a.app.Get("/api/stats/trend", a.handleStatsTrend)
a.app.Get("/api/info", a.handleInfo)
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
@@ -592,6 +615,24 @@ func (a *App) setupServer() error {
return nil
}
// startWorkers starts the background loops that live as long as ctx.
func (a *App) startWorkers(ctx context.Context) {
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
a.wsServer.Start(ctx)
// Start download data aggregation worker (runs every hour)
go a.startAggregationWorker(ctx)
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
// 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 {
// Cancellable worker context: aggregation + stats broadcaster goroutines
// watch ctx.Done() and exit, so Shutdown can stop them before closing
@@ -600,12 +641,7 @@ func (a *App) Run() error {
a.cancel = cancel
defer cancel()
// Start download data aggregation worker (runs every hour)
go a.startAggregationWorker(ctx)
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
a.startWorkers(ctx)
// Start Fiber server in goroutine. Branch on TLS to pick Listen vs ListenTLS.
errChan := make(chan error, 1)
@@ -879,13 +915,13 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
}
ou, err := url.Parse(origin)
if err != nil || ou.Scheme == "" || ou.Host == "" {
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
return false
}
originScheme := strings.ToLower(ou.Scheme)
originHost, ok := normalizeOriginHost(originScheme, ou.Host)
if !ok {
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
return false
}
@@ -916,7 +952,7 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
log.Warn().
Str("origin", origin).
Str("host", r.Host).
Msg("Rejecting WebSocket upgrade: Origin not in allowlist")
Msg("Rejecting origin: Origin not in allowlist")
return false
}
}
+94
View File
@@ -0,0 +1,94 @@
package app
import (
"net/http"
"net/url"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/rs/zerolog/log"
)
const (
headerOrigin = "Origin"
corsAllowedMethods = "GET, POST, PATCH, DELETE, OPTIONS"
corsAllowedHeaders = "Content-Type, Authorization, X-API-Key"
corsPreflightMaxAge = "600"
headerACRMethod = "Access-Control-Request-Method"
headerACAllowOrigin = "Access-Control-Allow-Origin"
headerACAllowMethods = "Access-Control-Allow-Methods"
headerACAllowHeaders = "Access-Control-Allow-Headers"
headerACMaxAge = "Access-Control-Max-Age"
)
// apiOriginGuard enforces server.allowed_origins on /api. A browser at another origin cannot
// read responses (no CORS grant) and cannot change state (403), whatever the handlers set.
// With nothing configured only the request's own host counts as same-origin.
// Requests with neither Origin nor Referer come from non-browser clients and pass.
func apiOriginGuard(allowed []string) fiber.Handler {
check := buildCheckOrigin(allowed)
originAllowed := func(c fiber.Ctx, origin string) bool {
r := &http.Request{Header: http.Header{headerOrigin: {origin}}, Host: c.Host()}
return check(r)
}
return func(c fiber.Ctx) error {
origin := c.Get(headerOrigin)
method := c.Method()
if method == http.MethodOptions && origin != "" && c.Get(headerACRMethod) != "" {
if !originAllowed(c, origin) {
return c.SendStatus(fiber.StatusForbidden)
}
setCORSGrant(c, origin)
c.Set(headerACMaxAge, corsPreflightMaxAge)
return c.SendStatus(fiber.StatusNoContent)
}
if !isSafeMethod(method) {
source := origin
if source == "" {
source = refererOrigin(c.Get(fiber.HeaderReferer))
}
if source != "" && !originAllowed(c, source) {
log.Warn().Str("method", method).Str("path", c.Path()).Str("origin", source).Msg("Rejecting cross-origin state-changing request")
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "cross-origin request not allowed"})
}
}
err := c.Next()
// Drop any grant a handler or upstream set; the allowlist decides.
c.Response().Header.Del(headerACAllowOrigin)
c.Response().Header.Del(headerACAllowMethods)
c.Response().Header.Del(headerACAllowHeaders)
c.Vary(headerOrigin)
if origin != "" && originAllowed(c, origin) {
setCORSGrant(c, origin)
}
return err
}
}
func setCORSGrant(c fiber.Ctx, origin string) {
c.Set(headerACAllowOrigin, origin)
c.Set(headerACAllowMethods, corsAllowedMethods)
c.Set(headerACAllowHeaders, corsAllowedHeaders)
c.Vary(headerOrigin)
}
func isSafeMethod(m string) bool {
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
}
// refererOrigin returns scheme://host of a Referer, or "" when it is absent or malformed.
func refererOrigin(referer string) string {
if strings.TrimSpace(referer) == "" {
return ""
}
u, err := url.Parse(referer)
if err != nil || u.Scheme == "" || u.Host == "" {
return "null" // present but unusable: never matches the allowlist
}
return u.Scheme + "://" + u.Host
}
+144
View File
@@ -0,0 +1,144 @@
package app
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const dashboardOrigin = "https://gohoarder.example.com"
func seedPackage(t *testing.T, a *App) {
t.Helper()
entry, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*cache.FetchResult, error) {
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
}
func apiCall(t *testing.T, a *App, method, target string, headers map[string]string) *http.Response {
t.Helper()
req := httptest.NewRequest(method, target, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
require.NoError(t, err)
t.Cleanup(func() { _ = resp.Body.Close() })
return resp
}
func corsApp(t *testing.T, origins ...string) *App {
return newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = origins })
}
const deletePath = "/api/packages/npm/left-pad/1.3.0"
func TestAPIDeleteFromDisallowedOriginForbidden(t *testing.T) {
a := corsApp(t, dashboardOrigin)
seedPackage(t, a)
for _, h := range []map[string]string{
{"Origin": "https://evil.example.net"},
{"Origin": "null"},
{"Referer": "https://evil.example.net/page"},
{"Origin": "https://evil.example.net", "Referer": dashboardOrigin + "/x"},
} {
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
assert.Equal(t, http.StatusForbidden, resp.StatusCode, "%v", h)
}
resp := apiCall(t, a, http.MethodGet, "/api/packages/npm", nil)
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
assert.NoError(t, err, "a refused request must not delete")
}
func TestAPIDeleteFromAllowedOriginWorks(t *testing.T) {
for name, h := range map[string]map[string]string{
"origin": {"Origin": dashboardOrigin},
"referer": {"Referer": dashboardOrigin + "/packages"},
"no-fetch": nil, // curl and server-to-server callers send neither header
} {
t.Run(name, func(t *testing.T) {
a := corsApp(t, dashboardOrigin)
seedPackage(t, a)
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
assert.Equal(t, http.StatusOK, resp.StatusCode)
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
assert.Error(t, err, "package must be gone")
})
}
}
func TestAPIPostFromDisallowedOriginForbidden(t *testing.T) {
a := corsApp(t, dashboardOrigin)
resp := apiCall(t, a, http.MethodPost, "/api/admin/prewarming/trigger", map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}
func TestAPIGetStaysPublicWithoutWildcardCORS(t *testing.T) {
a := corsApp(t, dashboardOrigin)
resp := apiCall(t, a, http.MethodGet, "/api/stats", nil)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": dashboardOrigin})
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, dashboardOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
assert.Contains(t, resp.Header.Values("Vary"), "Origin")
// Served, but a browser at a foreign origin cannot read it.
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
}
func TestAPIPreflightAnswersOnlyAllowedOrigins(t *testing.T) {
a := corsApp(t, dashboardOrigin)
preflight := func(origin string) *http.Response {
return apiCall(t, a, http.MethodOptions, deletePath, map[string]string{
"Origin": origin, "Access-Control-Request-Method": "DELETE",
})
}
ok := preflight(dashboardOrigin)
assert.Equal(t, http.StatusNoContent, ok.StatusCode)
assert.Equal(t, dashboardOrigin, ok.Header.Get("Access-Control-Allow-Origin"))
assert.Contains(t, ok.Header.Get("Access-Control-Allow-Methods"), "DELETE")
bad := preflight("https://evil.example.net")
assert.Equal(t, http.StatusForbidden, bad.StatusCode)
assert.Empty(t, bad.Header.Get("Access-Control-Allow-Origin"))
}
// With nothing configured, only the host the request was sent to counts as same-origin.
func TestAPISameOriginRuleWhenNoOriginsConfigured(t *testing.T) {
a := corsApp(t)
seedPackage(t, a)
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "http://example.com"}) // httptest.NewRequest Host
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestAPIOriginMatchingUsesAllowlistRules(t *testing.T) {
a := corsApp(t, "https://*.example.org")
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://ui.example.org"})
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://example.org.evil.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}
+67
View File
@@ -0,0 +1,67 @@
package app
import (
"go/ast"
"go/parser"
"go/token"
"net/http"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
func TestHandlersSetNoCORSHeaders(t *testing.T) {
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
for _, f := range files {
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
continue
}
parsed, err := parser.ParseFile(fset, f, nil, 0)
if err != nil {
t.Fatalf("parse %s: %v", f, err)
}
ast.Inspect(parsed, func(n ast.Node) bool {
lit, ok := n.(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return true
}
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
}
return true
})
}
}
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
const dashboard = "https://dash.example.com"
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
targets := []string{
"/api/stats", "/api/info", "/api/config", "/api/packages",
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
"/api/analytics/search?q=x", "/api/stats/timeseries",
}
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
for _, target := range targets {
hdr := map[string]string{}
if origin != "" {
hdr["Origin"] = origin
}
code, h, _ := doRequest(t, a, target, hdr)
if code == http.StatusNotFound {
t.Errorf("GET %s = 404, route missing", target)
}
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
}
}
}
}
+68
View File
@@ -0,0 +1,68 @@
package app
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
func doDelete(t *testing.T, a *App, target string) (int, string) {
t.Helper()
req := httptest.NewRequest(http.MethodDelete, target, nil)
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
if err != nil {
t.Fatalf("DELETE %s: %v", target, err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
return resp.StatusCode, string(body)
}
func TestDeleteMissingPackageIs404(t *testing.T) {
a := newTestApp(t, nil)
for _, target := range []string{
"/api/packages/npm/nope/1.0.0",
"/api/packages/pypi/nope/1.0.0",
"/api/packages/go/example.com/nope/v1.0.0",
} {
code, body := doDelete(t, a, target)
if code != http.StatusNotFound {
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
}
var out map[string]string
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
}
}
}
func TestDeleteExistingPackageIs200(t *testing.T) {
a := newTestApp(t, nil)
ctx := context.Background()
err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
})
if err != nil {
t.Fatalf("SavePackage: %v", err)
}
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
}
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
t.Errorf("second DELETE = %d %s, want 404", code, body)
}
}
+190 -194
View File
@@ -1,12 +1,18 @@
package app
import (
"context"
stderrors "errors"
"fmt"
"slices"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/internal/version"
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
"github.com/rs/zerolog/log"
)
@@ -14,9 +20,6 @@ import (
// handlePackages handles /api/packages endpoint
func (a *App) handlePackages(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -37,166 +40,184 @@ func (a *App) handlePackages(c fiber.Ctx) error {
}
}
// handleListPackages returns list of cached packages
// packageSummary is the list payload for one package when scan results are attached.
func packageSummary(pkg *metadata.Package) map[string]interface{} {
summary := map[string]interface{}{
"id": pkg.ID,
"registry": pkg.Registry,
"name": pkg.Name,
"version": pkg.Version,
"size": pkg.Size,
"checksum_sha256": pkg.ChecksumSHA256,
"cached_at": pkg.CachedAt,
"last_accessed": pkg.LastAccessed,
"download_count": pkg.DownloadCount,
}
if pkg.ReleaseVersion != "" {
summary["release_version"] = pkg.ReleaseVersion
}
return summary
}
// Pagination limits of GET /api/packages.
const (
defaultPageSize = 25
maxPageSize = 200
)
// listParams are the parsed query parameters of GET /api/packages.
type listParams struct {
opts metadata.GroupListOptions
paged bool
}
// parseSeverities reads a comma-separated severity filter such as "critical,high".
func parseSeverities(raw string) ([]string, error) {
var out []string
for _, part := range strings.Split(raw, ",") {
sev := strings.ToLower(strings.TrimSpace(part))
if sev == "" || slices.Contains(out, sev) {
continue
}
if !slices.Contains(metadata.Severities, sev) {
return nil, fmt.Errorf("invalid severity %q, must be one of: %s", sev, strings.Join(metadata.Severities, ", "))
}
out = append(out, sev)
}
return out, nil
}
// parseListParams reads page, page_size, registry, q, sort, order and severity.
// Without page or page_size the list is unpaginated, as it was before paging existed.
func parseListParams(c fiber.Ctx) (listParams, error) {
p := listParams{opts: metadata.GroupListOptions{
Registry: c.Query("registry"),
Query: c.Query("q"),
SortBy: metadata.GroupSortName,
}}
switch sortBy := c.Query("sort"); sortBy {
case metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize:
p.opts.SortBy = sortBy
p.opts.SortDesc = sortBy != metadata.GroupSortName
}
switch c.Query("order") {
case "asc":
p.opts.SortDesc = false
case "desc":
p.opts.SortDesc = true
}
severities, err := parseSeverities(c.Query("severity"))
if err != nil {
return p, err
}
p.opts.Severities = severities
if c.Query("page") != "" || c.Query("page_size") != "" {
p.paged = true
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
p.opts.PageSize = fiber.Query[int](c, "page_size", defaultPageSize)
if p.opts.PageSize < 1 {
p.opts.PageSize = defaultPageSize
}
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
}
return p, nil
}
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDecision, error) {
if a.scanManager != nil {
return a.scanManager.ScanDecisions(ctx, ids)
}
summaries, err := a.metadata.GetScanSummaries(ctx, ids, false)
if err != nil {
return nil, err
}
out := make([]scanner.ScanDecision, len(summaries))
for i, s := range summaries {
out[i] = scanner.ScanDecision{Summary: s}
}
return out, nil
}
// vulnerabilityInfo is the per-row scan block of the list payload.
func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) map[string]interface{} {
if !pkg.SecurityScanned {
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false}
}
d, ok := decisions[pkg.ID]
if !ok || !d.Summary.HasScan {
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false}
}
sum := d.Summary
return map[string]interface{}{
"scanned": true,
"status": sum.Status,
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
"counts": map[string]int{
"critical": sum.Critical,
"high": sum.High,
"moderate": sum.Moderate,
"low": sum.Low,
},
"total": sum.Total,
"isBlocked": d.Blocked,
}
}
// handleListPackages returns cached packages, one page of groups when page or
// page_size is given and every group otherwise.
func (a *App) handleListPackages(c fiber.Ctx) error {
ctx := c.Context()
params, err := parseListParams(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
}
// Get packages from metadata store
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
Limit: 1000, // Get more to account for duplicates
Offset: 0,
})
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
if err != nil {
log.Error().Err(err).Msg("Failed to list packages")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
}
log.Debug().Int("total_packages_from_db", len(allPackages)).Msg("Retrieved packages from database")
// Filter, clean, and deduplicate packages
// Map stores both cleaned package and original name for scan lookups
type packageEntry struct {
pkg *metadata.Package
originalName string
response := fiber.Map{
"total": len(page.Packages),
"total_groups": page.TotalGroups,
}
seen := make(map[string]*packageEntry)
skippedCount := 0
for _, pkg := range allPackages {
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
skippedCount++
log.Debug().
Str("name", pkg.Name).
Str("version", pkg.Version).
Str("registry", pkg.Registry).
Msg("Skipping metadata entry")
continue
if params.paged {
response["page"] = params.opts.Page
response["page_size"] = params.opts.PageSize
}
if !a.config.Security.Enabled {
response["packages"] = page.Packages
return c.Status(fiber.StatusOK).JSON(response)
}
var scannedIDs []string
for _, pkg := range page.Packages {
if pkg.SecurityScanned {
scannedIDs = append(scannedIDs, pkg.ID)
}
// Clean the package name (remove /@v/version.ext suffix)
originalName := pkg.Name
cleanName := pkg.Name
if idx := strings.Index(cleanName, "/@v/"); idx != -1 {
cleanName = cleanName[:idx]
}
decisions := map[string]scanner.ScanDecision{}
if len(scannedIDs) > 0 {
list, err := a.scanDecisions(ctx, scannedIDs)
if err != nil {
log.Error().Err(err).Msg("Failed to load scan summaries")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
}
// Create deduplication key
key := cleanName + "@" + pkg.Version
// Keep the entry with the largest size (typically .zip files)
if existing, ok := seen[key]; !ok || pkg.Size > existing.pkg.Size {
// Create a copy with cleaned name
cleanPkg := *pkg
cleanPkg.Name = cleanName
seen[key] = &packageEntry{
pkg: &cleanPkg,
originalName: originalName,
}
for _, d := range list {
decisions[d.Summary.PackageID] = d
}
}
log.Debug().
Int("skipped_metadata", skippedCount).
Int("unique_packages", len(seen)).
Msg("Filtered and deduplicated packages")
// Convert map to slice, keeping track of original names
type packageWithOriginalName struct {
pkg *metadata.Package
originalName string
enhanced := make([]map[string]interface{}, 0, len(page.Packages))
for _, pkg := range page.Packages {
pkgMap := packageSummary(pkg)
pkgMap["vulnerabilities"] = vulnerabilityInfo(pkg, decisions)
enhanced = append(enhanced, pkgMap)
}
packagesWithNames := make([]packageWithOriginalName, 0, len(seen))
for _, entry := range seen {
packagesWithNames = append(packagesWithNames, packageWithOriginalName{
pkg: entry.pkg,
originalName: entry.originalName,
})
}
// Enhance packages with vulnerability information if security scanning is enabled
var response map[string]interface{}
if a.config.Security.Enabled {
enhancedPackages := make([]map[string]interface{}, 0, len(packagesWithNames))
for _, entry := range packagesWithNames {
pkg := entry.pkg
pkgMap := map[string]interface{}{
"id": pkg.ID,
"registry": pkg.Registry,
"name": pkg.Name,
"version": pkg.Version,
"size": pkg.Size,
"checksum_sha256": pkg.ChecksumSHA256,
"cached_at": pkg.CachedAt,
"last_accessed": pkg.LastAccessed,
"download_count": pkg.DownloadCount,
}
// Add vulnerability info if scanned
if pkg.SecurityScanned {
// Use original name for scan result lookup (handles Go packages with /@v/ suffix)
scanResult, err := a.metadata.GetScanResult(ctx, pkg.Registry, entry.originalName, pkg.Version)
if err == nil && scanResult != nil {
// Count vulnerabilities by severity
severityCounts := make(map[string]int)
for _, vuln := range scanResult.Vulnerabilities {
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
}
// Check if package should be blocked based on thresholds
isBlocked := false
if a.scanManager != nil {
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, entry.originalName, pkg.Version)
isBlocked = blocked
}
pkgMap["vulnerabilities"] = map[string]interface{}{
"scanned": true,
"status": scanResult.Status,
"scannedAt": scanResult.ScannedAt.Format(time.RFC3339),
"counts": map[string]int{
"critical": severityCounts["CRITICAL"],
"high": severityCounts["HIGH"],
"moderate": severityCounts["MODERATE"],
"low": severityCounts["LOW"],
},
"total": scanResult.VulnerabilityCount,
"isBlocked": isBlocked,
}
} else {
pkgMap["vulnerabilities"] = map[string]interface{}{
"scanned": false,
"status": "pending",
"isBlocked": false,
}
}
} else {
pkgMap["vulnerabilities"] = map[string]interface{}{
"scanned": false,
"status": "not_scanned",
"isBlocked": false,
}
}
enhancedPackages = append(enhancedPackages, pkgMap)
}
response = map[string]interface{}{
"packages": enhancedPackages,
"total": len(enhancedPackages),
}
} else {
// Non-enhanced mode - just return the packages
packages := make([]*metadata.Package, 0, len(packagesWithNames))
for _, entry := range packagesWithNames {
packages = append(packages, entry.pkg)
}
response = map[string]interface{}{
"packages": packages,
"total": len(packages),
}
}
// Success response
response["packages"] = enhanced
return c.Status(fiber.StatusOK).JSON(response)
}
@@ -227,7 +248,8 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
if registry == "go" {
// List all packages matching the base name and version
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
Limit: 1000,
Registry: registry,
NamePrefix: name,
})
if err != nil {
log.Error().Err(err).Msg("Failed to list packages for deletion")
@@ -294,6 +316,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
} else {
// For NPM and PyPI, delete directly
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
var appErr *apperrors.Error
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
}
log.Error().
Err(err).
Str("registry", registry).
@@ -333,9 +359,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
// handleStats handles /api/stats endpoint
func (a *App) handleStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -354,42 +377,23 @@ func (a *App) handleStats(c fiber.Ctx) error {
cacheStats = &metadata.Stats{}
}
// Get all packages to calculate per-registry breakdown
packages, err := a.metadata.ListPackages(ctx, nil)
registryStats := make(map[string]map[string]interface{})
byRegistry, err := a.metadata.GetRegistryStats(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to list packages")
packages = []*metadata.Package{}
log.Error().Err(err).Msg("Failed to get registry stats")
}
for _, rs := range byRegistry {
registryStats[rs.Registry] = map[string]interface{}{
"count": int(rs.Count),
"size": rs.Size,
"downloads": rs.Downloads,
}
}
// Calculate per-registry breakdown and blocked packages count
registryStats := make(map[string]map[string]interface{})
blockedCount := int64(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" {
continue
}
// Track per-registry stats
if _, ok := registryStats[pkg.Registry]; !ok {
registryStats[pkg.Registry] = map[string]interface{}{
"count": 0,
"size": int64(0),
"downloads": int64(0),
}
}
registryStats[pkg.Registry]["count"] = registryStats[pkg.Registry]["count"].(int) + 1
registryStats[pkg.Registry]["size"] = registryStats[pkg.Registry]["size"].(int64) + pkg.Size
registryStats[pkg.Registry]["downloads"] = registryStats[pkg.Registry]["downloads"].(int64) + int64(pkg.DownloadCount)
// Check if package is blocked (only if security scanning is enabled and package is scanned)
if a.config.Security.Enabled && a.scanManager != nil && pkg.SecurityScanned {
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, pkg.Name, pkg.Version)
if blocked {
blockedCount++
}
}
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
blockedCount, err := a.countBlocked(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to judge scanned packages")
}
// Combine statistics using database stats for accuracy
@@ -398,6 +402,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
"total_downloads": cacheStats.TotalDownloads,
"total_size": cacheStats.TotalSize,
"max_cache_size": a.config.Cache.MaxSizeBytes,
"idle_ttl": int64(a.config.Cache.IdleTTL / time.Second), // seconds, 0 = idle eviction off
"cache_hits": cacheStats.TotalDownloads,
"cache_misses": 0, // TODO: Track cache misses
"cache_evictions": 0, // TODO: Track evictions
@@ -423,9 +428,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
// Returns time-series download statistics for charts
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -465,9 +467,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
// Returns runtime configuration for the frontend
func (a *App) handleConfig(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -499,9 +498,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
// handleInfo handles /api/info endpoint
func (a *App) handleInfo(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
-3
View File
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
// handleAdminBypasses handles /api/admin/bypasses endpoint
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
-7
View File
@@ -10,7 +10,6 @@ import (
// handleAnalyticsTopPackages returns the most downloaded packages
func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
// Get limit from query params (default: 10)
limit := 10
@@ -31,7 +30,6 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
// handleAnalyticsTrendingPackages returns trending packages
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
// Get limit from query params (default: 10)
limit := 10
@@ -52,7 +50,6 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
// handleAnalyticsTrends returns download trends over time
func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
trends := a.analyticsEngine.GetTrends()
@@ -64,7 +61,6 @@ func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
// handleAnalyticsTotalStats returns overall statistics
func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
stats := a.analyticsEngine.GetTotalStats()
@@ -74,7 +70,6 @@ func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
// handleAnalyticsRegistryStats returns per-registry statistics
func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
registry := c.Params("registry")
if registry == "" {
@@ -91,7 +86,6 @@ func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
// handleAnalyticsPackageStats returns statistics for a specific package
func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
registry := c.Params("registry")
name := c.Params("name")
@@ -117,7 +111,6 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
// handleAnalyticsSearch searches for packages matching a query
func (a *App) handleAnalyticsSearch(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
query := c.Query("q")
if query == "" {
+77
View File
@@ -0,0 +1,77 @@
package app
import (
"context"
"errors"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/rs/zerolog/log"
)
// trendPeriods maps the period query value of /api/stats/trend to days of history.
var trendPeriods = map[string]int{"30day": 30, "90day": 90, "1year": 365}
const defaultTrendPeriod = "30day"
// handleStatsTrend returns one snapshot per day for the period, oldest first.
// Vulnerability fields are null for days before vulnerability history starts.
func (a *App) handleStatsTrend(c fiber.Ctx) error {
period := c.Query("period", defaultTrendPeriod)
days, ok := trendPeriods[period]
if !ok {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "invalid period, must be one of: 30day, 90day, 1year",
})
}
today := time.Now().UTC().Truncate(24 * time.Hour)
from := today.AddDate(0, 0, -(days - 1))
points, err := a.metadata.GetStatsTrend(c.Context(), from)
if err != nil && !errors.Is(err, metadata.ErrNotImplemented) {
log.Error().Err(err).Str("period", period).Msg("Failed to get stats trend")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get stats trend"})
}
if points == nil {
points = []*metadata.StatsSnapshot{}
}
var vulnStart *string
for _, p := range points {
if p.VulnerablePackages != nil {
vulnStart = &p.Date
break
}
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"period": period,
"from": from.Format(metadata.StatsSnapshotDateLayout),
"to": today.Format(metadata.StatsSnapshotDateLayout),
"vulnerability_history_start": vulnStart,
"points": points,
})
}
// countBlocked counts scanned artifacts the blocking policy refuses.
func (a *App) countBlocked(ctx context.Context) (int64, error) {
if !a.config.Security.Enabled || a.scanManager == nil {
return 0, nil
}
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
if err != nil {
return 0, err
}
var blocked int64
for _, d := range decisions {
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
blocked++
}
}
return blocked, nil
}
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
type blockedCounterSetter interface {
SetBlockedCounter(func(context.Context) (int64, error))
}
+41 -13
View File
@@ -1,6 +1,7 @@
package app
import (
"context"
"strings"
"github.com/gofiber/fiber/v3"
@@ -11,9 +12,6 @@ import (
// handleVulnerabilities handles /api/packages/{registry}/{name}/{version}/vulnerabilities endpoint
func (a *App) handleVulnerabilities(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -45,11 +43,15 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
Str("version", version).
Msg("Getting vulnerabilities for package")
key, pkg, pkgErr := a.resolvePackageKey(ctx, registry, name, version)
releaseVersion := ""
if pkgErr == nil && pkg != nil {
releaseVersion = pkg.ReleaseVersion
}
// Get scan result from metadata store
scanResult, err := a.metadata.GetScanResult(ctx, registry, name, version)
scanResult, err := a.metadata.GetScanResult(ctx, registry, key, version)
if err != nil {
// Check if package exists
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
if pkgErr != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
}
@@ -57,9 +59,10 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
// Package exists but not scanned yet
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"package": fiber.Map{
"registry": registry,
"name": name,
"version": version,
"registry": registry,
"name": name,
"version": version,
"release_version": releaseVersion,
},
"scanned": false,
"status": "pending",
@@ -89,11 +92,15 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
}
packageKey := registry + "/" + bypassName + "@" + version
packageKeyNoVersion := registry + "/" + bypassName
releaseKey := ""
if releaseVersion != "" {
releaseKey = registry + "/" + bypassName + "@" + releaseVersion
}
bypassedCVEs := make(map[string]*metadata.CVEBypass)
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypeCVE && bypass.Active {
// Check if bypass applies to this package
if bypass.AppliesTo == "" || bypass.AppliesTo == packageKey || bypass.AppliesTo == packageKeyNoVersion {
if bypass.AppliesTo == "" || bypass.AppliesTo == packageKey || bypass.AppliesTo == packageKeyNoVersion || (releaseKey != "" && bypass.AppliesTo == releaseKey) {
bypassedCVEs[strings.ToUpper(bypass.Target)] = bypass
}
}
@@ -141,9 +148,10 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
// Build response
response := fiber.Map{
"package": fiber.Map{
"registry": registry,
"name": name,
"version": version,
"registry": registry,
"name": name,
"version": version,
"release_version": releaseVersion,
},
"scanned": true,
"scanner": scanResult.Scanner,
@@ -162,3 +170,23 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(response)
}
// goCacheKeyExts orders the Go cache files a module version is stored under; the
// .zip carries the scan result.
var goCacheKeyExts = []string{"zip", "mod", "info"}
// resolvePackageKey maps the name the dashboard shows to the stored row name.
// Go rows are stored under cache keys (module/@v/version.ext), not the module path.
func (a *App) resolvePackageKey(ctx context.Context, registry, name, version string) (string, *metadata.Package, error) {
pkg, err := a.metadata.GetPackage(ctx, registry, name, version)
if err == nil || registry != "go" || strings.Contains(name, "/@v/") {
return name, pkg, err
}
for _, ext := range goCacheKeyExts {
key := name + "/@v/" + version + "." + ext
if p, kerr := a.metadata.GetPackage(ctx, registry, key, version); kerr == nil {
return key, p, nil
}
}
return name, nil, err
}
+39
View File
@@ -0,0 +1,39 @@
package app
import (
"encoding/json"
"net/http"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
func TestStatsReportsIdleTTLSeconds(t *testing.T) {
for name, tt := range map[string]struct {
idle time.Duration
want float64
}{
"a week": {idle: 168 * time.Hour, want: 604800},
"disabled": {idle: 0, want: 0},
} {
t.Run(name, func(t *testing.T) {
a := newTestApp(t, func(c *config.Config) { c.Cache.IdleTTL = tt.idle })
code, _, body := doRequest(t, a, "/api/stats", nil)
if code != http.StatusOK {
t.Fatalf("status %d, body %q", code, body)
}
var resp struct {
Stats map[string]any `json:"stats"`
}
if err := json.Unmarshal([]byte(body), &resp); err != nil {
t.Fatalf("decode %q: %v", body, err)
}
got, ok := resp.Stats["idle_ttl"].(float64)
if !ok || got != tt.want {
t.Errorf("stats.idle_ttl = %v, want %v (body %s)", resp.Stats["idle_ttl"], tt.want, body)
}
})
}
}
+20
View File
@@ -0,0 +1,20 @@
package app
import (
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
func TestPackageSummaryCarriesReleaseVersion(t *testing.T) {
withRelease := packageSummary(&metadata.Package{Name: "six", Version: "six-1.17.0.tar.gz", ReleaseVersion: "1.17.0"})
if got := withRelease["release_version"]; got != "1.17.0" {
t.Errorf("release_version = %v, want 1.17.0", got)
}
if got := withRelease["version"]; got != "six-1.17.0.tar.gz" {
t.Errorf("version = %v, want the cache key", got)
}
if _, ok := packageSummary(&metadata.Package{Name: "left-pad", Version: "1.3.0"})["release_version"]; ok {
t.Error("a row without a release version must not send the field")
}
}
+144
View File
@@ -0,0 +1,144 @@
package app
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
type listResponse struct {
Packages []struct {
Name string `json:"name"`
Version string `json:"version"`
Registry string `json:"registry"`
Vulnerabilities struct {
Status string `json:"status"`
IsBlocked bool `json:"isBlocked"`
Total int `json:"total"`
Counts struct {
Critical int `json:"critical"`
} `json:"counts"`
} `json:"vulnerabilities"`
} `json:"packages"`
Total int `json:"total"`
TotalGroups int `json:"total_groups"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
func getList(t *testing.T, a *App, target string) listResponse {
t.Helper()
code, _, body := doRequest(t, a, target, nil)
if code != 200 {
t.Fatalf("GET %s = %d %s", target, code, body)
}
var out listResponse
if err := json.Unmarshal([]byte(body), &out); err != nil {
t.Fatalf("decode %s: %v", body, err)
}
return out
}
func TestListPackagesPagesGroupsAndAttachesScans(t *testing.T) {
a, _ := newScanningApp(t)
seedScanned(t, a, 0, 60)
page := getList(t, a, "/api/packages?page=2&page_size=25")
if page.TotalGroups != 60 || page.Page != 2 || page.PageSize != 25 {
t.Fatalf("paging fields = %+v", page)
}
if len(page.Packages) != 25 || page.Total != 25 {
t.Fatalf("page 2 holds %d rows (total %d), want 25", len(page.Packages), page.Total)
}
if first := page.Packages[0].Name; first != "pkg-025" {
t.Errorf("page 2 starts at %q, want pkg-025 (name order)", first)
}
last := getList(t, a, "/api/packages?page=3&page_size=25")
if len(last.Packages) != 10 {
t.Errorf("last page holds %d rows, want 10", len(last.Packages))
}
found := getList(t, a, "/api/packages?q=PKG-005&page_size=10")
if found.TotalGroups != 1 || len(found.Packages) != 1 {
t.Fatalf("search pkg-005 = %+v", found)
}
v := found.Packages[0].Vulnerabilities
if v.Status != "vulnerable" || !v.IsBlocked || v.Total != 1 || v.Counts.Critical != 1 {
t.Errorf("pkg-005 scan block = %+v, want vulnerable, blocked, one critical", v)
}
clean := getList(t, a, "/api/packages?q=pkg-006&page_size=10")
if cv := clean.Packages[0].Vulnerabilities; cv.Status != "clean" || cv.IsBlocked {
t.Errorf("pkg-006 scan block = %+v, want clean and not blocked", cv)
}
if none := getList(t, a, "/api/packages?registry=pypi&page_size=10"); none.TotalGroups != 0 || len(none.Packages) != 0 {
t.Errorf("pypi filter = %+v, want empty", none)
}
}
func TestListPackagesRecentFirst(t *testing.T) {
a, _ := newScanningApp(t)
seedScanned(t, a, 0, 30)
recent := getList(t, a, "/api/packages?sort=cached_at&order=desc&page=1&page_size=3")
got := []string{recent.Packages[0].Name, recent.Packages[1].Name, recent.Packages[2].Name}
want := []string{"pkg-000", "pkg-001", "pkg-002"} // seedScanned caches pkg-N N minutes ago
for i := range want {
if got[i] != want[i] {
t.Fatalf("recent = %v, want %v", got, want)
}
}
}
// The unpaginated list used to stop at 1000 rows without saying so.
func TestListPackagesUnpaginatedHasNoCap(t *testing.T) {
a := newTestApp(t, nil)
ctx := context.Background()
const rows = 1005
now := time.Now()
for i := 0; i < rows; i++ {
name := fmt.Sprintf("bulk-%04d", i)
if err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name, Size: 1, CachedAt: now, LastAccessed: now,
}); err != nil {
t.Fatalf("SavePackage: %v", err)
}
}
all := getList(t, a, "/api/packages")
if len(all.Packages) != rows || all.Total != rows || all.TotalGroups != rows {
t.Fatalf("unpaginated list = %d rows, total %d, groups %d; want %d", len(all.Packages), all.Total, all.TotalGroups, rows)
}
if capped := getList(t, a, "/api/packages?page_size=100000"); capped.PageSize != maxPageSize || len(capped.Packages) != maxPageSize {
t.Errorf("page_size clamp: size %d, rows %d, want %d", capped.PageSize, len(capped.Packages), maxPageSize)
}
}
func TestStatsFromAggregates(t *testing.T) {
a, _ := newScanningApp(t)
seedScanned(t, a, 0, 60)
code, _, body := doRequest(t, a, "/api/stats", nil)
if code != 200 {
t.Fatalf("GET /api/stats = %d %s", code, body)
}
var out struct {
Stats map[string]float64 `json:"stats"`
Registries map[string]map[string]float64 `json:"registries"`
}
if err := json.Unmarshal([]byte(body), &out); err != nil {
t.Fatal(err)
}
if out.Stats["total_packages"] != 60 || out.Stats["scanned_packages"] != 60 || out.Stats["vulnerable_packages"] != 12 {
t.Errorf("stats = %v", out.Stats)
}
if out.Stats["blocked_packages"] != 12 {
t.Errorf("blocked_packages = %v, want the 12 critical packages", out.Stats["blocked_packages"])
}
if npm := out.Registries["npm"]; npm["count"] != 60 || npm["size"] != 6000 {
t.Errorf("npm registry = %v, want 60 rows and 6000 bytes", npm)
}
}
+32
View File
@@ -3,6 +3,7 @@ package app
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"io"
"net"
@@ -18,6 +19,7 @@ import (
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// newTestApp builds a full App on temp storage with the given config tweaks.
@@ -284,3 +286,33 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
}
}
func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`))
}))
t.Cleanup(upstream.Close)
a := newTestApp(t, func(c *config.Config) {
c.Handlers.NPM.UpstreamRegistry = upstream.URL
c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute}
})
if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK {
t.Fatalf("status = %d, body %q", code, body)
}
pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"})
if err != nil {
t.Fatal(err)
}
for _, p := range pkgs {
if p.ExpiresAt == nil {
continue
}
if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute {
t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got)
}
return
}
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
}
+95
View File
@@ -0,0 +1,95 @@
package app
import (
"context"
"fmt"
"net/http"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
"gorm.io/gorm"
)
// seedScanned stores n scanned npm packages, every fifth with a critical finding.
func seedScanned(t *testing.T, a *App, from, n int) {
t.Helper()
ctx := context.Background()
now := time.Now()
for i := from; i < from+n; i++ {
name := fmt.Sprintf("pkg-%03d", i)
err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name + "/1.0.0",
Size: 100, CachedAt: now.Add(-time.Duration(i) * time.Minute), LastAccessed: now,
})
if err != nil {
t.Fatalf("SavePackage: %v", err)
}
res := &metadata.ScanResult{
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "test",
Status: metadata.ScanStatusClean, ScannedAt: now,
}
if i%5 == 0 {
res.Status = metadata.ScanStatusVulnerable
res.VulnerabilityCount = 1
res.Vulnerabilities = []metadata.Vulnerability{{ID: fmt.Sprintf("CVE-2026-%04d", i), Severity: "critical"}}
}
if err := a.metadata.SaveScanResult(ctx, res); err != nil {
t.Fatalf("SaveScanResult: %v", err)
}
}
}
func newScanningApp(t *testing.T) (*App, *dbcount.Counter) {
t.Helper()
a := newTestApp(t, func(c *config.Config) {
c.Security.Enabled = true
c.Security.Scanners.Static.Enabled = false
c.Security.UpdateDBOnStartup = false
})
store, ok := a.metadata.(*gormstore.GORMStoreV2)
if !ok {
t.Fatalf("metadata store is %T, want *gormstore.GORMStoreV2", a.metadata)
}
var counter *dbcount.Counter
store.WrapDB(func(db *gorm.DB) *gorm.DB {
counted, c := dbcount.Attach(db)
counter = c
return counted
})
return a, counter
}
// queriesFor reports how many SQL statements one GET runs.
func queriesFor(t *testing.T, a *App, c *dbcount.Counter, target string) int {
t.Helper()
c.Reset()
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
t.Fatalf("GET %s = %d %s", target, code, body)
}
return c.Count()
}
// The dashboard endpoints must cost the same number of statements for 20 rows and for 120.
func TestDashboardEndpointsQueryCountIsConstant(t *testing.T) {
a, counter := newScanningApp(t)
targets := []string{"/api/packages", "/api/packages?page=1&page_size=25", "/api/stats"}
seedScanned(t, a, 0, 20)
small := map[string]int{}
for _, target := range targets {
small[target] = queriesFor(t, a, counter, target)
}
seedScanned(t, a, 20, 100)
for _, target := range targets {
large := queriesFor(t, a, counter, target)
t.Logf("%-40s 20 rows: %3d queries, 120 rows: %3d queries", target, small[target], large)
if large != small[target] {
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows; the count must not grow with rows", target, small[target], large)
}
}
}
+37
View File
@@ -0,0 +1,37 @@
package app
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
const recentPackagesURL = "/api/packages?page=1&page_size=10&sort=cached_at&order=desc"
// Fiber v3 defaults to an 8192-byte read buffer; OIDC session cookies plus a long Referer exceed it.
func TestLargeRequestHeadersAreAccepted(t *testing.T) {
a := newTestApp(t, nil)
headers := map[string]string{
"Cookie": "session=" + strings.Repeat("a", 5000),
"Referer": "https://dash.example.com/" + strings.Repeat("r", 5000),
}
code, _, body := doRequest(t, a, recentPackagesURL, headers)
if code != http.StatusOK {
t.Fatalf("GET with ~10KB of headers = %d %q, want 200", code, body)
}
}
func TestReadBufferSizeIsConfigurable(t *testing.T) {
if got := config.Default().Server.ReadBufferSize; got != 16384 {
t.Fatalf("default server.read_buffer_size = %d, want 16384", got)
}
a := newTestApp(t, func(c *config.Config) { c.Server.ReadBufferSize = 4096 })
req := httptest.NewRequest(http.MethodGet, recentPackagesURL, nil)
req.Header.Set("Cookie", "session="+strings.Repeat("a", 6000))
if _, err := a.app.Test(req); err == nil || !strings.Contains(err.Error(), "small read buffer") {
t.Errorf("6KB header with a 4096 buffer: err = %v, want a small-read-buffer rejection", err)
}
}
+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
}
+49
View File
@@ -0,0 +1,49 @@
package app
import (
"net/http"
"testing"
)
func TestSeverityFilterOnPackagesList(t *testing.T) {
a, _ := newScanningApp(t)
seedScanned(t, a, 0, 60) // every fifth package carries one critical finding
cases := []struct {
query string
want int
}{
{"", 60},
{"?severity=", 60},
{"?severity=critical", 12},
{"?severity=Critical,high", 12},
{"?severity=high", 0},
{"?severity=high,moderate,low", 0},
{"?severity=critical&q=pkg-005", 1},
{"?severity=critical&q=pkg-006", 0},
}
for _, c := range cases {
if got := getList(t, a, "/api/packages"+c.query); len(got.Packages) != c.want {
t.Errorf("%q returned %d packages, want %d", c.query, len(got.Packages), c.want)
}
}
paged := getList(t, a, "/api/packages?severity=critical&page=1&page_size=5")
if paged.TotalGroups != 12 || len(paged.Packages) != 5 {
t.Errorf("paged severity list = %d groups, %d rows; want 12 groups, 5 rows", paged.TotalGroups, len(paged.Packages))
}
for _, p := range getList(t, a, "/api/packages?severity=critical").Packages {
if p.Vulnerabilities.Counts.Critical == 0 {
t.Errorf("%s has no critical finding but passed the critical filter", p.Name)
}
}
}
func TestSeverityFilterRejectsUnknownValue(t *testing.T) {
a, _ := newScanningApp(t)
for _, q := range []string{"?severity=urgent", "?severity=critical,nope"} {
if code, _, body := doRequest(t, a, "/api/packages"+q, nil); code != http.StatusBadRequest {
t.Errorf("%q = %d %s, want 400", q, code, body)
}
}
}
+58
View File
@@ -0,0 +1,58 @@
package app
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
func listTree(t *testing.T, dir string) string {
t.Helper()
var names []string
err := filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
if err == nil {
names = append(names, p)
}
return nil
})
if err != nil {
t.Fatal(err)
}
return strings.Join(names, "\n")
}
// Shutdown must leave nothing running against the data directory: a late SQLite close deletes
// its -wal/-shm files after Shutdown returned and breaks the removal of the directory.
func TestShutdownLeavesDataDirectoryStable(t *testing.T) {
for i := 0; i < 40; i++ {
dir := t.TempDir()
cfg := config.Default()
cfg.Storage.Backend = "filesystem"
cfg.Storage.Path = filepath.Join(dir, "store")
cfg.Metadata.Backend = "sqlite"
cfg.Metadata.SQLite.Path = filepath.Join(dir, "meta", "meta.db")
if err := os.MkdirAll(filepath.Dir(cfg.Metadata.SQLite.Path), 0o750); err != nil {
t.Fatal(err)
}
cfg.Security.Enabled = false
cfg.Prewarming.Enabled = false
cfg.Auth.Enabled = false
a, err := New(cfg)
if err != nil {
t.Fatalf("New: %v", err)
}
doRequest(t, a, "/api/stats", nil)
if err := a.Shutdown(); err != nil {
t.Fatalf("Shutdown: %v", err)
}
before := listTree(t, dir)
time.Sleep(20 * time.Millisecond)
if after := listTree(t, dir); before != after {
t.Fatalf("iteration %d: data directory changed after Shutdown:\nbefore:\n%s\nafter:\n%s", i, before, after)
}
}
}
+130
View File
@@ -0,0 +1,130 @@
package app
import (
"encoding/json"
"net/http"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
)
type trendResponse struct {
VulnerabilityHistoryStart *string `json:"vulnerability_history_start"`
Period string `json:"period"`
From string `json:"from"`
To string `json:"to"`
Points []struct {
VulnerablePackages *int64 `json:"vulnerable_packages"`
Blocked *int64 `json:"blocked"`
Date string `json:"date"`
TotalPackages int64 `json:"total_packages"`
} `json:"points"`
}
func trendDay(daysAgo int) string {
return time.Now().UTC().AddDate(0, 0, -daysAgo).Format("2006-01-02")
}
func getTrend(t *testing.T, a *App, target string) trendResponse {
t.Helper()
code, _, body := doRequest(t, a, target, nil)
if code != http.StatusOK {
t.Fatalf("GET %s = %d %s", target, code, body)
}
var out trendResponse
if err := json.Unmarshal([]byte(body), &out); err != nil {
t.Fatalf("decode %s: %v", body, err)
}
return out
}
func TestSeverityAndTrendQueryCountIsConstant(t *testing.T) {
a, counter := newScanningApp(t)
targets := []string{
"/api/packages?severity=critical,high",
"/api/packages?severity=low&page=1&page_size=25",
"/api/stats/trend?period=90day",
}
seedScanned(t, a, 0, 20)
small := map[string]int{}
for _, target := range targets {
small[target] = queriesFor(t, a, counter, target)
}
seedScanned(t, a, 20, 100)
for _, target := range targets {
large := queriesFor(t, a, counter, target)
t.Logf("%-50s 20 rows: %2d queries, 120 rows: %2d queries", target, small[target], large)
if large != small[target] {
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows", target, small[target], large)
}
}
if n := small["/api/stats/trend?period=90day"]; n != 1 {
t.Errorf("trend costs %d statements, want 1", n)
}
}
func TestStatsTrendEndpoint(t *testing.T) {
a := newTestApp(t, nil)
empty := getTrend(t, a, "/api/stats/trend")
if empty.Period != "30day" || empty.Points == nil || len(empty.Points) != 0 || empty.VulnerabilityHistoryStart != nil {
t.Fatalf("empty trend = %+v, want the default period, no points and no vulnerability start", empty)
}
store := a.metadata.(*gormstore.GORMStoreV2)
one, two := int64(1), int64(2)
for _, row := range []gormstore.StatsSnapshotModel{
{Day: trendDay(100), TotalPackages: 5},
{Day: trendDay(40), TotalPackages: 6},
{Day: trendDay(2), TotalPackages: 7},
{Day: trendDay(1), TotalPackages: 8, VulnerablePackages: &two, Blocked: &one},
} {
if err := store.DB().Create(&row).Error; err != nil {
t.Fatalf("seed snapshot: %v", err)
}
}
cases := []struct {
target string
period string
points int
}{
{"/api/stats/trend", "30day", 2},
{"/api/stats/trend?period=30day", "30day", 2},
{"/api/stats/trend?period=90day", "90day", 3},
{"/api/stats/trend?period=1year", "1year", 4},
}
for _, c := range cases {
got := getTrend(t, a, c.target)
if got.Period != c.period || len(got.Points) != c.points {
t.Errorf("%s = period %q, %d points; want %q, %d", c.target, got.Period, len(got.Points), c.period, c.points)
}
}
got := getTrend(t, a, "/api/stats/trend")
if got.To != trendDay(0) || got.From != trendDay(29) {
t.Errorf("window = %s..%s, want %s..%s", got.From, got.To, trendDay(29), trendDay(0))
}
if got.Points[0].Date != trendDay(2) || got.Points[1].Date != trendDay(1) {
t.Errorf("points not oldest first: %+v", got.Points)
}
if got.Points[0].VulnerablePackages != nil || got.Points[0].Blocked != nil {
t.Errorf("a day without vulnerability data must carry null, got %+v", got.Points[0])
}
if v := got.Points[1].VulnerablePackages; v == nil || *v != 2 {
t.Errorf("vulnerable_packages = %v, want 2", v)
}
if got.VulnerabilityHistoryStart == nil || *got.VulnerabilityHistoryStart != trendDay(1) {
t.Errorf("vulnerability_history_start = %v, want %s", got.VulnerabilityHistoryStart, trendDay(1))
}
}
func TestStatsTrendRejectsUnknownPeriod(t *testing.T) {
a := newTestApp(t, nil)
for _, p := range []string{"7day", "1day", "bogus", "1YEAR"} {
if code, _, body := doRequest(t, a, "/api/stats/trend?period="+p, nil); code != http.StatusBadRequest {
t.Errorf("period=%s = %d %s, want 400", p, code, body)
}
}
}
+60
View File
@@ -0,0 +1,60 @@
package app
import (
"context"
"encoding/json"
"net/http"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// The list shows Go modules by module path, but rows are stored under cache keys.
func TestGoVulnerabilityDetailsResolveCacheKeyNames(t *testing.T) {
a := newTestApp(t, nil)
ctx := context.Background()
const module, version = "github.com/go-git/go-git/v5", "v5.3.0"
for _, ext := range []string{"info", "mod", "zip"} {
name := module + "/@v/" + version + "." + ext
err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "go", Name: name, Version: version, StorageKey: "go/" + name,
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
})
if err != nil {
t.Fatalf("SavePackage %s: %v", name, err)
}
}
err := a.metadata.SaveScanResult(ctx, &metadata.ScanResult{
Registry: "go", PackageName: module + "/@v/" + version + ".zip", PackageVersion: version,
Scanner: "osv", Status: metadata.ScanStatusVulnerable, ScannedAt: time.Now(),
Vulnerabilities: []metadata.Vulnerability{{ID: "GHSA-test", Severity: "critical"}},
VulnerabilityCount: 1,
})
if err != nil {
t.Fatalf("SaveScanResult: %v", err)
}
code, _, body := doRequest(t, a, "/api/packages/go/"+module+"/"+version+"/vulnerabilities", nil)
if code != http.StatusOK {
t.Fatalf("GET details = %d %s, want 200", code, body)
}
var out struct {
Scanned bool `json:"scanned"`
Count int `json:"vulnerability_count"`
}
if err := json.Unmarshal([]byte(body), &out); err != nil {
t.Fatalf("decode %q: %v", body, err)
}
if !out.Scanned || out.Count != 1 {
t.Errorf("details = %s, want the .zip scan with 1 vulnerability", body)
}
}
func TestGoVulnerabilityDetailsMissingModuleIs404(t *testing.T) {
a := newTestApp(t, nil)
code, _, body := doRequest(t, a, "/api/packages/go/example.com/nope/v1.0.0/vulnerabilities", nil)
if code != http.StatusNotFound {
t.Errorf("GET missing = %d %s, want 404", code, body)
}
}
+38
View File
@@ -0,0 +1,38 @@
package app
import (
"context"
"testing"
"time"
)
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
// event loop: without it the 256-slot broadcast channel fills and every later
// event is dropped.
func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
a := newTestApp(t, nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a.startWorkers(ctx)
// Bursts stay under the 256-slot channel and wait for the loop to drain between them, so the
// result depends on the loop running, not on how fast the scheduler runs it.
const (
bursts = 10
burstLen = 100
)
for b := 0; b < bursts; b++ {
for i := 0; i < burstLen; i++ {
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
}
deadline := time.Now().Add(10 * time.Second)
for a.wsServer.Pending() > 0 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
}
if dropped := a.wsServer.Dropped(); dropped != 0 {
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
}
}
+107 -31
View File
@@ -8,6 +8,7 @@ import (
"encoding/base64"
stderrors "errors"
"fmt"
"strings"
"sync"
"time"
@@ -154,10 +155,12 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to generate random key")
}
rawKey := base64.URLEncoding.EncodeToString(keyBytes)
secret := base64.URLEncoding.EncodeToString(keyBytes)
id := keyPrefix + generateID()
rawKey := id + keySeparator + secret
// Hash the key with the configured cost.
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), m.cfg.BcryptCost)
hashedKey, err := bcrypt.GenerateFromPassword([]byte(secret), m.cfg.BcryptCost)
if err != nil {
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key")
}
@@ -169,7 +172,7 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
}
apiKey := &APIKey{
ID: generateID(),
ID: id,
Name: name,
HashedKey: string(hashedKey),
Role: role,
@@ -198,46 +201,119 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
return apiKey, rawKey, nil
}
// Key format: "<id>.<secret>" with id "ghk_<random>". The id is public and selects one stored
// key; the bcrypt hash covers the secret only. Keys minted before the format
// existed have no id in the raw key and hash the whole raw key.
const (
keyPrefix = "ghk_"
keySeparator = "."
// maxLegacyCompares bounds concurrent bcrypt checks against pre-id keys,
// which can only be found by trying each one.
maxLegacyCompares = 4
// legacyIDLen is the length of base64url(16 bytes).
legacyIDLen = 24
)
var (
bcryptCompare = bcrypt.CompareHashAndPassword
legacySlots = make(chan struct{}, maxLegacyCompares)
// dummyHash keeps the cost of an unknown id equal to a wrong secret.
dummyHash = mustHash("gohoarder-dummy-secret")
)
func mustHash(s string) []byte {
h, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
if err != nil {
panic(fmt.Sprintf("auth: dummy hash: %v", err))
}
return h
}
// ValidateAPIKey validates an API key and returns the associated key object.
// Hot path: snapshots candidates, runs bcrypt without holding the lock.
// LastUsedAt is updated in-memory under the write lock and flushed to the
// store via a fire-and-forget goroutine.
// A key with an id costs exactly one bcrypt compare, whatever the number of
// stored keys. LastUsedAt is updated in-memory under the write lock and
// flushed to the store via a fire-and-forget goroutine.
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) {
// Phase 1: snapshot non-expired candidates under RLock. We hold pointers
// to APIKey; APIKey.HashedKey is an immutable string so reading it
// without a lock is safe even if the key is later removed from the map.
var apiKey *APIKey
if id, secret, ok := splitKey(rawKey); ok {
apiKey = m.validateByID(id, secret)
} else {
apiKey = m.validateLegacy(ctx, rawKey)
}
if apiKey == nil {
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
}
// Re-check the key still exists to avoid resurrecting a revoked key's metadata.
usedAt := time.Now()
m.mu.Lock()
if _, ok := m.keys[apiKey.ID]; ok {
apiKey.LastUsedAt = usedAt
}
m.mu.Unlock()
// Async store update: never block validation on a DB write.
m.persistLastUsedAsync(apiKey.ID, usedAt)
return apiKey, nil
}
func splitKey(rawKey string) (id, secret string, ok bool) {
if !strings.HasPrefix(rawKey, keyPrefix) {
return "", "", false
}
return strings.Cut(rawKey, keySeparator)
}
// hasKeyID reports whether k was minted with an id embedded in its raw key.
// Legacy ids are bare generateID output, which is always legacyIDLen long.
func hasKeyID(k *APIKey) bool {
return strings.HasPrefix(k.ID, keyPrefix) && len(k.ID) > legacyIDLen
}
func (m *Manager) validateByID(id, secret string) *APIKey {
m.mu.RLock()
apiKey := m.keys[id]
m.mu.RUnlock()
hash := dummyHash
if apiKey != nil {
hash = []byte(apiKey.HashedKey)
}
err := bcryptCompare(hash, []byte(secret))
if apiKey == nil || err != nil || expired(apiKey, time.Now()) {
return nil
}
return apiKey
}
func (m *Manager) validateLegacy(ctx context.Context, rawKey string) *APIKey {
m.mu.RLock()
candidates := make([]*APIKey, 0, len(m.keys))
now := time.Now()
for _, apiKey := range m.keys {
if apiKey.ExpiresAt != nil && now.After(*apiKey.ExpiresAt) {
continue
for _, k := range m.keys {
if !hasKeyID(k) && !expired(k, now) {
candidates = append(candidates, k)
}
candidates = append(candidates, apiKey)
}
m.mu.RUnlock()
// Phase 2: run bcrypt comparisons without holding any lock so concurrent
// auth checks can proceed in parallel.
for _, apiKey := range candidates {
if err := bcrypt.CompareHashAndPassword([]byte(apiKey.HashedKey), []byte(rawKey)); err == nil {
// Phase 3: briefly take the write lock to update LastUsedAt.
// Re-check the key still exists in the map to avoid resurrecting
// a revoked key's metadata.
usedAt := time.Now()
m.mu.Lock()
if _, ok := m.keys[apiKey.ID]; ok {
apiKey.LastUsedAt = usedAt
}
m.mu.Unlock()
// Async store update: never block validation on a DB write.
m.persistLastUsedAsync(apiKey.ID, usedAt)
return apiKey, nil
for _, k := range candidates {
select {
case legacySlots <- struct{}{}:
case <-ctx.Done():
return nil
}
err := bcryptCompare([]byte(k.HashedKey), []byte(rawKey))
<-legacySlots
if err == nil {
return k
}
}
return nil
}
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
func expired(k *APIKey, now time.Time) bool {
return k.ExpiresAt != nil && now.After(*k.ExpiresAt)
}
// persistLastUsedAsync flushes a LastUsedAt update to the store off the hot
+25 -1
View File
@@ -116,6 +116,15 @@ func (f *fakeStore) DeletePackage(context.Context, string, string, string) error
func (f *fakeStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) ListPackageGroups(context.Context, metadata.GroupListOptions) (*metadata.GroupPage, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) GetScanSummaries(context.Context, []string, bool) ([]*metadata.ScanSummary, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) GetRegistryStats(context.Context) ([]metadata.RegistryStat, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) UpdateDownloadCount(context.Context, string, string, string) error {
return metadata.ErrNotImplemented
}
@@ -147,7 +156,22 @@ func (f *fakeStore) GetTimeSeriesStats(context.Context, string, string) (*metada
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) AggregateDownloadData(context.Context) error { return metadata.ErrNotImplemented }
func (f *fakeStore) Close() error { return nil }
func (f *fakeStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) ClearArtifactExpiry(context.Context) (int64, error) {
return 0, metadata.ErrNotImplemented
}
func (f *fakeStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
return 0, metadata.ErrNotImplemented
}
func (f *fakeStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) Close() error { return nil }
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
func fastCfg() Config { return Config{BcryptCost: bcrypt.MinCost} }
+156
View File
@@ -0,0 +1,156 @@
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
// countBcrypt wraps bcryptCompare and returns the call counter.
func countBcrypt(t *testing.T) *atomic.Int64 {
t.Helper()
var n atomic.Int64
orig := bcryptCompare
bcryptCompare = func(h, p []byte) error {
n.Add(1)
return orig(h, p)
}
t.Cleanup(func() { bcryptCompare = orig })
return &n
}
func newTestManager() *Manager { return NewWithStore(Config{BcryptCost: bcrypt.MinCost}, nil) }
// addLegacyKey stores a key in the pre-key-id format: bcrypt of the whole raw key, no id in the key.
func addLegacyKey(t *testing.T, m *Manager) string {
t.Helper()
b := make([]byte, 32)
_, _ = rand.Read(b)
raw := base64.URLEncoding.EncodeToString(b)
h, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
k := &APIKey{ID: generateID(), Name: "legacy", HashedKey: string(h), Role: RoleReadOnly, CreatedAt: time.Now(), Permissions: getPermissionsForRole(RoleReadOnly)}
m.mu.Lock()
m.keys[k.ID] = k
m.mu.Unlock()
return raw
}
func TestValidateAPIKeyCostIndependentOfKeyCount(t *testing.T) {
m := newTestManager()
_, good, err := m.GenerateAPIKey("target", RoleReadWrite, nil)
if err != nil {
t.Fatal(err)
}
for i := 0; i < 50; i++ {
if _, _, err := m.GenerateAPIKey("filler", RoleReadOnly, nil); err != nil {
t.Fatal(err)
}
}
n := countBcrypt(t)
if _, err := m.ValidateAPIKey(context.Background(), good); err != nil {
t.Fatalf("valid key rejected: %v", err)
}
if got := n.Load(); got != 1 {
t.Errorf("valid key: %d bcrypt compares, want 1", got)
}
n.Store(0)
idPart := strings.SplitN(good, keySeparator, 2)[0]
cases := map[string]string{
"known id, wrong secret": idPart + keySeparator + "AAAA",
"unknown id": keyPrefix + "nope" + keySeparator + "AAAA",
"no secret": idPart + keySeparator,
}
for name, raw := range cases {
n.Store(0)
if _, err := m.ValidateAPIKey(context.Background(), raw); err == nil {
t.Errorf("%s: accepted", name)
}
if got := n.Load(); got != 1 {
t.Errorf("%s: %d bcrypt compares, want exactly 1", name, got)
}
}
}
func TestValidateAPIKeyRejectsSecretOfAnotherKey(t *testing.T) {
m := newTestManager()
a, _, _ := m.GenerateAPIKey("a", RoleAdmin, nil)
_, rawB, _ := m.GenerateAPIKey("b", RoleReadOnly, nil)
secretB := strings.SplitN(rawB, keySeparator, 2)[1]
if _, err := m.ValidateAPIKey(context.Background(), a.ID+keySeparator+secretB); err == nil {
t.Fatal("id of one key with the secret of another was accepted")
}
}
func TestLegacyKeysStillValidate(t *testing.T) {
m := newTestManager()
raw := addLegacyKey(t, m)
for i := 0; i < 3; i++ {
addLegacyKey(t, m)
}
k, err := m.ValidateAPIKey(context.Background(), raw)
if err != nil || k == nil || k.Name != "legacy" {
t.Fatalf("legacy key rejected: %v", err)
}
}
func TestNewFormatKeyNeverTouchesLegacyKeys(t *testing.T) {
m := newTestManager()
for i := 0; i < 20; i++ {
addLegacyKey(t, m)
}
_, raw, _ := m.GenerateAPIKey("new", RoleReadOnly, nil)
n := countBcrypt(t)
if _, err := m.ValidateAPIKey(context.Background(), raw+"x"); err == nil {
t.Fatal("bad key accepted")
}
if got := n.Load(); got != 1 {
t.Errorf("%d bcrypt compares with 20 legacy keys stored, want 1", got)
}
}
func TestLegacyComparesAreConcurrencyBounded(t *testing.T) {
m := newTestManager()
for i := 0; i < 5; i++ {
addLegacyKey(t, m)
}
var cur, peak atomic.Int64
orig := bcryptCompare
bcryptCompare = func(h, p []byte) error {
c := cur.Add(1)
for {
p := peak.Load()
if c <= p || peak.CompareAndSwap(p, c) {
break
}
}
time.Sleep(2 * time.Millisecond)
cur.Add(-1)
return orig(h, p)
}
t.Cleanup(func() { bcryptCompare = orig })
var wg sync.WaitGroup
for i := 0; i < 40; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = m.ValidateAPIKey(context.Background(), "bad-legacy-key-bad-legacy-key-bad-legacy-key-0000")
}()
}
wg.Wait()
if got := peak.Load(); got > maxLegacyCompares {
t.Errorf("peak concurrent legacy compares %d, want <= %d", got, maxLegacyCompares)
}
}
+268 -86
View File
@@ -8,11 +8,11 @@ import (
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
hoarderconfig "github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/events"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
@@ -47,12 +47,12 @@ 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
mu sync.RWMutex
bcMu sync.RWMutex
closeOnce sync.Once
evicting bool
evictMu sync.Mutex // serialises LRU eviction; a second caller waits and re-checks its quota
}
// SetBroadcaster wires an events.Broadcaster onto the manager so cache
@@ -81,17 +81,37 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
// Config holds cache manager configuration
type Config struct {
DefaultTTL time.Duration // Default TTL for cached packages
CleanupInterval time.Duration // How often to run cleanup
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
FailClosed bool // Refuse a package whose scan did not finish in time
Now func() time.Time // Clock; nil means time.Now
TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL
DefaultTTL time.Duration // Freshness TTL for metadata entries
CleanupInterval time.Duration // How often to run cleanup
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
FailClosed bool // Refuse a package whose scan did not finish in time
RescanAfter time.Duration // Rescan a cache hit whose scan result is older than this before serving (0 = off)
}
const defaultScanWaitTimeout = 30 * time.Second
// cleanupBatchSize bounds how many rows one cleanup query reads.
const cleanupBatchSize = metadata.DefaultBatchSize
// maxPurgeBatches bounds the soft-delete purge of one cleanup pass; the next pass continues.
const maxPurgeBatches = 100
// getAttempts bounds how often Get re-resolves an entry whose blob vanished.
const getAttempts = 2
// Eviction metric reasons.
const (
evictReasonTTL = "ttl"
evictReasonIdle = "idle"
)
// scannerToggle is implemented by scanners that can be switched off.
type scannerToggle interface {
Enabled() bool
@@ -155,8 +175,12 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
log.Info().Msg("Cache manager initialized with analytics tracking enabled")
}
if config.Now == nil {
config.Now = time.Now
}
if config.DefaultTTL == 0 {
config.DefaultTTL = 7 * 24 * time.Hour // 7 days default
config.DefaultTTL = hoarderconfig.DefaultMetadataTTL
}
if config.CleanupInterval == 0 {
@@ -191,6 +215,9 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
stopCh: make(chan struct{}),
}
// Rows cached before idle eviction existed carry an age-based expiry.
manager.clearArtifactExpiry(bgCtx)
// Start background cleanup worker
manager.cleanupWG.Add(1)
go manager.cleanupWorker()
@@ -203,36 +230,44 @@ func (m *Manager) Get(ctx context.Context, registry, name, version string, fetch
// Use singleflight to deduplicate concurrent requests
key := fmt.Sprintf("%s/%s/%s", registry, name, version)
result, err, _ := m.sf.Do(key, func() (interface{}, error) {
// getOrFetch returns a CacheEntry with Data == nil. Each caller
// re-opens its own storage reader below to avoid sharing a
// single io.ReadCloser across concurrent waiters.
return m.getOrFetch(ctx, registry, name, version, fetchFunc)
})
var openErr error
// A purge can delete the blob between the cache-hit probe and the open
// below. The second pass sees the miss and fetches again.
for attempt := 0; attempt < getAttempts; attempt++ {
result, err, _ := m.sf.Do(key, func() (interface{}, error) {
// getOrFetch returns a CacheEntry with Data == nil. Each caller
// re-opens its own storage reader below to avoid sharing a
// single io.ReadCloser across concurrent waiters.
return m.getOrFetch(ctx, registry, name, version, fetchFunc)
})
if err != nil {
return nil, err
if err != nil {
return nil, err
}
entry := result.(*CacheEntry)
if entry == nil || entry.Package == nil {
return nil, errors.New(errors.ErrCodeStorageFailure, "cache entry missing package metadata")
}
// Open a fresh ReadCloser per caller from storage.
data, err := m.storage.Get(ctx, entry.Package.StorageKey)
if err != nil {
openErr = err
continue
}
// Return a copy so concurrent waiters don't share the Data field.
return &CacheEntry{
Data: data,
Package: entry.Package,
UpstreamURL: entry.UpstreamURL,
CacheControl: entry.CacheControl,
FromCache: entry.FromCache,
}, nil
}
entry := result.(*CacheEntry)
if entry == nil || entry.Package == nil {
return nil, errors.New(errors.ErrCodeStorageFailure, "cache entry missing package metadata")
}
// Open a fresh ReadCloser per caller from storage.
data, err := m.storage.Get(ctx, entry.Package.StorageKey)
if err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to retrieve cached package")
}
// Return a copy so concurrent waiters don't share the Data field.
return &CacheEntry{
Data: data,
Package: entry.Package,
UpstreamURL: entry.UpstreamURL,
CacheControl: entry.CacheControl,
FromCache: entry.FromCache,
}, nil
return nil, errors.Wrap(openErr, errors.ErrCodeStorageFailure, "failed to retrieve cached package")
}
// getOrFetch implements the actual get-or-fetch logic
@@ -241,9 +276,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
if err == nil {
// Package found in metadata, check if expired
if pkg.ExpiresAt != nil && time.Now().After(*pkg.ExpiresAt) {
if pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt) {
log.Debug().Str("package", name).Str("version", version).Msg("Package expired, re-fetching")
metrics.RecordCacheEviction("ttl")
metrics.RecordCacheEviction(evictReasonTTL)
// Delete expired package
_ = m.deletePackage(ctx, pkg) // #nosec G104 -- Async cleanup
} else {
@@ -297,9 +332,11 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// entries (index pages, lists, .mod/.info) are not scannable
// packages, so skip them to avoid a bogus "clean" verdict and
// the extra database round-trip.
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
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")
@@ -313,12 +350,12 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// underlying transport is non-blocking. Only emitted on
// the cache-hit path — the miss-then-fetch path is
// covered by EventPackageCached emitted from store().
m.emit(string(websocket.EventPackageDownloaded), map[string]interface{}{
m.emit(string(websocket.EventPackageDownloaded), withReleaseVersion(map[string]interface{}{
"registry": registry,
"name": name,
"version": version,
"cache_hit": true,
})
}, pkg.ReleaseVersion))
// Data is intentionally nil; Get() opens a fresh reader per caller.
return &CacheEntry{
@@ -366,8 +403,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// Skip security scan wait for metadata entries (index pages, lists, etc.)
// Also skip Go module metadata files (.mod, .info)
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
// Wait briefly for initial scan to complete if scanner is enabled
// This prevents serving vulnerable packages on first request.
@@ -553,8 +589,16 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
_ = tempFile.Close() // #nosec G104 -- cleanup; scan may still read the file
// Create metadata entry
now := time.Now()
expiresAt := now.Add(m.config.DefaultTTL)
now := m.now()
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
// Artifacts are immutable, so only idle eviction removes them; metadata
// entries must refresh and keep a freshness expiry.
var expiresAt *time.Time
if isMetadataEntry {
exp := now.Add(m.metadataTTL(registry))
expiresAt = &exp
}
pkg := &metadata.Package{
ID: uuid.New().String(),
@@ -570,7 +614,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
AuthProvider: authProvider,
CachedAt: now,
LastAccessed: now,
ExpiresAt: &expiresAt,
ExpiresAt: expiresAt,
DownloadCount: 0,
Metadata: make(map[string]string),
}
@@ -583,8 +627,6 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
// TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed
// based on upstream Cache-Control. Plumbing per-response TTL from registry handlers
// is out of scope here and tracked separately.
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
if err := m.metadata.SavePackage(ctx, pkg); err != nil {
// Clean up storage if metadata save fails
_ = m.storage.Delete(ctx, storageKey) // #nosec G104 -- Cleanup, error logged
@@ -602,13 +644,13 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
scanStatus = "pending"
}
}
m.emit(string(websocket.EventPackageCached), map[string]interface{}{
m.emit(string(websocket.EventPackageCached), withReleaseVersion(map[string]interface{}{
"registry": registry,
"name": name,
"version": version,
"size": size,
"scan_status": scanStatus,
})
}, releaseVersion))
// Scan package if scanner is enabled (run in background to not block cache operations)
// Skip scanning metadata entries (index pages, lists, etc.)
@@ -662,6 +704,39 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
return pkg, nil
}
// ScanFile returns a local file holding a cached package, for a scan retry. Backends with a
// local path serve it directly; others are copied to a temp file that cleanup removes.
func (m *Manager) ScanFile(ctx context.Context, registry, name, version string) (string, func(), error) {
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
if err != nil {
return "", nil, err
}
if local, ok := m.storage.(storage.LocalPathProvider); ok {
path, pathErr := local.GetLocalPath(ctx, pkg.StorageKey)
return path, func() {}, pathErr
}
rc, err := m.storage.Get(ctx, pkg.StorageKey)
if err != nil {
return "", nil, err
}
defer func() { _ = rc.Close() }()
tmp, err := os.CreateTemp(os.TempDir(), "gohoarder-rescan-*")
if err != nil {
return "", nil, err
}
cleanup := func() { _ = os.Remove(tmp.Name()) } // #nosec G104 -- cleanup
if _, err := io.Copy(tmp, rc); err != nil {
_ = tmp.Close() // #nosec G104 -- cleanup
cleanup()
return "", nil, err
}
if err := tmp.Close(); err != nil {
cleanup()
return "", nil, err
}
return tmp.Name(), cleanup, nil
}
// Delete removes a package from cache
func (m *Manager) Delete(ctx context.Context, registry, name, version string) error {
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
@@ -672,6 +747,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er
return m.deletePackage(ctx, pkg)
}
// metadataTTL returns the freshness window for a registry's metadata entries.
func (m *Manager) metadataTTL(registry string) time.Duration {
if ttl, ok := m.config.TTLOverrides[registry]; ok {
return ttl
}
return m.config.DefaultTTL
}
// deletePackage deletes a package from both storage and metadata
func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error {
// Delete from storage
@@ -685,19 +768,8 @@ func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) erro
// evict implements LRU eviction
func (m *Manager) evict(ctx context.Context, needed int64) error {
m.mu.Lock()
if m.evicting {
m.mu.Unlock()
return errors.New(errors.ErrCodeStorageFailure, "eviction already in progress")
}
m.evicting = true
m.mu.Unlock()
defer func() {
m.mu.Lock()
m.evicting = false
m.mu.Unlock()
}()
m.evictMu.Lock()
defer m.evictMu.Unlock()
log.Info().Int64("needed", needed).Msg("Starting LRU eviction")
@@ -715,12 +787,14 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
break
}
deleted := 0
for _, pkg := range packages {
if err := m.deletePackage(ctx, pkg); err != nil {
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to evict package")
continue
}
deleted++
freed += pkg.Size
metrics.RecordCacheEviction("lru")
@@ -729,8 +803,8 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
}
}
if len(packages) < opts.Limit {
break // No more packages
if len(packages) < opts.Limit || deleted == 0 {
break // No more packages, or the same rows would be listed again
}
}
@@ -738,7 +812,7 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
return nil
}
// cleanupWorker runs periodic cleanup of expired packages.
// cleanupWorker runs periodic cleanup of expired and idle packages.
// Exits when stopCh is closed (via Close()).
func (m *Manager) cleanupWorker() {
defer m.cleanupWG.Done()
@@ -751,39 +825,139 @@ func (m *Manager) cleanupWorker() {
case <-m.stopCh:
return
case <-ticker.C:
ctx := context.Background()
m.cleanup(ctx)
m.cleanup(m.bgCtx)
}
}
}
// cleanup removes expired packages
func (m *Manager) cleanup(ctx context.Context) {
log.Debug().Msg("Starting cleanup worker")
func (m *Manager) now() time.Time {
return m.config.Now()
}
// List all packages
packages, err := m.metadata.ListPackages(ctx, &metadata.ListOptions{})
// clearArtifactExpiry drops the age-based expiry that older versions set on artifacts.
func (m *Manager) clearArtifactExpiry(ctx context.Context) {
cleared, err := m.metadata.ClearArtifactExpiry(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to list packages for cleanup")
log.Error().Err(err).Msg("Failed to clear artifact expiry")
return
}
if cleared > 0 {
log.Info().Int64("count", cleared).Msg("Cleared age-based expiry from cached artifacts")
}
}
now := time.Now()
var cleaned int
// purgeResult totals the packages one purge pass removed.
type purgeResult struct {
bytes int64
count int
}
for _, pkg := range packages {
if pkg.ExpiresAt != nil && now.After(*pkg.ExpiresAt) {
if err := m.deletePackage(ctx, pkg); err != nil {
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to clean up expired package")
// purge deletes packages in bounded batches until the list query runs dry.
// stillDue re-checks each package just before deletion so one requested after
// the batch was read is kept.
func (m *Manager) purge(
ctx context.Context,
reason string,
list func(limit int) ([]*metadata.Package, error),
stillDue func(*metadata.Package) bool,
) purgeResult {
var res purgeResult
seen := make(map[string]struct{})
for ctx.Err() == nil {
batch, err := list(cleanupBatchSize)
if err != nil {
log.Error().Err(err).Str("reason", reason).Msg("Failed to list packages for cleanup")
return res
}
unseen := 0
for _, pkg := range batch {
key := m.generateStorageKey(pkg.Registry, pkg.Name, pkg.Version)
if _, dup := seen[key]; dup {
continue
}
cleaned++
seen[key] = struct{}{}
unseen++
current, err := m.metadata.GetPackage(ctx, pkg.Registry, pkg.Name, pkg.Version)
if err != nil || current == nil || !stillDue(current) {
continue
}
if err := m.deletePackage(ctx, current); err != nil {
log.Warn().Err(err).Str("package", pkg.Name).Str("reason", reason).Msg("Failed to clean up package")
continue
}
res.count++
res.bytes += current.Size
metrics.RecordCacheEviction(reason)
}
// A short batch is the last one; a batch of only repeats means every
// remaining row failed to delete.
if len(batch) < cleanupBatchSize || unseen == 0 {
return res
}
}
return res
}
if cleaned > 0 {
log.Info().Int("count", cleaned).Msg("Cleanup completed")
// cleanup removes metadata entries past their freshness expiry and, when
// IdleTTL is set, every package not requested within IdleTTL.
func (m *Manager) cleanup(ctx context.Context) {
start := m.now()
log.Debug().Msg("Starting cleanup worker")
m.clearArtifactExpiry(ctx)
expired := m.purge(ctx, evictReasonTTL,
func(limit int) ([]*metadata.Package, error) {
return m.metadata.ListExpiredPackages(ctx, start, limit)
},
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(start) })
var idle purgeResult
if m.config.IdleTTL > 0 {
cutoff := start.Add(-m.config.IdleTTL)
idle = m.purge(ctx, evictReasonIdle,
func(limit int) ([]*metadata.Package, error) {
return m.metadata.ListIdlePackages(ctx, cutoff, limit)
},
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
}
purged := m.purgeDeleted(ctx, start)
log.Info().
Int("expired", expired.count).
Int("idle", idle.count).
Int64("bytes_freed", expired.bytes+idle.bytes).
Dur("idle_ttl", m.config.IdleTTL).
Int64("purged_deleted", purged).
Dur("deleted_retention", m.config.DeletedRetention).
Msg("Cleanup completed")
}
// purgeDeleted hard-deletes soft-deleted rows past DeletedRetention in bounded
// batches and returns how many it removed.
func (m *Manager) purgeDeleted(ctx context.Context, now time.Time) int64 {
if m.config.DeletedRetention <= 0 {
return 0
}
cutoff := now.Add(-m.config.DeletedRetention)
var total int64
for i := 0; i < maxPurgeBatches && ctx.Err() == nil; i++ {
n, err := m.metadata.PurgeDeletedPackages(ctx, cutoff, cleanupBatchSize)
if err != nil {
log.Error().Err(err).Msg("Failed to purge soft-deleted packages")
break
}
total += n
if n < cleanupBatchSize {
break
}
}
return total
}
// generateStorageKey generates a storage key for a package
@@ -853,3 +1027,11 @@ func (m *Manager) Close() error {
return err
}
// withReleaseVersion adds release_version to an event payload when the cache key is not a release version.
func withReleaseVersion(payload map[string]interface{}, releaseVersion string) map[string]interface{} {
if releaseVersion != "" {
payload["release_version"] = releaseVersion
}
return payload
}
+44 -1
View File
@@ -145,6 +145,30 @@ func (m *MockMetadataStore) ListPackages(ctx context.Context, opts *metadata.Lis
return args.Get(0).([]*metadata.Package), args.Error(1)
}
func (m *MockMetadataStore) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
args := m.Called(ctx, opts)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*metadata.GroupPage), args.Error(1)
}
func (m *MockMetadataStore) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
args := m.Called(ctx, packageIDs, withDetails)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).([]*metadata.ScanSummary), args.Error(1)
}
func (m *MockMetadataStore) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
args := m.Called(ctx)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).([]metadata.RegistryStat), args.Error(1)
}
func (m *MockMetadataStore) UpdateDownloadCount(ctx context.Context, registry, name, version string) error {
args := m.Called(ctx, registry, name, version)
return args.Error(0)
@@ -230,6 +254,25 @@ func (m *MockMetadataStore) AggregateDownloadData(ctx context.Context) error {
return args.Error(0)
}
// The idle-eviction queries are not mocked per test: no expiry, no idle rows.
func (m *MockMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, nil
}
func (m *MockMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, nil
}
func (m *MockMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
func (m *MockMetadataStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
return 0, nil
}
func (m *MockMetadataStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
return nil, nil
}
// API key methods are not used by the cache package; stub them out so the
// mock continues to satisfy metadata.MetadataStore after the interface gained
// API key persistence methods.
@@ -335,7 +378,7 @@ func TestNew(t *testing.T) {
// Verify defaults were set
if tt.config.DefaultTTL == 0 {
assert.Equal(t, 7*24*time.Hour, manager.config.DefaultTTL)
assert.Equal(t, 24*time.Hour, manager.config.DefaultTTL)
}
if tt.config.CleanupInterval == 0 {
assert.Equal(t, 1*time.Hour, manager.config.CleanupInterval)
+24
View File
@@ -0,0 +1,24 @@
package cache
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
// Clients gate on a 72h release age; a metadata page that stays fresh longer would hide the gate's inputs.
func TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate(t *testing.T) {
h := newIdleHarness(t, Config{})
entry := h.get(t, "left-pad", "metadata")
require.NotNil(t, entry.Package.ExpiresAt)
require.Equal(t, 24*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
}
func TestMetadataEntryExplicitTTLWins(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 6 * time.Hour})
entry := h.get(t, "left-pad", "metadata")
require.Equal(t, 6*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
}
+398
View File
@@ -0,0 +1,398 @@
package cache
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
"github.com/lukaszraczylo/gohoarder/pkg/storage"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
)
func evictions(c prometheus.Counter) float64 {
var m dto.Metric
if err := c.Write(&m); err != nil {
panic(err)
}
return m.GetCounter().GetValue()
}
type fakeClock struct {
now time.Time
mu sync.Mutex
}
func newFakeClock() *fakeClock {
return &fakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
}
func (c *fakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *fakeClock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.now = c.now.Add(d)
}
type memStorage struct {
storage.StorageBackend
objects map[string][]byte
mu sync.Mutex
}
func newMemStorage() *memStorage { return &memStorage{objects: map[string][]byte{}} }
func (s *memStorage) Get(_ context.Context, key string) (io.ReadCloser, error) {
s.mu.Lock()
defer s.mu.Unlock()
b, ok := s.objects[key]
if !ok {
return nil, errors.New("not found")
}
return io.NopCloser(bytes.NewReader(b)), nil
}
func (s *memStorage) Put(_ context.Context, key string, data io.Reader, _ *storage.PutOptions) error {
b, err := io.ReadAll(data)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.objects[key] = b
return nil
}
func (s *memStorage) Delete(_ context.Context, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.objects, key)
return nil
}
func (s *memStorage) GetQuota(context.Context) (*storage.QuotaInfo, error) {
return &storage.QuotaInfo{}, nil
}
func (s *memStorage) Close() error { return nil }
func (s *memStorage) has(key string) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.objects[key]
return ok
}
// memMetadata mirrors the real store's contract: UpdateDownloadCount stamps
// last_accessed, and the list queries are ordered and bounded.
type memMetadata struct {
metadata.MetadataStore
clock *fakeClock
pkgs map[string]*metadata.Package
onList func()
maxLimit int
mu sync.Mutex
idleCalls int
}
func newMemMetadata(clock *fakeClock) *memMetadata {
return &memMetadata{clock: clock, pkgs: map[string]*metadata.Package{}}
}
func pkgKey(registry, name, version string) string { return registry + "/" + name + "/" + version }
func (m *memMetadata) SavePackage(_ context.Context, pkg *metadata.Package) error {
m.mu.Lock()
defer m.mu.Unlock()
cp := *pkg
m.pkgs[pkgKey(pkg.Registry, pkg.Name, pkg.Version)] = &cp
return nil
}
func (m *memMetadata) GetPackage(_ context.Context, registry, name, version string) (*metadata.Package, error) {
m.mu.Lock()
defer m.mu.Unlock()
p, ok := m.pkgs[pkgKey(registry, name, version)]
if !ok {
return nil, errors.New("not found")
}
cp := *p
return &cp, nil
}
func (m *memMetadata) DeletePackage(_ context.Context, registry, name, version string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.pkgs, pkgKey(registry, name, version))
return nil
}
func (m *memMetadata) UpdateDownloadCount(_ context.Context, registry, name, version string) error {
m.mu.Lock()
defer m.mu.Unlock()
p, ok := m.pkgs[pkgKey(registry, name, version)]
if !ok {
return errors.New("not found")
}
p.DownloadCount++
p.LastAccessed = m.clock.Now()
return nil
}
func (m *memMetadata) list(limit int, match func(*metadata.Package) bool, less func(a, b *metadata.Package) bool) []*metadata.Package {
m.mu.Lock()
if limit > m.maxLimit {
m.maxLimit = limit
}
var out []*metadata.Package
for _, p := range m.pkgs {
if match(p) {
cp := *p
out = append(out, &cp)
}
}
m.mu.Unlock()
sort.Slice(out, func(i, j int) bool { return less(out[i], out[j]) })
if limit > 0 && len(out) > limit {
out = out[:limit]
}
if m.onList != nil {
m.onList()
}
return out
}
func (m *memMetadata) ListIdlePackages(_ context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
m.mu.Lock()
m.idleCalls++
m.mu.Unlock()
return m.list(limit,
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
}
func (m *memMetadata) ListExpiredPackages(_ context.Context, before time.Time, limit int) ([]*metadata.Package, error) {
return m.list(limit,
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(before) },
func(a, b *metadata.Package) bool { return a.ExpiresAt.Before(*b.ExpiresAt) }), nil
}
func (m *memMetadata) ClearArtifactExpiry(context.Context) (int64, error) {
m.mu.Lock()
defer m.mu.Unlock()
var n int64
for _, p := range m.pkgs {
if p.ExpiresAt != nil && !metadata.IsMetadataEntry(p.Registry, p.Name, p.Version) {
p.ExpiresAt = nil
n++
}
}
return n, nil
}
func (m *memMetadata) Close() error { return nil }
func (m *memMetadata) count() int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.pkgs)
}
type idleHarness struct {
mgr *Manager
clock *fakeClock
meta *memMetadata
store *memStorage
fetches int
}
func newIdleHarness(t *testing.T, cfg Config) *idleHarness {
t.Helper()
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
h.meta = newMemMetadata(h.clock)
cfg.Now = h.clock.Now
if cfg.CleanupInterval == 0 {
cfg.CleanupInterval = 24 * time.Hour
}
return h.start(t, cfg)
}
func (h *idleHarness) start(t *testing.T, cfg Config) *idleHarness {
t.Helper()
mgr, err := New(h.store, h.meta, nil, nil, cfg)
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
h.mgr = mgr
return h
}
func (h *idleHarness) get(t *testing.T, name, version string) *CacheEntry {
t.Helper()
entry, err := h.mgr.Get(context.Background(), "npm", name, version, func(context.Context) (*FetchResult, error) {
h.fetches++
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
return entry
}
func (h *idleHarness) exists(name, version string) bool {
_, err := h.meta.GetPackage(context.Background(), "npm", name, version)
return err == nil && h.store.has(fmt.Sprintf("npm/%s/%s", name, version))
}
const (
day = 24 * time.Hour
artifactVer = "4.17.21"
)
func TestIdleTTL_AccessedArtifactSurvivesDefaultTTL(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
entry := h.get(t, "lodash", artifactVer)
require.Nil(t, entry.Package.ExpiresAt, "an artifact is immutable: no age-based expiry")
h.clock.Advance(2 * day)
h.get(t, "lodash", artifactVer) // touches last_accessed
h.clock.Advance(2 * day) // 4 days after caching, past DefaultTTL; idle for only 2
h.mgr.cleanup(context.Background())
require.True(t, h.exists("lodash", artifactVer))
h.get(t, "lodash", artifactVer)
require.Equal(t, 1, h.fetches, "served from cache, not re-fetched")
}
func TestIdleTTL_IdleArtifactIsDeletedFromStorageAndMetadata(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
h.get(t, "lodash", artifactVer)
h.get(t, "left-pad", "1.3.0")
h.clock.Advance(2 * day)
h.get(t, "left-pad", "1.3.0") // keeps left-pad alive
h.clock.Advance(2 * day) // lodash idle for 4 days
before := evictions(metrics.CacheEvictions.WithLabelValues("idle"))
h.mgr.cleanup(context.Background())
require.False(t, h.exists("lodash", artifactVer))
require.False(t, h.store.has("npm/lodash/"+artifactVer), "storage object removed")
_, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
require.Error(t, err, "metadata row removed")
require.True(t, h.exists("left-pad", "1.3.0"))
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("idle")))
}
func TestIdleTTL_IdleMetadataEntryIsDeleted(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: 3 * day})
h.get(t, "lodash", "metadata")
h.clock.Advance(4 * day)
h.mgr.cleanup(context.Background())
require.False(t, h.exists("lodash", "metadata"))
}
func TestIdleTTL_MetadataEntryPastFreshnessTTLIsRefetched(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 7 * day})
entry := h.get(t, "lodash", "metadata")
require.NotNil(t, entry.Package.ExpiresAt)
require.Equal(t, h.clock.Now().Add(time.Hour), *entry.Package.ExpiresAt)
h.clock.Advance(30 * time.Minute)
h.get(t, "lodash", "metadata")
require.Equal(t, 1, h.fetches, "still fresh")
h.clock.Advance(2 * time.Hour) // recently requested, but stale
before := evictions(metrics.CacheEvictions.WithLabelValues("ttl"))
h.get(t, "lodash", "metadata")
require.Equal(t, 2, h.fetches, "stale metadata is re-fetched")
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("ttl")))
}
func TestIdleTTL_CleanupRemovesExpiredMetadataOnly(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 30 * day})
h.get(t, "lodash", "metadata")
h.get(t, "lodash", artifactVer)
h.clock.Advance(2 * time.Hour)
h.mgr.cleanup(context.Background())
require.False(t, h.exists("lodash", "metadata"), "past its freshness expiry")
require.True(t, h.exists("lodash", artifactVer), "artifacts have no age-based expiry")
}
func TestIdleTTL_ZeroDisablesIdleEviction(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 0})
h.get(t, "lodash", artifactVer)
h.clock.Advance(365 * day)
h.mgr.cleanup(context.Background())
require.True(t, h.exists("lodash", artifactVer))
require.Zero(t, h.meta.idleCalls, "no idle query when disabled")
}
func TestIdleTTL_CleanupReadsBoundedBatches(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: day, IdleTTL: day})
const total = 1250
for i := 0; i < total; i++ {
name := fmt.Sprintf("pkg-%d", i)
h.get(t, name, "1.0.0")
}
h.clock.Advance(2 * day)
h.mgr.cleanup(context.Background())
require.Zero(t, h.meta.count(), "every idle item removed across batches")
require.Positive(t, h.meta.maxLimit)
require.LessOrEqual(t, h.meta.maxLimit, cleanupBatchSize, "never loads more than one batch")
require.Zero(t, len(h.store.objects))
}
func TestIdleTTL_ItemRequestedDuringCleanupSurvives(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: day})
h.get(t, "lodash", artifactVer)
h.clock.Advance(2 * day)
h.meta.onList = func() {
h.meta.onList = nil
require.NoError(t, h.meta.UpdateDownloadCount(context.Background(), "npm", "lodash", artifactVer))
}
h.mgr.cleanup(context.Background())
require.True(t, h.exists("lodash", artifactVer), "a request between listing and deleting wins")
}
func TestIdleTTL_StartupClearsLegacyArtifactExpiry(t *testing.T) {
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
h.meta = newMemMetadata(h.clock)
past := h.clock.Now().Add(-day)
require.NoError(t, h.meta.SavePackage(context.Background(), &metadata.Package{
Registry: "npm", Name: "lodash", Version: artifactVer, StorageKey: "npm/lodash/" + artifactVer,
LastAccessed: h.clock.Now(), ExpiresAt: &past,
}))
require.NoError(t, h.store.Put(context.Background(), "npm/lodash/"+artifactVer, strings.NewReader("x"), nil))
h.start(t, Config{DefaultTTL: 7 * day, IdleTTL: 7 * day, Now: h.clock.Now, CleanupInterval: 24 * time.Hour})
h.get(t, "lodash", artifactVer)
require.Zero(t, h.fetches, "the legacy 7-day expiry no longer evicts a popular artifact")
p, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
require.NoError(t, err)
require.Nil(t, p.ExpiresAt)
}
+104
View File
@@ -0,0 +1,104 @@
package cache
import (
"context"
"errors"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
// evictMeta adds the LRU list and a switchable delete failure to memMetadata.
type evictMeta struct {
*memMetadata
listGate chan struct{}
listing chan struct{}
failDelete atomic.Bool
}
func (m *evictMeta) ListPackages(_ context.Context, opts *metadata.ListOptions) ([]*metadata.Package, error) {
if m.listing != nil {
select {
case m.listing <- struct{}{}:
default:
}
<-m.listGate
}
return m.list(opts.Limit,
func(*metadata.Package) bool { return true },
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
}
func (m *evictMeta) DeletePackage(ctx context.Context, registry, name, version string) error {
if m.failDelete.Load() {
return errors.New("db down")
}
return m.memMetadata.DeletePackage(ctx, registry, name, version)
}
func seedPackages(t *testing.T, m *memMetadata, store *memStorage, n int, size int64) {
t.Helper()
for i := 0; i < n; i++ {
name := "pkg" + strings.Repeat("x", i%7) + string(rune('a'+i%26)) + time.Duration(i).String()
key := "npm/" + name + "/1.0.0"
require.NoError(t, store.Put(context.Background(), key, strings.NewReader("d"), nil))
require.NoError(t, m.SavePackage(context.Background(), &metadata.Package{
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: key, Size: size,
LastAccessed: m.clock.Now().Add(time.Duration(i) * time.Second),
}))
}
}
// evict must return when no package can be deleted instead of re-listing the same rows forever.
func TestEvictTerminatesWhenDeletesFail(t *testing.T) {
clock := newFakeClock()
store := newMemStorage()
meta := &evictMeta{memMetadata: newMemMetadata(clock)}
seedPackages(t, meta.memMetadata, store, 250, 1)
meta.failDelete.Store(true)
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
done := make(chan error, 1)
go func() { done <- mgr.evict(context.Background(), 1000) }()
select {
case err := <-done:
require.NoError(t, err)
case <-time.After(3 * time.Second):
t.Fatal("evict did not terminate with failing deletes")
}
}
// A store that overlaps a running eviction must wait for it, not fail as over quota.
func TestEvictWaitsForRunningEviction(t *testing.T) {
clock := newFakeClock()
store := newMemStorage()
meta := &evictMeta{memMetadata: newMemMetadata(clock), listGate: make(chan struct{}), listing: make(chan struct{}, 1)}
seedPackages(t, meta.memMetadata, store, 3, 10)
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
var wg sync.WaitGroup
errs := make([]error, 2)
wg.Add(1)
go func() { defer wg.Done(); errs[0] = mgr.evict(context.Background(), 10) }()
<-meta.listing // first eviction is inside its list query
wg.Add(1)
go func() { defer wg.Done(); errs[1] = mgr.evict(context.Background(), 10) }()
time.Sleep(100 * time.Millisecond)
close(meta.listGate)
wg.Wait()
require.NoError(t, errs[0])
require.NoError(t, errs[1])
}
+54
View File
@@ -0,0 +1,54 @@
package cache
import (
"context"
"io"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// racyStorage deletes the blob and the row when the second Get opens it, as a purge would.
type racyStorage struct {
*memStorage
meta *memMetadata
gets atomic.Int32
armed atomic.Bool
}
func (s *racyStorage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
if s.armed.Load() && s.gets.Add(1) == 2 {
_ = s.Delete(ctx, key)
_ = s.meta.DeletePackage(ctx, "npm", "left-pad", "1.0.0")
}
return s.memStorage.Get(ctx, key)
}
// A purge between the cache-hit probe and the caller's open must not fail the request.
func TestGetRecoversFromPurgeBetweenProbeAndOpen(t *testing.T) {
clock := newFakeClock()
meta := newMemMetadata(clock)
store := &racyStorage{memStorage: newMemStorage(), meta: meta}
mgr, err := New(store, meta, nil, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
fetch := func(context.Context) (*FetchResult, error) {
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload")), UpstreamURL: "https://upstream/x"}, nil
}
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.0.0", fetch)
require.NoError(t, err)
_ = entry.Data.Close()
store.armed.Store(true)
entry, err = mgr.Get(context.Background(), "npm", "left-pad", "1.0.0", fetch)
require.NoError(t, err)
body, err := io.ReadAll(entry.Data)
require.NoError(t, err)
_ = entry.Data.Close()
require.Equal(t, "payload", string(body))
}
+90
View File
@@ -0,0 +1,90 @@
package cache
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// purgeRecorder plays a store holding `pending` soft-deleted rows.
type purgeRecorder struct {
*memMetadata
err error
cutoffs []time.Time
limits []int
pending int64
mu sync.Mutex
}
func (p *purgeRecorder) PurgeDeletedPackages(_ context.Context, before time.Time, limit int) (int64, error) {
p.mu.Lock()
defer p.mu.Unlock()
p.cutoffs = append(p.cutoffs, before)
p.limits = append(p.limits, limit)
if p.err != nil {
return 0, p.err
}
n := min(p.pending, int64(limit))
p.pending -= n
return n, nil
}
func newPurgeHarness(t *testing.T, retention time.Duration, pending int64) (*idleHarness, *purgeRecorder) {
t.Helper()
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
rec := &purgeRecorder{memMetadata: newMemMetadata(h.clock), pending: pending}
h.meta = rec.memMetadata
mgr, err := New(h.store, rec, nil, nil, Config{Now: h.clock.Now, CleanupInterval: 24 * time.Hour, DeletedRetention: retention})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
h.mgr = mgr
return h, rec
}
func TestCleanupPurgesDeletedRowsPastRetention(t *testing.T) {
h, rec := newPurgeHarness(t, 30*day, 3*int64(cleanupBatchSize)+7)
h.mgr.cleanup(context.Background())
require.Zero(t, rec.pending, "batches continue until the store runs dry")
require.Len(t, rec.limits, 4, "three full batches and a short one")
for _, limit := range rec.limits {
require.Equal(t, cleanupBatchSize, limit, "every batch is bounded")
}
require.Equal(t, h.clock.Now().Add(-30*day), rec.cutoffs[0], "the cutoff is now minus the retention")
}
func TestCleanupPurgeIsBoundedPerPass(t *testing.T) {
_, rec := newPurgeHarness(t, 30*day, int64(maxPurgeBatches+50)*int64(cleanupBatchSize))
h := &Manager{config: Config{DeletedRetention: day, Now: time.Now}, metadata: rec}
got := h.purgeDeleted(context.Background(), time.Now())
require.EqualValues(t, maxPurgeBatches*cleanupBatchSize, got)
require.EqualValues(t, 50*cleanupBatchSize, rec.pending, "the next pass continues where this one stopped")
}
func TestCleanupSkipsPurgeWhenRetentionIsZero(t *testing.T) {
h, rec := newPurgeHarness(t, 0, 10)
h.mgr.cleanup(context.Background())
require.Empty(t, rec.limits, "zero keeps every row")
require.EqualValues(t, 10, rec.pending)
}
func TestCleanupPurgeFailureDoesNotStopCleanup(t *testing.T) {
h, rec := newPurgeHarness(t, 30*day, 10)
rec.err = errors.New("db down")
h.get(t, "lodash", "metadata")
h.clock.Advance(2 * day)
h.mgr.cleanup(context.Background())
require.Len(t, rec.limits, 1, "one failed attempt, no retry loop")
require.False(t, h.exists("lodash", "metadata"), "expired metadata is still removed")
}
+13
View File
@@ -0,0 +1,13 @@
package cache
import "testing"
func TestWithReleaseVersion(t *testing.T) {
with := withReleaseVersion(map[string]interface{}{"version": "six-1.17.0.tar.gz"}, "1.17.0")
if with["release_version"] != "1.17.0" || with["version"] != "six-1.17.0.tar.gz" {
t.Errorf("payload = %v", with)
}
if _, ok := withReleaseVersion(map[string]interface{}{"version": "1.3.0"}, "")["release_version"]; ok {
t.Error("empty release version must not be sent")
}
}
+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")
}
+75
View File
@@ -0,0 +1,75 @@
package cache
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
"github.com/stretchr/testify/require"
)
// listingMetadata adds the full listing the rescan worker walks.
type listingMetadata struct{ scanMetadata }
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
}
// bodyScanner reports the bytes it can read at the path it is given.
type bodyScanner struct{ seen chan string }
func (*bodyScanner) Name() string { return "body-scanner" }
func (*bodyScanner) Health(context.Context) error { return nil }
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
body, err := os.ReadFile(path)
if err != nil {
s.seen <- "unreadable"
return nil, err
}
s.seen <- string(body)
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
}
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
// through the cache's file source instead of skipping the package.
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
clock := newFakeClock()
store := newMemStorage() // no GetLocalPath, like S3 and SMB
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
require.NoError(t, err)
t.Cleanup(scanMgr.Stop)
bs := &bodyScanner{seen: make(chan string, 8)}
scanMgr.RegisterScanner(bs)
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
scanMgr.SetFileSource(mgr.ScanFile)
ctx := context.Background()
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
CachedAt: clock.Now(), LastAccessed: clock.Now(),
}))
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
runCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() { worker.Start(runCtx); close(done) }()
t.Cleanup(func() { cancel(); <-done })
select {
case got := <-bs.seen:
require.Equal(t, "tarball-bytes", got)
case <-time.After(5 * time.Second):
t.Fatal("rescan never scanned the remote-storage package")
}
}
+92
View File
@@ -0,0 +1,92 @@
package cache
import (
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/stretchr/testify/require"
)
// scanMetadata lets the real scanner.Manager record results against the in-memory store.
type scanMetadata struct {
*memMetadata
}
func (scanMetadata) SaveScanResult(context.Context, *metadata.ScanResult) error { return nil }
func (scanMetadata) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
return nil, fmt.Errorf("no result")
}
// fileScanner fails on infrastructure once, then succeeds; it records what it could read.
type fileScanner struct {
seen chan string
mu sync.Mutex
n int
}
func (*fileScanner) Name() string { return "file-scanner" }
func (*fileScanner) Health(context.Context) error { return nil }
func (s *fileScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
s.mu.Lock()
s.n++
n := s.n
s.mu.Unlock()
body, err := os.ReadFile(path)
if err != nil {
s.seen <- "unreadable"
} else {
s.seen <- string(body)
}
if n == 1 {
return nil, fmt.Errorf("%w: scanner timed out", scanerr.ErrInfrastructure)
}
if err != nil {
return nil, err
}
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "file-scanner", Status: metadata.ScanStatusClean}, nil
}
// On a backend with no local path (S3, SMB) the scan source is a temp file removed after the
// first scan; a retry must read the blob again instead of scanning a path that is gone.
func TestScanRetryOnRemoteStorageReadsBlobAgain(t *testing.T) {
clock := newFakeClock()
store := newMemStorage() // no GetLocalPath, like S3 and SMB
meta := scanMetadata{newMemMetadata(clock)}
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 50 * time.Millisecond}, meta)
require.NoError(t, err)
t.Cleanup(scanMgr.Stop)
fs := &fileScanner{seen: make(chan string, 8)}
scanMgr.RegisterScanner(fs)
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour, ScanWaitTimeout: 200 * time.Millisecond})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
scanMgr.SetFileSource(mgr.ScanFile)
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*FetchResult, error) {
return &FetchResult{Data: io.NopCloser(strings.NewReader("tarball-bytes"))}, nil
})
require.NoError(t, err)
_, _ = io.Copy(io.Discard, entry.Data)
_ = entry.Data.Close()
for attempt := 1; attempt <= 2; attempt++ {
select {
case got := <-fs.seen:
require.Equal(t, "tarball-bytes", got, "scan attempt %d must read the blob", attempt)
case <-time.After(5 * time.Second):
t.Fatalf("scan attempt %d never ran", attempt)
}
}
}
+70
View File
@@ -0,0 +1,70 @@
package cache
import (
"context"
"io"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
// policyBlocker blocks every package it is asked about.
type policyBlocker struct{ checks atomic.Int32 }
func (s *policyBlocker) ScanPackage(context.Context, string, string, string, string) error {
return nil
}
func (s *policyBlocker) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
s.checks.Add(1)
return true, "blocked by policy", nil
}
// Only Go's .mod and .info files are exempt from scanning; a package of any
// other registry whose name ends in .mod or .info is a real package.
func TestCacheHitScansPackagesNamedLikeGoMetadata(t *testing.T) {
tests := []struct {
registry, name, version string
wantBlocked bool
}{
{"npm", "left.info", "1.0.0", true},
{"npm", "left.mod", "1.0.0", true},
{"pypi", "foo.info", "foo.info-1.0.tar.gz", true},
{"go", "github.com/a/b/@v/v1.0.0.zip", "v1.0.0", true},
{"go", "github.com/a/b/@v/v1.0.0.mod", "v1.0.0", false},
{"go", "github.com/a/b/@v/v1.0.0.info", "v1.0.0", false},
{"npm", "left-pad", "metadata", false},
}
for _, tt := range tests {
t.Run(tt.registry+"/"+tt.name, func(t *testing.T) {
clock := newFakeClock()
store := newMemStorage()
meta := newMemMetadata(clock)
key := tt.registry + "/" + tt.name + "/" + tt.version
require.NoError(t, store.Put(context.Background(), key, strings.NewReader("data"), nil))
require.NoError(t, meta.SavePackage(context.Background(), &metadata.Package{
Registry: tt.registry, Name: tt.name, Version: tt.version, StorageKey: key, Size: 4, LastAccessed: clock.Now(),
}))
scanner := &policyBlocker{}
mgr, err := New(store, meta, scanner, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
entry, err := mgr.Get(context.Background(), tt.registry, tt.name, tt.version, nil)
if tt.wantBlocked {
require.Error(t, err)
return
}
require.NoError(t, err)
_, _ = io.Copy(io.Discard, entry.Data)
_ = entry.Data.Close()
require.Zero(t, scanner.checks.Load(), "metadata entries must not be scanned")
})
}
}
+38
View File
@@ -0,0 +1,38 @@
package cache
import (
"context"
"io"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry {
t.Helper()
entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) {
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
return entry
}
func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) {
h := newIdleHarness(t, Config{
DefaultTTL: 6 * time.Hour,
TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour},
})
require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()))
require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now()))
require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl")
}
func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) {
h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}})
require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry")
}
+76 -27
View File
@@ -35,6 +35,7 @@ type ServerConfig struct {
ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout"`
IdleTimeout time.Duration `mapstructure:"idle_timeout" json:"idle_timeout"`
ReadBufferSize int `mapstructure:"read_buffer_size" json:"read_buffer_size"` // bytes; caps the request line plus headers
}
// TLSConfig contains TLS/HTTPS configuration
@@ -133,28 +134,61 @@ type MySQLConfig struct {
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
}
// DefaultMetadataTTL is the freshness window for metadata pages. It stays below the 72h
// release-age gate clients apply, so a cached page never hides the entries the gate reads.
const DefaultMetadataTTL = 24 * time.Hour
// DefaultReadBufferSize is the HTTP server read buffer. Fiber's own 8192 rejects browsers
// that send OIDC session cookies plus a long Referer or URL with 431.
const DefaultReadBufferSize = 16384
// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name.
var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"}
// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name.
func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
out := make(map[string]time.Duration, len(c.TTLOverrides))
for key, ttl := range c.TTLOverrides {
out[ttlOverrideRegistries[key]] = ttl
}
return out
}
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
const DefaultIdleTTL = 7 * 24 * time.Hour
// DefaultDeletedRetention is how long a soft-deleted package row is kept before cleanup purges it.
const DefaultDeletedRetention = 30 * 24 * time.Hour
// CacheConfig contains cache management configuration
type CacheConfig struct {
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
// DeletedRetention is how long soft-deleted package rows stay before cleanup purges them; 0 keeps them forever.
DeletedRetention time.Duration `mapstructure:"deleted_retention" json:"deleted_retention"`
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
}
// 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
@@ -326,11 +360,12 @@ type PyPIHandlerConfig struct {
func Default() *Config {
return &Config{
Server: ServerConfig{
Host: "0.0.0.0",
Port: 8080,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
IdleTimeout: 2 * time.Minute,
Host: "0.0.0.0",
Port: 8080,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
IdleTimeout: 2 * time.Minute,
ReadBufferSize: DefaultReadBufferSize,
TLS: TLSConfig{
Enabled: false,
},
@@ -351,15 +386,12 @@ func Default() *Config {
},
},
Cache: CacheConfig{
DefaultTTL: 7 * 24 * time.Hour,
CleanupInterval: 1 * time.Hour,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
TTLOverrides: map[string]time.Duration{
"npm": 7 * 24 * time.Hour,
"pip": 7 * 24 * time.Hour,
"go": 7 * 24 * time.Hour,
},
DefaultTTL: DefaultMetadataTTL,
CleanupInterval: 1 * time.Hour,
IdleTTL: DefaultIdleTTL,
DeletedRetention: DefaultDeletedRetention,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
},
Security: SecurityConfig{
Enabled: false,
@@ -502,9 +534,26 @@ func (c *Config) Validate() error {
}
// Validate cache
if c.Server.ReadBufferSize < 0 {
return fmt.Errorf("server.read_buffer_size cannot be negative")
}
if c.Cache.DefaultTTL < 0 {
return fmt.Errorf("cache.default_ttl cannot be negative")
}
if c.Cache.IdleTTL < 0 {
return fmt.Errorf("cache.idle_ttl cannot be negative")
}
for key, ttl := range c.Cache.TTLOverrides {
if _, ok := ttlOverrideRegistries[key]; !ok {
return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key)
}
if ttl <= 0 {
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
}
}
if c.Cache.DeletedRetention < 0 {
return fmt.Errorf("cache.deleted_retention cannot be negative")
}
if c.Cache.MaxSizeBytes < 0 {
return fmt.Errorf("cache.max_size_bytes cannot be negative")
}
+88
View File
@@ -0,0 +1,88 @@
package config
import (
"os"
"path/filepath"
"regexp"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestDefaultMetadataTTL(t *testing.T) {
require.Equal(t, 24*time.Hour, Default().Cache.DefaultTTL)
for registry, ttl := range Default().Cache.TTLOverrides {
require.LessOrEqual(t, ttl, 72*time.Hour, "override %s outlives the 72h release-age gate", registry)
}
}
// The shipped examples must not teach a metadata TTL longer than the release-age gate.
func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) {
for file, key := range map[string]string{
"../../config.yaml.example": `default_ttl`,
"../../helm/gohoarder/values.yaml": `defaultTTL`,
} {
raw, err := os.ReadFile(file)
require.NoError(t, err)
m := regexp.MustCompile(`(?m)^\s*` + key + `:\s*"?(\d+h)"?`).FindSubmatch(raw)
require.NotNil(t, m, "%s has no %s", file, key)
ttl, err := time.ParseDuration(string(m[1]))
require.NoError(t, err)
require.Equal(t, 24*time.Hour, ttl, file)
for _, o := range regexp.MustCompile(`(?m)^\s+(?:npm|pip|go):\s*"(\d+h)"`).FindAllSubmatch(raw, -1) {
d, err := time.ParseDuration(string(o[1]))
require.NoError(t, err)
require.LessOrEqual(t, d, 72*time.Hour, "%s: override %s", file, o[0])
}
}
}
func TestTTLOverridesValidation(t *testing.T) {
for name, tc := range map[string]struct {
overrides map[string]time.Duration
wantErr string
}{
"known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""},
"pip alias": {map[string]time.Duration{"pip": time.Hour}, ""},
"unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"},
"zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"},
"negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"},
} {
t.Run(name, func(t *testing.T) {
c := Default()
c.Cache.TTLOverrides = tc.overrides
err := c.Validate()
if tc.wantErr == "" {
require.NoError(t, err)
return
}
require.ErrorContains(t, err, tc.wantErr)
})
}
}
func TestMetadataTTLOverridesNormalisesPip(t *testing.T) {
c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}}
require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides())
}
func TestDefaultsKeepNoTTLOverrides(t *testing.T) {
require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl")
}
func TestLoadReadsTTLOverridesFromYAML(t *testing.T) {
write := func(body string) string {
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return path
}
cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n"))
require.NoError(t, err)
require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides())
_, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n"))
require.ErrorContains(t, err, "cache.ttl_overrides")
}
+41
View File
@@ -0,0 +1,41 @@
package config
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestDeletedRetentionDefaultsToThirtyDays(t *testing.T) {
require.Equal(t, 30*24*time.Hour, Default().Cache.DeletedRetention)
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
require.NoError(t, err)
require.Equal(t, 30*24*time.Hour, cfg.Cache.DeletedRetention, "an unset key keeps the default")
}
func TestDeletedRetentionParse(t *testing.T) {
tests := []struct {
name string
yaml string
want time.Duration
wantErr bool
}{
{name: "duration string", yaml: "cache:\n deleted_retention: 48h\n", want: 48 * time.Hour},
{name: "zero keeps rows", yaml: "cache:\n deleted_retention: 0\n", want: 0},
{name: "quoted duration", yaml: "cache:\n deleted_retention: \"720h\"\n", want: 720 * time.Hour},
{name: "negative rejected", yaml: "cache:\n deleted_retention: -1h\n", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, err := loadCacheYAML(t, tt.yaml)
if tt.wantErr {
require.ErrorContains(t, err, "cache.deleted_retention")
return
}
require.NoError(t, err)
require.Equal(t, tt.want, cfg.Cache.DeletedRetention)
})
}
}
+51
View File
@@ -0,0 +1,51 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func loadCacheYAML(t *testing.T, cacheYAML string) (*Config, error) {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(cacheYAML), 0600))
return Load(path)
}
func TestIdleTTLDefaultsToAWeek(t *testing.T) {
require.Equal(t, 168*time.Hour, Default().Cache.IdleTTL)
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
require.NoError(t, err)
require.Equal(t, 168*time.Hour, cfg.Cache.IdleTTL, "an unset key keeps the default")
}
func TestIdleTTLParse(t *testing.T) {
tests := []struct {
name string
yaml string
want time.Duration
wantErr bool
}{
{name: "duration string", yaml: "cache:\n idle_ttl: 72h\n", want: 72 * time.Hour},
{name: "zero disables", yaml: "cache:\n idle_ttl: 0\n", want: 0},
{name: "quoted zero disables", yaml: "cache:\n idle_ttl: \"0\"\n", want: 0},
{name: "quoted duration", yaml: "cache:\n idle_ttl: \"168h\"\n", want: 168 * time.Hour},
{name: "negative rejected", yaml: "cache:\n idle_ttl: -1h\n", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, err := loadCacheYAML(t, tt.yaml)
if tt.wantErr {
require.ErrorContains(t, err, "cache.idle_ttl")
return
}
require.NoError(t, err)
require.Equal(t, tt.want, cfg.Cache.IdleTTL)
})
}
}
+153
View File
@@ -0,0 +1,153 @@
package file
import (
"context"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// packageKey identifies a file-store record, which has no numeric id.
func packageKey(p *metadata.Package) string {
return p.Registry + "/" + p.Name + "@" + p.Version
}
// listRecords returns package records only: the store's walk also yields scan result files.
func (s *Store) listRecords(ctx context.Context) ([]*metadata.Package, error) {
all, err := s.ListPackages(ctx, nil)
if err != nil {
return nil, err
}
out := all[:0]
for _, p := range all {
if p.Registry != "" && p.Name != "" {
out = append(out, p)
}
}
return out, nil
}
// ListPackageGroups pages groups in memory.
func (s *Store) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
all, err := s.listRecords(ctx)
if err != nil {
return nil, err
}
for _, p := range all {
if p.ID == "" {
p.ID = packageKey(p)
}
}
if len(opts.Severities) > 0 {
if all, err = s.withSeverity(ctx, all, opts.Severities); err != nil {
return nil, err
}
}
return metadata.PageGroups(all, opts), nil
}
// withSeverity keeps the packages whose scan holds a vulnerability of one of the severities.
func (s *Store) withSeverity(ctx context.Context, all []*metadata.Package, severities []string) ([]*metadata.Package, error) {
sums, err := s.GetScanSummaries(ctx, nil, false)
if err != nil {
return nil, err
}
hit := make(map[string]struct{}, len(sums))
for _, sum := range sums {
for _, sev := range severities {
if (sev == metadata.SeverityCritical && sum.Critical > 0) || (sev == metadata.SeverityHigh && sum.High > 0) ||
(sev == metadata.SeverityModerate && sum.Moderate > 0) || (sev == metadata.SeverityLow && sum.Low > 0) {
hit[sum.PackageID] = struct{}{}
break
}
}
}
out := all[:0]
for _, p := range all {
if _, ok := hit[p.ID]; ok {
out = append(out, p)
}
}
return out, nil
}
// GetScanSummaries reads each scanned package's latest scan file.
func (s *Store) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
all, err := s.listRecords(ctx)
if err != nil {
return nil, err
}
want := make(map[string]struct{}, len(packageIDs))
for _, id := range packageIDs {
want[id] = struct{}{}
}
var out []*metadata.ScanSummary
for _, p := range all {
id := p.ID
if id == "" {
id = packageKey(p)
}
if _, ok := want[id]; packageIDs != nil && !ok || !p.SecurityScanned {
continue
}
sum := &metadata.ScanSummary{
Registry: p.Registry, PackageID: id, Name: p.Name, Version: p.Version, ReleaseVersion: p.ReleaseVersion,
}
res, err := s.GetScanResult(ctx, p.Registry, p.Name, p.Version)
if err != nil {
return nil, err
}
if res != nil {
sum.HasScan = true
sum.Status = res.Status
sum.ScannedAt = res.ScannedAt
sum.Total = res.VulnerabilityCount
sum.Details = res.Details
for _, v := range res.Vulnerabilities {
switch metadata.NormalizeSeverity(v.Severity) {
case "CRITICAL":
sum.Critical++
case "HIGH":
sum.High++
case "MODERATE":
sum.Moderate++
default:
sum.Low++
}
}
if withDetails {
sum.Vulnerabilities = res.Vulnerabilities
}
}
out = append(out, sum)
}
return out, nil
}
// GetRegistryStats totals artifacts per registry.
func (s *Store) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
all, err := s.listRecords(ctx)
if err != nil {
return nil, err
}
byRegistry := map[string]*metadata.RegistryStat{}
var order []string
for _, p := range all {
if metadata.IsMetadataVersion(p.Version) {
continue
}
st, ok := byRegistry[p.Registry]
if !ok {
st = &metadata.RegistryStat{Registry: p.Registry}
byRegistry[p.Registry] = st
order = append(order, p.Registry)
}
st.Count++
st.Size += p.Size
st.Downloads += p.DownloadCount
}
out := make([]metadata.RegistryStat, 0, len(order))
for _, r := range order {
out = append(out, *byRegistry[r])
}
return out, nil
}

Some files were not shown because too many files have changed in this diff Show More