Compare commits

...
6 Commits
Author SHA1 Message Date
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
14 changed files with 192 additions and 22 deletions
+3 -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
@@ -147,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
+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
+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
+1 -1
View File
@@ -79,7 +79,7 @@ describe('TrendChart', () => {
expect(critical.attributes('aria-pressed')).toBe('true')
expect(vulnerable()).toContain('with lines for critical')
expect(wrapper.text()).toContain('Critical (highest severity)')
expect(wrapper.text()).toContain('Packages with critical vulnerabilities')
await critical.trigger('click')
await flushPromises()
+2 -2
View File
@@ -51,7 +51,7 @@
type="multiple"
variant="outline"
size="sm"
aria-label="Add a line per highest severity"
aria-label="Add a line per severity"
>
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
{{ formatSeverityName(level) }}
@@ -172,7 +172,7 @@ const vulnerableLabel = computed(() => {
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: `${formatSeverityName(level)} (highest severity)`,
name: `Packages with ${level} vulnerabilities`,
data: values(level),
tone: SEVERITY_LINE_TONES[level],
})),
+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
}
}
+23 -2
View File
@@ -1,6 +1,7 @@
package app
import (
"context"
"strings"
"github.com/gofiber/fiber/v3"
@@ -42,14 +43,14 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
Str("version", version).
Msg("Getting vulnerabilities for package")
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
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 {
if pkgErr != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
@@ -169,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
}
+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)
}
}
@@ -3,6 +3,7 @@ package gormstore
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
@@ -52,6 +53,19 @@ func checkSeverityFilter(t *testing.T, store *GORMStoreV2) {
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "cr"}), "composes with search")
require.Empty(t, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "high"}))
// The trend snapshot counts a package under every severity it holds, exactly as the filter selects it.
snap, err := liveSnapshot(ctx, store.db, time.Now(), nil)
require.NoError(t, err)
for sev, got := range map[string]*int64{
metadata.SeverityCritical: snap.Critical, metadata.SeverityHigh: snap.High,
metadata.SeverityModerate: snap.Moderate, metadata.SeverityLow: snap.Low,
} {
require.EqualValues(t, len(pick(metadata.GroupListOptions{Severities: []string{sev}})), *got, sev)
}
require.EqualValues(t, 5, *snap.VulnerablePackages)
require.EqualValues(t, len(pick(metadata.GroupListOptions{Severities: metadata.Severities})), *snap.VulnerablePackages)
require.EqualValues(t, [4]int64{1, 2, 1, 2}, [4]int64{*snap.Critical, *snap.High, *snap.Moderate, *snap.Low}, "multi counts under high and low")
}
func checkSeverityFilterStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
+17 -10
View File
@@ -39,14 +39,18 @@ func liveSnapshot(ctx context.Context, db *gorm.DB, at time.Time, blocked *int64
Moderate int64
Low int64
}
// A package counts under every severity its latest scan holds, as the severity filter selects it.
scanned := func(col string) string {
return "COALESCE(SUM(CASE WHEN security_scanned = ? AND id IN (" + latestScanWith(col+" > 0") + ") THEN 1 ELSE 0 END), 0)"
}
err := artifactPackages(db.WithContext(ctx).Model(&PackageModel{})).Select(`
COUNT(*) AS total,
COALESCE(SUM(size), 0) AS size,
COALESCE(SUM(CASE WHEN vulnerability_count > 0 THEN 1 ELSE 0 END), 0) AS vulnerable,
COALESCE(SUM(CASE WHEN highest_severity = 'critical' THEN 1 ELSE 0 END), 0) AS critical,
COALESCE(SUM(CASE WHEN highest_severity = 'high' THEN 1 ELSE 0 END), 0) AS high,
COALESCE(SUM(CASE WHEN highest_severity = 'medium' THEN 1 ELSE 0 END), 0) AS moderate,
COALESCE(SUM(CASE WHEN highest_severity = 'low' THEN 1 ELSE 0 END), 0) AS low`).
`+scanned("vuln_count")+` AS vulnerable,
`+scanned(severityColumns[metadata.SeverityCritical])+` AS critical,
`+scanned(severityColumns[metadata.SeverityHigh])+` AS high,
`+scanned(severityColumns[metadata.SeverityModerate])+` AS moderate,
`+scanned(severityColumns[metadata.SeverityLow])+` AS low`, true, true, true, true, true).
Scan(&r).Error
if err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats for snapshot")
@@ -214,14 +218,17 @@ func (p backfillPackage) stateAtDayEnd(end time.Time, scans []backfillScan, with
if sc.vulns > 0 {
st.vulnerable = 1
}
switch {
case sc.critical > 0:
// Every severity the scan holds counts, as in liveSnapshot.
if sc.critical > 0 {
st.critical = 1
case sc.high > 0:
}
if sc.high > 0 {
st.high = 1
case sc.moderate > 0:
}
if sc.moderate > 0 {
st.moderate = 1
case sc.lowCounts > 0:
}
if sc.lowCounts > 0 {
st.low = 1
}
return st
+2 -2
View File
@@ -106,11 +106,11 @@ func checkBackfillStatsSnapshots(t *testing.T, store *GORMStoreV2) {
require.Equal(t, [5]int64{1, 0, 1, 0, 0}, vulns(day(4)))
require.EqualValues(t, 2, day(3).TotalPackages)
require.Equal(t, [5]int64{2, 1, 1, 0, 0}, vulns(day(3)))
require.Equal(t, [5]int64{2, 1, 1, 0, 1}, vulns(day(3)), "a counts under critical and low")
require.EqualValues(t, 1, day(2).TotalPackages, "b was deleted on day -2; early lived and died within it")
require.EqualValues(t, 10, day(2).TotalSize)
require.Equal(t, [5]int64{1, 1, 0, 0, 0}, vulns(day(2)))
require.Equal(t, [5]int64{1, 1, 0, 0, 1}, vulns(day(2)))
require.EqualValues(t, 1, day(1).TotalPackages)
require.Equal(t, [5]int64{0, 0, 0, 0, 0}, vulns(day(1)), "the clean rescan clears the vulnerability")
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# Builds the frontend image from a Dockerfile and checks that the SPA HTML is revalidated on every
# load while hashed assets stay immutable. A cached index.html keeps old bundles after a deploy.
# Usage: scripts/check_frontend_html_cache.sh [Dockerfile]
set -eu
dockerfile="${1:-Dockerfile.frontend}"
root="$(git rev-parse --show-toplevel)"
work="$(mktemp -d)"
tag="gohoarder-frontend-cache-check:$$"
front="gohoarder-cache-check-$$"
cleanup() {
docker rm -f "$front" >/dev/null 2>&1 || true
docker rmi "$tag" >/dev/null 2>&1 || true
rm -rf "$work"
}
trap cleanup EXIT
mkdir -p "$work/frontend/dist/assets"
echo '<html></html>' >"$work/frontend/dist/index.html"
echo 'console.log(1)' >"$work/frontend/dist/assets/index-abc123.js"
cp "$root/$dockerfile" "$work/Dockerfile"
docker build -q --load -t "$tag" "$work" >/dev/null
docker run -d --name "$front" -e BACKEND_HOST=127.0.0.1 -e BACKEND_PORT=8080 "$tag" >/dev/null
headers() {
for _ in 1 2 3 4 5 6 7 8 9 10; do
out="$(docker exec "$front" wget -S -qO /dev/null "http://127.0.0.1$1" 2>&1 || true)"
case "$out" in *"HTTP/"*) printf '%s' "$out" | grep -i 'cache-control' || true; return ;; esac
sleep 1
done
}
status=0
for path in / /index.html /packages /package/go/example.com/mod/v1.0.0; do
cc="$(headers "$path")"
case "$cc" in
*no-cache*) echo "ok: $path is revalidated" ;;
*) echo "FAIL: $path Cache-Control [$cc], want no-cache"; status=1 ;;
esac
done
cc="$(headers /assets/index-abc123.js)"
case "$cc" in
*immutable*) echo "ok: hashed asset is immutable" ;;
*) echo "FAIL: asset Cache-Control [$cc], want immutable"; status=1 ;;
esac
exit "$status"