diff --git a/CHANGELOG.md b/CHANGELOG.md index d1b9c18..8dbe9b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ an example value. See `deploy/host/README.md`. ## [Unreleased] +### Added + +- A "CVEs" tab after Artifacts has three views. "Staging" lists the packages to bump to clear the HIGH and CRITICAL CVEs found in the staging images, split into "Ours to bump", "Base OS" and "Not classified yet". Entries that are new since you last looked are marked, and "Mark all as seen" clears the markers; the markers are kept in your browser, and the tab shows a badge when there are new entries. "Released" shows, for each released image, how many of its CVEs the current staging image already fixes. "By image" is the CVE table that used to be on Overview. +- `GET /api/cve/report` returns the data behind the CVEs tab: the staging work list and the released-image view. It is public, like the other CVE endpoints. + +### Changed + +- The CVE table moved from Overview to the "By image" view of the new CVEs tab. +- After upgrading, images scanned before this version are rescanned once at startup so their findings can be classified. Until the rescan finishes, their packages appear under "Not classified yet". Entries marked as seen before that rescan finishes may show as new once more afterwards, because the rescan adds the file a library was found in. + ## [0.2.10] - 2026-11-17 ### Added diff --git a/README.md b/README.md index 1743ea4..d0c608b 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ The dashboard polls OBS on a schedule and consumes RabbitMQ build events, stores - Package cards showing live rollup state (building, failed, succeeded, published) across all PPG OBS projects. - Per-target build event log: build started, succeeded, failed, published — filterable by tag and time window. - Artifacts view — binary package download links and container image pull commands, browsable by version, repo, and arch; covers dev builds, releases, and PRs. +- CVEs tab — the packages to bump to clear HIGH and CRITICAL CVEs in staging images, what the current staging image already fixes for each released image, and the per-image CVE table; new entries since your last look are marked. - Tag-based filtering (RPM, DEB, container) and version selector. - PR build tracking: dedicated board context per OBS PR branch. - SSE-based live updates — cards and event log update in real time without a page refresh. diff --git a/backend/internal/api/cache.go b/backend/internal/api/cache.go new file mode 100644 index 0000000..0cbeff8 --- /dev/null +++ b/backend/internal/api/cache.go @@ -0,0 +1,63 @@ +package api + +import ( + "context" + "sync" + "time" +) + +// ttlCache caches one value per key for ttl, with single-flight fetches +// (mirrors releaseArtifactsCache). Failed fetches are not cached. +type ttlCache[T any] struct { + mu sync.Mutex + ttl time.Duration + entries map[string]ttlCacheEntry[T] + inflight map[string]chan struct{} +} + +type ttlCacheEntry[T any] struct { + value T + expires time.Time + err error +} + +func newTTLCache[T any](ttl time.Duration) *ttlCache[T] { + return &ttlCache[T]{ttl: ttl, entries: map[string]ttlCacheEntry[T]{}, inflight: map[string]chan struct{}{}} +} + +func (c *ttlCache[T]) Get(ctx context.Context, key string, fetch func(context.Context) (T, error)) (T, error) { + var zero T + now := time.Now() + c.mu.Lock() + if entry, ok := c.entries[key]; ok && now.Before(entry.expires) { + c.mu.Unlock() + return entry.value, entry.err + } + if wait, ok := c.inflight[key]; ok { + c.mu.Unlock() + select { + case <-wait: + case <-ctx.Done(): + return zero, ctx.Err() + } + c.mu.Lock() + entry := c.entries[key] + c.mu.Unlock() + return entry.value, entry.err + } + wait := make(chan struct{}) + c.inflight[key] = wait + c.mu.Unlock() + + value, err := fetch(ctx) + c.mu.Lock() + expires := time.Now() + if err == nil { + expires = expires.Add(c.ttl) + } + c.entries[key] = ttlCacheEntry[T]{value: value, expires: expires, err: err} + delete(c.inflight, key) + close(wait) + c.mu.Unlock() + return value, err +} diff --git a/backend/internal/api/cve_report.go b/backend/internal/api/cve_report.go new file mode 100644 index 0000000..aa335c2 --- /dev/null +++ b/backend/internal/api/cve_report.go @@ -0,0 +1,42 @@ +package api + +import ( + "context" + "database/sql" + "encoding/json" + "log/slog" + "net/http" + "time" + + "github.com/percona/obs-dashboard/internal/cvereport" + "github.com/percona/obs-dashboard/internal/store" +) + +// cveReportHandler serves GET /api/cve/report: the staging work list and the +// released/staging comparison, aggregated by cvereport. +func cveReportHandler(db *sql.DB, cache *ttlCache[cvereport.Report]) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + rep, err := cache.Get(r.Context(), "report", func(ctx context.Context) (cvereport.Report, error) { + staging, err := store.QueryImageScans(db, "ppg:staging") + if err != nil { + return cvereport.Report{}, err + } + released, err := store.QueryImageScans(db, "ppg:releases") + if err != nil { + return cvereport.Report{}, err + } + versions, err := store.QueryContainerVersions(db) + if err != nil { + return cvereport.Report{}, err + } + return cvereport.Build(staging, released, versions, time.Now()), nil + }) + if err != nil { + slog.Error("api: cve report", "err", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(rep) + } +} diff --git a/backend/internal/api/cve_report_test.go b/backend/internal/api/cve_report_test.go new file mode 100644 index 0000000..f955bb5 --- /dev/null +++ b/backend/internal/api/cve_report_test.go @@ -0,0 +1,103 @@ +package api + +import ( + "database/sql" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/percona/obs-dashboard/internal/cvereport" + "github.com/percona/obs-dashboard/internal/model" + "github.com/percona/obs-dashboard/internal/store" +) + +func seedReportScan(t *testing.T, db *sql.DB, project string, ids ...string) { + t.Helper() + var findings []model.CveFinding + for _, id := range ids { + findings = append(findings, model.CveFinding{ + ID: id, PkgName: "openssl", InstalledVersion: "1", FixedVersion: "2", + Severity: "HIGH", Class: "os-pkgs", Vendor: "Red Hat, Inc.", Src: "openssl", + }) + } + scan := model.CveScan{ + Repo: "ubi9", Arch: "x86_64", ImageRef: "img", ScannedAt: time.Now().UTC(), + HighCount: len(ids), Findings: findings, + } + if err := store.UpsertCveScan(db, project, "pg", scan); err != nil { + t.Fatalf("UpsertCveScan: %v", err) + } +} + +func TestCveReportHandler(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatalf("store.Open: %v", err) + } + t.Cleanup(func() { db.Close() }) + h := cveReportHandler(db, newTTLCache[cvereport.Report](time.Minute)) + + // Empty DB: arrays are never null. + rec := httptest.NewRecorder() + h(rec, httptest.NewRequest(http.MethodGet, "/api/cve/report", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("empty: expected 200, got %d", rec.Code) + } + body := rec.Body.String() + if strings.Contains(body, "null") { + t.Fatalf("empty: body contains null: %s", body) + } + for _, want := range []string{`"ours":[]`, `"released":[]`} { + if !strings.Contains(body, want) { + t.Fatalf("empty: body missing %s: %s", want, body) + } + } + + seedReportScan(t, db, "ppg:staging:18:containers", "CVE-1") + seedReportScan(t, db, "ppg:releases:18:containers", "CVE-1", "CVE-2") + h = cveReportHandler(db, newTTLCache[cvereport.Report](time.Minute)) + rec = httptest.NewRecorder() + h(rec, httptest.NewRequest(http.MethodGet, "/api/cve/report", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", rec.Code) + } + var rep cvereport.Report + if err := json.NewDecoder(rec.Body).Decode(&rep); err != nil { + t.Fatalf("decode: %v", err) + } + if len(rep.Staging.BaseOS) != 1 { + t.Fatalf("staging.base_os: expected 1 row, got %d", len(rep.Staging.BaseOS)) + } + if len(rep.Released) != 1 || rep.Released[0].Total != 2 || rep.Released[0].FixedInStaging != 1 { + t.Fatalf("released: unexpected %+v", rep.Released) + } +} + +func TestCveReportHandlerStoreError(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatalf("store.Open: %v", err) + } + db.Close() + h := cveReportHandler(db, newTTLCache[cvereport.Report](time.Minute)) + rec := httptest.NewRecorder() + h(rec, httptest.NewRequest(http.MethodGet, "/api/cve/report", nil)) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("expected 500, got %d", rec.Code) + } +} + +func TestCveReportRoute(t *testing.T) { + router := setupTestServer(t) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/cve/report", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", rec.Code) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/json" { + t.Fatalf("expected JSON, got %q", ct) + } +} diff --git a/backend/internal/api/overview.go b/backend/internal/api/overview.go index 7695aa8..c82e558 100644 --- a/backend/internal/api/overview.go +++ b/backend/internal/api/overview.go @@ -7,7 +7,6 @@ import ( "net/http" "sort" "strings" - "sync" "time" "github.com/percona/obs-dashboard/internal/store" @@ -294,61 +293,6 @@ func buildOverviewSnapshot(window string, now time.Time, return snap } -// ── cache (mirrors releaseArtifactsCache: TTL + singleflight) ── - -type overviewCache struct { - mu sync.Mutex - ttl time.Duration - entries map[string]overviewCacheEntry - inflight map[string]chan struct{} -} - -type overviewCacheEntry struct { - snapshot OverviewSnapshot - expires time.Time - err error -} - -func newOverviewCache(ttl time.Duration) *overviewCache { - return &overviewCache{ttl: ttl, entries: map[string]overviewCacheEntry{}, inflight: map[string]chan struct{}{}} -} - -func (c *overviewCache) Get(ctx context.Context, key string, fetch func(context.Context) (OverviewSnapshot, error)) (OverviewSnapshot, error) { - now := time.Now() - c.mu.Lock() - if entry, ok := c.entries[key]; ok && now.Before(entry.expires) { - c.mu.Unlock() - return entry.snapshot, entry.err - } - if wait, ok := c.inflight[key]; ok { - c.mu.Unlock() - select { - case <-wait: - case <-ctx.Done(): - return OverviewSnapshot{}, ctx.Err() - } - c.mu.Lock() - entry := c.entries[key] - c.mu.Unlock() - return entry.snapshot, entry.err - } - wait := make(chan struct{}) - c.inflight[key] = wait - c.mu.Unlock() - - snapshot, err := fetch(ctx) - c.mu.Lock() - expires := time.Now() - if err == nil { - expires = expires.Add(c.ttl) - } - c.entries[key] = overviewCacheEntry{snapshot: snapshot, expires: expires, err: err} - delete(c.inflight, key) - close(wait) - c.mu.Unlock() - return snapshot, err -} - // ── handler ── // mergeInstanceCounts folds unstamped (pre-migration) targets into the @@ -379,7 +323,7 @@ func mergeInstanceCounts(counts []store.InstanceTargetCounts, defaultSlug string } // overviewHandler serves GET /api/overview?window=24h|48h|7d. -func overviewHandler(db *sql.DB, defaultSlug string, cache *overviewCache) http.HandlerFunc { +func overviewHandler(db *sql.DB, defaultSlug string, cache *ttlCache[OverviewSnapshot]) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { window := r.URL.Query().Get("window") if window == "" { diff --git a/backend/internal/api/overview_test.go b/backend/internal/api/overview_test.go index 3f73fef..d480d3a 100644 --- a/backend/internal/api/overview_test.go +++ b/backend/internal/api/overview_test.go @@ -188,7 +188,7 @@ func TestOverviewHandlerWindowValidation(t *testing.T) { t.Fatal(err) } defer db.Close() - h := overviewHandler(db, "opensuse", newOverviewCache(time.Minute)) + h := overviewHandler(db, "opensuse", newTTLCache[OverviewSnapshot](time.Minute)) for _, tc := range []struct { q string @@ -225,7 +225,7 @@ func TestOverviewHandlerByInstance(t *testing.T) { } } - h := overviewHandler(db, "opensuse", newOverviewCache(time.Minute)) + h := overviewHandler(db, "opensuse", newTTLCache[OverviewSnapshot](time.Minute)) w := httptest.NewRecorder() h(w, httptest.NewRequest(http.MethodGet, "/api/overview", nil)) if w.Code != http.StatusOK { @@ -255,7 +255,7 @@ func TestOverviewHandlerCaches(t *testing.T) { t.Fatal(err) } defer db.Close() - h := overviewHandler(db, "opensuse", newOverviewCache(time.Minute)) + h := overviewHandler(db, "opensuse", newTTLCache[OverviewSnapshot](time.Minute)) w := httptest.NewRecorder() h(w, httptest.NewRequest(http.MethodGet, "/api/overview", nil)) diff --git a/backend/internal/api/server.go b/backend/internal/api/server.go index 8283142..0fd2d82 100644 --- a/backend/internal/api/server.go +++ b/backend/internal/api/server.go @@ -11,6 +11,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/percona/obs-dashboard/internal/auth" + "github.com/percona/obs-dashboard/internal/cvereport" "github.com/percona/obs-dashboard/internal/hub" "github.com/percona/obs-dashboard/internal/obs" "github.com/percona/obs-dashboard/internal/upgrade" @@ -61,7 +62,8 @@ func NewRouter(db *sql.DB, h *hub.Hub, fleet *obs.Fleet, ws Statter, telemetryEn r.Get("/healthz", healthzHandler) releaseArtifacts := newReleaseArtifactsCache(10 * time.Minute) metadataCache := newBinaryListCache(5 * time.Minute) - overview := newOverviewCache(60 * time.Second) + overview := newTTLCache[OverviewSnapshot](60 * time.Second) + cveReport := newTTLCache[cvereport.Report](30 * time.Second) r.Route("/api/products/{product}/{tier}/{version}", func(r chi.Router) { r.Get("/packages", packagesHandler(db)) @@ -97,6 +99,7 @@ func NewRouter(db *sql.DB, h *hub.Hub, fleet *obs.Fleet, ws Statter, telemetryEn r.Get("/api/overview", overviewHandler(db, fleet.Default().Slug, overview)) r.Get("/api/cve/scans", cveScansHandler(db)) r.Get("/api/cve/findings", cveFindingsHandler(db)) + r.Get("/api/cve/report", cveReportHandler(db, cveReport)) // State-changing actions: signed-in, allowlisted users only. r.Group(func(r chi.Router) { diff --git a/backend/internal/cve/owner.go b/backend/internal/cve/owner.go new file mode 100644 index 0000000..e5a2be3 --- /dev/null +++ b/backend/internal/cve/owner.go @@ -0,0 +1,60 @@ +package cve + +import ( + "path" + "regexp" + "strings" + + "github.com/percona/obs-dashboard/internal/cvereport" +) + +// rpmInfo is one RPM from trivy's package list. +type rpmInfo struct{ Name, Version, Src, Vendor string } + +var pythonPrefix = regexp.MustCompile(`python(\d+(\.\d+)?)?`) + +// normLangName reduces a Python distribution or RPM name to a comparable stem: +// lowercase, without a "percona-" prefix, "pythonX.Y" markers or separators. +func normLangName(s string) string { + s = strings.TrimPrefix(strings.ToLower(s), "percona-") + s = pythonPrefix.ReplaceAllString(s, "") + return strings.NewReplacer("-", "", "_", "", ".", "").Replace(s) +} + +// soleSource returns the one distinct source package among srcs, or "" when +// there are none or several. +func soleSource(srcs map[string]bool) string { + if len(srcs) != 1 { + return "" + } + for s := range srcs { + return s + } + return "" +} + +// goBinaryOwner returns the source package of the team's RPM that ships the +// Go binary at p, when exactly one distinct source package matches. +func goBinaryOwner(p string, rpms []rpmInfo) string { + base := path.Base(p) + srcs := map[string]bool{} + for _, r := range rpms { + if cvereport.OursVendor(r.Vendor) && (r.Name == base || r.Name == "percona-"+base) { + srcs[r.Src] = true + } + } + return soleSource(srcs) +} + +// pythonOwner returns the source package of the team's RPM that provides the +// Python package name at version, when exactly one distinct source package matches. +func pythonOwner(name, version string, rpms []rpmInfo) string { + want := normLangName(name) + srcs := map[string]bool{} + for _, r := range rpms { + if cvereport.OursVendor(r.Vendor) && r.Version == version && normLangName(r.Name) == want { + srcs[r.Src] = true + } + } + return soleSource(srcs) +} diff --git a/backend/internal/cve/owner_test.go b/backend/internal/cve/owner_test.go new file mode 100644 index 0000000..582b420 --- /dev/null +++ b/backend/internal/cve/owner_test.go @@ -0,0 +1,43 @@ +package cve + +import "testing" + +func TestNormLangName(t *testing.T) { + for in, want := range map[string]string{ + "dnspython": "dns", + "python3.12-dns": "dns", + "python-dateutil": "dateutil", + "python3.12-dateutil": "dateutil", + "systemd-python": "systemd", + "python3-ydiff": "ydiff", + "psycopg2": "psycopg2", + "python3.12-psycopg2": "psycopg2", + "percona-patroni": "patroni", + } { + if got := normLangName(in); got != want { + t.Errorf("normLangName(%q) = %q, want %q", in, got, want) + } + } +} + +func TestResolveOwnerAmbiguous(t *testing.T) { + rpms := []rpmInfo{ + {Name: "gosu", Version: "1", Src: "a", Vendor: "Percona, LLC"}, + {Name: "percona-gosu", Version: "1", Src: "b", Vendor: "Percona, LLC"}, + {Name: "python3-dns", Version: "2.9.0", Src: "a", Vendor: "Percona, LLC"}, + {Name: "python3.12-dns", Version: "2.9.0", Src: "b", Vendor: "Percona, LLC"}, + } + if got := goBinaryOwner("usr/sbin/gosu", rpms); got != "" { + t.Errorf("goBinaryOwner = %q, want empty", got) + } + if got := pythonOwner("dnspython", "2.9.0", rpms); got != "" { + t.Errorf("pythonOwner = %q, want empty", got) + } +} + +func TestResolveOwnerIgnoresBaseOS(t *testing.T) { + rpms := []rpmInfo{{Name: "gosu", Version: "1", Src: "gosu", Vendor: "Red Hat, Inc."}} + if got := goBinaryOwner("usr/sbin/gosu", rpms); got != "" { + t.Errorf("goBinaryOwner = %q, want empty", got) + } +} diff --git a/backend/internal/cve/rescan_test.go b/backend/internal/cve/rescan_test.go index b62f527..cfb1512 100644 --- a/backend/internal/cve/rescan_test.go +++ b/backend/internal/cve/rescan_test.go @@ -127,3 +127,75 @@ func TestRescanVulnerableSkipsPendingUntilScanned(t *testing.T) { time.Sleep(10 * time.Millisecond) } } + +func putFindingScan(t *testing.T, db *sql.DB, project, name, repo, class string) { + t.Helper() + if err := store.UpsertCveScan(db, project, name, model.CveScan{ + Repo: repo, Arch: "x86_64", ImageRef: "ref", ScannedAt: time.Now().UTC(), HighCount: 1, + Findings: []model.CveFinding{{ID: "CVE-1", PkgName: "x", Severity: "HIGH", Class: class}}, + }); err != nil { + t.Fatal(err) + } +} + +func TestRescanUnclassifiedQueuesOnlyUnclassified(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + + putPackage(t, db, "p", "old", model.RollupPublished, "images") + putFindingScan(t, db, "p", "old", "images", "") + putPackage(t, db, "p", "new", model.RollupPublished, "images") + putFindingScan(t, db, "p", "new", "images", "os-pkgs") + + got := make(chan cve.ScanRequest, 10) + s := cve.NewScanner(db, hub.New(), 0, cve.WithEnqueueFn(func(r cve.ScanRequest) { got <- r })) + n, err := s.RescanUnclassified() + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("queued %d images, want 1", n) + } + select { + case req := <-got: + if req.Package != "old" { + t.Errorf("unexpected request %+v", req) + } + case <-time.After(time.Second): + t.Fatal("no request enqueued") + } + select { + case req := <-got: + t.Errorf("unexpected extra request %+v", req) + case <-time.After(50 * time.Millisecond): + } +} + +func TestRescanUnclassifiedNothingToDo(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + + putPackage(t, db, "p", "new", model.RollupPublished, "images") + putFindingScan(t, db, "p", "new", "images", "os-pkgs") + + got := make(chan cve.ScanRequest, 10) + s := cve.NewScanner(db, hub.New(), 0, cve.WithEnqueueFn(func(r cve.ScanRequest) { got <- r })) + n, err := s.RescanUnclassified() + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Fatalf("queued %d images, want 0", n) + } + select { + case req := <-got: + t.Errorf("unexpected request %+v", req) + case <-time.After(50 * time.Millisecond): + } +} diff --git a/backend/internal/cve/scanner.go b/backend/internal/cve/scanner.go index eab4cb0..53f8d9f 100644 --- a/backend/internal/cve/scanner.go +++ b/backend/internal/cve/scanner.go @@ -168,6 +168,22 @@ func (s *Scanner) RescanVulnerable() (int, error) { if err != nil { return 0, err } + return s.rescanImages(imgs, "vulnerable") +} + +// RescanUnclassified queues a fresh scan of every image whose stored +// findings predate classification. A no-op once all have been rescanned. +func (s *Scanner) RescanUnclassified() (int, error) { + imgs, err := store.QueryUnclassifiedImages(s.db) + if err != nil { + return 0, err + } + return s.rescanImages(imgs, "unclassified") +} + +// rescanImages queues the published container images among imgs; what only +// labels the log line. +func (s *Scanner) rescanImages(imgs []store.VulnerableImage, what string) (int, error) { repos := map[[2]string]map[string]bool{} var order [][2]string for _, img := range imgs { @@ -225,7 +241,7 @@ func (s *Scanner) RescanVulnerable() (int, error) { } } }() - slog.Info("cve: rescan of vulnerable images queued", "images", images, "packages", len(reqs)) + slog.Info("cve: rescan queued", "what", what, "images", images, "packages", len(reqs)) return images, nil } @@ -345,6 +361,7 @@ func (s *Scanner) runTrivy(ctx context.Context, imageRef, platform, repo, arch s "--platform", "linux/"+platform, "--severity", "HIGH,CRITICAL", "--ignore-unfixed", + "--list-all-pkgs", "-f", "json", "-q", imageRef, @@ -368,9 +385,22 @@ func (s *Scanner) runTrivy(ctx context.Context, imageRef, platform, repo, arch s type trivyOutput struct { Results []struct { + Target string `json:"Target"` + Class string `json:"Class"` + Type string `json:"Type"` + Packages []struct { + ID string `json:"ID"` + Name string `json:"Name"` + Version string `json:"Version"` + SrcName string `json:"SrcName"` + Maintainer string `json:"Maintainer"` + FilePath string `json:"FilePath"` + } `json:"Packages"` Vulnerabilities []struct { VulnerabilityID string `json:"VulnerabilityID"` + PkgID string `json:"PkgID"` PkgName string `json:"PkgName"` + PkgPath string `json:"PkgPath"` InstalledVersion string `json:"InstalledVersion"` FixedVersion string `json:"FixedVersion"` Severity string `json:"Severity"` @@ -390,6 +420,23 @@ func parseTrivyOutput(data []byte, imageRef, repo, arch string) (model.CveScan, ImageRef: imageRef, ScannedAt: time.Now().UTC(), } + + // RPMs first: language findings are matched against them for ownership. + var rpms []rpmInfo + rpmByID := map[string]rpmInfo{} + for _, result := range raw.Results { + if result.Class != "os-pkgs" { + continue + } + for _, p := range result.Packages { + r := rpmInfo{Name: p.Name, Version: p.Version, Src: p.SrcName, Vendor: p.Maintainer} + rpms = append(rpms, r) + if p.ID != "" { + rpmByID[p.ID] = r + } + } + } + for _, result := range raw.Results { for _, v := range result.Vulnerabilities { f := model.CveFinding{ @@ -399,6 +446,33 @@ func parseTrivyOutput(data []byte, imageRef, repo, arch string) (model.CveScan, FixedVersion: v.FixedVersion, Severity: v.Severity, Title: v.Title, + Class: result.Class, + Type: result.Type, + } + switch { + case result.Class == "os-pkgs": + if v.PkgID == "" { + break + } + if r, ok := rpmByID[v.PkgID]; ok { + f.Src, f.Vendor = r.Src, r.Vendor + } + case result.Class == "lang-pkgs" && result.Type == "gobinary": + f.Path = result.Target + f.Owner = goBinaryOwner(f.Path, rpms) + case result.Class == "lang-pkgs": + f.Path = v.PkgPath + if f.Path == "" { + for _, p := range result.Packages { + if p.Name == v.PkgName && p.Version == v.InstalledVersion { + f.Path = p.FilePath + break + } + } + } + if result.Type == "python-pkg" { + f.Owner = pythonOwner(v.PkgName, v.InstalledVersion, rpms) + } } scan.Findings = append(scan.Findings, f) switch v.Severity { diff --git a/backend/internal/cve/scanner_test.go b/backend/internal/cve/scanner_test.go index 8c19845..859ce31 100644 --- a/backend/internal/cve/scanner_test.go +++ b/backend/internal/cve/scanner_test.go @@ -2,6 +2,8 @@ package cve_test import ( "context" + "os" + "slices" "sync" "testing" "time" @@ -213,3 +215,103 @@ func TestScannerUsesTargetInstanceURLs(t *testing.T) { t.Errorf("image ref = %q", gotRef) } } + +func TestParseTrivyOutputClassificationFields(t *testing.T) { + data, err := os.ReadFile("testdata/trivy-listall.json") + if err != nil { + t.Fatal(err) + } + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + s := cve.NewScanner(db, hub.New(), 1, cve.WithExecFn(func(ctx context.Context, name string, args ...string) ([]byte, error) { + return data, nil + })) + s.ScanNow(context.Background(), cve.ScanRequest{ + Project: "proj", Package: "mypkg", PrimaryTag: "1.0", + Targets: []model.Target{{Repo: "images", Arch: "x86_64", State: "succeeded"}}, + }) + scans, err := store.QueryCveScans(db, "proj", "mypkg") + if err != nil || len(scans) != 1 { + t.Fatalf("scans=%d err=%v", len(scans), err) + } + scan := scans[0] + if scan.CriticalCount != 2 || scan.HighCount != 6 { + t.Errorf("counts: critical=%d high=%d", scan.CriticalCount, scan.HighCount) + } + byID := map[string]model.CveFinding{} + for _, f := range scan.Findings { + byID[f.ID] = f + } + py := "usr/lib/python3.12/site-packages/dnspython-2.9.0.dist-info/METADATA" + want := []struct{ id, class, typ, path, src, vendor, owner string }{ + {"CVE-2026-0001", "os-pkgs", "redhat", "", "krb5", "Red Hat, Inc.", ""}, + {"CVE-2026-0002", "os-pkgs", "redhat", "", "percona-pgbouncer", "Percona, LLC", ""}, + {"CVE-2026-0003", "os-pkgs", "redhat", "", "", "", ""}, + {"CVE-2026-0004", "lang-pkgs", "gobinary", "usr/sbin/gosu", "", "", "gosu"}, + {"CVE-2026-0005", "lang-pkgs", "gobinary", "usr/sbin/gosu", "", "", "gosu"}, + {"CVE-2026-0006", "lang-pkgs", "gobinary", "usr/local/bin/mystery", "", "", ""}, + {"CVE-2026-0007", "lang-pkgs", "python-pkg", py, "", "", "python3.12-dns"}, + {"CVE-2026-0008", "lang-pkgs", "python-pkg", "opt/app/requests-2.0.0.dist-info/METADATA", "", "", ""}, + } + for _, w := range want { + f, ok := byID[w.id] + if !ok { + t.Errorf("%s missing", w.id) + continue + } + got := [6]string{f.Class, f.Type, f.Path, f.Src, f.Vendor, f.Owner} + exp := [6]string{w.class, w.typ, w.path, w.src, w.vendor, w.owner} + if got != exp { + t.Errorf("%s: got %q want %q", w.id, got, exp) + } + } +} + +func TestRunTrivyListsAllPackages(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + var args []string + s := cve.NewScanner(db, hub.New(), 1, cve.WithExecFn(func(ctx context.Context, name string, a ...string) ([]byte, error) { + args = a + return []byte(trivyCleanJSON), nil + })) + s.ScanNow(context.Background(), cve.ScanRequest{ + Project: "proj", Package: "mypkg", PrimaryTag: "1.0", + Targets: []model.Target{{Repo: "images", Arch: "x86_64", State: "succeeded"}}, + }) + if !slices.Contains(args, "--list-all-pkgs") { + t.Errorf("args missing --list-all-pkgs: %v", args) + } +} + +func TestParseTrivyOutputEmptyPkgIDStaysUnclassified(t *testing.T) { + data := []byte(`{"Results":[{"Target":"img","Class":"os-pkgs","Type":"redhat", +"Packages":[{"Name":"noid","Version":"1","SrcName":"noid-src","Maintainer":"Percona, LLC"}], +"Vulnerabilities":[{"VulnerabilityID":"CVE-2026-9000","PkgName":"other","InstalledVersion":"1","FixedVersion":"2","Severity":"HIGH","Title":"t"}]}]}`) + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + s := cve.NewScanner(db, hub.New(), 1, cve.WithExecFn(func(ctx context.Context, name string, args ...string) ([]byte, error) { + return data, nil + })) + s.ScanNow(context.Background(), cve.ScanRequest{ + Project: "proj", Package: "mypkg", PrimaryTag: "1.0", + Targets: []model.Target{{Repo: "images", Arch: "x86_64", State: "succeeded"}}, + }) + scans, err := store.QueryCveScans(db, "proj", "mypkg") + if err != nil || len(scans) != 1 || len(scans[0].Findings) != 1 { + t.Fatalf("scans=%v err=%v", scans, err) + } + f := scans[0].Findings[0] + if f.Vendor != "" || f.Src != "" { + t.Errorf("vendor=%q src=%q, want both empty", f.Vendor, f.Src) + } +} diff --git a/backend/internal/cve/scheduler.go b/backend/internal/cve/scheduler.go index f55ea7f..c3a7a44 100644 --- a/backend/internal/cve/scheduler.go +++ b/backend/internal/cve/scheduler.go @@ -21,6 +21,9 @@ func NewNightlyScheduler(db *sql.DB, scanner *Scanner) *NightlyScheduler { func (n *NightlyScheduler) Run(ctx context.Context) { n.enqueueUnscanned(ctx) + if _, err := n.scanner.RescanUnclassified(); err != nil { + slog.Warn("cve scheduler: rescan unclassified", "err", err) + } timer := time.NewTimer(time.Until(nextNightlyRun())) defer timer.Stop() diff --git a/backend/internal/cve/scheduler_test.go b/backend/internal/cve/scheduler_test.go index 939941c..d25a36f 100644 --- a/backend/internal/cve/scheduler_test.go +++ b/backend/internal/cve/scheduler_test.go @@ -101,3 +101,32 @@ func TestSchedulerSkipsAlreadyScanned(t *testing.T) { t.Errorf("expected already-scanned package to be skipped, but got %d enqueued", len(enqueued)) } } + +func TestRunQueuesUnclassifiedAtStartup(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + + putPackage(t, db, "isv:percona", "old", model.RollupPublished, "images") + putFindingScan(t, db, "isv:percona", "old", "images", "") + + enqueued := make(chan cve.ScanRequest, 10) + scanner := cve.NewScanner(db, hub.New(), 0, cve.WithEnqueueFn(func(req cve.ScanRequest) { + enqueued <- req + })) + sched := cve.NewNightlyScheduler(db, scanner) + + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + go sched.Run(ctx) + <-ctx.Done() + + if len(enqueued) != 1 { + t.Fatalf("enqueued %d requests, want 1", len(enqueued)) + } + if req := <-enqueued; req.Package != "old" { + t.Errorf("unexpected package %q", req.Package) + } +} diff --git a/backend/internal/cve/testdata/trivy-listall.json b/backend/internal/cve/testdata/trivy-listall.json new file mode 100644 index 0000000..c8c9100 --- /dev/null +++ b/backend/internal/cve/testdata/trivy-listall.json @@ -0,0 +1,53 @@ +{ + "SchemaVersion": 2, + "Results": [ + { + "Target": "registry.example/pg (redhat 9.8)", + "Class": "os-pkgs", + "Type": "redhat", + "Packages": [ + {"ID": "krb5-libs@1.21.1-10.el9_8.1.x86_64", "Name": "krb5-libs", "Version": "1.21.1", "SrcName": "krb5", "Maintainer": "Red Hat, Inc."}, + {"ID": "percona-pgbouncer@1.24.0-1.el9.x86_64", "Name": "percona-pgbouncer", "Version": "1.24.0", "SrcName": "percona-pgbouncer", "Maintainer": "Percona, LLC"}, + {"ID": "gosu@1.17-1.el9.x86_64", "Name": "gosu", "Version": "1.17", "SrcName": "gosu", "Maintainer": "obs://obs.pg.labs.percona.com/isv:percona:ppg:common:deps"}, + {"ID": "python3.12-dns@2.9.0-1.el9.noarch", "Name": "python3.12-dns", "Version": "2.9.0", "SrcName": "python3.12-dns", "Maintainer": "Percona, LLC"}, + {"ID": "percona-patroni@4.1.5-6.3.el9.x86_64", "Name": "percona-patroni", "Version": "4.1.5", "SrcName": "percona-patroni", "Maintainer": "Percona, LLC"} + ], + "Vulnerabilities": [ + {"VulnerabilityID": "CVE-2026-0001", "PkgID": "krb5-libs@1.21.1-10.el9_8.1.x86_64", "PkgName": "krb5-libs", "InstalledVersion": "1.21.1-10.el9_8.1", "FixedVersion": "1.21.1-10.el9_9.2", "Severity": "HIGH", "Title": "krb5 flaw"}, + {"VulnerabilityID": "CVE-2026-0002", "PkgID": "percona-pgbouncer@1.24.0-1.el9.x86_64", "PkgName": "percona-pgbouncer", "InstalledVersion": "1.24.0-1.el9", "FixedVersion": "1.24.1-1.el9", "Severity": "HIGH", "Title": "pgbouncer flaw"}, + {"VulnerabilityID": "CVE-2026-0003", "PkgID": "ghost@1-1.x86_64", "PkgName": "ghost", "InstalledVersion": "1-1", "FixedVersion": "1-2", "Severity": "CRITICAL", "Title": "ghost flaw"} + ] + }, + { + "Target": "usr/sbin/gosu", + "Class": "lang-pkgs", + "Type": "gobinary", + "Vulnerabilities": [ + {"VulnerabilityID": "CVE-2026-0004", "PkgName": "stdlib", "InstalledVersion": "v1.26.3", "FixedVersion": "1.25.11, 1.26.4", "Severity": "CRITICAL", "Title": "go stdlib flaw"}, + {"VulnerabilityID": "CVE-2026-0005", "PkgName": "golang.org/x/net", "InstalledVersion": "v0.54.0", "FixedVersion": "0.55.0", "Severity": "HIGH", "Title": "x/net flaw"} + ] + }, + { + "Target": "usr/local/bin/mystery", + "Class": "lang-pkgs", + "Type": "gobinary", + "Vulnerabilities": [ + {"VulnerabilityID": "CVE-2026-0006", "PkgName": "golang.org/x/net", "InstalledVersion": "v0.54.0", "FixedVersion": "0.55.0", "Severity": "HIGH", "Title": "x/net flaw"} + ] + }, + { + "Target": "Python", + "Class": "lang-pkgs", + "Type": "python-pkg", + "Packages": [ + {"Name": "dnspython", "Version": "2.9.0", "FilePath": "usr/lib/python3.12/site-packages/dnspython-2.9.0.dist-info/METADATA"}, + {"Name": "patroni", "Version": "4.1.5", "FilePath": "usr/lib/python3.12/site-packages/patroni-4.1.5.dist-info/METADATA"}, + {"Name": "requests", "Version": "2.0.0", "FilePath": "opt/app/requests-2.0.0.dist-info/METADATA"} + ], + "Vulnerabilities": [ + {"VulnerabilityID": "CVE-2026-0007", "PkgName": "dnspython", "PkgPath": "usr/lib/python3.12/site-packages/dnspython-2.9.0.dist-info/METADATA", "InstalledVersion": "2.9.0", "FixedVersion": "2.9.2", "Severity": "HIGH", "Title": "dnspython flaw"}, + {"VulnerabilityID": "CVE-2026-0008", "PkgName": "requests", "PkgPath": "opt/app/requests-2.0.0.dist-info/METADATA", "InstalledVersion": "2.0.0", "FixedVersion": "2.32.0", "Severity": "HIGH", "Title": "requests flaw"} + ] + } + ] +} diff --git a/backend/internal/cvereport/classify.go b/backend/internal/cvereport/classify.go new file mode 100644 index 0000000..93580b4 --- /dev/null +++ b/backend/internal/cvereport/classify.go @@ -0,0 +1,80 @@ +// Package cvereport turns stored CVE scans into the rows shown in the CVEs tab. +package cvereport + +import ( + "strings" + + "github.com/percona/obs-dashboard/internal/model" +) + +// Lists a row can belong to. +const ( + ListOurs = "ours" + ListBaseOS = "base_os" + ListUnclassified = "unclassified" +) + +// Kinds of row. +const ( + KindGoRuntime = "go_runtime" + KindBundled = "bundled_library" + KindOBSPackage = "obs_package" + KindBaseOS = "base_os" + KindUnclassified = "unclassified" +) + +const ( + classLangPkgs = "lang-pkgs" + typeGoBinary = "gobinary" + goStdlib = "stdlib" + goRuntimePkg = "golang" +) + +// OursVendor reports whether an RPM vendor is the team's: it starts with +// Percona or obs://. +func OursVendor(vendor string) bool { + return strings.HasPrefix(vendor, "Percona") || strings.HasPrefix(vendor, "obs://") +} + +// Classify places one finding. name is the package to bump (or the file +// path / package name when no owner is known). Vendor rule: Percona or obs:// +// is ours; Red Hat, Inc. or Fedora Project is base OS; anything else is +// unclassified. +func Classify(f model.CveFinding) (list, name, kind string) { + if f.Class == classLangPkgs { + return classifyLang(f) + } + name = f.Src + if name == "" { + name = f.PkgName + } + if f.Class != "os-pkgs" { + return ListUnclassified, name, KindUnclassified + } + switch { + case OursVendor(f.Vendor): + return ListOurs, name, KindOBSPackage + case f.Vendor == "Red Hat, Inc." || f.Vendor == "Fedora Project": + return ListBaseOS, name, KindBaseOS + } + return ListUnclassified, name, KindUnclassified +} + +func classifyLang(f model.CveFinding) (string, string, string) { + if f.Type == typeGoBinary && f.PkgName == goStdlib { + return ListOurs, goRuntimePkg, KindGoRuntime + } + switch { + case f.Owner != "": + return ListOurs, f.Owner, KindBundled + case f.Type == typeGoBinary: + return ListOurs, f.Path, KindBundled + } + if f.Path == "" { + return ListOurs, f.PkgName, KindBundled + } + return ListOurs, f.PkgName + " (" + f.Path + ")", KindBundled +} + +// RowKey is "|". +func RowKey(list, name string) string { return list + "|" + name } diff --git a/backend/internal/cvereport/classify_test.go b/backend/internal/cvereport/classify_test.go new file mode 100644 index 0000000..81d00b3 --- /dev/null +++ b/backend/internal/cvereport/classify_test.go @@ -0,0 +1,53 @@ +package cvereport + +import ( + "testing" + + "github.com/percona/obs-dashboard/internal/model" +) + +func TestClassify(t *testing.T) { + tests := []struct { + name string + f model.CveFinding + wantList, wantName string + wantKind string + }{ + {"percona vendor", model.CveFinding{Class: "os-pkgs", Vendor: "Percona, LLC", Src: "percona-pgbouncer"}, ListOurs, "percona-pgbouncer", KindOBSPackage}, + {"obs vendor", model.CveFinding{Class: "os-pkgs", Vendor: "obs://obs.pg.labs.percona.com/isv:percona:ppg:common:deps", Src: "curl"}, ListOurs, "curl", KindOBSPackage}, + {"red hat", model.CveFinding{Class: "os-pkgs", Vendor: "Red Hat, Inc.", Src: "openssl", PkgName: "openssl-libs"}, ListBaseOS, "openssl", KindBaseOS}, + {"fedora", model.CveFinding{Class: "os-pkgs", Vendor: "Fedora Project", Src: "x"}, ListBaseOS, "x", KindBaseOS}, + {"unknown vendor", model.CveFinding{Class: "os-pkgs", Vendor: "Acme", Src: "foo"}, ListUnclassified, "foo", KindUnclassified}, + {"no vendor no src", model.CveFinding{Class: "os-pkgs", PkgName: "ghost"}, ListUnclassified, "ghost", KindUnclassified}, + {"old scan", model.CveFinding{PkgName: "openssl"}, ListUnclassified, "openssl", KindUnclassified}, + {"known vendor empty src", model.CveFinding{Class: "os-pkgs", Vendor: "Red Hat, Inc.", PkgName: "glibc"}, ListBaseOS, "glibc", KindBaseOS}, + {"go stdlib", model.CveFinding{Class: "lang-pkgs", Type: "gobinary", PkgName: "stdlib", Path: "usr/bin/etcd", Owner: "etcd"}, ListOurs, "golang", KindGoRuntime}, + {"go library owned", model.CveFinding{Class: "lang-pkgs", Type: "gobinary", PkgName: "golang.org/x/net", Path: "usr/bin/etcd", Owner: "etcd"}, ListOurs, "etcd", KindBundled}, + {"go library unowned", model.CveFinding{Class: "lang-pkgs", Type: "gobinary", PkgName: "golang.org/x/net", Path: "usr/local/bin/mystery"}, ListOurs, "usr/local/bin/mystery", KindBundled}, + {"python owned", model.CveFinding{Class: "lang-pkgs", Type: "python-pkg", PkgName: "dnspython", Path: "usr/lib/python3.12/site-packages/dnspython-2.0.dist-info/METADATA", Owner: "python3.12-dns"}, ListOurs, "python3.12-dns", KindBundled}, + {"python unowned", model.CveFinding{Class: "lang-pkgs", Type: "python-pkg", PkgName: "requests", Path: "opt/app/requests-2.0.0.dist-info/METADATA"}, ListOurs, "requests (opt/app/requests-2.0.0.dist-info/METADATA)", KindBundled}, + {"python unowned no path", model.CveFinding{Class: "lang-pkgs", Type: "python-pkg", PkgName: "requests"}, ListOurs, "requests", KindBundled}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + list, name, kind := Classify(tt.f) + if list != tt.wantList || name != tt.wantName || kind != tt.wantKind { + t.Errorf("got (%q,%q,%q), want (%q,%q,%q)", list, name, kind, tt.wantList, tt.wantName, tt.wantKind) + } + }) + } +} + +func TestRowKey(t *testing.T) { + if got := RowKey(ListOurs, "etcd"); got != "ours|etcd" { + t.Errorf("got %q", got) + } +} + +func TestOursVendor(t *testing.T) { + for v, want := range map[string]bool{"Percona, LLC": true, "obs://x/y": true, "Red Hat, Inc.": false, "": false} { + if got := OursVendor(v); got != want { + t.Errorf("OursVendor(%q) = %v", v, got) + } + } +} diff --git a/backend/internal/cvereport/released.go b/backend/internal/cvereport/released.go new file mode 100644 index 0000000..5757e46 --- /dev/null +++ b/backend/internal/cvereport/released.go @@ -0,0 +1,207 @@ +package cvereport + +import ( + "sort" + "strings" + + "github.com/percona/obs-dashboard/internal/model" +) + +// Released status of one CVE against the current staging image. +const ( + StatusFixed = "fixed" + StatusOpen = "open" + StatusNoStaging = "no_staging" +) + +const ( + releasesPrefix = "ppg:releases" + stagingPrefix = "ppg:staging" +) + +type ReleasedCVE struct { + ID string `json:"id"` + Pkg string `json:"pkg"` + Installed string `json:"installed"` + Fixed string `json:"fixed"` + Severity string `json:"severity"` + Title string `json:"title"` + Status string `json:"status"` // "fixed" | "open" | "no_staging" + StagingRowKey string `json:"staging_row_key,omitempty"` // when Status == "open" +} + +type ReleasedImage struct { + Project string `json:"project"` + Package string `json:"package"` + Repo string `json:"repo"` + Version string `json:"version"` + StagingProject string `json:"staging_project"` + StagingVersion string `json:"staging_version,omitempty"` + Total int `json:"total"` + FixedInStaging int `json:"fixed_in_staging"` + CVEs []ReleasedCVE `json:"cves"` +} + +type cveKey struct{ id, pkg string } + +// stagingProjectOf maps a released project to its staging counterpart. +func stagingProjectOf(project string) string { + if strings.HasPrefix(project, releasesPrefix) { + return stagingPrefix + strings.TrimPrefix(project, releasesPrefix) + } + return project +} + +// BuildReleased pairs released scans with staging scans. versions maps +// "/" to the package version. +func BuildReleased(released, staging []model.ImageCveScan, versions map[string]string) []ReleasedImage { + // staging findings by image, arch, then (CVE id, pkg). + stg := map[imageKey]map[string]map[cveKey]model.CveFinding{} + for _, sc := range staging { + ik := imageKey{sc.Project, sc.Package, sc.Repo} + if stg[ik] == nil { + stg[ik] = map[string]map[cveKey]model.CveFinding{} + } + m := stg[ik][sc.Arch] + if m == nil { + m = map[cveKey]model.CveFinding{} + stg[ik][sc.Arch] = m + } + for _, f := range sc.Findings { + k := cveKey{f.ID, f.PkgName} + if _, ok := m[k]; !ok { + m[k] = f + } + } + } + + // released findings by image, arch. + rel := map[imageKey]map[string][]model.CveFinding{} + for _, sc := range released { + if len(sc.Findings) == 0 { + continue + } + ik := imageKey{sc.Project, sc.Package, sc.Repo} + if rel[ik] == nil { + rel[ik] = map[string][]model.CveFinding{} + } + rel[ik][sc.Arch] = append(rel[ik][sc.Arch], sc.Findings...) + } + + out := make([]ReleasedImage, 0, len(rel)) + for ik, byArch := range rel { + arches := make([]string, 0, len(byArch)) + for ar := range byArch { + arches = append(arches, ar) + } + sort.Strings(arches) + + stgIk := imageKey{stagingProjectOf(ik.project), ik.pkg, ik.repo} + counterparts := stg[stgIk] + im := ReleasedImage{ + Project: ik.project, + Package: ik.pkg, + Repo: ik.repo, + Version: versions[ik.project+"/"+ik.pkg], + StagingProject: stgIk.project, + CVEs: []ReleasedCVE{}, + } + + cves := map[cveKey]*ReleasedCVE{} + var order []cveKey + for _, ar := range arches { + for _, f := range byArch[ar] { + k := cveKey{f.ID, f.PkgName} + if cves[k] != nil { + continue + } + cves[k] = &ReleasedCVE{ID: f.ID, Pkg: f.PkgName, Installed: f.InstalledVersion, + Fixed: f.FixedVersion, Severity: f.Severity, Title: f.Title} + order = append(order, k) + } + } + + haveCounterpart := false + for _, ar := range arches { + if _, ok := counterparts[ar]; ok { + haveCounterpart = true + break + } + } + if haveCounterpart { + im.StagingVersion = versions[stgIk.project+"/"+stgIk.pkg] + } + + for _, k := range order { + c := cves[k] + switch { + case !haveCounterpart: + c.Status = StatusNoStaging + default: + c.Status = StatusFixed + for _, ar := range arches { + if f, ok := counterparts[ar][k]; ok { + list, name, _ := Classify(f) + c.Status = StatusOpen + c.StagingRowKey = RowKey(list, name) + break + } + } + } + if c.Status == StatusFixed { + im.FixedInStaging++ + } + im.CVEs = append(im.CVEs, *c) + } + im.Total = len(im.CVEs) + sortReleasedCVEs(im.CVEs) + out = append(out, im) + } + + sort.Slice(out, func(i, j int) bool { + x, y := out[i], out[j] + if x.Project != y.Project { + return x.Project < y.Project + } + if x.Package != y.Package { + return x.Package < y.Package + } + return x.Repo < y.Repo + }) + return out +} + +func statusRank(s string) int { + switch s { + case StatusOpen: + return 0 + case StatusNoStaging: + return 1 + } + return 2 +} + +func severityRank(s string) int { + if s == "CRITICAL" { + return 0 + } + return 1 +} + +// sortReleasedCVEs orders open, no_staging, fixed; then CRITICAL before HIGH; +// then by id and package. +func sortReleasedCVEs(cs []ReleasedCVE) { + sort.Slice(cs, func(i, j int) bool { + x, y := cs[i], cs[j] + if a, b := statusRank(x.Status), statusRank(y.Status); a != b { + return a < b + } + if a, b := severityRank(x.Severity), severityRank(y.Severity); a != b { + return a < b + } + if x.ID != y.ID { + return x.ID < y.ID + } + return x.Pkg < y.Pkg + }) +} diff --git a/backend/internal/cvereport/released_test.go b/backend/internal/cvereport/released_test.go new file mode 100644 index 0000000..b9c633e --- /dev/null +++ b/backend/internal/cvereport/released_test.go @@ -0,0 +1,174 @@ +package cvereport + +import ( + "encoding/json" + "testing" + "time" + + "github.com/percona/obs-dashboard/internal/model" +) + +const ( + relProj = "ppg:releases:18:containers" + stgProj = "ppg:staging:18:containers" +) + +func relFindings() []model.CveFinding { + return []model.CveFinding{ + {ID: "CVE-A", PkgName: "openssl", InstalledVersion: "1", FixedVersion: "2", Severity: "HIGH", Title: "a", + Class: "os-pkgs", Vendor: "Red Hat, Inc."}, + {ID: "CVE-B", PkgName: "stdlib", InstalledVersion: "1.24", FixedVersion: "1.25", Severity: "CRITICAL", Title: "b", + Class: "lang-pkgs", Type: "gobinary", Path: "usr/bin/etcd", Owner: "etcd"}, + {ID: "CVE-C", PkgName: "gnutls", InstalledVersion: "1", FixedVersion: "2", Severity: "HIGH", Title: "c", + Class: "os-pkgs", Vendor: "Red Hat, Inc."}, + } +} + +func relScans() []model.ImageCveScan { + return []model.ImageCveScan{ + scan(relProj, "pg", "ubi9", "x86_64", relFindings()...), + scan(relProj, "pg", "ubi9", "aarch64", relFindings()...), + } +} + +var testVersions = map[string]string{ + relProj + "/pg": "18.4-1-1.1", + stgProj + "/pg": "18.4-1-2.34", +} + +func statusOf(im ReleasedImage) map[string]ReleasedCVE { + m := map[string]ReleasedCVE{} + for _, c := range im.CVEs { + m[c.ID] = c + } + return m +} + +func TestReleasedFixedAndOpen(t *testing.T) { + b := relFindings()[1] + got := BuildReleased(relScans(), []model.ImageCveScan{ + scan(stgProj, "pg", "ubi9", "x86_64", b), + scan(stgProj, "pg", "ubi9", "aarch64", b), + }, testVersions) + if len(got) != 1 { + t.Fatalf("images = %d", len(got)) + } + im := got[0] + if im.Total != 3 || im.FixedInStaging != 2 || im.StagingProject != stgProj || + im.Version != "18.4-1-1.1" || im.StagingVersion != "18.4-1-2.34" { + t.Fatalf("image = %+v", im) + } + m := statusOf(im) + if m["CVE-A"].Status != "fixed" || m["CVE-C"].Status != "fixed" { + t.Errorf("A/C = %+v %+v", m["CVE-A"], m["CVE-C"]) + } + if m["CVE-B"].Status != "open" || m["CVE-B"].StagingRowKey != "ours|golang" { + t.Errorf("B = %+v", m["CVE-B"]) + } + if m["CVE-A"].StagingRowKey != "" { + t.Errorf("fixed CVE carries a row key: %+v", m["CVE-A"]) + } +} + +func TestReleasedOpenOnOneArch(t *testing.T) { + a := relFindings()[0] + got := BuildReleased(relScans(), []model.ImageCveScan{ + scan(stgProj, "pg", "ubi9", "x86_64"), + scan(stgProj, "pg", "ubi9", "aarch64", a), + }, testVersions) + m := statusOf(got[0]) + if m["CVE-A"].Status != "open" || m["CVE-A"].StagingRowKey != "base_os|openssl" { + t.Errorf("A = %+v", m["CVE-A"]) + } + if m["CVE-C"].Status != "fixed" { + t.Errorf("C = %+v", m["CVE-C"]) + } +} + +func TestReleasedPartialCounterpart(t *testing.T) { + got := BuildReleased(relScans(), []model.ImageCveScan{ + scan(stgProj, "pg", "ubi9", "x86_64"), + }, testVersions) + im := got[0] + if im.FixedInStaging != 3 { + t.Fatalf("fixed = %d", im.FixedInStaging) + } + for _, c := range im.CVEs { + if c.Status != "fixed" { + t.Errorf("%s = %s", c.ID, c.Status) + } + } +} + +func TestReleasedNoStaging(t *testing.T) { + got := BuildReleased(relScans(), nil, testVersions) + im := got[0] + if im.FixedInStaging != 0 || im.StagingVersion != "" || im.Total != 3 || im.StagingProject != stgProj { + t.Fatalf("image = %+v", im) + } + for _, c := range im.CVEs { + if c.Status != "no_staging" { + t.Errorf("%s = %s", c.ID, c.Status) + } + } +} + +func TestReleasedSkipsCleanAndSorts(t *testing.T) { + if got := BuildReleased(nil, nil, nil); got == nil || len(got) != 0 { + t.Fatalf("empty = %#v", got) + } + f := relFindings() + released := []model.ImageCveScan{ + scan("ppg:releases:18:containers", "zz", "ubi9", "x86_64", f[0]), + scan("ppg:releases:18:containers", "clean", "ubi9", "x86_64"), + scan("ppg:releases:17:containers", "pg", "ubi9", "x86_64", f...), + scan("ppg:releases:18:containers", "pg", "ubi9", "x86_64", f[0]), + scan("ppg:releases:18:containers", "pg", "ubi8", "x86_64", f[0]), + } + staging := []model.ImageCveScan{ + scan("ppg:staging:17:containers", "pg", "ubi9", "x86_64", f[1], f[0]), + } + got := BuildReleased(released, staging, nil) + var order []string + for _, im := range got { + order = append(order, im.Project+"/"+im.Package+"/"+im.Repo) + } + want := []string{ + "ppg:releases:17:containers/pg/ubi9", + "ppg:releases:18:containers/pg/ubi8", + "ppg:releases:18:containers/pg/ubi9", + "ppg:releases:18:containers/zz/ubi9", + } + if len(order) != len(want) { + t.Fatalf("order = %v", order) + } + for i := range want { + if order[i] != want[i] { + t.Fatalf("order = %v", order) + } + } + // open first, then no_staging, then fixed; CRITICAL before HIGH; then id. + var ids []string + for _, c := range got[0].CVEs { + ids = append(ids, c.ID+":"+c.Status) + } + wantIDs := []string{"CVE-B:open", "CVE-A:open", "CVE-C:fixed"} + if len(ids) != 3 || ids[0] != wantIDs[0] || ids[1] != wantIDs[1] || ids[2] != wantIDs[2] { + t.Fatalf("cves = %v", ids) + } +} + +func TestBuildReport(t *testing.T) { + now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.FixedZone("x", 3600)) + b := relFindings()[1] + r := Build([]model.ImageCveScan{scan(stgProj, "pg", "ubi9", "x86_64", b)}, relScans(), testVersions, now) + if r.GeneratedAt != "2026-11-17T11:00:00Z" { + t.Errorf("generated_at = %q", r.GeneratedAt) + } + if len(r.Staging.Ours) != 1 || len(r.Released) != 1 { + t.Errorf("report = %+v", r) + } + if _, err := json.Marshal(r); err != nil { + t.Fatal(err) + } +} diff --git a/backend/internal/cvereport/report.go b/backend/internal/cvereport/report.go new file mode 100644 index 0000000..2c45fab --- /dev/null +++ b/backend/internal/cvereport/report.go @@ -0,0 +1,22 @@ +package cvereport + +import ( + "time" + + "github.com/percona/obs-dashboard/internal/model" +) + +type Report struct { + GeneratedAt string `json:"generated_at"` + Staging Staging `json:"staging"` + Released []ReleasedImage `json:"released"` +} + +// Build assembles the whole report. Both scan slices include clean scans. +func Build(staging, released []model.ImageCveScan, versions map[string]string, now time.Time) Report { + return Report{ + GeneratedAt: now.UTC().Format(time.RFC3339), + Staging: BuildStaging(staging), + Released: BuildReleased(released, staging, versions), + } +} diff --git a/backend/internal/cvereport/staging.go b/backend/internal/cvereport/staging.go new file mode 100644 index 0000000..42e426e --- /dev/null +++ b/backend/internal/cvereport/staging.go @@ -0,0 +1,191 @@ +package cvereport + +import ( + "sort" + + "github.com/percona/obs-dashboard/internal/model" +) + +type Fix struct { + Pkg string `json:"pkg"` + Installed string `json:"installed"` + Fixed string `json:"fixed"` +} + +type Entry struct { + ID string `json:"id"` + Pkg string `json:"pkg"` + Path string `json:"path,omitempty"` + Severity string `json:"severity"` + Title string `json:"title"` + SeenKey string `json:"seen_key"` // "||" +} + +type ImageRef struct { + Project string `json:"project"` + Package string `json:"package"` + Repo string `json:"repo"` + Arches []string `json:"arches"` +} + +type Row struct { + Key string `json:"key"` + Name string `json:"name"` + Kind string `json:"kind"` + Vendor string `json:"vendor,omitempty"` // unclassified RPMs only + Worst string `json:"worst"` // "CRITICAL" | "HIGH" + CVEs int `json:"cves"` // distinct CVE ids + Fixes []Fix `json:"fixes"` + Entries []Entry `json:"entries"` + Images []ImageRef `json:"images"` +} + +type Staging struct { + Ours []Row `json:"ours"` + BaseOS []Row `json:"base_os"` + Unclassified []Row `json:"unclassified"` + CVEs int `json:"cves"` // distinct CVE ids across all rows + Images int `json:"images"` // distinct images with at least one finding +} + +type imageKey struct{ project, pkg, repo string } + +// rowAcc accumulates one row while scans are walked. +type rowAcc struct { + list string + row Row + cves map[string]bool + fixes map[Fix]bool + entries map[string]Entry + arches map[imageKey]map[string]bool +} + +// BuildStaging aggregates staging scans into one row per package to bump, +// across images and arches. +func BuildStaging(scans []model.ImageCveScan) Staging { + accs := map[string]*rowAcc{} + allCVEs := map[string]bool{} + allImages := map[imageKey]bool{} + + for _, sc := range scans { + ik := imageKey{sc.Project, sc.Package, sc.Repo} + for _, f := range sc.Findings { + list, name, kind := Classify(f) + key := RowKey(list, name) + a := accs[key] + if a == nil { + a = &rowAcc{ + list: list, + row: Row{Key: key, Name: name, Kind: kind, Worst: "HIGH"}, + cves: map[string]bool{}, + fixes: map[Fix]bool{}, + entries: map[string]Entry{}, + arches: map[imageKey]map[string]bool{}, + } + accs[key] = a + } + if f.Severity == "CRITICAL" { + a.row.Worst = "CRITICAL" + } + if list == ListUnclassified && a.row.Vendor == "" && f.Class == "os-pkgs" { + a.row.Vendor = f.Vendor + } + a.cves[f.ID] = true + a.fixes[Fix{f.PkgName, f.InstalledVersion, f.FixedVersion}] = true + sk := f.ID + "|" + f.PkgName + "|" + f.Path + if _, ok := a.entries[sk]; !ok { + a.entries[sk] = Entry{ID: f.ID, Pkg: f.PkgName, Path: f.Path, Severity: f.Severity, Title: f.Title, SeenKey: sk} + } + if a.arches[ik] == nil { + a.arches[ik] = map[string]bool{} + } + a.arches[ik][sc.Arch] = true + allCVEs[f.ID] = true + allImages[ik] = true + } + } + + out := Staging{Ours: []Row{}, BaseOS: []Row{}, Unclassified: []Row{}, CVEs: len(allCVEs), Images: len(allImages)} + for _, a := range accs { + r := a.finish() + switch a.list { + case ListOurs: + out.Ours = append(out.Ours, r) + case ListBaseOS: + out.BaseOS = append(out.BaseOS, r) + default: + out.Unclassified = append(out.Unclassified, r) + } + } + sortRows(out.Ours) + sortRows(out.BaseOS) + sortRows(out.Unclassified) + return out +} + +func (a *rowAcc) finish() Row { + r := a.row + r.CVEs = len(a.cves) + r.Fixes = make([]Fix, 0, len(a.fixes)) + for f := range a.fixes { + r.Fixes = append(r.Fixes, f) + } + sort.Slice(r.Fixes, func(i, j int) bool { + x, y := r.Fixes[i], r.Fixes[j] + if x.Pkg != y.Pkg { + return x.Pkg < y.Pkg + } + if x.Installed != y.Installed { + return x.Installed < y.Installed + } + return x.Fixed < y.Fixed + }) + r.Entries = make([]Entry, 0, len(a.entries)) + for _, e := range a.entries { + r.Entries = append(r.Entries, e) + } + sort.Slice(r.Entries, func(i, j int) bool { + x, y := r.Entries[i], r.Entries[j] + if x.ID != y.ID { + return x.ID < y.ID + } + if x.Pkg != y.Pkg { + return x.Pkg < y.Pkg + } + return x.Path < y.Path + }) + r.Images = make([]ImageRef, 0, len(a.arches)) + for ik, set := range a.arches { + arches := make([]string, 0, len(set)) + for ar := range set { + arches = append(arches, ar) + } + sort.Strings(arches) + r.Images = append(r.Images, ImageRef{Project: ik.project, Package: ik.pkg, Repo: ik.repo, Arches: arches}) + } + sort.Slice(r.Images, func(i, j int) bool { + x, y := r.Images[i], r.Images[j] + if x.Project != y.Project { + return x.Project < y.Project + } + if x.Package != y.Package { + return x.Package < y.Package + } + return x.Repo < y.Repo + }) + return r +} + +// sortRows orders CRITICAL before HIGH, then more images first, then by name. +func sortRows(rows []Row) { + sort.Slice(rows, func(i, j int) bool { + a, b := rows[i], rows[j] + if (a.Worst == "CRITICAL") != (b.Worst == "CRITICAL") { + return a.Worst == "CRITICAL" + } + if len(a.Images) != len(b.Images) { + return len(a.Images) > len(b.Images) + } + return a.Name < b.Name + }) +} diff --git a/backend/internal/cvereport/staging_test.go b/backend/internal/cvereport/staging_test.go new file mode 100644 index 0000000..e4aac91 --- /dev/null +++ b/backend/internal/cvereport/staging_test.go @@ -0,0 +1,110 @@ +package cvereport + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/percona/obs-dashboard/internal/model" +) + +func scan(project, pkg, repo, arch string, fs ...model.CveFinding) model.ImageCveScan { + return model.ImageCveScan{Project: project, Package: pkg, CveScan: model.CveScan{Repo: repo, Arch: arch, Findings: fs}} +} + +func rhel(id, pkg, sev string) model.CveFinding { + return model.CveFinding{ID: id, PkgName: pkg, InstalledVersion: "1", FixedVersion: "2", Severity: sev, Title: "t", + Class: "os-pkgs", Vendor: "Red Hat, Inc.", Src: "openssl"} +} + +func TestBuildStagingOneRowAcrossImages(t *testing.T) { + fs := []model.CveFinding{rhel("CVE-1", "openssl-libs", "HIGH"), rhel("CVE-1", "openssl", "HIGH")} + s := BuildStaging([]model.ImageCveScan{ + scan("ppg:staging:18:containers", "pg", "ubi9", "x86_64", fs...), + scan("ppg:staging:18:containers", "pg", "ubi9", "aarch64", fs...), + scan("ppg:staging:17:containers", "pg", "ubi9", "x86_64", fs...), + }) + if len(s.BaseOS) != 1 { + t.Fatalf("base os rows = %d", len(s.BaseOS)) + } + r := s.BaseOS[0] + if r.Key != "base_os|openssl" || r.CVEs != 1 || len(r.Entries) != 2 || len(r.Fixes) != 2 || len(r.Images) != 2 { + t.Fatalf("row = %+v", r) + } + if r.Entries[0].SeenKey != "CVE-1|openssl|" || r.Entries[1].SeenKey != "CVE-1|openssl-libs|" { + t.Errorf("seen keys = %q %q", r.Entries[0].SeenKey, r.Entries[1].SeenKey) + } + var found bool + for _, im := range r.Images { + if im.Project == "ppg:staging:18:containers" { + found = true + if !reflect.DeepEqual(im.Arches, []string{"aarch64", "x86_64"}) { + t.Errorf("arches = %v", im.Arches) + } + } + } + if !found { + t.Error("18 image missing") + } + if r.Images[0].Project != "ppg:staging:17:containers" { + t.Errorf("images not sorted: %+v", r.Images) + } + if s.CVEs != 1 || s.Images != 2 { + t.Errorf("CVEs=%d Images=%d", s.CVEs, s.Images) + } +} + +func TestBuildStagingGolangRow(t *testing.T) { + g := func(path string) model.CveFinding { + return model.CveFinding{ID: "CVE-9", PkgName: "stdlib", InstalledVersion: "1.21", FixedVersion: "1.22", Severity: "HIGH", + Class: "lang-pkgs", Type: "gobinary", Path: path} + } + s := BuildStaging([]model.ImageCveScan{scan("ppg:staging:18:containers", "pg", "ubi9", "x86_64", g("usr/bin/etcd"), g("usr/sbin/gosu"))}) + if len(s.Ours) != 1 { + t.Fatalf("ours = %d", len(s.Ours)) + } + r := s.Ours[0] + if r.Key != "ours|golang" || r.Kind != KindGoRuntime || len(r.Entries) != 2 || r.Entries[0].Path == r.Entries[1].Path { + t.Errorf("row = %+v", r) + } +} + +func TestBuildStagingOrdering(t *testing.T) { + mk := func(name, sev string) model.CveFinding { + return model.CveFinding{ID: "CVE-" + name, PkgName: name, Severity: sev, Class: "os-pkgs", Vendor: "Percona, LLC", Src: name} + } + var scans []model.ImageCveScan + for _, p := range []string{"p1", "p2", "p3"} { + scans = append(scans, scan("ppg:staging:"+p, "pg", "ubi9", "x86_64", mk("a", "HIGH"), mk("c", "HIGH"))) + } + scans = append(scans, scan("ppg:staging:p1", "pg", "ubi9", "x86_64", mk("b", "CRITICAL"))) + s := BuildStaging(scans) + var names []string + for _, r := range s.Ours { + names = append(names, r.Name) + } + if !reflect.DeepEqual(names, []string{"b", "a", "c"}) { + t.Errorf("order = %v", names) + } + if s.Ours[0].Worst != "CRITICAL" { + t.Errorf("worst = %q", s.Ours[0].Worst) + } +} + +func TestBuildStagingUnclassifiedVendor(t *testing.T) { + f := model.CveFinding{ID: "CVE-5", PkgName: "foo", Severity: "HIGH", Class: "os-pkgs", Vendor: "Acme", Src: "foo"} + s := BuildStaging([]model.ImageCveScan{ + scan("ppg:staging:18", "pg", "ubi9", "x86_64", f), + scan("ppg:staging:18", "clean", "ubi9", "x86_64"), + }) + if len(s.Unclassified) != 1 || s.Unclassified[0].Vendor != "Acme" || s.Images != 1 { + t.Fatalf("got %+v", s) + } + + e := BuildStaging(nil) + b, _ := json.Marshal(e) + want := `{"ours":[],"base_os":[],"unclassified":[],"cves":0,"images":0}` + if string(b) != want { + t.Errorf("empty json = %s", b) + } +} diff --git a/backend/internal/model/types.go b/backend/internal/model/types.go index 33b244a..c6c8494 100644 --- a/backend/internal/model/types.go +++ b/backend/internal/model/types.go @@ -63,6 +63,12 @@ type CveFinding struct { FixedVersion string `json:"fixed"` Severity string `json:"severity"` Title string `json:"title"` + Class string `json:"class,omitempty"` // trivy result Class: "os-pkgs" | "lang-pkgs" + Type string `json:"pkg_type,omitempty"` // trivy result Type: "redhat", "gobinary", "python-pkg", … + Path string `json:"path,omitempty"` // binary (gobinary) or package file (other lang-pkgs); empty for RPMs + Src string `json:"src,omitempty"` // RPM source package name + Vendor string `json:"vendor,omitempty"` // RPM vendor (trivy "Maintainer") + Owner string `json:"owner,omitempty"` // source package of the RPM that ships Path, when resolved } type CveScan struct { diff --git a/backend/internal/store/cve.go b/backend/internal/store/cve.go index 0c86c0c..2ba233e 100644 --- a/backend/internal/store/cve.go +++ b/backend/internal/store/cve.go @@ -151,11 +151,24 @@ func AttachCveScans(db *sql.DB, packages []*model.Package) error { // subprojects: "ppg:staging" matches "ppg:staging" and "ppg:staging:18", not // "ppg:staging2". The prefix is compared literally, not as a LIKE pattern. func QueryVulnerableScans(db *sql.DB, projectPrefix string) ([]model.ImageCveScan, error) { + return queryScans(db, projectPrefix, true) +} + +// QueryImageScans returns every per-arch scan under projectPrefix, clean +// scans included. Prefix semantics and ordering as QueryVulnerableScans. +func QueryImageScans(db *sql.DB, projectPrefix string) ([]model.ImageCveScan, error) { + return queryScans(db, projectPrefix, false) +} + +func queryScans(db *sql.DB, projectPrefix string, vulnerableOnly bool) ([]model.ImageCveScan, error) { + cond := "" + if vulnerableOnly { + cond = "critical_count + high_count > 0 AND " + } rows, err := db.Query(` SELECT project, package, repo, arch, image_ref, scanned_at, critical_count, high_count, findings_json, cve_since, clean_since FROM cve_scans - WHERE critical_count + high_count > 0 - AND (?1 = '' OR project = ?1 OR substr(project, 1, length(?1) + 1) = ?1 || ':') + WHERE `+cond+`(?1 = '' OR project = ?1 OR substr(project, 1, length(?1) + 1) = ?1 || ':') ORDER BY project, package, repo, arch`, projectPrefix, ) @@ -166,6 +179,49 @@ func QueryVulnerableScans(db *sql.DB, projectPrefix string) ([]model.ImageCveSca return scanImageCveRows(rows) } +// QueryUnclassifiedImages lists images with at least one stored finding that +// has no "class" (scanned before classification existed). +func QueryUnclassifiedImages(db *sql.DB) ([]VulnerableImage, error) { + rows, err := db.Query(` + SELECT DISTINCT s.project, s.package, s.repo + FROM cve_scans s, json_each(s.findings_json) f + WHERE json_type(s.findings_json) = 'array' + AND json_extract(f.value, '$.class') IS NULL + ORDER BY s.project, s.package, s.repo`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []VulnerableImage + for rows.Next() { + var v VulnerableImage + if err := rows.Scan(&v.Project, &v.Package, &v.Repo); err != nil { + return nil, err + } + out = append(out, v) + } + return out, rows.Err() +} + +// QueryContainerVersions maps "/" to the package version for +// every container package. +func QueryContainerVersions(db *sql.DB) (map[string]string, error) { + rows, err := db.Query(`SELECT project, name, version FROM packages WHERE is_container = 1`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]string{} + for rows.Next() { + var project, name, version string + if err := rows.Scan(&project, &name, &version); err != nil { + return nil, err + } + out[project+"/"+name] = version + } + return out, rows.Err() +} + // QueryCvePeriods returns completed CVE episodes for a package, newest first. func QueryCvePeriods(db *sql.DB, project, pkg string) ([]model.CvePeriod, error) { rows, err := db.Query(` diff --git a/backend/internal/store/cve_test.go b/backend/internal/store/cve_test.go index 18af1fe..ed0f156 100644 --- a/backend/internal/store/cve_test.go +++ b/backend/internal/store/cve_test.go @@ -472,3 +472,136 @@ func TestQueryVulnerableScans(t *testing.T) { } }) } + +func TestQueryImageScans(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + + at := time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC) + vuln := model.CveScan{ + Repo: "images", Arch: "x86_64", ImageRef: "r/v:1", ScannedAt: at, HighCount: 1, + Findings: []model.CveFinding{{ID: "CVE-2026-0001", PkgName: "openssl", Severity: "HIGH"}}, + } + clean := model.CveScan{Repo: "images", Arch: "x86_64", ImageRef: "r/c:1", ScannedAt: at} + seed := []struct { + project, pkg string + scan model.CveScan + }{ + {"ppg:staging:18:containers", "vuln", vuln}, + {"ppg:staging:18:containers", "clean", clean}, + {"ppg:staging2:x", "lookalike", vuln}, + {"ppg:releases:18:containers", "rel", vuln}, + } + for _, s := range seed { + if err := store.UpsertCveScan(db, s.project, s.pkg, s.scan); err != nil { + t.Fatal(err) + } + } + keys := func(scans []model.ImageCveScan) []string { + var out []string + for _, s := range scans { + out = append(out, s.Project+"/"+s.Package+"/"+s.Arch) + } + return out + } + check := func(prefix string, want []string) { + t.Helper() + scans, err := store.QueryImageScans(db, prefix) + if err != nil { + t.Fatal(err) + } + got := keys(scans) + if len(got) != len(want) { + t.Fatalf("prefix %q: got %v, want %v", prefix, got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("prefix %q: got %v, want %v", prefix, got, want) + } + } + } + check("ppg:staging", []string{ + "ppg:staging:18:containers/clean/x86_64", + "ppg:staging:18:containers/vuln/x86_64", + }) + check("", []string{ + "ppg:releases:18:containers/rel/x86_64", + "ppg:staging2:x/lookalike/x86_64", + "ppg:staging:18:containers/clean/x86_64", + "ppg:staging:18:containers/vuln/x86_64", + }) +} + +func TestQueryUnclassifiedImages(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + + at := time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC) + scan := func(findings ...model.CveFinding) model.CveScan { + return model.CveScan{ + Repo: "images", Arch: "x86_64", ImageRef: "r", ScannedAt: at, + HighCount: len(findings), Findings: findings, + } + } + plain := model.CveFinding{ID: "CVE-1", PkgName: "a", Severity: "HIGH"} + classified := model.CveFinding{ID: "CVE-2", PkgName: "b", Severity: "HIGH", Class: "os-pkgs"} + seed := []struct { + pkg string + scan model.CveScan + }{ + {"A", scan(plain)}, + {"B", scan(classified)}, + {"C", scan(classified, plain)}, + {"D", scan()}, + } + for _, s := range seed { + if err := store.UpsertCveScan(db, "p", s.pkg, s.scan); err != nil { + t.Fatal(err) + } + } + got, err := store.QueryUnclassifiedImages(db) + if err != nil { + t.Fatal(err) + } + want := []store.VulnerableImage{{"p", "A", "images"}, {"p", "C", "images"}} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("row %d: got %v, want %v", i, got[i], want[i]) + } + } +} + +func TestQueryContainerVersions(t *testing.T) { + db, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + + yes, no := true, false + now := time.Now().UTC().Truncate(time.Second) + for _, p := range []*model.Package{ + {Project: "ppg:staging:18:containers", Name: "pg18", IsContainer: &yes, Version: "18.4-1-2.34", RollupState: model.RollupPublished, UpdatedAt: now}, + {Project: "ppg:staging:18", Name: "rpm", IsContainer: &no, Version: "1.0", RollupState: model.RollupPublished, UpdatedAt: now}, + } { + if err := store.UpsertPackageState(db, p, now); err != nil { + t.Fatal(err) + } + } + got, err := store.QueryContainerVersions(db) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got["ppg:staging:18:containers/pg18"] != "18.4-1-2.34" { + t.Fatalf("got %v", got) + } +} diff --git a/docs/superpowers/plans/2026-11-17-cve-tab.md b/docs/superpowers/plans/2026-11-17-cve-tab.md new file mode 100644 index 0000000..4467827 --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-cve-tab.md @@ -0,0 +1,787 @@ +# CVE Tab Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development (recommended) or superpowers-extended-cc:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A "CVEs" main tab that lists what to bump on staging (ours vs. base OS, with new-since-last-look markers) and, for released images, which CVEs the current staging image already fixes. + +**Architecture:** The scanner keeps a few extra trivy fields per finding in the existing `findings_json`. A new pure Go package `internal/cvereport` classifies findings and aggregates them into one report; `GET /api/cve/report` serves it from a short TTL cache. The frontend fetches the report once per app (for the tab badge), keeps "seen" state in `localStorage`, and renders three views; the existing `CveExposureTable` moves in unchanged as "By image". + +**Tech Stack:** Go 1.25 (chi, modernc sqlite), Vue 3 ` diff --git a/frontend/src/components/cve/CveByImageView.vue b/frontend/src/components/cve/CveByImageView.vue new file mode 100644 index 0000000..9b7f55a --- /dev/null +++ b/frontend/src/components/cve/CveByImageView.vue @@ -0,0 +1,19 @@ + + + diff --git a/frontend/src/components/cve/CvePanel.test.ts b/frontend/src/components/cve/CvePanel.test.ts new file mode 100644 index 0000000..f99b526 --- /dev/null +++ b/frontend/src/components/cve/CvePanel.test.ts @@ -0,0 +1,123 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import CvePanel from './CvePanel.vue' +import { resetCveReportForTests } from '../../composables/useCveReport' +import { resetAuthForTests } from '../../composables/useAuth' + +const overview = { + window: '24h', previous_window_rebuild_total: 0, top_repo: null, fix_time: null, by_instance: [], + projects: [{ + project: 'ppg:releases:17', rebuilds: 0, + images: [{ project: 'isv:percona:ppg:17', name: 'img', repo: 'images', base_os: '', critical: 1, high: 0, oldest_open_days: 2, avg_fix_hours: 0 }], + }], +} + +class FakeES { onmessage = null; close() {} } + +const golangRow = { + key: 'ours|golang', name: 'golang', kind: 'go_runtime', worst: 'CRITICAL', cves: 1, + fixes: [{ pkg: 'golang', installed: '1.22.1', fixed: '1.22.5' }], + entries: [{ id: 'CVE-2025-0002', pkg: 'golang', severity: 'CRITICAL', title: 't', seen_key: 'CVE-2025-0002|golang|' }], + images: [{ project: 'ppg:staging', package: 'p', repo: 'ubi9', arches: ['x86_64'] }], +} +const releasedImage = { + project: 'ppg:releases:18:containers', package: 'p', repo: 'ubi9', version: '1', staging_project: 'ppg:staging', staging_version: '2', + total: 1, fixed_in_staging: 0, + cves: [{ id: 'CVE-2025-0002', pkg: 'golang', installed: '1.22.1', fixed: '1.22.5', severity: 'CRITICAL', title: 't', status: 'open', staging_row_key: 'ours|golang' }], +} + +function stubFetch(reportOk: boolean, withRows = false) { + vi.stubGlobal('fetch', vi.fn(async (url: string) => { + if (url.startsWith('/api/cve/report')) { + return reportOk + ? { ok: true, statusText: 'OK', json: async () => withRows + ? ({ generated_at: '', staging: { ours: [golangRow], base_os: [], unclassified: [], cves: 1, images: 1 }, released: [releasedImage] }) + : ({ generated_at: '', staging: { ours: [], base_os: [], unclassified: [], cves: 0, images: 0 }, released: [] }) } + : { ok: false, statusText: 'Internal Server Error', json: async () => ({}) } + } + return { ok: true, statusText: 'OK', json: async () => overview } + })) +} + +beforeEach(() => { + resetAuthForTests() + resetCveReportForTests() + vi.stubGlobal('EventSource', FakeES) +}) +afterEach(() => vi.unstubAllGlobals()) + +describe('CvePanel', () => { + it('renders the by-image table for view=images', async () => { + stubFetch(true) + const w = mount(CvePanel, { props: { view: 'images' } }) + await flushPromises() + expect(w.text()).toContain('img') + expect(w.findComponent({ name: 'CveExposureTable' }).exists()).toBe(true) + }) + + it('fetches overview data only while the By image view is shown', async () => { + stubFetch(true) + const overviewCalls = () => (fetch as unknown as ReturnType).mock.calls.filter(c => String(c[0]).startsWith('/api/overview')).length + const w = mount(CvePanel, { props: { view: 'staging' } }) + await flushPromises() + expect(overviewCalls()).toBe(0) + await w.setProps({ view: 'images' }) + await flushPromises() + expect(overviewCalls()).toBeGreaterThan(0) + }) + + it('emits update:view when a segment is clicked', async () => { + stubFetch(true) + const w = mount(CvePanel, { props: { view: 'staging' } }) + await flushPromises() + const btn = w.findAll('button').find(b => b.text() === 'Released')! + await btn.trigger('click') + expect(w.emitted('update:view')).toEqual([['released']]) + }) + + it('shows an error with Retry on staging, while By image still renders', async () => { + stubFetch(false) + const w = mount(CvePanel, { props: { view: 'staging' } }) + await w.vm.$nextTick() + // the panel does not start the fetch itself; trigger the first (failing) load here + const { useCveReport } = await import('../../composables/useCveReport') + await useCveReport().refresh() + await flushPromises() + const err = w.find('[data-testid="cve-report-error"]') + expect(err.exists()).toBe(true) + expect(err.find('button').text()).toBe('Retry') + stubFetch(true) + await err.find('button').trigger('click') + await flushPromises() + expect(w.find('[data-testid="cve-report-error"]').exists()).toBe(false) + expect(w.findComponent({ name: 'CveStagingView' }).exists()).toBe(true) + await w.setProps({ view: 'images' }) + await flushPromises() + expect(w.findComponent({ name: 'CveExposureTable' }).exists()).toBe(true) + }) + + it('jumps from a released CVE to its expanded staging row', async () => { + stubFetch(true, true) + const w = mount(CvePanel, { props: { view: 'released' } }) + const { useCveReport } = await import('../../composables/useCveReport') + await useCveReport().refresh() + await flushPromises() + const rv = w.findComponent({ name: 'CveReleasedView' }) + expect(rv.exists()).toBe(true) + rv.vm.$emit('open-staging-row', 'ours|golang') + expect(w.emitted('update:view')).toEqual([['staging']]) + await w.setProps({ view: 'staging' }) + await flushPromises() + expect(w.find('[data-testid="cve-row-ours|golang"]').attributes('aria-expanded')).toBe('true') + }) + + it('never shows the released view while the report is missing', async () => { + stubFetch(false) + const w = mount(CvePanel, { props: { view: 'released' } }) + const { useCveReport } = await import('../../composables/useCveReport') + await useCveReport().refresh() + await flushPromises() + expect(w.findComponent({ name: 'CveReleasedView' }).exists()).toBe(false) + }) +}) diff --git a/frontend/src/components/cve/CvePanel.vue b/frontend/src/components/cve/CvePanel.vue new file mode 100644 index 0000000..822904e --- /dev/null +++ b/frontend/src/components/cve/CvePanel.vue @@ -0,0 +1,72 @@ + + + diff --git a/frontend/src/components/cve/CveReleasedView.test.ts b/frontend/src/components/cve/CveReleasedView.test.ts new file mode 100644 index 0000000..e79aba5 --- /dev/null +++ b/frontend/src/components/cve/CveReleasedView.test.ts @@ -0,0 +1,66 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest' +import { mount } from '@vue/test-utils' +import CveReleasedView from './CveReleasedView.vue' +import type { ReleasedImage } from '../../types/cveReport' + +const image: ReleasedImage = { + project: 'ppg:releases:18:containers', + package: 'percona-distribution-postgresql', + repo: 'ubi9', + version: '18.4-1-1.1', + staging_project: 'ppg:staging:18:containers', + staging_version: '18.4-1-2.34', + total: 3, + fixed_in_staging: 1, + cves: [ + { id: 'CVE-2025-0001', pkg: 'openssl', installed: '3.0.1', fixed: '3.0.2', severity: 'HIGH', title: 't1', status: 'fixed' }, + { id: 'CVE-2025-0002', pkg: 'golang', installed: '1.22.1', fixed: '1.22.5', severity: 'CRITICAL', title: 't2', status: 'open', staging_row_key: 'ours|golang' }, + { id: 'CVE-2025-0003', pkg: 'zlib', installed: '1.2.1', fixed: '1.2.2', severity: 'HIGH', title: 't3', status: 'no_staging' }, + ], +} + +describe('CveReleasedView', () => { + it('shows the fixed count, both versions and the PG major with repo', () => { + const w = mount(CveReleasedView, { props: { released: [image] } }) + const text = w.text() + expect(text).toContain('1 of 3') + expect(text).toContain('18.4-1-1.1') + expect(text).toContain('18.4-1-2.34') + expect(text).toContain('18 · ubi9') + }) + + it('expands to the status of each CVE and links an open one to its staging row', async () => { + const w = mount(CveReleasedView, { props: { released: [image] } }) + const head = w.find('button[aria-expanded]') + expect(head.attributes('aria-expanded')).toBe('false') + await head.trigger('click') + expect(head.attributes('aria-expanded')).toBe('true') + const text = w.text() + expect(text).toContain('Fixed in staging') + expect(text).toContain('Still open in staging') + expect(text).toContain('No staging image to compare') + expect(text).toContain('CVE-2025-0002') + const link = w.findAll('button').find(b => b.text() === 'golang')! + expect(link).toBeTruthy() + await link.trigger('click') + expect(w.emitted('open-staging-row')).toEqual([['ours|golang']]) + }) + + it('shows a dash when there is no staging version', () => { + const w = mount(CveReleasedView, { props: { released: [{ ...image, staging_version: undefined, fixed_in_staging: 0 }] } }) + expect(w.text()).toContain('—') + }) + + it('has no new markers and no mark-all-as-seen', async () => { + const w = mount(CveReleasedView, { props: { released: [image] } }) + await w.find('button[aria-expanded]').trigger('click') + expect(w.find('[data-testid="cve-new-tag"]').exists()).toBe(false) + expect(w.find('[data-testid="cve-mark-seen"]').exists()).toBe(false) + }) + + it('renders an empty state for no released images', () => { + const w = mount(CveReleasedView, { props: { released: [] } }) + expect(w.find('[data-testid="cve-empty"]').exists()).toBe(true) + }) +}) diff --git a/frontend/src/components/cve/CveReleasedView.vue b/frontend/src/components/cve/CveReleasedView.vue new file mode 100644 index 0000000..fe37200 --- /dev/null +++ b/frontend/src/components/cve/CveReleasedView.vue @@ -0,0 +1,112 @@ + + + diff --git a/frontend/src/components/cve/CveStagingView.test.ts b/frontend/src/components/cve/CveStagingView.test.ts new file mode 100644 index 0000000..c9ec433 --- /dev/null +++ b/frontend/src/components/cve/CveStagingView.test.ts @@ -0,0 +1,197 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import CveStagingView from './CveStagingView.vue' +import { resetCveSeenForTests, SEEN_STORAGE_KEY, useCveSeen } from '../../composables/useCveSeen' +import { resetCveReportForTests, useCveReport } from '../../composables/useCveReport' +import { resetAuthForTests, useAuth } from '../../composables/useAuth' +import type { CveRow, CveStaging } from '../../types/cveReport' + +const img = (repo: string) => ({ project: 'ppg:staging:17', package: 'postgresql', repo, arches: ['x86_64', 'aarch64'] }) + +function golang(): CveRow { + return { + key: 'ours|golang', name: 'golang', kind: 'go_runtime', worst: 'CRITICAL', cves: 2, + fixes: [{ pkg: 'stdlib', installed: '1.22.1', fixed: '1.22.5' }, { pkg: 'golang', installed: '1.22.1', fixed: '1.22.6' }], + entries: [ + { id: 'CVE-2024-0001', pkg: 'stdlib', severity: 'CRITICAL', title: 'Go stdlib flaw', seen_key: 'CVE-2024-0001|stdlib|' }, + { id: 'CVE-2024-0002', pkg: 'stdlib', severity: 'HIGH', title: 'Go net flaw', seen_key: 'CVE-2024-0002|stdlib|' }, + ], + images: [img('ubi8'), img('ubi9')], + } +} +function etcd(): CveRow { + return { + key: 'ours|etcd', name: 'etcd', kind: 'bundled_library', worst: 'HIGH', cves: 1, + fixes: [{ pkg: 'grpc', installed: '1.0', fixed: '1.1' }], + entries: [{ id: 'CVE-2024-0003', pkg: 'grpc', path: 'usr/bin/etcd', severity: 'HIGH', title: 'grpc flaw', seen_key: 'CVE-2024-0003|grpc|usr/bin/etcd' }], + images: [img('ubi9')], + } +} +function openssl(): CveRow { + return { + key: 'base_os|openssl', name: 'openssl', kind: 'base_os', worst: 'HIGH', cves: 1, + fixes: [{ pkg: 'openssl', installed: '3.0.1', fixed: '3.0.2' }, { pkg: 'openssl-libs', installed: '3.0.1', fixed: '3.0.2' }], + entries: [ + { id: 'CVE-2024-0004', pkg: 'openssl', severity: 'HIGH', title: 'openssl flaw', seen_key: 'CVE-2024-0004|openssl|' }, + { id: 'CVE-2024-0004', pkg: 'openssl-libs', severity: 'HIGH', title: 'openssl flaw', seen_key: 'CVE-2024-0004|openssl-libs|' }, + ], + images: [img('ubi9')], + } +} +function staging(unclassified: CveRow[] = []): CveStaging { + return { ours: [etcd(), golang()], base_os: [openssl()], unclassified, cves: 4, images: 2 } +} + +function mountView(props: { staging?: CveStaging; focusRowKey?: string | null } = {}) { + return mount(CveStagingView, { props: { staging: props.staging ?? staging(), focusRowKey: props.focusRowKey ?? null } }) +} +function rowOf(w: ReturnType, key: string) { + return w.find(`[data-testid="cve-row-${key}"]`) +} +function markSeen(keys: string[]) { + localStorage.setItem(SEEN_STORAGE_KEY, JSON.stringify(keys)) + resetCveSeenForTests() +} + +beforeEach(() => { + localStorage.clear() + resetCveSeenForTests() + resetCveReportForTests() + resetAuthForTests() +}) +afterEach(() => vi.unstubAllGlobals()) + +describe('CveStagingView', () => { + it('shows the header line', () => { + expect(mountView().find('[data-testid="cve-staging-header"]').text()).toBe('2 things to bump · 4 CVEs · 2 images') + }) + + it('shows both fix lines for one package at two installed versions', async () => { + const fix = (pkg: string, installed: string, fixed: string) => ({ pkg, installed, fixed }) + const head = fix('a', '1', '2'), tail = fix('z', '1', '2') + const g1 = fix('grpc', '1.0', '1.1'), g2 = fix('grpc', '1.2', '1.3') + const withFixes = (fixes: ReturnType[]) => ({ ours: [{ ...etcd(), fixes }], base_os: [], unclassified: [], cves: 1, images: 1 }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const mid = fix('b', '1', '2') + const w = mountView({ staging: withFixes([head, g1, mid, tail]) }) + await w.setProps({ staging: withFixes([head, mid, g1, g2, tail]) }) + expect(warn.mock.calls.filter(c => String(c[0]).includes('Duplicate keys'))).toHaveLength(0) + warn.mockRestore() + const text = rowOf(w, 'ours|etcd').text() + expect(text).toContain('grpc 1.0 → 1.1') + expect(text).toContain('grpc 1.2 → 1.3') + }) + + it('uses the singular for one thing, one CVE and one image', () => { + const w = mountView({ staging: { ours: [etcd()], base_os: [], unclassified: [], cves: 1, images: 1 } }) + expect(w.find('[data-testid="cve-staging-header"]').text()).toBe('1 thing to bump · 1 CVE · 1 image') + }) + + it('renders Ours and Base OS, and Not classified only with rows', () => { + const w = mountView() + expect(w.text()).toContain('Ours to bump') + expect(w.text()).toContain('Base OS') + expect(w.text()).not.toContain('Not classified yet') + const u: CveRow = { ...etcd(), key: 'unclassified|thing', name: 'thing', kind: 'unclassified', vendor: 'Acme' } + const w2 = mountView({ staging: staging([u]) }) + expect(w2.text()).toContain('Not classified yet') + expect(w2.text()).toContain('Acme') + }) + + it('shows a one-line empty state for an empty Ours or Base OS list', () => { + const w = mountView({ staging: { ours: [], base_os: [], unclassified: [], cves: 0, images: 0 } }) + expect(w.findAll('[data-testid="cve-empty"]')).toHaveLength(2) + expect(w.find('[data-testid="cve-staging-header"]').text()).toBe('0 things to bump · 0 CVEs · 0 images') + }) + + it('flags rows with new entries and sorts them first', () => { + markSeen(['CVE-2024-0003|grpc|usr/bin/etcd']) + const w = mountView() + expect(rowOf(w, 'ours|golang').find('[data-testid="cve-new-tag"]').exists()).toBe(true) + expect(rowOf(w, 'base_os|openssl').find('[data-testid="cve-new-tag"]').exists()).toBe(true) + expect(rowOf(w, 'ours|etcd').find('[data-testid="cve-new-tag"]').exists()).toBe(false) + const rows = w.findAll('[data-testid^="cve-row-"]').map(r => r.attributes('data-testid')) + expect(rows.indexOf('cve-row-ours|golang')).toBeLessThan(rows.indexOf('cve-row-ours|etcd')) + }) + + it('expands a row to its entries and images, tagging only new entries', async () => { + markSeen(['CVE-2024-0002|stdlib|']) + const w = mountView() + const btn = rowOf(w, 'ours|golang') + expect(btn.attributes('aria-expanded')).toBe('false') + await btn.trigger('click') + expect(btn.attributes('aria-expanded')).toBe('true') + const region = w.find(`#${btn.attributes('aria-controls')}`) + expect(region.text()).toContain('CVE-2024-0001') + expect(region.text()).toContain('Go stdlib flaw') + expect(region.text()).toContain('CVE-2024-0002') + expect(region.text()).toContain('Go net flaw') + expect(region.text()).toContain('ppg:staging:17') + expect(region.text()).toContain('postgresql') + expect(region.text()).toContain('ubi8') + expect(region.text()).toContain('x86_64') + expect(region.text()).toContain('aarch64') + const entries = region.findAll('[data-testid="cve-entry"]') + expect(entries).toHaveLength(2) + expect(entries[0].find('[data-testid="cve-new-tag"]').exists()).toBe(true) + expect(entries[1].find('[data-testid="cve-new-tag"]').exists()).toBe(false) + }) + + it('does not clear markers on opening or remounting', async () => { + const w = mountView() + await rowOf(w, 'ours|golang').trigger('click') + w.unmount() + const w2 = mountView() + expect(w2.findAll('[data-testid="cve-new-tag"]').length).toBeGreaterThan(0) + expect(localStorage.getItem(SEEN_STORAGE_KEY)).toBeNull() + }) + + it('Mark all as seen clears every marker and the header count', async () => { + const { newCount } = useCveReport() + const w = mountView() + await w.find('[data-testid="cve-mark-seen"]').trigger('click') + expect(w.findAll('[data-testid="cve-new-tag"]')).toHaveLength(0) + expect(newCount.value).toBe(0) + }) + + it('has no markers and no Mark all as seen when storage is unavailable', () => { + localStorage.setItem(SEEN_STORAGE_KEY, 'not json') + resetCveSeenForTests() + expect(useCveSeen().available.value).toBe(false) + const w = mountView() + expect(w.findAll('[data-testid="cve-new-tag"]')).toHaveLength(0) + expect(w.find('[data-testid="cve-mark-seen"]').exists()).toBe(false) + }) + + it('shows Rescan only when signed in', () => { + expect(mountView().find('[data-testid="cve-rescan"]').exists()).toBe(false) + useAuth().user.value = 'alice@percona.com' + expect(mountView().find('[data-testid="cve-rescan"]').exists()).toBe(true) + }) + + it('posts the rescan like the by-image table does', async () => { + const fetchMock = vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ queued: 2 }) })) + vi.stubGlobal('fetch', fetchMock) + useAuth().user.value = 'alice@percona.com' + const w = mountView() + await w.find('[data-testid="cve-rescan"]').trigger('click') + await vi.waitFor(() => expect(w.find('[data-testid="cve-rescan-status"]').text()).toBe('Queued 2 images')) + expect(fetchMock).toHaveBeenCalledWith('/api/cve/rescan', { method: 'POST' }) + }) + + it('shows kind labels and every fix line', () => { + const w = mountView() + expect(rowOf(w, 'ours|golang').text()).toContain('Go runtime') + expect(rowOf(w, 'ours|etcd').text()).toContain('bundled library') + const text = rowOf(w, 'ours|golang').text() + expect(text).toContain('stdlib 1.22.1 → 1.22.5') + expect(text).toContain('golang 1.22.1 → 1.22.6') + }) + + it('renders the focused row expanded', () => { + const w = mountView({ focusRowKey: 'ours|etcd' }) + expect(rowOf(w, 'ours|etcd').attributes('aria-expanded')).toBe('true') + expect(rowOf(w, 'ours|golang').attributes('aria-expanded')).toBe('false') + }) +}) diff --git a/frontend/src/components/cve/CveStagingView.vue b/frontend/src/components/cve/CveStagingView.vue new file mode 100644 index 0000000..8059c7c --- /dev/null +++ b/frontend/src/components/cve/CveStagingView.vue @@ -0,0 +1,70 @@ + + + diff --git a/frontend/src/components/cve/CveWorklistTable.vue b/frontend/src/components/cve/CveWorklistTable.vue new file mode 100644 index 0000000..690a357 --- /dev/null +++ b/frontend/src/components/cve/CveWorklistTable.vue @@ -0,0 +1,126 @@ + + + diff --git a/frontend/src/composables/useCveReport.test.ts b/frontend/src/composables/useCveReport.test.ts new file mode 100644 index 0000000..2e57ca7 --- /dev/null +++ b/frontend/src/composables/useCveReport.test.ts @@ -0,0 +1,74 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises } from '@vue/test-utils' +import { resetCveReportForTests, useCveReport } from './useCveReport' +import { resetCveSeenForTests, useCveSeen } from './useCveSeen' +import type { CveReport, CveRow } from '../types/cveReport' + +function row(name: string, ids: string[]): CveRow { + return { + key: `ours|${name}`, name, kind: 'obs_package', worst: 'HIGH', cves: ids.length, fixes: [], images: [], + entries: ids.map(id => ({ id, pkg: name, severity: 'HIGH' as const, title: 't', seen_key: `${id}|${name}|` })), + } +} + +export const fixtureReport: CveReport = { + generated_at: '2026-11-17T00:00:00Z', + staging: { ours: [row('etcd', ['CVE-1', 'CVE-2'])], base_os: [row('openssl', ['CVE-3'])], unclassified: [], cves: 3, images: 2 }, + released: [], +} + +class FakeES { static last: FakeES | null = null; onmessage: (() => void) | null = null; constructor() { FakeES.last = this } close() {} } + +let fetchMock: ReturnType +beforeEach(() => { + localStorage.clear() + resetCveSeenForTests() + resetCveReportForTests() + fetchMock = vi.fn(async () => ({ ok: true, statusText: 'OK', json: async () => fixtureReport })) + vi.stubGlobal('fetch', fetchMock) + vi.stubGlobal('EventSource', FakeES) +}) +afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() }) + +describe('useCveReport', () => { + it('start() fetches once even when called twice', async () => { + const r = useCveReport() + r.start(); r.start() + await flushPromises() + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(fetchMock.mock.calls[0][0]).toBe('/api/cve/report') + expect(r.report.value).toEqual(fixtureReport) + }) + + it('a 500 sets error and leaves report null; refresh() clears it on success', async () => { + fetchMock.mockResolvedValueOnce({ ok: false, statusText: 'Internal Server Error', json: async () => ({}) }) + const r = useCveReport() + await r.refresh() + expect(r.error.value).toBe('Internal Server Error') + expect(r.report.value).toBeNull() + await r.refresh() + expect(r.error.value).toBeNull() + expect(r.report.value).not.toBeNull() + }) + + it('newCount counts distinct unseen keys, and is 0 after markAllSeen', async () => { + const r = useCveReport() + expect(r.newCount.value).toBe(0) + await r.refresh() + expect(r.newCount.value).toBe(3) + useCveSeen().markAllSeen(['CVE-1|etcd|', 'CVE-2|etcd|', 'CVE-3|openssl|']) + expect(r.newCount.value).toBe(0) + }) + + it('refetches 2 s after a stream message', async () => { + vi.useFakeTimers() + const r = useCveReport() + r.start() + await vi.advanceTimersByTimeAsync(0) + expect(fetchMock).toHaveBeenCalledTimes(1) + FakeES.last!.onmessage!() + await vi.advanceTimersByTimeAsync(2000) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) +}) diff --git a/frontend/src/composables/useCveReport.ts b/frontend/src/composables/useCveReport.ts new file mode 100644 index 0000000..a801b8d --- /dev/null +++ b/frontend/src/composables/useCveReport.ts @@ -0,0 +1,66 @@ +import { computed, readonly, ref } from 'vue' +import type { CveReport } from '../types/cveReport' +import { countNew } from '../lib/cveReport' +import { useCveSeen } from './useCveSeen' + +// Module-level singleton: the header badge and the CVEs panel share one +// report and one stream subscription. +const report = ref(null) +const loading = ref(false) +const error = ref(null) + +let es: EventSource | null = null +let debounce: ReturnType | null = null +let started = false + +async function refresh(): Promise { + loading.value = true + try { + const res = await fetch('/api/cve/report') + if (!res.ok) throw new Error(res.statusText) + report.value = await res.json() as CveReport + error.value = null + } catch (e) { + error.value = e instanceof Error ? e.message : 'failed to load CVE report' + } finally { + loading.value = false + } +} + +// Idempotent: the first call fetches and subscribes to the app's global +// stream; any message schedules a debounced refetch (mirrors useOverviewData). +function start(): void { + if (started) return + started = true + void refresh() + es = new EventSource('/api/stream') + es.onmessage = () => { + if (debounce) clearTimeout(debounce) + debounce = setTimeout(() => { void refresh() }, 2000) + } +} + +const { isNew } = useCveSeen() +const newCount = computed(() => (report.value ? countNew(report.value.staging, isNew) : 0)) + +export function useCveReport() { + return { + report: readonly(report), + loading: readonly(loading), + error: readonly(error), + refresh, + start, + newCount, + } +} + +export function resetCveReportForTests(): void { + es?.close() + es = null + if (debounce) clearTimeout(debounce) + debounce = null + started = false + report.value = null + loading.value = false + error.value = null +} diff --git a/frontend/src/composables/useCveRescan.ts b/frontend/src/composables/useCveRescan.ts new file mode 100644 index 0000000..f11ce83 --- /dev/null +++ b/frontend/src/composables/useCveRescan.ts @@ -0,0 +1,48 @@ +import { onUnmounted, ref } from 'vue' +import { handleUnauthorized } from './useAuth' +import { errorText } from './http' + +const RESCAN_COOLDOWN_MS = 10_000 + +// POST /api/cve/rescan with a busy/cooldown state and a status message. +// Results arrive through the scan events on the global stream, which already +// trigger refetches, so callers need no result handling. +export function useCveRescan() { + const rescanBusy = ref(false) + const rescanMsg = ref(null) + const rescanFailed = ref(false) + let rescanTimer: ReturnType | null = null + onUnmounted(() => { if (rescanTimer) clearTimeout(rescanTimer) }) + + async function rescan() { + if (rescanBusy.value) return + rescanBusy.value = true + rescanFailed.value = false + rescanMsg.value = null + let cooldown = false + try { + const res = await fetch('/api/cve/rescan', { method: 'POST' }) + if (res.status === 401) { + handleUnauthorized() + return + } + if (!res.ok) throw new Error(await errorText(res)) + const { queued } = await res.json() as { queued: number } + rescanMsg.value = queued > 0 + ? `Queued ${queued} image${queued === 1 ? '' : 's'}` + : 'Nothing queued: rescans already pending' + cooldown = true + } catch (e) { + rescanFailed.value = true + rescanMsg.value = `Rescan failed: ${e instanceof Error ? e.message : 'network error'}` + } finally { + if (cooldown) { + rescanTimer = setTimeout(() => { rescanBusy.value = false; rescanMsg.value = null }, RESCAN_COOLDOWN_MS) + } else { + rescanBusy.value = false + } + } + } + + return { rescanBusy, rescanMsg, rescanFailed, rescan } +} diff --git a/frontend/src/composables/useCveSeen.test.ts b/frontend/src/composables/useCveSeen.test.ts new file mode 100644 index 0000000..f02d141 --- /dev/null +++ b/frontend/src/composables/useCveSeen.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SEEN_STORAGE_KEY, resetCveSeenForTests, useCveSeen } from './useCveSeen' + +beforeEach(() => { + localStorage.clear() + resetCveSeenForTests() +}) +afterEach(() => vi.restoreAllMocks()) + +describe('useCveSeen', () => { + it('is new until marked seen, and persists', () => { + const { isNew, markAllSeen } = useCveSeen() + expect(isNew('CVE-1|openssl|')).toBe(true) + markAllSeen(['CVE-1|openssl|']) + expect(isNew('CVE-1|openssl|')).toBe(false) + expect(JSON.parse(localStorage.getItem(SEEN_STORAGE_KEY)!)).toContain('CVE-1|openssl|') + }) + + it('stays seen after a reload', () => { + const { isNew, markAllSeen } = useCveSeen() + markAllSeen(['CVE-1|openssl|']) + resetCveSeenForTests() + expect(isNew('CVE-1|openssl|')).toBe(false) + expect(isNew('CVE-2|x|')).toBe(true) + }) + + it('only adds to the seen set', () => { + const { isNew, markAllSeen } = useCveSeen() + markAllSeen(['a']) + markAllSeen(['b']) + expect(isNew('a')).toBe(false) + expect(isNew('b')).toBe(false) + }) + + it('disables markers on corrupt JSON without throwing', () => { + localStorage.setItem(SEEN_STORAGE_KEY, '{not json') + resetCveSeenForTests() + const { available, isNew, markAllSeen } = useCveSeen() + expect(available.value).toBe(false) + expect(isNew('anything')).toBe(false) + expect(() => markAllSeen(['a'])).not.toThrow() + }) + + it('treats valid JSON that is not a string array as corrupt', () => { + localStorage.setItem(SEEN_STORAGE_KEY, '{"a":1}') + resetCveSeenForTests() + const { available, isNew } = useCveSeen() + expect(available.value).toBe(false) + expect(isNew('a')).toBe(false) + }) + + it('disables markers when getItem throws', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + resetCveSeenForTests() + const { available, isNew } = useCveSeen() + expect(available.value).toBe(false) + expect(isNew('a')).toBe(false) + }) + + it('disables markers when setItem throws', () => { + const { available, isNew, markAllSeen } = useCveSeen() + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + expect(() => markAllSeen(['a'])).not.toThrow() + expect(available.value).toBe(false) + expect(isNew('a')).toBe(false) + }) +}) diff --git a/frontend/src/composables/useCveSeen.ts b/frontend/src/composables/useCveSeen.ts new file mode 100644 index 0000000..26c1d33 --- /dev/null +++ b/frontend/src/composables/useCveSeen.ts @@ -0,0 +1,56 @@ +import { readonly, ref } from 'vue' + +export const SEEN_STORAGE_KEY = 'obsboard.cve.seen.v1' + +// Module-level singleton: the set of CVE seen keys this browser has +// acknowledged. When storage is unusable, markers are disabled entirely +// (available false, nothing is new) rather than flagging everything. +const seen = ref>(new Set()) +const available = ref(true) + +function load(): void { + try { + const raw = localStorage.getItem(SEEN_STORAGE_KEY) + if (raw === null) { + seen.value = new Set() + available.value = true + return + } + const parsed: unknown = JSON.parse(raw) + if (!Array.isArray(parsed) || !parsed.every(k => typeof k === 'string')) { + throw new Error('seen set is not an array of strings') + } + seen.value = new Set(parsed as string[]) + available.value = true + } catch { + seen.value = new Set() + available.value = false + } +} + +load() + +function isNew(seenKey: string): boolean { + return available.value && !seen.value.has(seenKey) +} + +function markAllSeen(seenKeys: string[]): void { + if (!available.value) return + const next = new Set(seen.value) + for (const k of seenKeys) next.add(k) + try { + localStorage.setItem(SEEN_STORAGE_KEY, JSON.stringify([...next])) + seen.value = next + } catch { + seen.value = new Set() + available.value = false + } +} + +export function useCveSeen() { + return { available: readonly(available), isNew, markAllSeen } +} + +export function resetCveSeenForTests(): void { + load() +} diff --git a/frontend/src/composables/useUrlState.ts b/frontend/src/composables/useUrlState.ts index 2560fb0..3827e13 100644 --- a/frontend/src/composables/useUrlState.ts +++ b/frontend/src/composables/useUrlState.ts @@ -2,8 +2,9 @@ import { watch, watchEffect, onMounted, ref, type Ref } from 'vue' import type { Context } from '../types/api' import { PPG_STAGING_CONTEXT } from '../lib/contexts' import type { WindowKey } from '../types/overview' +import type { CveView } from '../types/cveReport' -export type MainTab = 'board' | 'artifacts' | 'overview' | 'release' | 'settings' +export type MainTab = 'board' | 'artifacts' | 'overview' | 'release' | 'settings' | 'cves' export function contextToKey(ctx: Context): string { const parts = ctx.prefix.split(':') @@ -30,6 +31,7 @@ interface UrlStateOptions { artifactsContexts: Ref overviewWindow: Ref activeInstances: Ref + cveView: Ref } export function useUrlState(state: UrlStateOptions): void { @@ -37,7 +39,7 @@ export function useUrlState(state: UrlStateOptions): void { mainTab, boardCtx, version, activeTags, artifactsCtx, artifactsVersion, artifactsTab, boardContexts, artifactsContexts, overviewWindow, - activeInstances, + activeInstances, cveView, } = state // Pending raw URL keys awaiting context list population (PR contexts load async) @@ -50,7 +52,7 @@ export function useUrlState(state: UrlStateOptions): void { const params = new URLSearchParams(window.location.search) const tab = params.get('tab') - if (tab === 'board' || tab === 'artifacts' || tab === 'overview' || tab === 'release' || tab === 'settings') mainTab.value = tab + if (tab === 'board' || tab === 'artifacts' || tab === 'overview' || tab === 'release' || tab === 'settings' || tab === 'cves') mainTab.value = tab const ver = params.get('version') if (ver) version.value = ver @@ -70,6 +72,9 @@ export function useUrlState(state: UrlStateOptions): void { const owin = params.get('owin') if (owin === '24h' || owin === '48h' || owin === '7d') overviewWindow.value = owin + const cview = params.get('cview') + if (cview === 'released' || cview === 'images') cveView.value = cview + const ctxKey = params.get('ctx') if (ctxKey) { const resolved = keyToContext(ctxKey, boardContexts.value) @@ -134,6 +139,8 @@ export function useUrlState(state: UrlStateOptions): void { if (overviewWindow.value !== '24h') params.set('owin', overviewWindow.value) + if (cveView.value !== 'staging') params.set('cview', cveView.value) + const search = params.toString() history.replaceState(null, '', search ? `?${search}` : window.location.pathname) }) diff --git a/frontend/src/lib/cveReport.test.ts b/frontend/src/lib/cveReport.test.ts new file mode 100644 index 0000000..5015391 --- /dev/null +++ b/frontend/src/lib/cveReport.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest' +import type { CveEntry, CveImageRef, CveRow, CveStaging } from '../types/cveReport' +import { allRows, allSeenKeys, countNew, imagesSummary, rowIsNew, sortRows } from './cveReport' + +const entry = (seen_key: string): CveEntry => + ({ id: 'CVE-X', pkg: 'p', severity: 'HIGH', title: 't', seen_key }) +const row = (key: string, keys: string[]): CveRow => + ({ key, name: key, kind: 'obs_package', worst: 'HIGH', cves: keys.length, fixes: [], entries: keys.map(entry), images: [] }) +const staging = (ours: CveRow[], base_os: CveRow[] = [], unclassified: CveRow[] = []): CveStaging => + ({ ours, base_os, unclassified, cves: 0, images: 0 }) +const img = (repo: string): CveImageRef => ({ project: 'p', package: 'k', repo, arches: [] }) + +describe('cveReport helpers', () => { + it('allRows concatenates ours, base_os, unclassified', () => { + const a = row('ours|a', []), b = row('base_os|b', []), c = row('unclassified|c', []) + expect(allRows(staging([a], [b], [c]))).toEqual([a, b, c]) + }) + + it('allSeenKeys is distinct', () => { + const s = staging([row('ours|a', ['k1', 'k2'])], [row('base_os|b', ['k2'])]) + expect(allSeenKeys(s)).toEqual(['k1', 'k2']) + }) + + it('countNew counts a shared key once', () => { + const s = staging([row('ours|a', ['k1'])], [row('base_os|b', ['k1', 'k2'])]) + expect(countNew(s, () => true)).toBe(2) + expect(countNew(s, k => k === 'k1')).toBe(1) + }) + + it('rowIsNew is false when all entries are seen', () => { + const r = row('ours|a', ['k1', 'k2']) + expect(rowIsNew(r, () => false)).toBe(false) + expect(rowIsNew(r, k => k === 'k2')).toBe(true) + }) + + it('sortRows puts new rows first and keeps the rest in order', () => { + const a = row('a', ['ka']), b = row('b', ['kb']), c = row('c', ['kc']), d = row('d', ['kd']) + const isNew = (k: string) => k === 'kc' || k === 'kd' + expect(sortRows([a, b, c, d], isNew).map(r => r.key)).toEqual(['c', 'd', 'a', 'b']) + expect(sortRows([a, b], () => false).map(r => r.key)).toEqual(['a', 'b']) + }) + + it('imagesSummary', () => { + expect(imagesSummary([img('ubi9'), img('ubi9'), img('ubi8')])).toBe('3 images · ubi8, ubi9') + expect(imagesSummary([img('ubi9')])).toBe('1 image · ubi9') + const inProject = (project: string, repo: string): CveImageRef => ({ project, package: 'k', repo, arches: [] }) + expect(imagesSummary([ + inProject('ppg:staging:18', 'ubi9'), inProject('ppg:staging:17', 'ubi9'), inProject('ppg:staging:17', 'ubi8'), + ])).toBe('3 images · PG 17, 18 · ubi8, ubi9') + expect(imagesSummary([inProject('ppg:releases:16:containers', 'ubi9'), inProject('ppg:staging:devel', 'ubi9')])) + .toBe('2 images · PG 16 · ubi9') + }) +}) diff --git a/frontend/src/lib/cveReport.ts b/frontend/src/lib/cveReport.ts new file mode 100644 index 0000000..a2b6f3e --- /dev/null +++ b/frontend/src/lib/cveReport.ts @@ -0,0 +1,51 @@ +import type { CveImageRef, CveKind, CveRow, CveStaging } from '../types/cveReport' + +export const KIND_LABEL: Record = { + go_runtime: 'Go runtime', + bundled_library: 'bundled library', + obs_package: 'OBS package', + base_os: 'base OS', + unclassified: 'not classified', +} + +export function allRows(s: CveStaging): CveRow[] { + return [...s.ours, ...s.base_os, ...s.unclassified] +} + +export function allSeenKeys(s: CveStaging): string[] { + const keys = new Set() + for (const row of allRows(s)) for (const e of row.entries) keys.add(e.seen_key) + return [...keys] +} + +export function rowIsNew(row: CveRow, isNew: (k: string) => boolean): boolean { + return row.entries.some(e => isNew(e.seen_key)) +} + +export function countNew(s: CveStaging, isNew: (k: string) => boolean): number { + return allSeenKeys(s).filter(isNew).length +} + +// Rows with new entries first; Array.prototype.sort is stable, so the server +// order is kept within each group. +export function sortRows(rows: CveRow[], isNew: (k: string) => boolean): CveRow[] { + const flagged = rows.map(row => ({ row, fresh: rowIsNew(row, isNew) })) + return flagged.sort((a, b) => Number(b.fresh) - Number(a.fresh)).map(f => f.row) +} + +// PG major: the project segment right after "ppg:staging:" or "ppg:releases:". +function pgMajor(project: string): number | null { + const m = /^ppg:(?:staging|releases):(\d+)(?::|$)/.exec(project) + return m ? Number(m[1]) : null +} + +// "6 images · PG 17, 18 · ubi8, ubi9" +export function imagesSummary(images: CveImageRef[]): string { + const repos = [...new Set(images.map(i => i.repo))].sort() + const majors = [...new Set(images.map(i => pgMajor(i.project)).filter((m): m is number => m !== null))].sort((a, b) => a - b) + const n = images.length + const parts = [`${n} ${n === 1 ? 'image' : 'images'}`] + if (majors.length) parts.push(`PG ${majors.join(', ')}`) + parts.push(repos.join(', ')) + return parts.join(' · ') +} diff --git a/frontend/src/lib/overview.ts b/frontend/src/lib/overview.ts index 77a555c..48479e0 100644 --- a/frontend/src/lib/overview.ts +++ b/frontend/src/lib/overview.ts @@ -6,6 +6,14 @@ import { isPRProject } from './project' export const PROJECT_ACCENTS = ['#6E3FF3', '#2A78D4', '#1F9D55', '#E08A00', '#B0203A'] +// Accent for a project by its position in the NAME-sorted project list (not +// snapshot ordering, which is rebuild-sorted and would shuffle colours between +// windows/refetches). +export function projectAccent(sortedProjects: string[], project: string): string { + const idx = sortedProjects.indexOf(project) + return PROJECT_ACCENTS[Math.max(0, idx) % PROJECT_ACCENTS.length] +} + export function ageColor(days: number): string { if (days >= 45) return 'var(--crit)' if (days >= 21) return 'var(--high)' diff --git a/frontend/src/types/cveReport.ts b/frontend/src/types/cveReport.ts new file mode 100644 index 0000000..135ebe4 --- /dev/null +++ b/frontend/src/types/cveReport.ts @@ -0,0 +1,12 @@ +// Mirrors the JSON produced by backend/internal/cvereport exactly. +export type CveList = 'ours' | 'base_os' | 'unclassified' +export type CveKind = 'go_runtime' | 'bundled_library' | 'obs_package' | 'base_os' | 'unclassified' +export interface CveFix { pkg: string; installed: string; fixed: string } +export interface CveEntry { id: string; pkg: string; path?: string; severity: 'HIGH' | 'CRITICAL'; title: string; seen_key: string } +export interface CveImageRef { project: string; package: string; repo: string; arches: string[] } +export interface CveRow { key: string; name: string; kind: CveKind; vendor?: string; worst: 'HIGH' | 'CRITICAL'; cves: number; fixes: CveFix[]; entries: CveEntry[]; images: CveImageRef[] } +export interface CveStaging { ours: CveRow[]; base_os: CveRow[]; unclassified: CveRow[]; cves: number; images: number } +export interface ReleasedCve { id: string; pkg: string; installed: string; fixed: string; severity: 'HIGH' | 'CRITICAL'; title: string; status: 'fixed' | 'open' | 'no_staging'; staging_row_key?: string } +export interface ReleasedImage { project: string; package: string; repo: string; version: string; staging_project: string; staging_version?: string; total: number; fixed_in_staging: number; cves: ReleasedCve[] } +export interface CveReport { generated_at: string; staging: CveStaging; released: ReleasedImage[] } +export type CveView = 'staging' | 'released' | 'images'