mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
feat(api): add /api/system and per-package verdicts
Add a read-only /api/system endpoint with the effective scan policy, scanner health, rescan, cache and pre-warming settings. It exposes no credentials or paths. The package list now carries a verdict (cleared, held, bypassed or pending) with the reason and the applied bypass. /api/stats adds bypassed_packages. The vulnerability detail response adds the decision, a per-scanner severity breakdown and detected_by on each finding.
This commit is contained in:
@@ -463,6 +463,7 @@ func (a *App) setupServer() error {
|
||||
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
|
||||
a.app.Get("/api/info", mwAuth, a.handleInfo)
|
||||
a.app.Get("/api/system", mwAuth, a.handleSystem)
|
||||
|
||||
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
|
||||
a.app.Get("/api/analytics/trending", mwAuth, a.handleAnalyticsTrendingPackages)
|
||||
@@ -478,6 +479,7 @@ func (a *App) setupServer() error {
|
||||
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", a.handleStatsTrend)
|
||||
a.app.Get("/api/info", a.handleInfo)
|
||||
a.app.Get("/api/system", a.handleSystem)
|
||||
|
||||
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
|
||||
a.app.Get("/api/analytics/trending", a.handleAnalyticsTrendingPackages)
|
||||
|
||||
+50
-7
@@ -139,17 +139,53 @@ func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDe
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-row scan block of the list payload.
|
||||
// Verdicts the dashboard shows for a cached package.
|
||||
const (
|
||||
VerdictCleared = "cleared"
|
||||
VerdictHeld = "held"
|
||||
VerdictBypassed = "bypassed"
|
||||
VerdictPending = "pending"
|
||||
)
|
||||
|
||||
// verdictOf names the outcome of a scan decision: held beats bypassed, which beats cleared.
|
||||
func verdictOf(d scanner.ScanDecision) string {
|
||||
switch {
|
||||
case d.Blocked:
|
||||
return VerdictHeld
|
||||
case d.Bypass != nil:
|
||||
return VerdictBypassed
|
||||
default:
|
||||
return VerdictCleared
|
||||
}
|
||||
}
|
||||
|
||||
// bypassSummary is the public view of the bypass that waved a package through.
|
||||
func bypassSummary(b *metadata.CVEBypass) map[string]interface{} {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"id": b.ID,
|
||||
"type": b.Type,
|
||||
"target": b.Target,
|
||||
"reason": b.Reason,
|
||||
"created_by": b.CreatedBy,
|
||||
"created_at": b.CreatedAt,
|
||||
"expires_at": b.ExpiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-package scan block of the list response; verdict, reason and bypass extend the original fields.
|
||||
func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) map[string]interface{} {
|
||||
if !pkg.SecurityScanned {
|
||||
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false}
|
||||
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false, "verdict": VerdictPending}
|
||||
}
|
||||
d, ok := decisions[pkg.ID]
|
||||
if !ok || !d.Summary.HasScan {
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false}
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false, "verdict": VerdictPending}
|
||||
}
|
||||
sum := d.Summary
|
||||
return map[string]interface{}{
|
||||
info := map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": sum.Status,
|
||||
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
|
||||
@@ -161,11 +197,17 @@ func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanD
|
||||
},
|
||||
"total": sum.Total,
|
||||
"isBlocked": d.Blocked,
|
||||
"verdict": verdictOf(d),
|
||||
}
|
||||
if d.Reason != "" {
|
||||
info["reason"] = d.Reason
|
||||
}
|
||||
if d.Bypass != nil {
|
||||
info["bypass"] = bypassSummary(d.Bypass)
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// handleListPackages returns cached packages, one page of groups when page or
|
||||
// page_size is given and every group otherwise.
|
||||
func (a *App) handleListPackages(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
params, err := parseListParams(c)
|
||||
@@ -391,7 +433,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
blockedCount, err := a.countBlocked(ctx)
|
||||
blockedCount, bypassedCount, err := a.countVerdicts(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
@@ -410,6 +452,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
"scanned_packages": cacheStats.ScannedPackages,
|
||||
"vulnerable_packages": cacheStats.VulnerablePackages,
|
||||
"blocked_packages": blockedCount,
|
||||
"bypassed_packages": bypassedCount,
|
||||
}
|
||||
|
||||
// Convert registry stats to interface map
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/ghsa"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/govulncheck"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/grype"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/npmaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/osv"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/pipaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/trivy"
|
||||
)
|
||||
|
||||
type scannerSwitch struct {
|
||||
name string
|
||||
enabled bool
|
||||
}
|
||||
|
||||
// scannerSwitches lists every scanner the manager can register, in display order.
|
||||
func scannerSwitches(s config.ScannersConfig) []scannerSwitch {
|
||||
return []scannerSwitch{
|
||||
{trivy.ScannerName, s.Trivy.Enabled},
|
||||
{grype.ScannerName, s.Grype.Enabled},
|
||||
{osv.ScannerName, s.OSV.Enabled},
|
||||
{govulncheck.ScannerName, s.Govulncheck.Enabled},
|
||||
{npmaudit.ScannerName, s.NpmAudit.Enabled},
|
||||
{pipaudit.ScannerName, s.PipAudit.Enabled},
|
||||
{ghsa.ScannerName, s.GHSA.Enabled},
|
||||
}
|
||||
}
|
||||
|
||||
func seconds(d time.Duration) int64 { return int64(d / time.Second) }
|
||||
|
||||
// systemScanners joins the configured scanners with their cached health; disabled scanners report no health.
|
||||
func (a *App) systemScanners(ctx context.Context) []fiber.Map {
|
||||
sec := a.config.Security
|
||||
health := map[string]fiber.Map{}
|
||||
if sec.Enabled && a.scanManager != nil {
|
||||
for _, st := range a.scanManager.Statuses(ctx) {
|
||||
health[st.Name] = fiber.Map{"healthy": st.Healthy, "version": st.Version}
|
||||
}
|
||||
}
|
||||
out := make([]fiber.Map, 0, 7)
|
||||
for _, sw := range scannerSwitches(sec.Scanners) {
|
||||
entry := fiber.Map{"name": sw.name, "enabled": sw.enabled && sec.Enabled, "healthy": nil, "version": ""}
|
||||
if h, ok := health[sw.name]; ok {
|
||||
entry["healthy"], entry["version"] = h["healthy"], h["version"]
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// handleSystem reports the effective policy and settings; it exposes no credentials, DSNs or paths.
|
||||
// Durations are whole seconds; a negative threshold means unlimited.
|
||||
func (a *App) handleSystem(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
if c.Method() != "GET" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "method not allowed"})
|
||||
}
|
||||
|
||||
sec := a.config.Security
|
||||
scanWait := sec.ScanWaitTimeout
|
||||
if scanWait == 0 {
|
||||
scanWait = cache.DefaultScanWaitTimeout
|
||||
}
|
||||
concurrency := max(sec.RescanConcurrency, 1)
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"version": version.Version,
|
||||
"security": fiber.Map{
|
||||
"enabled": sec.Enabled,
|
||||
"fail_closed": sec.FailClosed,
|
||||
"scan_on_download": sec.ScanOnDownload,
|
||||
"block_on_severity": sec.BlockOnSeverity,
|
||||
"block_thresholds": fiber.Map{
|
||||
"critical": sec.BlockThresholds.Critical,
|
||||
"high": sec.BlockThresholds.High,
|
||||
"moderate": sec.BlockThresholds.Medium,
|
||||
"low": sec.BlockThresholds.Low,
|
||||
},
|
||||
"scan_wait_timeout": seconds(scanWait),
|
||||
"scanners": a.systemScanners(c.Context()),
|
||||
"rescan": fiber.Map{
|
||||
"interval": seconds(sec.RescanInterval),
|
||||
"active_window": seconds(sec.RescanActiveWindow),
|
||||
"concurrency": concurrency,
|
||||
"on_access": sec.RescanOnAccess,
|
||||
},
|
||||
},
|
||||
"cache": fiber.Map{
|
||||
"max_size": a.config.Cache.MaxSizeBytes,
|
||||
"idle_ttl": seconds(a.config.Cache.IdleTTL),
|
||||
"default_ttl": seconds(a.config.Cache.DefaultTTL),
|
||||
},
|
||||
"prewarming": fiber.Map{
|
||||
"enabled": a.prewarmWorker != nil && a.config.Prewarming.Enabled,
|
||||
"interval": seconds(a.config.Prewarming.Interval),
|
||||
"top_packages": a.config.Prewarming.TopPackages,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// jsonAt walks decoded JSON along keys (strings) and indexes (ints); a missing step yields nil.
|
||||
func jsonAt(v any, path ...any) any {
|
||||
for _, step := range path {
|
||||
switch k := step.(type) {
|
||||
case string:
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
v = m[k]
|
||||
case int:
|
||||
l, ok := v.([]any)
|
||||
if !ok || k >= len(l) {
|
||||
return nil
|
||||
}
|
||||
v = l[k]
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func getJSON(t *testing.T, a *App, target string) (map[string]any, string) {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out, body
|
||||
}
|
||||
|
||||
func disableAllScanners(c *config.Config) {
|
||||
sc := &c.Security.Scanners
|
||||
sc.Trivy.Enabled, sc.Grype.Enabled, sc.OSV.Enabled, sc.Govulncheck.Enabled = false, false, false, false
|
||||
sc.NpmAudit.Enabled, sc.PipAudit.Enabled, sc.GHSA.Enabled = false, false, false
|
||||
}
|
||||
|
||||
func TestSystemReportsEffectivePolicy(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
c.Security.FailClosed = true
|
||||
c.Security.BlockOnSeverity = "critical"
|
||||
c.Security.RescanInterval = 6 * time.Hour
|
||||
c.Security.RescanConcurrency = 0
|
||||
c.Security.ScanWaitTimeout = 0
|
||||
disableAllScanners(c)
|
||||
c.Cache.MaxSizeBytes = 1 << 30
|
||||
c.Cache.IdleTTL = 24 * time.Hour
|
||||
c.Cache.DefaultTTL = 7 * 24 * time.Hour
|
||||
})
|
||||
|
||||
out, _ := getJSON(t, a, "/api/system")
|
||||
checks := map[string][2]any{
|
||||
"fail_closed": {jsonAt(out, "security", "fail_closed"), true},
|
||||
"block_on_severity": {jsonAt(out, "security", "block_on_severity"), "critical"},
|
||||
"rescan interval": {jsonAt(out, "security", "rescan", "interval"), float64(6 * 3600)},
|
||||
"rescan workers": {jsonAt(out, "security", "rescan", "concurrency"), float64(1)},
|
||||
"scan wait": {jsonAt(out, "security", "scan_wait_timeout"), float64(30)},
|
||||
"cache max": {jsonAt(out, "cache", "max_size"), float64(1 << 30)},
|
||||
"cache idle": {jsonAt(out, "cache", "idle_ttl"), float64(86400)},
|
||||
"cache default": {jsonAt(out, "cache", "default_ttl"), float64(7 * 86400)},
|
||||
}
|
||||
for name, c := range checks {
|
||||
if c[0] != c[1] {
|
||||
t.Errorf("%s = %v, want %v", name, c[0], c[1])
|
||||
}
|
||||
}
|
||||
scanners, _ := jsonAt(out, "security", "scanners").([]any)
|
||||
if len(scanners) != 7 {
|
||||
t.Fatalf("scanners = %d entries, want all 7", len(scanners))
|
||||
}
|
||||
for i := range scanners {
|
||||
if jsonAt(scanners, i, "enabled") != false || jsonAt(scanners, i, "healthy") != nil {
|
||||
t.Errorf("disabled scanner %v reported %v", jsonAt(scanners, i, "name"), scanners[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The system view is for display only; no configured secret or path may appear in it.
|
||||
func TestSystemLeaksNoSecrets(t *testing.T) {
|
||||
const secret = "ghp_super-secret-token"
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
disableAllScanners(c)
|
||||
c.Security.Scanners.GHSA.Token = secret
|
||||
c.Security.Scanners.Trivy.CacheDB = "/srv/private/trivy-db"
|
||||
})
|
||||
_, body := getJSON(t, a, "/api/system")
|
||||
for _, banned := range []string{secret, "/srv/private", "token", "dsn", "password"} {
|
||||
if strings.Contains(strings.ToLower(body), strings.ToLower(banned)) {
|
||||
t.Errorf("/api/system exposes %q: %s", banned, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemRequiresAuthWhenEnabled(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Auth.Enabled = true })
|
||||
code, _, _ := doRequest(t, a, "/api/system", nil)
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Errorf("GET /api/system without a key = %d, want 401", code)
|
||||
}
|
||||
}
|
||||
|
||||
func seedBypassed(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for _, name := range []string{"held", "waved", "plain"} {
|
||||
if err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name, Size: 10, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
res := &metadata.ScanResult{Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "trivy+osv", Status: metadata.ScanStatusClean, ScannedAt: now}
|
||||
if name != "plain" {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.VulnerabilityCount = 2
|
||||
res.Vulnerabilities = []metadata.Vulnerability{
|
||||
{ID: "CVE-2021-44906", Severity: "critical", DetectedBy: []string{"trivy", "osv"}, FixedIn: "1.2.6"},
|
||||
{ID: "CVE-2022-0001", Severity: "low", DetectedBy: []string{"osv"}},
|
||||
}
|
||||
}
|
||||
if err := a.metadata.SaveScanResult(ctx, res); err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
}
|
||||
if err := a.metadata.SaveCVEBypass(ctx, &metadata.CVEBypass{
|
||||
Type: metadata.BypassTypePackage, Target: "npm/[email protected]", Reason: "vendor patch", CreatedBy: "alice",
|
||||
Active: true, ExpiresAt: now.Add(48 * time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveCVEBypass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newVerdictApp(t *testing.T) *App {
|
||||
t.Helper()
|
||||
a, _ := newScanningApp(t)
|
||||
a.config.Security.BlockOnSeverity = "critical"
|
||||
seedBypassed(t, a)
|
||||
return a
|
||||
}
|
||||
|
||||
func TestListPackagesCarriesVerdicts(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages")
|
||||
pkgs, _ := out["packages"].([]any)
|
||||
got := map[string]string{}
|
||||
for i := range pkgs {
|
||||
name, _ := jsonAt(pkgs, i, "name").(string)
|
||||
verdict, _ := jsonAt(pkgs, i, "vulnerabilities", "verdict").(string)
|
||||
got[name] = verdict
|
||||
if name == "held" && jsonAt(pkgs, i, "vulnerabilities", "reason") == nil {
|
||||
t.Errorf("held package has no reason")
|
||||
}
|
||||
if name == "waved" && jsonAt(pkgs, i, "vulnerabilities", "bypass", "created_by") != "alice" {
|
||||
t.Errorf("bypassed package bypass = %v", jsonAt(pkgs, i, "vulnerabilities", "bypass"))
|
||||
}
|
||||
}
|
||||
want := map[string]string{"held": VerdictHeld, "waved": VerdictBypassed, "plain": VerdictCleared}
|
||||
for name, verdict := range want {
|
||||
if got[name] != verdict {
|
||||
t.Errorf("%s verdict = %q, want %q", name, got[name], verdict)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsCountsBypassedPackages(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/stats")
|
||||
if jsonAt(out, "stats", "blocked_packages") != float64(1) || jsonAt(out, "stats", "bypassed_packages") != float64(1) {
|
||||
t.Errorf("stats = %v, want 1 held and 1 bypassed", out["stats"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVulnerabilityDetailsExplainVerdictAndScanners(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
details := func(name string) map[string]any {
|
||||
out, _ := getJSON(t, a, "/api/packages/npm/"+name+"/1.0.0/vulnerabilities")
|
||||
return out
|
||||
}
|
||||
|
||||
held := details("held")
|
||||
if jsonAt(held, "decision", "verdict") != VerdictHeld || jsonAt(held, "decision", "blocked") != true || jsonAt(held, "decision", "reason") == "" {
|
||||
t.Errorf("held decision = %v", held["decision"])
|
||||
}
|
||||
scanners, _ := held["scanners"].([]any)
|
||||
if len(scanners) != 2 {
|
||||
t.Fatalf("scanners = %v, want trivy and osv", scanners)
|
||||
}
|
||||
findings := map[string]any{}
|
||||
for i := range scanners {
|
||||
findings[jsonAt(scanners, i, "name").(string)] = jsonAt(scanners, i, "findings")
|
||||
}
|
||||
if findings["trivy"] != float64(1) || findings["osv"] != float64(2) {
|
||||
t.Errorf("findings per scanner = %v, want trivy 1, osv 2", findings)
|
||||
}
|
||||
if jsonAt(scanners, 0, "severity_counts", "critical") != float64(1) {
|
||||
t.Errorf("trivy severity counts = %v", jsonAt(scanners, 0, "severity_counts"))
|
||||
}
|
||||
if by, _ := jsonAt(held, "vulnerabilities", 0, "detected_by").([]any); len(by) != 2 {
|
||||
t.Errorf("detected_by = %v", by)
|
||||
}
|
||||
|
||||
waved := details("waved")
|
||||
if jsonAt(waved, "decision", "verdict") != VerdictBypassed || jsonAt(waved, "decision", "blocked") != false ||
|
||||
jsonAt(waved, "decision", "bypass", "reason") != "vendor patch" {
|
||||
t.Errorf("bypassed decision = %v", waved["decision"])
|
||||
}
|
||||
|
||||
plain := details("plain")
|
||||
if jsonAt(plain, "decision", "verdict") != VerdictCleared || jsonAt(plain, "decision", "bypass") != nil {
|
||||
t.Errorf("clean decision = %v", plain["decision"])
|
||||
}
|
||||
}
|
||||
@@ -55,20 +55,31 @@ func (a *App) handleStatsTrend(c fiber.Ctx) error {
|
||||
|
||||
// countBlocked counts scanned artifacts the blocking policy refuses.
|
||||
func (a *App) countBlocked(ctx context.Context) (int64, error) {
|
||||
blocked, _, err := a.countVerdicts(ctx)
|
||||
return blocked, err
|
||||
}
|
||||
|
||||
// countVerdicts counts scanned artifacts that are held and that pass only because an admin bypass applies.
|
||||
func (a *App) countVerdicts(ctx context.Context) (blocked, bypassed int64, err error) {
|
||||
if !a.config.Security.Enabled || a.scanManager == nil {
|
||||
return 0, nil
|
||||
return 0, 0, nil
|
||||
}
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, 0, err
|
||||
}
|
||||
var blocked int64
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
if metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
continue
|
||||
}
|
||||
switch verdictOf(d) {
|
||||
case VerdictHeld:
|
||||
blocked++
|
||||
case VerdictBypassed:
|
||||
bypassed++
|
||||
}
|
||||
}
|
||||
return blocked, nil
|
||||
return blocked, bypassed, nil
|
||||
}
|
||||
|
||||
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
|
||||
|
||||
@@ -70,6 +70,8 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
"vulnerability_count": 0,
|
||||
"message": "Package not yet scanned for vulnerabilities",
|
||||
"security_scanned": pkg.SecurityScanned,
|
||||
"decision": fiber.Map{"verdict": VerdictPending, "blocked": false, "reason": "", "bypass": nil},
|
||||
"scanners": []interface{}{},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -135,6 +137,7 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
"description": vuln.Description,
|
||||
"references": vuln.References,
|
||||
"fixed_in": vuln.FixedIn,
|
||||
"detected_by": vuln.DetectedBy,
|
||||
"bypassed": bypassed,
|
||||
}
|
||||
|
||||
@@ -166,6 +169,8 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
"low": severityCounts["LOW"],
|
||||
},
|
||||
"bypassed_count": len(scanResult.Vulnerabilities) - (severityCounts["CRITICAL"] + severityCounts["HIGH"] + severityCounts["MODERATE"] + severityCounts["LOW"]),
|
||||
"scanners": scannerBreakdown(scanResult),
|
||||
"decision": a.packageDecision(ctx, pkg),
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
@@ -190,3 +195,58 @@ func (a *App) resolvePackageKey(ctx context.Context, registry, name, version str
|
||||
}
|
||||
return name, nil, err
|
||||
}
|
||||
|
||||
// scannerBreakdown counts each scanner's findings by severity, from the merged scan's detected_by lists.
|
||||
func scannerBreakdown(res *metadata.ScanResult) []map[string]interface{} {
|
||||
names := strings.Split(res.Scanner, "+")
|
||||
counts := make(map[string]map[string]int, len(names))
|
||||
for _, n := range names {
|
||||
counts[n] = map[string]int{"critical": 0, "high": 0, "moderate": 0, "low": 0}
|
||||
}
|
||||
for _, v := range res.Vulnerabilities {
|
||||
by := v.DetectedBy
|
||||
if len(by) == 0 && len(names) == 1 {
|
||||
by = names
|
||||
}
|
||||
sev := strings.ToLower(metadata.NormalizeSeverity(v.Severity))
|
||||
for _, n := range by {
|
||||
if c, ok := counts[n]; ok {
|
||||
c[sev]++
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]map[string]interface{}, 0, len(names))
|
||||
for _, n := range names {
|
||||
if n == "" {
|
||||
continue
|
||||
}
|
||||
c := counts[n]
|
||||
out = append(out, map[string]interface{}{
|
||||
"name": n,
|
||||
"findings": c["critical"] + c["high"] + c["moderate"] + c["low"],
|
||||
"severity_counts": c,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// packageDecision is the verdict the proxy applies to one package, with the bypass that applied.
|
||||
func (a *App) packageDecision(ctx context.Context, pkg *metadata.Package) fiber.Map {
|
||||
decision := fiber.Map{"verdict": VerdictCleared, "blocked": false, "reason": "", "bypass": nil}
|
||||
if pkg == nil {
|
||||
return decision
|
||||
}
|
||||
list, err := a.scanDecisions(ctx, []string{pkg.ID})
|
||||
if err != nil || len(list) == 0 {
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to judge package")
|
||||
}
|
||||
return decision
|
||||
}
|
||||
d := list[0]
|
||||
decision["verdict"] = verdictOf(d)
|
||||
decision["blocked"] = d.Blocked
|
||||
decision["reason"] = d.Reason
|
||||
decision["bypass"] = bypassSummary(d.Bypass)
|
||||
return decision
|
||||
}
|
||||
|
||||
Vendored
+3
-2
@@ -95,7 +95,8 @@ type Config struct {
|
||||
RescanAfter time.Duration // Rescan a cache hit whose scan result is older than this before serving (0 = off)
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
// DefaultScanWaitTimeout is how long a first download waits for its scan when none is configured.
|
||||
const DefaultScanWaitTimeout = 30 * time.Second
|
||||
|
||||
// cleanupBatchSize bounds how many rows one cleanup query reads.
|
||||
const cleanupBatchSize = metadata.DefaultBatchSize
|
||||
@@ -196,7 +197,7 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
}
|
||||
|
||||
if config.ScanWaitTimeout == 0 {
|
||||
config.ScanWaitTimeout = defaultScanWaitTimeout
|
||||
config.ScanWaitTimeout = DefaultScanWaitTimeout
|
||||
}
|
||||
|
||||
if config.MaxPackageSize == 0 {
|
||||
|
||||
Reference in New Issue
Block a user