Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: redesigned risk based security view (#4204)
Kyle Mendellcac682df3161
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex ad7e4a1d5..f82261fcf 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -104,6 +104,7 @@ type registerJobsParams struct {ScheduledPrune *scheduler.ScheduledPruneJobFilesystemWatcher *scheduler.FilesystemWatcherJobVulnerabilityScan *scheduler.VulnerabilityScanJob+ VulnerabilityRisk *scheduler.VulnerabilityRiskJobAutoPatch *scheduler.AutoPatchJobAutoHeal *scheduler.AutoHealJobActivitySweep *scheduler.ActivitySweepJob@@ -151,6 +152,7 @@ func registerJobs(params registerJobsParams) error {params.ExpiredSessionsCleanup,params.ScheduledPrune,params.VulnerabilityScan,+ params.VulnerabilityRisk,params.AutoPatch,params.AutoHeal,params.ActivitySweep,@@ -196,6 +198,7 @@ func registerJobs(params registerJobsParams) error {FilesystemWatcher: params.FilesystemWatcher,ScheduledPrune: params.ScheduledPrune,VulnerabilityScan: params.VulnerabilityScan,+ VulnerabilityRisk: params.VulnerabilityRisk,AutoPatch: params.AutoPatch,AutoHeal: params.AutoHeal,Apns: params.Apns,@@ -284,6 +287,7 @@ type settingsSubscriptionsParams struct {FilesystemWatcher *scheduler.FilesystemWatcherJobScheduledPrune *scheduler.ScheduledPruneJobVulnerabilityScan *scheduler.VulnerabilityScanJob+ VulnerabilityRisk *scheduler.VulnerabilityRiskJobAutoPatch *scheduler.AutoPatchJobAutoHeal *scheduler.AutoHealJobApns *apns.ApnsService@@ -308,6 +312,13 @@ func setupSettingsSubscriptionsInternal(params settingsSubscriptionsParams) errosubscribe := func(keys []string, callback func([]libarcane.SettingUpdate)) {unsubscribes = append(unsubscribes, params.Settings.SubscribeSettingsChanges(keys, callback))}+ rescheduleOn := func(keys []string, job schedulertypes.Job) {+ subscribe(keys, func(_ []libarcane.SettingUpdate) {+ if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, job); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to reschedule job", "job", job.Name(), "error", err)+ }+ })+ }timeoutSyncExecutor, cancelTimeoutSync, err := setupTimeoutSettingsSubscriptionInternal(params, subscribe)if err != nil {return err@@ -329,11 +340,7 @@ func setupSettingsSubscriptionsInternal(params settingsSubscriptionsParams) erro})})- subscribe([]string{"autoUpdate", "autoUpdateInterval"}, func(_ []libarcane.SettingUpdate) {- if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.AutoUpdate); err != nil {- slog.WarnContext(params.LifecycleCtx, "Failed to reschedule auto-update job", "error", err)- }- })+ rescheduleOn([]string{"autoUpdate", "autoUpdateInterval"}, params.AutoUpdate)subscribe([]string{"projectsDirectory", "followProjectSymlinks"}, func(_ []libarcane.SettingUpdate) {if params.FilesystemWatcher != nil {@@ -351,38 +358,14 @@ func setupSettingsSubscriptionsInternal(params settingsSubscriptionsParams) erro}})- subscribe([]string{"scheduledPruneEnabled", "scheduledPruneInterval"}, func(_ []libarcane.SettingUpdate) {- if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.ScheduledPrune); err != nil {- slog.WarnContext(params.LifecycleCtx, "Failed to reschedule scheduled-prune job", "error", err)- }- })-- subscribe(- []string{- features.VulnerabilityManagementSettingKey, "vulnerabilityScanEnabled", "vulnerabilityScanInterval", "trivyNetwork", "trivySecurityOpts", "trivyPrivileged",- "trivyResourceLimitsEnabled", "trivyCpuLimit", "trivyMemoryLimitMb", "trivyConcurrentScanContainers",- },- func(_ []libarcane.SettingUpdate) {- if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.VulnerabilityScan); err != nil {- slog.WarnContext(params.LifecycleCtx, "Failed to reschedule vulnerability-scan job", "error", err)- }- },- )-- subscribe([]string{features.VulnerabilityManagementSettingKey, "imageAutoPatchEnabled", "imageAutoPatchInterval"}, func(_ []libarcane.SettingUpdate) {- if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.AutoPatch); err != nil {- slog.WarnContext(params.LifecycleCtx, "Failed to reschedule auto-patch job", "error", err)- }- })-- subscribe(- []string{"autoHealEnabled", "autoHealInterval", "autoHealExcludedContainers", "autoHealMaxRestarts", "autoHealRestartWindow"},- func(_ []libarcane.SettingUpdate) {- if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.AutoHeal); err != nil {- slog.WarnContext(params.LifecycleCtx, "Failed to reschedule auto-heal job", "error", err)- }- },- )+ rescheduleOn([]string{"scheduledPruneEnabled", "scheduledPruneInterval"}, params.ScheduledPrune)+ rescheduleOn([]string{+ features.VulnerabilityManagementSettingKey, "vulnerabilityScanEnabled", "vulnerabilityScanInterval", "trivyNetwork", "trivySecurityOpts", "trivyPrivileged",+ "trivyResourceLimitsEnabled", "trivyCpuLimit", "trivyMemoryLimitMb", "trivyConcurrentScanContainers",+ }, params.VulnerabilityScan)+ rescheduleOn([]string{features.VulnerabilityManagementSettingKey}, params.VulnerabilityRisk)+ rescheduleOn([]string{features.VulnerabilityManagementSettingKey, "imageAutoPatchEnabled", "imageAutoPatchInterval"}, params.AutoPatch)+ rescheduleOn([]string{"autoHealEnabled", "autoHealInterval", "autoHealExcludedContainers", "autoHealMaxRestarts", "autoHealRestartWindow"}, params.AutoHeal)params.Lifecycle.Append(fx.Hook{OnStop: func(ctx context.Context) error {diff --git a/backend/internal/bootstrap/jobs_bootstrap_test.go b/backend/internal/bootstrap/jobs_bootstrap_test.goindex cd4c5c488..0cc1b217c 100644--- a/backend/internal/bootstrap/jobs_bootstrap_test.go+++ b/backend/internal/bootstrap/jobs_bootstrap_test.go@@ -136,13 +136,14 @@ func TestFeatureChangeReschedulesScanAndPatchJobsInternal(t *testing.T) {ActorRuntime: runtime,Settings: settings,VulnerabilityScan: scheduler.NewVulnerabilityScanJob(nil, nil),+ VulnerabilityRisk: scheduler.NewVulnerabilityRiskJob(nil, nil),AutoPatch: scheduler.NewAutoPatchJob(nil, nil),}))- require.Len(t, settings.featureCallbacks, 2)+ require.Len(t, settings.featureCallbacks, 3)for _, callback := range settings.featureCallbacks {callback([]libarcane.SettingUpdate{{Key: features.VulnerabilityManagementSettingKey, Value: "false"}})}- require.ElementsMatch(t, []string{scheduler.VulnerabilityScanJobName, scheduler.AutoPatchJobName}, schedulerStub.jobs)+ require.ElementsMatch(t, []string{scheduler.VulnerabilityScanJobName, scheduler.VulnerabilityRiskJobName, scheduler.AutoPatchJobName}, schedulerStub.jobs)stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()require.NoError(t, lifecycle.Stop(stopCtx))diff --git a/backend/internal/config/schema/schema.go b/backend/internal/config/schema/schema.goindex d7524dd44..22a25718f 100644--- a/backend/internal/config/schema/schema.go+++ b/backend/internal/config/schema/schema.go@@ -132,6 +132,9 @@ var overrideDocRules = map[string]overrideDocRule{"vulnerabilityScanInterval": {requires: "FEATURE_VULNERABILITY_MANAGEMENT_ENABLED=true and VULNERABILITY_SCAN_ENABLED=true to have effect at runtime.",},+ "vulnerabilityThreatIntelEnabled": {+ requires: "FEATURE_VULNERABILITY_MANAGEMENT_ENABLED=true to have effect at runtime.",+ },"autoHealInterval": {requires: "AUTO_HEAL_ENABLED=true to have effect at runtime.",},diff --git a/backend/internal/config/schema/schema_test.go b/backend/internal/config/schema/schema_test.goindex 29a33ef59..43fe6f242 100644--- a/backend/internal/config/schema/schema_test.go+++ b/backend/internal/config/schema/schema_test.go@@ -381,4 +381,5 @@ var expectedSettingOverrideKeys = []string{"volumeHelperIdleTimeout","vulnerabilityScanEnabled","vulnerabilityScanInterval",+ "vulnerabilityThreatIntelEnabled",}diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.goindex 028c940fc..6cbe749cf 100644--- a/backend/internal/database/database_test.go+++ b/backend/internal/database/database_test.go@@ -119,6 +119,44 @@ func TestMigration066_GlobalVariables_UpAndDown(t *testing.T) {assert.Zero(t, rowCount)}+func TestMigration088_VulnerabilityRisk_BackfillsCVSSAndDowngrades(t *testing.T) {+ ctx := context.Background()+ rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-vulnerability-risk.db")++ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 87))+ _, err := rawDB.Exec(`INSERT INTO vulnerability_scans (id, image_name, status, scan_time) VALUES ('img-1', 'nginx:latest', 'completed', CURRENT_TIMESTAMP)`)+ require.NoError(t, err)+ _, err = rawDB.Exec(`INSERT INTO vulnerability_scan_items (image_id, vulnerability_id, pkg_name, severity, details) VALUES+ ('img-1', 'CVE-V3', 'openssl', 'HIGH', '{"cvss":{"v2Score":5,"v3Score":7.5}}'),+ ('img-1', 'CVE-V2', 'curl', 'MEDIUM', '{"cvss":{"v2Score":4.3}}'),+ ('img-1', 'CVE-NONE', 'zlib', 'LOW', NULL)`)+ require.NoError(t, err)++ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 88))+ scores := map[string]stdsql.NullFloat64{}+ rows, err := rawDB.Query(`SELECT vulnerability_id, cvss_score FROM vulnerability_scan_items`)+ require.NoError(t, err)+ for rows.Next() {+ var id string+ var score stdsql.NullFloat64+ require.NoError(t, rows.Scan(&id, &score))+ scores[id] = score+ }+ require.NoError(t, rows.Err())+ require.NoError(t, rows.Close())+ assert.InDelta(t, 7.5, scores["CVE-V3"].Float64, 0.001)+ assert.InDelta(t, 4.3, scores["CVE-V2"].Float64, 0.001)+ assert.False(t, scores["CVE-NONE"].Valid)++ var tableCount int+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('vulnerability_threat_intel', 'vulnerability_risk_snapshots')`).Scan(&tableCount))+ assert.Equal(t, 2, tableCount)++ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 87))+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('vulnerability_threat_intel', 'vulnerability_risk_snapshots')`).Scan(&tableCount))+ assert.Zero(t, tableCount)+}+func TestMigration067_ActivityBatchID_UpAndDown(t *testing.T) {ctx := context.Background()rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-activity-batch-id.db")diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex a830fa7f8..5283cf540 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -147,6 +147,7 @@ var JobOptions = fx.Options(scheduler.NewScheduledPruneJob,provideFilesystemWatcherJobInternal,scheduler.NewVulnerabilityScanJob,+ scheduler.NewVulnerabilityRiskJob,scheduler.NewAutoPatchJob,scheduler.NewAutoHealJob,scheduler.NewActivitySweepJob,diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.goindex 086724018..53becf70c 100644--- a/backend/internal/settings/model.go+++ b/backend/internal/settings/model.go@@ -130,6 +130,7 @@ type Settings struct {FeatureVulnerabilityManagementEnabled SettingVariable `key:"featureVulnerabilityManagementEnabled,public,envOverride" meta:"label=Vulnerability management;type=boolean;keywords=features,vulnerability,security,scan,enable,disable;category=general;description=Enable vulnerability management for this environment. Disabling retains reports and configuration and leaves standalone image patching available"`VulnerabilityScanEnabled SettingVariable `key:"vulnerabilityScanEnabled" meta:"label=Scheduled Vulnerability Scan;type=boolean;keywords=vulnerability,scan,security,trivy,schedule,automatic,cve;category=security;description=Enable scheduled vulnerability scanning of all Docker images" catmeta:"id=security;title=Security;icon=shield;url=/settings/security;description=Configure vulnerability scanning and runtime security settings"`VulnerabilityScanInterval SettingVariable `key:"vulnerabilityScanInterval" meta:"label=Vulnerability Scan Interval;type=cron;keywords=vulnerability,scan,interval,schedule,frequency,trivy,cve;category=security;description=How often to run scheduled vulnerability scans (cron expression)"`+ VulnerabilityThreatIntelEnabled SettingVariable `key:"vulnerabilityThreatIntelEnabled,envOverride" meta:"label=Threat Intelligence;type=boolean;keywords=kev,cisa,epss,first,exploit,threat,intel,risk,airgap,offline,security;category=security;description=Fetch the CISA KEV catalog and FIRST EPSS scores to prioritize exploited vulnerabilities. Disable for air-gapped installs."`TrivyDbRegistry SettingVariable `key:"trivyDbRegistry,envOverride" meta:"label=Trivy DB Registry;type=select;keywords=trivy,db,java-db,checks,registry,ghcr,docker,hub,vulnerability,security,scanner;category=security;description=Container registry used to pull the Trivy vulnerability database artifacts"`TrivyNetwork SettingVariable `key:"trivyNetwork,envOverride" meta:"label=Trivy Network;type=text;keywords=trivy,network,mode,bridge,host,none,scanner,vulnerability,security;category=security;description=Docker network mode/network name used for Trivy scan containers. Leave empty to inherit Arcane's network automatically."`TrivySecurityOpts SettingVariable `key:"trivySecurityOpts,envOverride" meta:"label=Trivy Security Options;type=textarea;keywords=trivy,security,opt,security_opt,selinux,labels,apparmor,scanner;category=security;description=Docker security options applied to Trivy scan containers. Use commas or new lines to separate entries (for example: label=disable)"`diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.goindex b60211734..678ebc009 100644--- a/backend/internal/settings/service.go+++ b/backend/internal/settings/service.go@@ -249,6 +249,7 @@ func DefaultSettingsConfig() *Settings {FeatureVulnerabilityManagementEnabled: SettingVariable{Value: "true"},VulnerabilityScanEnabled: SettingVariable{Value: "false"},VulnerabilityScanInterval: SettingVariable{Value: "0 0 0 * * *"},+ VulnerabilityThreatIntelEnabled: SettingVariable{Value: "true"},TrivyDbRegistry: SettingVariable{Value: "ghcr.io"},TrivyNetwork: SettingVariable{Value: ""},TrivySecurityOpts: SettingVariable{Value: ""},diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.goindex 0115af13b..d66941c19 100644--- a/backend/internal/vulnerability/handler.go+++ b/backend/internal/vulnerability/handler.go@@ -65,6 +65,10 @@ type GetEnvironmentSummaryInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`}+type GetRiskOverviewInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}+type ListAllVulnerabilitiesInput struct {EnvironmentID string `path:"id" doc:"Environment ID"`Search string `query:"search" doc:"Search query"`@@ -206,6 +210,17 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *VulnerabilityServSecurity: handlerutil.DefaultOperationSecurity(),}, authz.PermVulnsRead, h.GetEnvironmentSummary)+ middleware.RegisterWithPermission(api, huma.Operation{+ Middlewares: featureMiddleware,+ OperationID: "get-environment-vulnerability-overview",+ Method: http.MethodGet,+ Path: "/environments/{id}/vulnerabilities/overview",+ Summary: "Get environment vulnerability risk overview",+ Description: "Retrieves the environment risk score, trend, drivers, riskiest images and priority findings",+ Tags: []string{"Vulnerabilities"},+ Security: handlerutil.DefaultOperationSecurity(),+ }, authz.PermVulnsRead, h.GetRiskOverview)+middleware.RegisterWithPermission(api, huma.Operation{Middlewares: featureMiddleware,OperationID: "list-environment-vulnerabilities",@@ -353,7 +368,7 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetS// GetScanResult retrieves the vulnerability scan result for an image.func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*handlerutil.Out[vulnerability.ScanResult], error) {- result, err := h.vulnerabilityService.GetScanResult(ctx, input.ImageID)+ result, err := h.vulnerabilityService.GetScanResult(ctx, input.EnvironmentID, input.ImageID)if err != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())}@@ -420,6 +435,21 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inp}, nil}+// GetRiskOverview returns the vulnerability risk overview for the environment.+func (h *VulnerabilityHandler) GetRiskOverview(ctx context.Context, input *GetRiskOverviewInput) (*handlerutil.Out[vulnerability.RiskOverview], error) {+ overview, err := h.vulnerabilityService.GetRiskOverview(ctx, input.EnvironmentID)+ if err != nil {+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability risk overview").Error())+ }++ return &handlerutil.Out[vulnerability.RiskOverview]{+ Body: base.ApiResponse[vulnerability.RiskOverview]{+ Success: true,+ Data: *overview,+ },+ }, nil+}+// GetEnvironmentSummary returns aggregated vulnerability info for the current environment.func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*handlerutil.Out[vulnerability.EnvironmentVulnerabilitySummary], error) {summary, err := h.vulnerabilityService.GetEnvironmentSummary(ctx)diff --git a/backend/internal/vulnerability/model.go b/backend/internal/vulnerability/model.goindex 9b63a309d..dfb4caf7a 100644--- a/backend/internal/vulnerability/model.go+++ b/backend/internal/vulnerability/model.go@@ -72,24 +72,68 @@ func (VulnerabilityReportRecord) TableName() string {// VulnerabilityScanItem is one CVE finding from a completed scan, normalized for list queries.type VulnerabilityScanItem struct {- ID int64 `json:"id" gorm:"primaryKey;autoIncrement;column:id"`- ImageID string `json:"imageId" gorm:"column:image_id;index"`- VulnerabilityID string `json:"vulnerabilityId" gorm:"column:vulnerability_id;index"`- PkgName string `json:"pkgName" gorm:"column:pkg_name"`- InstalledVersion string `json:"installedVersion" gorm:"column:installed_version"`- FixedVersion string `json:"fixedVersion" gorm:"column:fixed_version"`- Severity string `json:"severity" gorm:"column:severity;index"`- SeverityRank int `json:"severityRank" gorm:"column:severity_rank"`- PkgClass string `json:"pkgClass" gorm:"column:pkg_class"`- PkgType string `json:"pkgType" gorm:"column:pkg_type"`- Title string `json:"title" gorm:"column:title"`- Details *string `json:"-" gorm:"column:details"`+ ID int64 `json:"id" gorm:"primaryKey;autoIncrement;column:id"`+ ImageID string `json:"imageId" gorm:"column:image_id;index"`+ VulnerabilityID string `json:"vulnerabilityId" gorm:"column:vulnerability_id;index"`+ PkgName string `json:"pkgName" gorm:"column:pkg_name"`+ InstalledVersion string `json:"installedVersion" gorm:"column:installed_version"`+ FixedVersion string `json:"fixedVersion" gorm:"column:fixed_version"`+ Severity string `json:"severity" gorm:"column:severity;index"`+ SeverityRank int `json:"severityRank" gorm:"column:severity_rank"`+ PkgClass string `json:"pkgClass" gorm:"column:pkg_class"`+ PkgType string `json:"pkgType" gorm:"column:pkg_type"`+ Title string `json:"title" gorm:"column:title"`+ CVSSScore *float64 `json:"cvssScore,omitempty" gorm:"column:cvss_score"`+ Details *string `json:"-" gorm:"column:details"`}func (VulnerabilityScanItem) TableName() string {return "vulnerability_scan_items"}+// VulnerabilityThreatIntel caches CISA KEV and FIRST EPSS data per CVE.+type VulnerabilityThreatIntel struct {+ CVEID string `gorm:"column:cve_id;primaryKey"`+ KnownExploited bool `gorm:"column:known_exploited"`+ KEVDateAdded string `gorm:"column:kev_date_added"`+ KEVDueDate string `gorm:"column:kev_due_date"`+ KEVRansomware bool `gorm:"column:kev_ransomware"`+ EPSSScore *float64 `gorm:"column:epss_score"`+ EPSSPercentile *float64 `gorm:"column:epss_percentile"`+ EPSSCheckedAt *time.Time `gorm:"column:epss_checked_at"`+ UpdatedAt *time.Time `gorm:"column:updated_at"`+}++func (VulnerabilityThreatIntel) TableName() string {+ return "vulnerability_threat_intel"+}++// VulnerabilityRiskSnapshot stores one day of environment risk for the trend.+type VulnerabilityRiskSnapshot struct {+ SnapshotDate string `gorm:"column:snapshot_date;primaryKey"`+ RiskScore int `gorm:"column:risk_score"`+ RiskBand string `gorm:"column:risk_band"`+ CriticalCount int `gorm:"column:critical_count"`+ HighCount int `gorm:"column:high_count"`+ MediumCount int `gorm:"column:medium_count"`+ LowCount int `gorm:"column:low_count"`+ UnknownCount int `gorm:"column:unknown_count"`+ FindingsCount int `gorm:"column:findings_count"`+ KnownExploitedCount int `gorm:"column:known_exploited_count"`+ OverdueKnownExploitedCount int `gorm:"column:overdue_known_exploited_count"`+ HighEPSSCount int `gorm:"column:high_epss_count"`+ ExposedCriticalHighCount int `gorm:"column:exposed_critical_high_count"`+ FixableCount int `gorm:"column:fixable_count"`+ ImagesScanned int `gorm:"column:images_scanned"`+ ImagesTotal int `gorm:"column:images_total"`+ CreatedAt time.Time `gorm:"column:created_at;autoCreateTime"`+ UpdatedAt *time.Time `gorm:"column:updated_at"`+}++func (VulnerabilityRiskSnapshot) TableName() string {+ return "vulnerability_risk_snapshots"+}+type vulnerabilityScanItemDetailsInternal struct {Description string `json:"description,omitempty"`References []string `json:"references,omitempty"`diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.goindex 4385fa120..23ade1335 100644--- a/backend/internal/vulnerability/service_test.go+++ b/backend/internal/vulnerability/service_test.go@@ -6,8 +6,10 @@ import ("context""encoding/json""fmt"+ "math""net/http""net/http/httptest"+ "strings""sync/atomic""testing""time"@@ -705,3 +707,273 @@ func TestVulnerabilityService_ListAllVulnerabilities_PagesAndCountsWithInlineFilrequire.EqualValues(t, 1, page.TotalItems)require.EqualValues(t, 3, page.GrandTotalItems)}++func TestBuildScanInsightsInternal(t *testing.T) {+ vulns := []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-LOW", PkgName: "zlib", InstalledVersion: "1.0.0", Severity: vulnerability.SeverityLow, CVSS: &vulnerability.CVSSInfo{V3Score: 3}},+ {VulnerabilityID: "CVE-HIGH-1", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.2", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V3Score: 7.5}},+ {VulnerabilityID: "CVE-HIGH-2", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.10", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V2Score: 7.8}},+ {VulnerabilityID: "CVE-MED", PkgName: "curl", InstalledVersion: "8.0.0", Severity: vulnerability.SeverityMedium},+ }++ insights := buildScanInsightsInternal(vulns, nil, vulnerability.ImageExposureUnknown)++ require.Equal(t, "CVE-HIGH-2", insights.HighestVulnerabilityID)+ require.InDelta(t, 7.8, insights.HighestCVSS, 0.001)+ require.Equal(t, 2, insights.FixableCount)+ // 78 peak + 20*(1-e^(-(0.09+0.5625+0.6084+0.3025)/5)) ≈ 78 + 5.4+ require.Equal(t, 83, insights.RiskScore)+ require.Equal(t, vulnerability.RiskBandHigh, insights.RiskBand)++ require.Len(t, insights.TopPackages, 3)+ require.Equal(t, vulnerability.PackageInsight{PkgName: "openssl", Severity: vulnerability.SeverityHigh, Count: 2, InstalledVersion: "3.0.0", FixedVersion: "3.0.10"}, insights.TopPackages[0])+ require.Equal(t, "curl", insights.TopPackages[1].PkgName)+ require.Equal(t, "zlib", insights.TopPackages[2].PkgName)+}++func TestBuildScanInsightsInternal_CapsScoreAndTopPackages(t *testing.T) {+ vulns := make([]vulnerability.Vulnerability, 0, 8)+ for i := range 8 {+ vulns = append(vulns, vulnerability.Vulnerability{+ VulnerabilityID: fmt.Sprintf("CVE-%d", i),+ PkgName: fmt.Sprintf("pkg-%d", i),+ Severity: vulnerability.SeverityCritical,+ CVSS: &vulnerability.CVSSInfo{V3Score: 9.8},+ })+ }++ insights := buildScanInsightsInternal(vulns, nil, vulnerability.ImageExposureUnknown)++ require.Equal(t, 100, insights.RiskScore)+ require.Equal(t, vulnerability.RiskBandCritical, insights.RiskBand)+ require.Len(t, insights.TopPackages, topPackageInsightLimit)+}++func TestFindingRiskInternal(t *testing.T) {+ lowEPSS, highEPSS := 0.01, 0.97+ tests := []struct {+ name string+ base float64+ knownExploited bool+ epss *float64+ exposure vulnerability.ImageExposure+ want float64+ }{+ {name: "no intel running", base: 7.5, exposure: vulnerability.ImageExposureRunning, want: 7.5},+ {name: "unknown exposure is neutral", base: 7.5, exposure: vulnerability.ImageExposureUnknown, want: 7.5},+ {name: "known exploited", base: 6, knownExploited: true, exposure: vulnerability.ImageExposureRunning, want: 8.4},+ {name: "low epss", base: 7.5, epss: &lowEPSS, exposure: vulnerability.ImageExposureRunning, want: 6.375},+ {name: "high epss", base: 6, epss: &highEPSS, exposure: vulnerability.ImageExposureRunning, want: 6 * (0.8 + 0.5*math.Sqrt(0.97))},+ {name: "stopped", base: 5, exposure: vulnerability.ImageExposureStopped, want: 4},+ {name: "unused", base: 9.8, exposure: vulnerability.ImageExposureUnused, want: 4.9},+ {name: "clamped", base: 9.8, knownExploited: true, exposure: vulnerability.ImageExposureRunning, want: 10},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.InDelta(t, tt.want, findingRiskInternal(tt.base, tt.knownExploited, tt.epss, tt.exposure), 0.001)+ })+ }+}++func TestBuildScanInsightsInternal_ThreatIntelAndExposure(t *testing.T) {+ vulns := []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-KEV", PkgName: "openssl", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 6}},+ {VulnerabilityID: "CVE-OTHER", PkgName: "zlib", Severity: vulnerability.SeverityLow, CVSS: &vulnerability.CVSSInfo{V3Score: 3}},+ }+ intel := map[string]VulnerabilityThreatIntel{"CVE-KEV": {CVEID: "CVE-KEV", KnownExploited: true}}++ running := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureRunning)+ require.Equal(t, 1, running.KnownExploitedCount)+ require.Equal(t, vulnerability.ImageExposureRunning, running.Exposure)+ require.InDelta(t, 6.0, running.HighestCVSS, 0.001)+ require.Equal(t, vulnerability.RiskBandHigh, running.RiskBand)++ unused := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureUnused)+ require.Less(t, unused.RiskScore, running.RiskScore)+ require.Equal(t, vulnerability.RiskBandMedium, unused.RiskBand)+}++func riskTestServiceInternal(t *testing.T) (*VulnerabilityService, *settings.SettingsService, *database.DB) {+ t.Helper()+ settingsSvc, db := featureSettingsInternal(t)+ sqlDB, err := db.DB.DB()+ require.NoError(t, err)+ sqlDB.SetMaxOpenConns(1)+ require.NoError(t, db.AutoMigrate(&VulnerabilityThreatIntel{}, &VulnerabilityRiskSnapshot{}, &kv.KVEntry{}))+ svc := &VulnerabilityService{db: db, settingsService: settingsSvc, kvService: kv.NewKVService(db)}+ return svc, settingsSvc, db+}++func seedRiskScansInternal(t *testing.T, svc *VulnerabilityService) {+ t.Helper()+ scans := []*vulnerability.ScanResult{+ {+ ImageID: "sha256:web", ImageName: "web:latest", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(),+ Vulnerabilities: []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-2024-0001", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V3Score: 7.5}},+ {VulnerabilityID: "CVE-2024-0002", PkgName: "curl", InstalledVersion: "8.0.0", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 5.3}},+ {VulnerabilityID: "CVE-2024-0003", PkgName: "zlib", InstalledVersion: "1.2.0", Severity: vulnerability.SeverityCritical, CVSS: &vulnerability.CVSSInfo{V3Score: 9.8}},+ },+ },+ {+ ImageID: "sha256:db", ImageName: "db:16", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(),+ Vulnerabilities: []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-2024-0002", PkgName: "curl", InstalledVersion: "8.0.0", FixedVersion: "8.1.0", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 5.3}},+ {VulnerabilityID: "GHSA-xxxx", PkgName: "lodash", InstalledVersion: "4.0.0", Severity: vulnerability.SeverityLow},+ },+ },+ }+ for _, scan := range scans {+ require.NoError(t, svc.saveScanResult(t.Context(), scan))+ }+}++func TestVulnerabilityService_GetRiskOverview(t *testing.T) {+ svc, _, db := riskTestServiceInternal(t)+ seedRiskScansInternal(t, svc)+ require.NoError(t, db.Create(&VulnerabilityThreatIntel{CVEID: "CVE-2024-0002", KnownExploited: true, KEVRansomware: true, KEVDueDate: "2024-06-01"}).Error)+ require.NoError(t, db.Create(&VulnerabilityIgnore{ID: "ignore-1", EnvironmentID: "0", ImageID: "sha256:web", VulnerabilityID: "CVE-2024-0003", PkgName: "zlib", InstalledVersion: "1.2.0"}).Error)++ overview, err := svc.GetRiskOverview(t.Context(), "0")+ require.NoError(t, err)++ require.Equal(t, 4, overview.Summary.Total, "ignored finding is excluded")+ require.Zero(t, overview.Summary.Critical)+ require.Equal(t, 4, overview.Drivers.Findings)+ require.Equal(t, 2, overview.Drivers.Fixable)+ require.Equal(t, 1, overview.Drivers.KnownExploited)+ require.Equal(t, 1, overview.Drivers.OverdueKnownExploited, "KEV due date has passed")+ require.Equal(t, vulnerability.RiskExposureBreakdown{Unknown: 4}, overview.Exposure, "no daemon means unknown exposure")+ require.NotNil(t, overview.ScoreDriver)+ require.Equal(t, "CVE-2024-0001", overview.ScoreDriver.VulnerabilityID)+ require.Equal(t, "web:latest", overview.ScoreDriver.ImageName)+ require.InDelta(t, 7.5, overview.ScoreDriver.Risk, 0.001)+ require.Equal(t, 2, overview.Drivers.ImagesScanned)+ require.True(t, overview.ThreatIntel.Enabled)+ require.True(t, overview.ThreatIntel.Stale)++ require.Len(t, overview.RiskiestFindings, 3, "findings are deduplicated by CVE")+ require.Equal(t, "CVE-2024-0001", overview.RiskiestFindings[0].VulnerabilityID)+ kev := overview.RiskiestFindings[1]+ require.Equal(t, "CVE-2024-0002", kev.VulnerabilityID)+ require.True(t, kev.KnownExploited)+ require.True(t, kev.Ransomware)+ require.Equal(t, 2, kev.ImagesAffected)+ require.Equal(t, "8.1.0", kev.FixedVersion)+ require.InDelta(t, 5.3, kev.CVSS, 0.001, "CVSS comes from the stored cvss_score column")+ require.InDelta(t, 7.4, kev.Risk, 0.001)+ require.Equal(t, "GHSA-xxxx", overview.RiskiestFindings[2].VulnerabilityID)+ require.Len(t, overview.PrevalentFindings, 3)+ require.Equal(t, "CVE-2024-0002", overview.PrevalentFindings[0].VulnerabilityID, "the only CVE in two images leads by prevalence")++ // Peak 7.5 (x10) plus a small load bonus from the three unique CVEs.+ require.Equal(t, 75, overview.RiskScore)+ require.Equal(t, vulnerability.RiskBandHigh, overview.RiskBand)+ require.Len(t, overview.RiskiestImages, 2)+ require.Equal(t, "web:latest", overview.RiskiestImages[0].ImageName)+ require.Len(t, overview.Trend, 1)+ require.Nil(t, overview.Delta7d)+}++func TestVulnerabilityService_RecordRiskSnapshot(t *testing.T) {+ svc, _, db := riskTestServiceInternal(t)+ seedRiskScansInternal(t, svc)+ now := time.Now().UTC()+ require.NoError(t, db.Create(&[]VulnerabilityRiskSnapshot{+ {SnapshotDate: now.AddDate(0, 0, -500).Format(riskDateLayout), RiskScore: 10, RiskBand: "low"},+ {SnapshotDate: now.AddDate(0, 0, -7).Format(riskDateLayout), RiskScore: 60, RiskBand: "medium", KnownExploitedCount: 3},+ }).Error)++ require.NoError(t, svc.RecordRiskSnapshot(t.Context()))+ require.NoError(t, svc.RecordRiskSnapshot(t.Context()))++ var snapshots []VulnerabilityRiskSnapshot+ require.NoError(t, db.Order("snapshot_date").Find(&snapshots).Error)+ require.Len(t, snapshots, 2, "old snapshot pruned and same-day runs upserted")+ require.Equal(t, now.Format(riskDateLayout), snapshots[1].SnapshotDate)+ require.Equal(t, 5, snapshots[1].FindingsCount)++ overview, err := svc.GetRiskOverview(t.Context(), "0")+ require.NoError(t, err)+ require.Len(t, overview.Trend, 2)+ require.Equal(t, now.Format(riskDateLayout), overview.Trend[1].Date)+ require.NotNil(t, overview.Delta7d)+ require.Equal(t, overview.RiskScore-60, *overview.Delta7d)+ require.NotNil(t, overview.Drivers7dAgo)+ require.Equal(t, 3, overview.Drivers7dAgo.KnownExploited)+}++func TestVulnerabilityService_SyncThreatIntel(t *testing.T) {+ svc, settingsSvc, db := riskTestServiceInternal(t)++ vulns := make([]vulnerability.Vulnerability, 0, 151)+ for i := range 150 {+ vulns = append(vulns, vulnerability.Vulnerability{VulnerabilityID: fmt.Sprintf("CVE-2024-%04d", i), PkgName: "pkg", Severity: vulnerability.SeverityMedium})+ }+ vulns = append(vulns, vulnerability.Vulnerability{VulnerabilityID: "GHSA-abcd", PkgName: "pkg", Severity: vulnerability.SeverityLow})+ require.NoError(t, svc.saveScanResult(t.Context(), &vulnerability.ScanResult{ImageID: "sha256:big", ImageName: "big:1", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(), Vulnerabilities: vulns}))+ require.NoError(t, db.Create(&VulnerabilityThreatIntel{CVEID: "CVE-2019-DELISTED", KnownExploited: true, KEVDueDate: "2020-01-01"}).Error)++ var kevRequests, epssRequests atomic.Int32+ requestedGHSA := atomic.Bool{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/kev":+ kevRequests.Add(1)+ _, err := w.Write([]byte(`{"vulnerabilities":[{"cveID":"CVE-2024-0001","dateAdded":"2024-01-02","dueDate":"2024-01-23","knownRansomwareCampaignUse":"Known"}]}`))+ require.NoError(t, err)+ case "/epss":+ epssRequests.Add(1)+ ids := strings.Split(r.URL.Query().Get("cve"), ",")+ require.LessOrEqual(t, len(ids), epssBatchMaxIDs)+ data := make([]map[string]string, 0, len(ids))+ for _, id := range ids {+ if strings.HasPrefix(id, "GHSA") {+ requestedGHSA.Store(true)+ }+ if strings.HasSuffix(id, "9") {+ continue+ }+ data = append(data, map[string]string{"cve": id, "epss": "0.25", "percentile": "0.9"})+ }+ raw, err := json.Marshal(map[string]any{"data": data})+ require.NoError(t, err)+ _, err = w.Write(raw)+ require.NoError(t, err)+ default:+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ t.Cleanup(srv.Close)+ svc.httpClient = srv.Client()+ svc.kevFeedURL = srv.URL + "/kev"+ svc.epssAPIURL = srv.URL + "/epss"++ require.NoError(t, svc.SyncThreatIntel(t.Context(), false))+ require.EqualValues(t, 1, kevRequests.Load())+ require.GreaterOrEqual(t, epssRequests.Load(), int32(2))+ require.False(t, requestedGHSA.Load())++ var kev VulnerabilityThreatIntel+ require.NoError(t, db.First(&kev, "cve_id = ?", "CVE-2024-0001").Error)+ require.True(t, kev.KnownExploited, "EPSS upsert keeps KEV columns")+ require.True(t, kev.KEVRansomware)+ require.NotNil(t, kev.EPSSScore)+ require.InDelta(t, 0.25, *kev.EPSSScore, 0.0001)++ var missing VulnerabilityThreatIntel+ require.NoError(t, db.First(&missing, "cve_id = ?", "CVE-2024-0009").Error)+ require.Nil(t, missing.EPSSScore)+ require.NotNil(t, missing.EPSSCheckedAt, "CVEs missing from EPSS are marked checked")++ var delisted int64+ require.NoError(t, db.Model(&VulnerabilityThreatIntel{}).Where("cve_id = ?", "CVE-2019-DELISTED").Count(&delisted).Error)+ require.Zero(t, delisted, "delisted KEV entries without findings are pruned")++ require.NoError(t, svc.SyncThreatIntel(t.Context(), false))+ require.EqualValues(t, 1, kevRequests.Load(), "recent sync is skipped unless forced")++ require.NoError(t, settingsSvc.SetBoolSetting(t.Context(), threatIntelSettingKey, false))+ require.NoError(t, svc.SyncThreatIntel(t.Context(), true))+ require.EqualValues(t, 1, kevRequests.Load(), "disabled intel makes no requests")+}diff --git a/backend/internal/vulnerability/vulnerability.go b/backend/internal/vulnerability/vulnerability.goindex 6f9dd5059..23b54c540 100644--- a/backend/internal/vulnerability/vulnerability.go+++ b/backend/internal/vulnerability/vulnerability.go@@ -1,6 +1,7 @@package vulnerabilityimport (+ "net/http""sync""time"@@ -27,6 +28,8 @@ const (defaultScanSaveRetryAttempts = 3defaultScanSaveRetryDelay = 200 * time.MilliseconddefaultScanSaveRetryMaxDelay = 2 * time.Second+ defaultKEVFeedURL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"+ defaultEPSSAPIURL = "https://api.first.org/data/v1/epss")// VulnerabilityService handles vulnerability scanning of container images@@ -40,6 +43,10 @@ type VulnerabilityService struct {activityService *activity.ActivityServiceregistryService *registry.ContainerRegistryServicekvService *kv.KVService+ httpClient *http.Client+ // kevFeedURL and epssAPIURL are the threat intel sources; tests point them at local servers.+ kevFeedURL string+ epssAPIURL string// scanLocks provides per-image locking to allow concurrent scans of different// images while preventing duplicate scans of the same image.scanLocks utils.KeyedMutex@@ -52,7 +59,7 @@ type VulnerabilityService struct {}// NewVulnerabilityService creates a new VulnerabilityService instance-func NewVulnerabilityService(db *database.DB, cfg *config.Config, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, notificationService *notification.NotificationService, activityService *activity.ActivityService, registryService *registry.ContainerRegistryService, kvService *kv.KVService) *VulnerabilityService {+func NewVulnerabilityService(db *database.DB, cfg *config.Config, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, notificationService *notification.NotificationService, activityService *activity.ActivityService, registryService *registry.ContainerRegistryService, kvService *kv.KVService, httpClient *http.Client) *VulnerabilityService {return &VulnerabilityService{db: db,config: cfg,@@ -63,6 +70,9 @@ func NewVulnerabilityService(db *database.DB, cfg *config.Config, dockerServiceactivityService: activityService,registryService: registryService,kvService: kvService,+ httpClient: httpClient,+ kevFeedURL: defaultKEVFeedURL,+ epssAPIURL: defaultEPSSAPIURL,trivyScanSlots: nil,}}diff --git a/backend/internal/vulnerability/vulnerability_ignores.go b/backend/internal/vulnerability/vulnerability_ignores.goindex 8892175c9..513461268 100644--- a/backend/internal/vulnerability/vulnerability_ignores.go+++ b/backend/internal/vulnerability/vulnerability_ignores.go@@ -21,7 +21,7 @@ func vulnerabilityIgnoreKeyInternal(imageID, vulnerabilityID, pkgName, installedfunc (s *VulnerabilityService) filterIgnoredVulnerabilitiesForImage(ctx context.Context,- imageID string,+ envID, imageID string,vulns []vulnerability.Vulnerability,) ([]vulnerability.Vulnerability, error) {if s.db == nil || len(vulns) == 0 || imageID == "" {@@ -29,7 +29,7 @@ func (s *VulnerabilityService) filterIgnoredVulnerabilitiesForImage(}var ignores []VulnerabilityIgnore- if err := s.db.WithContext(ctx).Where("image_id = ?", imageID).Find(&ignores).Error; err != nil {+ if err := s.db.WithContext(ctx).Where("environment_id = ? AND image_id = ?", envID, imageID).Find(&ignores).Error; err != nil {return nil, err}if len(ignores) == 0 {diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.goindex 08a93bc7d..8ece0958e 100644--- a/backend/internal/vulnerability/vulnerability_query.go+++ b/backend/internal/vulnerability/vulnerability_query.go@@ -1,12 +1,18 @@package vulnerabilityimport (+ "cmp""context""encoding/json/v2""iter""log/slog"+ "math"+ "slices""sort""strings"+ "time"++ "github.com/moby/moby/api/types/container""github.com/getarcaneapp/arcane/types/v2/features"@@ -21,8 +27,38 @@ import ("github.com/getarcaneapp/arcane/types/v2/vulnerability")-// GetScanResult retrieves the most recent scan result for an image-func (s *VulnerabilityService) GetScanResult(ctx context.Context, imageID string) (*vulnerability.ScanResult, error) {+// GetScanResult retrieves the most recent scan result for an image, with risk insights for completed scans.+func (s *VulnerabilityService) GetScanResult(ctx context.Context, envID, imageID string) (*vulnerability.ScanResult, error) {+ result, err := s.loadScanResultInternal(ctx, imageID)+ if err != nil || result == nil || result.Status != vulnerability.ScanStatusCompleted || len(result.Vulnerabilities) == 0 {+ return result, err+ }++ vulns, err := s.filterIgnoredVulnerabilitiesForImage(ctx, envID, result.ImageID, result.Vulnerabilities)+ if err != nil {+ return nil, errors.WrapIf(err, "failed to filter ignored vulnerabilities")+ }+ intel := map[string]VulnerabilityThreatIntel{}+ if s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true) {+ cveIDs := make([]string, 0, len(vulns))+ for i := range vulns {+ cveIDs = append(cveIDs, vulns[i].VulnerabilityID)+ }+ var rows []VulnerabilityThreatIntel+ if err := s.db.WithContext(ctx).Where("cve_id IN ?", cveIDs).Find(&rows).Error; err != nil {+ slog.WarnContext(ctx, "failed to load threat intel for image insights", "error", err)+ }+ for _, row := range rows {+ intel[row.CVEID] = row+ }+ }+ usage, usageOK := s.containerUsageInternal(ctx)+ result.Insights = buildScanInsightsInternal(vulns, intel, imageExposureInternal(usage, usageOK, result.ImageID))+ return result, nil+}++// loadScanResultInternal reads the stored scan result for an image without computing insights.+func (s *VulnerabilityService) loadScanResultInternal(ctx context.Context, imageID string) (*vulnerability.ScanResult, error) {if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || s.db == nil {return nil, nil}@@ -87,7 +123,7 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strin// ListVulnerabilities returns a paginated, filtered list of vulnerabilities for an image.func (s *VulnerabilityService) ListVulnerabilities(ctx context.Context, imageID string, params pagination.QueryParams) ([]vulnerability.Vulnerability, pagination.Response, error) {- result, err := s.GetScanResult(ctx, imageID)+ result, err := s.loadScanResultInternal(ctx, imageID)if err != nil {return nil, pagination.Response{}, errors.WrapIf(err, "failed to get scan result")}@@ -300,6 +336,23 @@ var listAllVulnerabilitySortColumnsInternal = map[string]string{"imageName": "vulnerability_scans.image_name",}+// scanItemsQueryInternal joins scan items to completed scans and their ignore records, keeping ignored or active rows for the given images.+func scanItemsQueryInternal(ctx context.Context, db *gorm.DB, envID string, onlyIgnored bool, imageIDs mo.Option[[]string]) *gorm.DB {+ query := db.WithContext(ctx).+ Model(&VulnerabilityScanItem{}).+ Joins("JOIN vulnerability_scans ON vulnerability_scans.id = vulnerability_scan_items.image_id AND vulnerability_scans.status = ?", ScanStatusCompleted).+ Joins("LEFT JOIN vulnerability_ignores ON vulnerability_ignores.environment_id = ? AND vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version", envID)+ if onlyIgnored {+ query = query.Where("vulnerability_ignores.id IS NOT NULL")+ } else {+ query = query.Where("vulnerability_ignores.id IS NULL")+ }+ if ids, ok := imageIDs.Get(); ok {+ query = query.Where("vulnerability_scan_items.image_id IN ?", ids)+ }+ return query+}+// listAllVulnerabilitiesQueryInternal returns the base query used for counts and the filtered, ordered query on db; it clears params.Sort once ordering is applied.func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.Context, db *gorm.DB, envID string, params *pagination.QueryParams) (*gorm.DB, *gorm.DB) {// "ignored" flips the list from active to ignored vulnerabilities, the same@@ -307,20 +360,9 @@ func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.ConlyIgnored := params.Filters["ignored"] == "true"delete(params.Filters, "ignored")- base := db.WithContext(ctx).- Model(&VulnerabilityScanItem{}).+ base := scanItemsQueryInternal(ctx, db, envID, onlyIgnored, mo.TupleToOption(s.currentImageIDsInternal(ctx))).Select("vulnerability_scan_items.*", "vulnerability_scans.image_name AS image_name", "COALESCE(vulnerability_ignores.id, '') AS ignore_id").- Joins("JOIN vulnerability_scans ON vulnerability_scans.id = vulnerability_scan_items.image_id AND vulnerability_scans.status = ?", ScanStatusCompleted).- Joins("LEFT JOIN vulnerability_ignores ON vulnerability_ignores.environment_id = ? AND vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version", envID)- if onlyIgnored {- base = base.Where("vulnerability_ignores.id IS NOT NULL")- } else {- base = base.Where("vulnerability_ignores.id IS NULL")- }- if currentImageIDs, ok := s.currentImageIDsInternal(ctx); ok {- base = base.Where("vulnerability_scan_items.image_id IN ?", currentImageIDs)- }- base = base.Session(&gorm.Session{})+ Session(&gorm.Session{})q := pagination.ApplyFilter(base, "vulnerability_scan_items.severity", strings.ToUpper(params.Filters["severity"]))if params.Filters["fixAvailable"] == "true" {@@ -653,3 +695,384 @@ func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, ireturn result, nil}++const (+ threatIntelSettingKey = "vulnerabilityThreatIntelEnabled"+ highEPSSThreshold = 0.1+ riskTrendDays = 90+ riskDeltaDays = 7+ riskDeltaToleranceDays = 3+ riskSnapshotRetentionDays = 400+ riskiestImageLimit = 5+ topFindingLimit = 10+ riskDateLayout = "2006-01-02"+)++type imageUsageInternal struct {+ running int+ stopped int+}++// containerUsageInternal counts running and stopped containers per image ID; ok is false when the daemon could not be listed.+func (s *VulnerabilityService) containerUsageInternal(ctx context.Context) (map[string]imageUsageInternal, bool) {+ if s.dockerService == nil {+ return nil, false+ }+ containers, err := s.dockerService.ListContainers(ctx)+ if err != nil {+ slog.WarnContext(ctx, "failed to list containers for vulnerability risk", "error", err)+ return nil, false+ }+ usage := make(map[string]imageUsageInternal, len(containers))+ for i := range containers {+ entry := usage[containers[i].ImageID]+ switch containers[i].State {+ case container.StateRunning, container.StatePaused, container.StateRestarting:+ entry.running+++ case container.StateCreated, container.StateRemoving, container.StateExited, container.StateDead:+ entry.stopped+++ default:+ entry.stopped+++ }+ usage[containers[i].ImageID] = entry+ }+ return usage, true+}++func imageExposureInternal(usage map[string]imageUsageInternal, ok bool, imageID string) vulnerability.ImageExposure {+ switch {+ case !ok:+ return vulnerability.ImageExposureUnknown+ case usage[imageID].running > 0:+ return vulnerability.ImageExposureRunning+ case usage[imageID].stopped > 0:+ return vulnerability.ImageExposureStopped+ default:+ return vulnerability.ImageExposureUnused+ }+}++type riskFindingRowInternal struct {+ ImageID string `gorm:"column:image_id"`+ ImageName string `gorm:"column:image_name"`+ VulnerabilityID string `gorm:"column:vulnerability_id"`+ PkgName string `gorm:"column:pkg_name"`+ FixedVersion string `gorm:"column:fixed_version"`+ Severity string `gorm:"column:severity"`+ Title string `gorm:"column:title"`+ CVSSScore *float64 `gorm:"column:cvss_score"`+ KnownExploited bool `gorm:"column:known_exploited"`+ KEVRansomware bool `gorm:"column:kev_ransomware"`+ KEVDueDate string `gorm:"column:kev_due_date"`+ EPSSScore *float64 `gorm:"column:epss_score"`+}++type riskImageAggInternal struct {+ image vulnerability.RiskImage+ peak, load float64+}++type riskFindingAggInternal struct {+ finding vulnerability.RiskFinding+ // peakImage and peakExposure describe the riskiest instance of the CVE.+ peakImage string+ peakExposure vulnerability.ImageExposure+ images map[string]struct{}+ runningImages map[string]struct{}+}++func boolToIntInternal(b bool) int {+ if b {+ return 1+ }+ return 0+}++// riskAccumulatorInternal aggregates scored findings into environment, per-image and per-CVE totals.+type riskAccumulatorInternal struct {+ today string+ overview *vulnerability.RiskOverview+ images map[string]*riskImageAggInternal+ findings map[string]*riskFindingAggInternal+}++func (a *riskAccumulatorInternal) addInternal(row *riskFindingRowInternal, exposure vulnerability.ImageExposure, runningContainers int) {+ severity := vulnerability.Severity(row.Severity)+ base := baseScoreInternal(*cmp.Or(row.CVSSScore, new(0.0)), severity)+ risk := findingRiskInternal(base, row.KnownExploited, row.EPSSScore, exposure)+ fixable := strings.TrimSpace(row.FixedVersion) != ""++ summary := &a.overview.Summary+ switch severity {+ case vulnerability.SeverityCritical:+ summary.Critical+++ case vulnerability.SeverityHigh:+ summary.High+++ case vulnerability.SeverityMedium:+ summary.Medium+++ case vulnerability.SeverityLow:+ summary.Low+++ case vulnerability.SeverityUnknown:+ summary.Unknown+++ default:+ summary.Unknown+++ }+ summary.Total++++ switch exposure {+ case vulnerability.ImageExposureRunning:+ a.overview.Exposure.Running+++ case vulnerability.ImageExposureStopped:+ a.overview.Exposure.Stopped+++ case vulnerability.ImageExposureUnused:+ a.overview.Exposure.Unused+++ case vulnerability.ImageExposureUnknown:+ a.overview.Exposure.Unknown+++ }++ img, ok := a.images[row.ImageID]+ if !ok {+ img = &riskImageAggInternal{image: vulnerability.RiskImage{ImageID: row.ImageID, ImageName: row.ImageName, Exposure: exposure, RunningContainers: runningContainers}}+ a.images[row.ImageID] = img+ }+ img.image.Findings+++ img.peak = max(img.peak, risk)+ img.load += (risk / 10) * (risk / 10)+ img.image.Critical += boolToIntInternal(severity == vulnerability.SeverityCritical)+ img.image.High += boolToIntInternal(severity == vulnerability.SeverityHigh)+ img.image.KnownExploited += boolToIntInternal(row.KnownExploited)+ img.image.Fixable += boolToIntInternal(fixable)++ agg, ok := a.findings[row.VulnerabilityID]+ if !ok {+ agg = &riskFindingAggInternal{+ finding: vulnerability.RiskFinding{+ VulnerabilityID: row.VulnerabilityID,+ KnownExploited: row.KnownExploited,+ Ransomware: row.KEVRansomware,+ KEVDueDate: row.KEVDueDate,+ EPSS: row.EPSSScore,+ Risk: -1,+ },+ images: map[string]struct{}{},+ runningImages: map[string]struct{}{},+ }+ a.findings[row.VulnerabilityID] = agg+ }+ agg.images[row.ImageID] = struct{}{}+ if exposure == vulnerability.ImageExposureRunning {+ agg.runningImages[row.ImageID] = struct{}{}+ }+ // The riskiest instance of a CVE describes it; any fixed version beats none.+ if risk > agg.finding.Risk {+ agg.finding.Risk, agg.finding.CVSS, agg.finding.Severity = risk, base, severity+ agg.finding.PkgName, agg.finding.Title = row.PkgName, row.Title+ agg.peakImage, agg.peakExposure = row.ImageName, exposure+ if fixable {+ agg.finding.FixedVersion = row.FixedVersion+ }+ }+ if fixable && agg.finding.FixedVersion == "" {+ agg.finding.FixedVersion = row.FixedVersion+ }+}++// finishInternal derives the drivers and score, and ranks findings and images.+func (a *riskAccumulatorInternal) finishInternal() {+ overview := a.overview+ overview.Drivers.Findings = overview.Summary.Total++ peak, load := 0.0, 0.0+ findings := make([]*riskFindingAggInternal, 0, len(a.findings))+ for _, agg := range a.findings {+ f := &agg.finding+ f.ImagesAffected = len(agg.images)+ f.RunningImagesAffected = len(agg.runningImages)+ if f.Risk > peak || overview.ScoreDriver == nil {+ overview.ScoreDriver = &vulnerability.RiskScoreDriver{+ VulnerabilityID: f.VulnerabilityID,+ ImageName: agg.peakImage,+ Exposure: agg.peakExposure,+ KnownExploited: f.KnownExploited,+ Risk: math.Round(f.Risk*10) / 10,+ }+ }+ peak = max(peak, f.Risk)+ load += (f.Risk / 10) * (f.Risk / 10)+ overview.Drivers.KnownExploited += boolToIntInternal(f.KnownExploited)+ overview.Drivers.OverdueKnownExploited += boolToIntInternal(f.KnownExploited && f.KEVDueDate != "" && f.KEVDueDate < a.today)+ overview.Drivers.HighEPSS += boolToIntInternal(f.EPSS != nil && *f.EPSS >= highEPSSThreshold)+ overview.Drivers.ExposedCriticalHigh += boolToIntInternal(f.RunningImagesAffected > 0 && (f.Severity == vulnerability.SeverityCritical || f.Severity == vulnerability.SeverityHigh))+ findings = append(findings, agg)+ }+ overview.RiskScore = riskScoreInternal(peak, load, environmentRiskLoadScale)+ overview.RiskBand = riskBandInternal(overview.RiskScore)++ byRisk := slices.Clone(findings)+ slices.SortFunc(byRisk, func(a, b *riskFindingAggInternal) int {+ return cmp.Or(+ cmp.Compare(b.finding.Risk, a.finding.Risk),+ cmp.Compare(boolToIntInternal(b.finding.KnownExploited), boolToIntInternal(a.finding.KnownExploited)),+ cmp.Compare(b.finding.RunningImagesAffected, a.finding.RunningImagesAffected),+ cmp.Compare(*cmp.Or(b.finding.EPSS, new(0.0)), *cmp.Or(a.finding.EPSS, new(0.0))),+ strings.Compare(a.finding.VulnerabilityID, b.finding.VulnerabilityID),+ )+ })+ byPrevalence := slices.Clone(findings)+ slices.SortFunc(byPrevalence, func(a, b *riskFindingAggInternal) int {+ return cmp.Or(+ cmp.Compare(b.finding.ImagesAffected, a.finding.ImagesAffected),+ cmp.Compare(b.finding.RunningImagesAffected, a.finding.RunningImagesAffected),+ cmp.Compare(b.finding.Risk, a.finding.Risk),+ strings.Compare(a.finding.VulnerabilityID, b.finding.VulnerabilityID),+ )+ })+ for _, agg := range findings {+ agg.finding.Risk = math.Round(agg.finding.Risk*10) / 10+ }+ top := func(sorted []*riskFindingAggInternal) []vulnerability.RiskFinding {+ out := make([]vulnerability.RiskFinding, 0, min(len(sorted), topFindingLimit))+ for _, agg := range sorted[:min(len(sorted), topFindingLimit)] {+ out = append(out, agg.finding)+ }+ return out+ }+ overview.RiskiestFindings = top(byRisk)+ overview.PrevalentFindings = top(byPrevalence)++ overview.RiskiestImages = make([]vulnerability.RiskImage, 0, len(a.images))+ for _, img := range a.images {+ img.image.RiskScore = riskScoreInternal(img.peak, img.load, imageRiskLoadScale)+ img.image.RiskBand = riskBandInternal(img.image.RiskScore)+ overview.RiskiestImages = append(overview.RiskiestImages, img.image)+ }+ slices.SortFunc(overview.RiskiestImages, func(a, b vulnerability.RiskImage) int {+ return cmp.Or(+ cmp.Compare(b.RiskScore, a.RiskScore),+ cmp.Compare(b.KnownExploited, a.KnownExploited),+ cmp.Compare(b.Critical, a.Critical),+ strings.Compare(a.ImageName, b.ImageName),+ )+ })+ overview.RiskiestImages = overview.RiskiestImages[:min(len(overview.RiskiestImages), riskiestImageLimit)]+}++// computeRiskInternal scores every non-ignored finding of current images; the trend, deltas and intel status are left to callers.+func (s *VulnerabilityService) computeRiskInternal(ctx context.Context, envID string) (*vulnerability.RiskOverview, error) {+ intelEnabled := s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true)+ usage, usageOK := s.containerUsageInternal(ctx)+ imageIDs, imageIDsOK := s.currentImageIDsInternal(ctx)++ var rows []riskFindingRowInternal+ err := scanItemsQueryInternal(ctx, s.db.DB, envID, false, mo.TupleToOption(imageIDs, imageIDsOK)).+ Joins("LEFT JOIN vulnerability_threat_intel ON vulnerability_threat_intel.cve_id = vulnerability_scan_items.vulnerability_id").+ Select(+ "vulnerability_scan_items.image_id", "vulnerability_scans.image_name", "vulnerability_scan_items.vulnerability_id",+ "vulnerability_scan_items.pkg_name", "vulnerability_scan_items.fixed_version", "vulnerability_scan_items.severity",+ "vulnerability_scan_items.title", "vulnerability_scan_items.cvss_score",+ "COALESCE(vulnerability_threat_intel.known_exploited, FALSE) AS known_exploited",+ "COALESCE(vulnerability_threat_intel.kev_ransomware, FALSE) AS kev_ransomware",+ "COALESCE(vulnerability_threat_intel.kev_due_date, '') AS kev_due_date",+ "vulnerability_threat_intel.epss_score",+ ).+ Scan(&rows).Error+ if err != nil {+ return nil, errors.WrapIf(err, "failed to load vulnerability risk findings")+ }++ scanQuery := s.db.WithContext(ctx).Model(&VulnerabilityScanRecord{}).Where("status = ?", ScanStatusCompleted)+ if imageIDsOK {+ scanQuery = scanQuery.Where("id IN ?", imageIDs)+ }+ var scanned int64+ if err := scanQuery.Count(&scanned).Error; err != nil {+ return nil, errors.WrapIf(err, "failed to count scanned images")+ }++ acc := &riskAccumulatorInternal{+ today: s.riskNowInternal().Format(riskDateLayout),+ overview: &vulnerability.RiskOverview{Trend: []vulnerability.RiskTrendPoint{}},+ images: map[string]*riskImageAggInternal{},+ findings: map[string]*riskFindingAggInternal{},+ }+ acc.overview.Drivers.ImagesScanned = int(scanned)+ acc.overview.Drivers.ImagesTotal = int(scanned)+ if imageIDsOK {+ acc.overview.Drivers.ImagesTotal = len(imageIDs)+ }+ for i := range rows {+ row := &rows[i]+ if !intelEnabled {+ row.KnownExploited, row.KEVRansomware, row.KEVDueDate, row.EPSSScore = false, false, "", nil+ }+ acc.addInternal(row, imageExposureInternal(usage, usageOK, row.ImageID), usage[row.ImageID].running)+ acc.overview.Drivers.Fixable += boolToIntInternal(strings.TrimSpace(row.FixedVersion) != "")+ }+ acc.finishInternal()++ return acc.overview, nil+}++// riskNowInternal returns the current time in the configured timezone, which defines snapshot days.+func (s *VulnerabilityService) riskNowInternal() time.Time {+ if s.config == nil {+ return time.Now().UTC()+ }+ return time.Now().In(s.config.GetLocation())+}++// GetRiskOverview returns the environment risk score with its trend, drivers, riskiest images and top findings.+func (s *VulnerabilityService) GetRiskOverview(ctx context.Context, envID string) (*vulnerability.RiskOverview, error) {+ if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || s.db == nil {+ return nil, common.ErrFeatureDisabled+ }++ overview, err := s.computeRiskInternal(ctx, envID)+ if err != nil {+ return nil, err+ }++ now := s.riskNowInternal()+ today := now.Format(riskDateLayout)+ var snapshots []VulnerabilityRiskSnapshot+ if err := s.db.WithContext(ctx).+ Where("snapshot_date >= ?", now.AddDate(0, 0, -(riskTrendDays-1)).Format(riskDateLayout)).+ Order("snapshot_date ASC").+ Find(&snapshots).Error; err != nil {+ return nil, errors.WrapIf(err, "failed to load risk snapshots")+ }++ deltaDay := now.AddDate(0, 0, -riskDeltaDays).Format(riskDateLayout)+ deltaFloor := now.AddDate(0, 0, -(riskDeltaDays + riskDeltaToleranceDays)).Format(riskDateLayout)+ for i := range snapshots {+ snap := &snapshots[i]+ if snap.SnapshotDate == today {+ continue+ }+ overview.Trend = append(overview.Trend, vulnerability.RiskTrendPoint{Date: snap.SnapshotDate, RiskScore: snap.RiskScore})+ if snap.SnapshotDate <= deltaDay && snap.SnapshotDate >= deltaFloor {+ overview.Delta7d = new(overview.RiskScore - snap.RiskScore)+ overview.Drivers7dAgo = &vulnerability.RiskDrivers{+ KnownExploited: snap.KnownExploitedCount,+ OverdueKnownExploited: snap.OverdueKnownExploitedCount,+ HighEPSS: snap.HighEPSSCount,+ ExposedCriticalHigh: snap.ExposedCriticalHighCount,+ Fixable: snap.FixableCount,+ Findings: snap.FindingsCount,+ ImagesScanned: snap.ImagesScanned,+ ImagesTotal: snap.ImagesTotal,+ }+ }+ }+ overview.Trend = append(overview.Trend, vulnerability.RiskTrendPoint{Date: today, RiskScore: overview.RiskScore})++ overview.ThreatIntel.Enabled = s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true)+ if overview.ThreatIntel.Enabled {+ state := s.loadThreatIntelStateInternal(ctx)+ overview.ThreatIntel.LastSyncedAt = state.LastSyncedAt+ overview.ThreatIntel.Stale = state.LastSyncedAt == nil || time.Since(*state.LastSyncedAt) > threatIntelStaleAfter+ }+ overview.ComputedAt = time.Now()++ return overview, nil+}diff --git a/backend/internal/vulnerability/vulnerability_scan.go b/backend/internal/vulnerability/vulnerability_scan.goindex 125a193b4..e0425f658 100644--- a/backend/internal/vulnerability/vulnerability_scan.go+++ b/backend/internal/vulnerability/vulnerability_scan.go@@ -505,10 +505,11 @@ func (s *VulnerabilityService) saveScheduledSuccessfulScanInternal(func (s *VulnerabilityService) collectScheduledFixableSummaryInternal(ctx context.Context,+ envID string,result *vulnerability.ScanResult,summary *scheduledScanNotificationSummary,) {- fixableVulns := s.fixedVulnerabilitiesForNotifications(ctx, result)+ fixableVulns := s.fixedVulnerabilitiesForNotifications(ctx, envID, result)if len(fixableVulns) == 0 {return}@@ -702,6 +703,7 @@ func (s *VulnerabilityService) skipRecentlyScannedTargetsInternal(ctx context.Cofunc (s *VulnerabilityService) fixedVulnerabilitiesForNotifications(ctx context.Context,+ envID string,result *vulnerability.ScanResult,) []vulnerability.Vulnerability {if result == nil || result.Status != vulnerability.ScanStatusCompleted || len(result.Vulnerabilities) == 0 {@@ -709,7 +711,7 @@ func (s *VulnerabilityService) fixedVulnerabilitiesForNotifications(}vulnerabilities := result.Vulnerabilities- filtered, err := s.filterIgnoredVulnerabilitiesForImage(ctx, result.ImageID, vulnerabilities)+ filtered, err := s.filterIgnoredVulnerabilitiesForImage(ctx, envID, result.ImageID, vulnerabilities)if err != nil {slog.WarnContext(ctx, "failed to filter ignored vulnerabilities for notifications", "error", err)} else {diff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.goindex 323892aad..c10f0a596 100644--- a/backend/internal/vulnerability/vulnerability_store.go+++ b/backend/internal/vulnerability/vulnerability_store.go@@ -6,20 +6,29 @@ import ("context""encoding/json/v2""fmt"+ "io""io/fs""log/slog"+ "math"+ "net/http""os"+ "slices"+ "strconv""strings""time""emperror.dev/errors""go.getarcane.app/acfs"+ "golang.org/x/mod/semver""gorm.io/gorm""gorm.io/gorm/clause""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"+ "github.com/getarcaneapp/arcane/types/v2"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability")@@ -102,6 +111,9 @@ func buildScanItemsInternal(imageID string, vulns []vulnerability.Vulnerability)PkgType: v.Type,Title: v.Title,}+ if score := rawCVSSInternal(v.CVSS); score > 0 {+ item.CVSSScore = new(score)+ }if v.Description != "" || len(v.References) > 0 || v.CVSS != nil || v.PublishedDate != nil || v.LastModifiedDate != nil {raw, err := json.Marshal(vulnerabilityScanItemDetailsInternal{Description: v.Description,@@ -521,3 +533,446 @@ func buildSeveritySummaryFromVulnerabilitiesInternal(vulns []vulnerability.Vulne}return summary}++const (+ topPackageInsightLimit = 5+ threatFactorKEV = 1.4+ exposureFactorStopped = 0.8+ exposureFactorUnused = 0.5+ imageRiskLoadScale = 5.0+ environmentRiskLoadScale = 50.0+)++// rawCVSSInternal returns the CVSS v3 score, else v2, else 0.+func rawCVSSInternal(cvss *vulnerability.CVSSInfo) float64 {+ if cvss == nil {+ return 0+ }+ if cvss.V3Score > 0 {+ return cvss.V3Score+ }+ return cvss.V2Score+}++// baseScoreInternal returns the CVSS score, falling back to a severity midpoint when unscored.+func baseScoreInternal(cvss float64, severity vulnerability.Severity) float64 {+ if cvss > 0 {+ return cvss+ }+ switch severity {+ case vulnerability.SeverityCritical:+ return 9.5+ case vulnerability.SeverityHigh:+ return 8+ case vulnerability.SeverityMedium:+ return 5.5+ case vulnerability.SeverityLow:+ return 2.5+ case vulnerability.SeverityUnknown:+ return 0+ default:+ return 0+ }+}++// findingRiskInternal scales a 0-10 base score by exploitation evidence (KEV, EPSS) and container exposure.+func findingRiskInternal(base float64, knownExploited bool, epss *float64, exposure vulnerability.ImageExposure) float64 {+ threat := 1.0+ if knownExploited {+ threat = threatFactorKEV+ } else if epss != nil {+ threat = 0.8 + 0.5*math.Sqrt(*epss)+ }+ switch exposure {+ case vulnerability.ImageExposureStopped:+ threat *= exposureFactorStopped+ case vulnerability.ImageExposureUnused:+ threat *= exposureFactorUnused+ case vulnerability.ImageExposureRunning, vulnerability.ImageExposureUnknown:+ }+ return min(10, base*threat)+}++// riskScoreInternal maps the worst finding risk (x10) plus up to 20 points of finding load onto 0-100.+func riskScoreInternal(peak, load, loadScale float64) int {+ return min(100, int(math.Round(peak*10+20*(1-math.Exp(-load/loadScale)))))+}++func riskBandInternal(score int) vulnerability.RiskBand {+ switch {+ case score >= 90:+ return vulnerability.RiskBandCritical+ case score >= 70:+ return vulnerability.RiskBandHigh+ case score >= 40:+ return vulnerability.RiskBandMedium+ case score > 0:+ return vulnerability.RiskBandLow+ default:+ return vulnerability.RiskBandNone+ }+}++// isNewerFixedVersionInternal reports whether candidate supersedes current; non-semver fixes keep the first (most severe) one.+func isNewerFixedVersionInternal(candidate, current string) bool {+ if current == "" {+ return true+ }+ a, b := utils.EnsureVPrefix(candidate), utils.EnsureVPrefix(current)+ return semver.IsValid(a) && semver.IsValid(b) && semver.Compare(a, b) > 0+}++// buildScanInsightsInternal scores an image's findings using threat intel (keyed by CVE) and the image's exposure.+func buildScanInsightsInternal(vulns []vulnerability.Vulnerability, intel map[string]VulnerabilityThreatIntel, exposure vulnerability.ImageExposure) *vulnerability.ScanInsights {+ sorted := slices.Clone(vulns)+ slices.SortStableFunc(sorted, func(a, b vulnerability.Vulnerability) int {+ return severityRankInternal(b.Severity) - severityRankInternal(a.Severity)+ })++ insights := &vulnerability.ScanInsights{Exposure: exposure, TopPackages: []vulnerability.PackageInsight{}}+ peak, load := 0.0, 0.0+ packages := map[string]*vulnerability.PackageInsight{}+ var packageOrder []string++ for _, v := range sorted {+ base := baseScoreInternal(rawCVSSInternal(v.CVSS), v.Severity)+ if insights.HighestVulnerabilityID == "" || base > insights.HighestCVSS {+ insights.HighestCVSS = base+ insights.HighestVulnerabilityID = v.VulnerabilityID+ }+ threat := intel[v.VulnerabilityID]+ if threat.KnownExploited {+ insights.KnownExploitedCount+++ }+ risk := findingRiskInternal(base, threat.KnownExploited, threat.EPSSScore, exposure)+ peak = max(peak, risk)+ load += (risk / 10) * (risk / 10)+ fixedVersion := strings.TrimSpace(v.FixedVersion)+ if fixedVersion != "" {+ insights.FixableCount+++ }++ pkg, ok := packages[v.PkgName]+ if !ok {+ pkg = &vulnerability.PackageInsight{PkgName: v.PkgName, Severity: v.Severity, InstalledVersion: v.InstalledVersion}+ packages[v.PkgName] = pkg+ packageOrder = append(packageOrder, v.PkgName)+ }+ pkg.Count+++ if fixedVersion != "" && isNewerFixedVersionInternal(fixedVersion, pkg.FixedVersion) {+ pkg.FixedVersion = fixedVersion+ }+ }++ insights.RiskScore = riskScoreInternal(peak, load, imageRiskLoadScale)+ insights.RiskBand = riskBandInternal(insights.RiskScore)++ for _, name := range packageOrder {+ insights.TopPackages = append(insights.TopPackages, *packages[name])+ }+ slices.SortStableFunc(insights.TopPackages, func(a, b vulnerability.PackageInsight) int {+ if rank := severityRankInternal(b.Severity) - severityRankInternal(a.Severity); rank != 0 {+ return rank+ }+ return b.Count - a.Count+ })+ if len(insights.TopPackages) > topPackageInsightLimit {+ insights.TopPackages = insights.TopPackages[:topPackageInsightLimit]+ }++ return insights+}++const (+ threatIntelStateKey = "vuln:threat-intel:state:v1"+ threatIntelSyncInterval = 20 * time.Hour+ threatIntelStaleAfter = 72 * time.Hour+ kevFeedMaxBytes = 32 << 20+ epssBatchMaxIDs = 100+ epssBatchMaxChars = 1900+ epssBatchDelay = 250 * time.Millisecond+ epssMaxRetryAfter = time.Minute+ epssMaxCVEsPerSync = 20000+ threatIntelUpsertBatch = 500+)++type threatIntelStateInternal struct {+ LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"`+ ETag string `json:"etag,omitempty"`+ LastError string `json:"lastError,omitempty"`+}++func (s *VulnerabilityService) loadThreatIntelStateInternal(ctx context.Context) threatIntelStateInternal {+ var state threatIntelStateInternal+ if s.kvService == nil {+ return state+ }+ raw, ok, err := s.kvService.Get(ctx, threatIntelStateKey)+ if err != nil || !ok {+ return state+ }+ if err := json.Unmarshal([]byte(raw), &state); err != nil {+ slog.WarnContext(ctx, "failed to decode threat intel state", "error", err)+ }+ return state+}++// SyncThreatIntel refreshes the CISA KEV catalog and FIRST EPSS scores for scanned CVEs, at most every 20h unless forced.+func (s *VulnerabilityService) SyncThreatIntel(ctx context.Context, force bool) error {+ if s.db == nil || !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || !s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true) {+ return nil+ }+ state := s.loadThreatIntelStateInternal(ctx)+ if !force && state.LastSyncedAt != nil && time.Since(*state.LastSyncedAt) < threatIntelSyncInterval {+ return nil+ }++ etag, kevErr := s.syncKEVInternal(ctx, state.ETag)+ if kevErr == nil {+ state.ETag = etag+ }+ epssErr := s.syncEPSSInternal(ctx)+ pruneErr := s.db.WithContext(ctx).+ Where("known_exploited = ? AND NOT EXISTS (SELECT 1 FROM vulnerability_scan_items WHERE vulnerability_scan_items.vulnerability_id = vulnerability_threat_intel.cve_id)", false).+ Delete(&VulnerabilityThreatIntel{}).Error++ syncErr := errors.Combine(kevErr, epssErr, pruneErr)+ if syncErr == nil {+ state.LastSyncedAt = new(time.Now())+ state.LastError = ""+ } else {+ state.LastError = syncErr.Error()+ }+ if s.kvService != nil {+ raw, err := json.Marshal(state)+ if err == nil {+ err = s.kvService.Set(ctx, threatIntelStateKey, string(raw))+ }+ if err != nil {+ slog.WarnContext(ctx, "failed to store threat intel state", "error", err)+ }+ }+ return syncErr+}++// syncKEVInternal replaces the stored KEV flags with the current catalog and returns the feed ETag.+func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string) (string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.kevFeedURL, nil)+ if err != nil {+ return "", errors.WrapIf(err, "failed to build KEV request")+ }+ if etag != "" {+ req.Header.Set("If-None-Match", etag)+ }+ resp, err := s.httpClient.Do(req)+ if err != nil {+ return "", errors.WrapIf(err, "failed to fetch KEV catalog")+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode == http.StatusNotModified {+ return etag, nil+ }+ if resp.StatusCode != http.StatusOK {+ return "", errors.Errorf("KEV catalog returned HTTP %d", resp.StatusCode)+ }++ var feed struct {+ Vulnerabilities []struct {+ CVEID string `json:"cveID"`+ DateAdded string `json:"dateAdded"`+ DueDate string `json:"dueDate"`+ Ransomware string `json:"knownRansomwareCampaignUse"`+ } `json:"vulnerabilities"`+ }+ if err := json.UnmarshalRead(io.LimitReader(resp.Body, kevFeedMaxBytes), &feed); err != nil {+ return "", errors.WrapIf(err, "failed to decode KEV catalog")+ }++ now := time.Now()+ rows := make([]VulnerabilityThreatIntel, 0, len(feed.Vulnerabilities))+ for _, entry := range feed.Vulnerabilities {+ if entry.CVEID == "" {+ continue+ }+ rows = append(rows, VulnerabilityThreatIntel{+ CVEID: strings.ToUpper(entry.CVEID),+ KnownExploited: true,+ KEVDateAdded: entry.DateAdded,+ KEVDueDate: entry.DueDate,+ KEVRansomware: strings.EqualFold(entry.Ransomware, "Known"),+ UpdatedAt: &now,+ })+ }++ // The catalog only grows, so an empty or much smaller feed is a bad response; keep the cached flags.+ var cached int64+ if err := s.db.WithContext(ctx).Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Count(&cached).Error; err != nil {+ return "", errors.WrapIf(err, "failed to count cached KEV entries")+ }+ if len(rows) == 0 || int64(len(rows)) < cached/2 {+ return "", errors.Errorf("KEV catalog looks incomplete (%d entries, %d cached); keeping cached data", len(rows), cached)+ }++ err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ if err := tx.Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Updates(map[string]any{+ "known_exploited": false, "kev_date_added": "", "kev_due_date": "", "kev_ransomware": false, "updated_at": now,+ }).Error; err != nil {+ return err+ }+ return tx.Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "cve_id"}},+ DoUpdates: clause.AssignmentColumns([]string{"known_exploited", "kev_date_added", "kev_due_date", "kev_ransomware", "updated_at"}),+ }).CreateInBatches(rows, threatIntelUpsertBatch).Error+ })+ if err != nil {+ return "", errors.WrapIf(err, "failed to store KEV catalog")+ }+ return resp.Header.Get("ETag"), nil+}++// syncEPSSInternal fetches EPSS scores for scanned CVEs that were never checked or were checked over 20h ago.+func (s *VulnerabilityService) syncEPSSInternal(ctx context.Context) error {+ var cveIDs []string+ if err := s.db.WithContext(ctx).+ Model(&VulnerabilityScanItem{}).+ Distinct("vulnerability_scan_items.vulnerability_id").+ Joins("LEFT JOIN vulnerability_threat_intel ON vulnerability_threat_intel.cve_id = vulnerability_scan_items.vulnerability_id").+ Where("vulnerability_scan_items.vulnerability_id LIKE ?", "CVE-%").+ Where("vulnerability_threat_intel.epss_checked_at IS NULL OR vulnerability_threat_intel.epss_checked_at < ?", time.Now().Add(-threatIntelSyncInterval)).+ Limit(epssMaxCVEsPerSync).+ Pluck("vulnerability_scan_items.vulnerability_id", &cveIDs).Error; err != nil {+ return errors.WrapIf(err, "failed to list CVEs for EPSS")+ }++ for start := 0; start < len(cveIDs); {+ end, chars := start, 0+ for end < len(cveIDs) && end-start < epssBatchMaxIDs && chars+len(cveIDs[end])+1 <= epssBatchMaxChars {+ chars += len(cveIDs[end]) + 1+ end+++ }+ if err := s.fetchEPSSBatchInternal(ctx, cveIDs[start:end]); err != nil {+ return err+ }+ start = end+ if start < len(cveIDs) {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(epssBatchDelay):+ }+ }+ }+ return nil+}++func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveIDs []string) error {+ var resp *http.Response+ for attempt := 0; ; attempt++ {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.epssAPIURL+"?cve="+strings.Join(cveIDs, ","), nil)+ if err != nil {+ return errors.WrapIf(err, "failed to build EPSS request")+ }+ resp, err = s.httpClient.Do(req)+ if err != nil {+ return errors.WrapIf(err, "failed to fetch EPSS scores")+ }+ if resp.StatusCode != http.StatusTooManyRequests || attempt > 0 {+ break+ }+ if err := resp.Body.Close(); err != nil {+ slog.WarnContext(ctx, "failed to close rate-limited EPSS response", "error", err)+ }+ wait := epssMaxRetryAfter+ if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {+ wait = min(time.Duration(seconds)*time.Second, epssMaxRetryAfter)+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(wait):+ }+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ return errors.Errorf("EPSS API returned HTTP %d", resp.StatusCode)+ }++ var payload struct {+ Data []struct {+ CVE string `json:"cve"`+ EPSS string `json:"epss"`+ Percentile string `json:"percentile"`+ } `json:"data"`+ }+ if err := json.UnmarshalRead(resp.Body, &payload); err != nil {+ return errors.WrapIf(err, "failed to decode EPSS scores")+ }++ now := time.Now()+ rows := make(map[string]*VulnerabilityThreatIntel, len(cveIDs))+ for _, id := range cveIDs {+ rows[strings.ToUpper(id)] = &VulnerabilityThreatIntel{CVEID: id, EPSSCheckedAt: &now, UpdatedAt: &now}+ }+ for _, entry := range payload.Data {+ row, ok := rows[strings.ToUpper(entry.CVE)]+ if !ok {+ continue+ }+ if score, err := strconv.ParseFloat(entry.EPSS, 64); err == nil {+ row.EPSSScore = &score+ }+ if percentile, err := strconv.ParseFloat(entry.Percentile, 64); err == nil {+ row.EPSSPercentile = &percentile+ }+ }+ batch := make([]VulnerabilityThreatIntel, 0, len(rows))+ for _, row := range rows {+ batch = append(batch, *row)+ }+ return errors.WrapIf(s.db.WithContext(ctx).Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "cve_id"}},+ DoUpdates: clause.AssignmentColumns([]string{"epss_score", "epss_percentile", "epss_checked_at", "updated_at"}),+ }).Create(&batch).Error, "failed to store EPSS scores")+}++// RecordRiskSnapshot upserts today's environment risk snapshot and prunes snapshots past retention.+func (s *VulnerabilityService) RecordRiskSnapshot(ctx context.Context) error {+ if s.db == nil || !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {+ return nil+ }+ overview, err := s.computeRiskInternal(ctx, types.LocalDockerEnvironmentID)+ if err != nil {+ return err+ }++ now := s.riskNowInternal()+ snapshot := VulnerabilityRiskSnapshot{+ SnapshotDate: now.Format(riskDateLayout),+ RiskScore: overview.RiskScore,+ RiskBand: string(overview.RiskBand),+ CriticalCount: overview.Summary.Critical,+ HighCount: overview.Summary.High,+ MediumCount: overview.Summary.Medium,+ LowCount: overview.Summary.Low,+ UnknownCount: overview.Summary.Unknown,+ FindingsCount: overview.Drivers.Findings,+ KnownExploitedCount: overview.Drivers.KnownExploited,+ OverdueKnownExploitedCount: overview.Drivers.OverdueKnownExploited,+ HighEPSSCount: overview.Drivers.HighEPSS,+ ExposedCriticalHighCount: overview.Drivers.ExposedCriticalHigh,+ FixableCount: overview.Drivers.Fixable,+ ImagesScanned: overview.Drivers.ImagesScanned,+ ImagesTotal: overview.Drivers.ImagesTotal,+ UpdatedAt: &now,+ }+ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ if err := tx.Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "snapshot_date"}},+ DoUpdates: clause.AssignmentColumns([]string{"risk_score", "risk_band", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "findings_count", "known_exploited_count", "overdue_known_exploited_count", "high_epss_count", "exposed_critical_high_count", "fixable_count", "images_scanned", "images_total", "updated_at"}),+ }).Create(&snapshot).Error; err != nil {+ return errors.WrapIf(err, "failed to store risk snapshot")+ }+ return errors.WrapIf(tx.Where("snapshot_date < ?", now.AddDate(0, 0, -riskSnapshotRetentionDays).Format(riskDateLayout)).+ Delete(&VulnerabilityRiskSnapshot{}).Error, "failed to prune risk snapshots")+ })+}diff --git a/backend/internal/vulnerability/vulnerability_trivy.go b/backend/internal/vulnerability/vulnerability_trivy.goindex c604b92ee..ae2141ef7 100644--- a/backend/internal/vulnerability/vulnerability_trivy.go+++ b/backend/internal/vulnerability/vulnerability_trivy.go@@ -231,7 +231,7 @@ func (s *VulnerabilityService) scanSingleImage(}s.saveScheduledSuccessfulScanInternal(ctx, envID, imageID, imageName, user, result, duration)- s.collectScheduledFixableSummaryInternal(ctx, result, notificationSummary)+ s.collectScheduledFixableSummaryInternal(ctx, envID, result, notificationSummary)return scanStatusSuccess}diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.goindex 09772e562..d667c41f0 100644--- a/backend/pkg/libarcane/edge/commands.go+++ b/backend/pkg/libarcane/edge/commands.go@@ -69,6 +69,7 @@ var commandRoutes = []commandRoute{{Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/{imageId}/vulnerabilities/list", CommandName: "vulnerability.list"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/scanner-status", CommandName: "vulnerability.scanner_status"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/summary", CommandName: "vulnerability.summary"},+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/overview", CommandName: "vulnerability.overview"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/all", CommandName: "vulnerability.all"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/export", CommandName: "vulnerability.export"},{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/image-options", CommandName: "vulnerability.image_options"},diff --git a/backend/pkg/scheduler/vulnerability_risk_job.go b/backend/pkg/scheduler/vulnerability_risk_job.gonew file mode 100644index 000000000..e44d50631--- /dev/null+++ b/backend/pkg/scheduler/vulnerability_risk_job.go@@ -0,0 +1,66 @@+package scheduler++import (+ "context"+ "log/slog"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"+ "github.com/getarcaneapp/arcane/types/v2/features"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+)++const VulnerabilityRiskJobName = "vulnerability-risk"++// VulnerabilityRiskJob refreshes KEV/EPSS threat intel and records the daily environment risk snapshot.+// It runs hourly; both steps are idempotent (intel is gated at 20h, the snapshot is a daily upsert).+type VulnerabilityRiskJob struct {+ vulnerabilityService *vulnerability.VulnerabilityService+ settingsService *settings.SettingsService+}++// NewVulnerabilityRiskJob creates a new VulnerabilityRiskJob.+func NewVulnerabilityRiskJob(vulnerabilityService *vulnerability.VulnerabilityService, settingsService *settings.SettingsService) *VulnerabilityRiskJob {+ return &VulnerabilityRiskJob{+ vulnerabilityService: vulnerabilityService,+ settingsService: settingsService,+ }+}++func (j *VulnerabilityRiskJob) Name() string {+ return VulnerabilityRiskJobName+}++func (j *VulnerabilityRiskJob) ShouldSchedule(ctx context.Context) bool {+ return j.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement)+}++func (j *VulnerabilityRiskJob) Schedule(_ context.Context) string {+ return "0 17 * * * *"+}++func (j *VulnerabilityRiskJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {+ if !j.ShouldSchedule(ctx) {+ return schedulertypes.Outcome{Status: schedulertypes.Skipped}, nil+ }++ run, ok := jobcontext.Run(ctx)+ force := ok && run.Trigger != "scheduled"+ intelFailure := ""+ if err := j.vulnerabilityService.SyncThreatIntel(ctx, force); err != nil {+ slog.WarnContext(ctx, "threat intel sync failed", "error", err)+ intelFailure = "Threat intelligence sync failed: " + err.Error()+ }++ if err := j.vulnerabilityService.RecordRiskSnapshot(ctx); err != nil {+ slog.ErrorContext(ctx, "risk snapshot failed", "error", err)+ return schedulertypes.Outcome{}, err+ }++ // Offline installs keep recording snapshots; a failed sync is partial, not a retryable error.+ if intelFailure != "" {+ return schedulertypes.Outcome{Status: schedulertypes.Partial, Message: intelFailure}, nil+ }+ return schedulertypes.Outcome{Status: schedulertypes.Succeeded}, nil+}diff --git a/backend/resources/migrations/postgres/088_add_vulnerability_risk.sql b/backend/resources/migrations/postgres/088_add_vulnerability_risk.sqlnew file mode 100644index 000000000..2fb5d7fea--- /dev/null+++ b/backend/resources/migrations/postgres/088_add_vulnerability_risk.sql@@ -0,0 +1,49 @@+-- +goose Up+ALTER TABLE vulnerability_scan_items ADD COLUMN IF NOT EXISTS cvss_score DOUBLE PRECISION;+UPDATE vulnerability_scan_items+SET cvss_score = COALESCE(+ NULLIF((CAST(details AS jsonb) #>> '{cvss,v3Score}')::double precision, 0),+ NULLIF((CAST(details AS jsonb) #>> '{cvss,v2Score}')::double precision, 0)+)+WHERE details IS NOT NULL AND details <> '';++CREATE TABLE IF NOT EXISTS vulnerability_threat_intel (+ cve_id TEXT PRIMARY KEY,+ known_exploited BOOLEAN NOT NULL DEFAULT FALSE,+ kev_date_added TEXT NOT NULL DEFAULT '',+ kev_due_date TEXT NOT NULL DEFAULT '',+ kev_ransomware BOOLEAN NOT NULL DEFAULT FALSE,+ epss_score DOUBLE PRECISION,+ epss_percentile DOUBLE PRECISION,+ epss_checked_at TIMESTAMPTZ,+ updated_at TIMESTAMPTZ+);++CREATE INDEX IF NOT EXISTS idx_vulnerability_threat_intel_known_exploited ON vulnerability_threat_intel(known_exploited);++CREATE TABLE IF NOT EXISTS vulnerability_risk_snapshots (+ snapshot_date TEXT PRIMARY KEY,+ risk_score INTEGER NOT NULL DEFAULT 0,+ risk_band TEXT NOT NULL DEFAULT 'none',+ critical_count INTEGER NOT NULL DEFAULT 0,+ high_count INTEGER NOT NULL DEFAULT 0,+ medium_count INTEGER NOT NULL DEFAULT 0,+ low_count INTEGER NOT NULL DEFAULT 0,+ unknown_count INTEGER NOT NULL DEFAULT 0,+ findings_count INTEGER NOT NULL DEFAULT 0,+ known_exploited_count INTEGER NOT NULL DEFAULT 0,+ overdue_known_exploited_count INTEGER NOT NULL DEFAULT 0,+ high_epss_count INTEGER NOT NULL DEFAULT 0,+ exposed_critical_high_count INTEGER NOT NULL DEFAULT 0,+ fixable_count INTEGER NOT NULL DEFAULT 0,+ images_scanned INTEGER NOT NULL DEFAULT 0,+ images_total INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMPTZ+);++-- +goose Down+DROP TABLE IF EXISTS vulnerability_risk_snapshots;+DROP INDEX IF EXISTS idx_vulnerability_threat_intel_known_exploited;+DROP TABLE IF EXISTS vulnerability_threat_intel;+ALTER TABLE vulnerability_scan_items DROP COLUMN IF EXISTS cvss_score;diff --git a/backend/resources/migrations/sqlite/088_add_vulnerability_risk.sql b/backend/resources/migrations/sqlite/088_add_vulnerability_risk.sqlnew file mode 100644index 000000000..35f5d5c67--- /dev/null+++ b/backend/resources/migrations/sqlite/088_add_vulnerability_risk.sql@@ -0,0 +1,49 @@+-- +goose Up+ALTER TABLE vulnerability_scan_items ADD COLUMN cvss_score REAL;+UPDATE vulnerability_scan_items+SET cvss_score = COALESCE(+ NULLIF(CAST(json_extract(details, '$.cvss.v3Score') AS REAL), 0),+ NULLIF(CAST(json_extract(details, '$.cvss.v2Score') AS REAL), 0)+)+WHERE details IS NOT NULL AND json_valid(details);++CREATE TABLE IF NOT EXISTS vulnerability_threat_intel (+ cve_id TEXT PRIMARY KEY,+ known_exploited BOOLEAN NOT NULL DEFAULT false,+ kev_date_added TEXT NOT NULL DEFAULT '',+ kev_due_date TEXT NOT NULL DEFAULT '',+ kev_ransomware BOOLEAN NOT NULL DEFAULT false,+ epss_score REAL,+ epss_percentile REAL,+ epss_checked_at DATETIME,+ updated_at DATETIME+);++CREATE INDEX IF NOT EXISTS idx_vulnerability_threat_intel_known_exploited ON vulnerability_threat_intel(known_exploited);++CREATE TABLE IF NOT EXISTS vulnerability_risk_snapshots (+ snapshot_date TEXT PRIMARY KEY,+ risk_score INTEGER NOT NULL DEFAULT 0,+ risk_band TEXT NOT NULL DEFAULT 'none',+ critical_count INTEGER NOT NULL DEFAULT 0,+ high_count INTEGER NOT NULL DEFAULT 0,+ medium_count INTEGER NOT NULL DEFAULT 0,+ low_count INTEGER NOT NULL DEFAULT 0,+ unknown_count INTEGER NOT NULL DEFAULT 0,+ findings_count INTEGER NOT NULL DEFAULT 0,+ known_exploited_count INTEGER NOT NULL DEFAULT 0,+ overdue_known_exploited_count INTEGER NOT NULL DEFAULT 0,+ high_epss_count INTEGER NOT NULL DEFAULT 0,+ exposed_critical_high_count INTEGER NOT NULL DEFAULT 0,+ fixable_count INTEGER NOT NULL DEFAULT 0,+ images_scanned INTEGER NOT NULL DEFAULT 0,+ images_total INTEGER NOT NULL DEFAULT 0,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME+);++-- +goose Down+DROP TABLE IF EXISTS vulnerability_risk_snapshots;+DROP INDEX IF EXISTS idx_vulnerability_threat_intel_known_exploited;+DROP TABLE IF EXISTS vulnerability_threat_intel;+ALTER TABLE vulnerability_scan_items DROP COLUMN cvss_score;diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 986848766..e309ba5cf 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -988,6 +988,65 @@"vuln_installed_version": "Installed Version","vuln_fixed_version": "Fixed Version","vuln_no_fix": "No fix available",+ "vuln_risk_score": "Risk score",+ "vuln_risk_band_low": "Low risk",+ "vuln_risk_band_medium": "Medium risk",+ "vuln_risk_band_high": "High risk",+ "vuln_risk_band_critical": "Critical risk",+ "vuln_risk_score_help": "Starts at the highest finding risk (CVSS adjusted for known exploitation and container exposure) ×10, and rises by up to 20 points with the number and weight of all other findings.",+ "vuln_highest_cvss": "Highest CVSS",+ "vuln_cvss": "CVSS",+ "vuln_top_packages": "Top packages to update",+ "vuln_cve_count": "{count} CVEs",+ "vuln_cve_count_one": "1 CVE",+ "vuln_kev_badge": "KEV",+ "vuln_ransomware_badge": "Ransomware",+ "vuln_epss_value": "EPSS {value}%",+ "vuln_known_exploited_count": "{count} known exploited",+ "vuln_exposure_stopped": "Used only by stopped containers, risk reduced",+ "vuln_exposure_unused": "Not used by any container, risk reduced",+ "security_risk_trend": "Risk trend",+ "security_risk_trend_summary": "Risk score went from {from} to {to} over the last {days} days",+ "security_risk_trend_empty": "The trend fills in as daily risk snapshots are recorded.",+ "security_risk_delta_7d": "vs 7 days ago",+ "security_risk_delta_unchanged": "Unchanged from 7 days ago",+ "security_risk_range_30d": "30d",+ "security_risk_range_90d": "90d",+ "security_driver_known_exploited": "Known exploited",+ "security_driver_known_exploited_help": "CVEs listed in the CISA Known Exploited Vulnerabilities catalog.",+ "security_driver_high_epss": "Likely exploited",+ "security_driver_high_epss_help": "CVEs with a FIRST EPSS probability of 10% or more of being exploited in the next 30 days.",+ "security_driver_exposed": "Exposed critical/high",+ "security_driver_exposed_help": "Critical and high CVEs in images used by running containers.",+ "security_driver_overdue_kev": "Overdue KEV",+ "security_driver_overdue_kev_help": "Known exploited CVEs past the remediation due date set by CISA.",+ "security_score_driver": "Driven by {cve} in {image}",+ "security_severity_breakdown": "Findings by severity",+ "security_exposure_breakdown": "Findings by exposure",+ "security_exposure_breakdown_help": "Findings in images used by running containers carry full risk; images used only by stopped containers, or by none, count less.",+ "security_exposure_running": "Running",+ "security_driver_images_scanned_help": "Current images with a completed vulnerability scan.",+ "security_driver_of_images": "of {count} images",+ "security_top_vulnerabilities": "Top vulnerabilities",+ "security_top_vulnerabilities_risk_help": "Ranked by risk: CVSS adjusted for known exploitation, exploit probability and container exposure.",+ "security_top_vulnerabilities_prevalence_help": "Ranked by how many images contain the CVE, then by risk.",+ "security_rank_risk": "Risk",+ "security_rank_prevalence": "Prevalence",+ "security_risk_value": "Risk {value}",+ "security_riskiest_images": "Riskiest images",+ "security_images_affected": "{count} images",+ "security_images_affected_one": "1 image",+ "security_findings_count": "{count} findings",+ "security_running_containers": "{count} running",+ "security_image_stopped": "Stopped",+ "security_image_unused": "Unused",+ "security_overview_empty": "Scan your images to see the environment risk overview.",+ "security_threat_intel_updated": "Threat data from CISA KEV and FIRST EPSS, updated {time}",+ "security_threat_intel_stale": "Threat data from CISA KEV and FIRST EPSS is out of date (last updated {time})",+ "security_threat_intel_pending": "Threat data from CISA KEV and FIRST EPSS has not synced yet",+ "security_threat_intel_disabled": "Threat intelligence is off; scores use CVSS and container exposure only",+ "security_threat_intel_enabled_label": "Threat Intelligence",+ "security_threat_intel_enabled_description": "Fetch the CISA KEV catalog and FIRST EPSS scores to prioritize vulnerabilities that are exploited in the wild. Disable for air-gapped installs.","published": "Published","completed": "Completed","vuln_clean": "Clean",diff --git a/frontend/src/lib/components/settings/trivy-security-settings.svelte b/frontend/src/lib/components/settings/trivy-security-settings.svelteindex ca1c68eed..e8de5331f 100644--- a/frontend/src/lib/components/settings/trivy-security-settings.svelte+++ b/frontend/src/lib/components/settings/trivy-security-settings.svelte@@ -39,6 +39,7 @@| 'trivyServerUrl'| 'trivyServerToken'| 'trivyIgnoreUnfixed'+ | 'vulnerabilityThreatIntelEnabled'| 'trivyConfig'| 'trivyIgnore'>;@@ -187,6 +188,14 @@<Switch id="trivyIgnoreUnfixedSwitch" bind:checked={formInputs.trivyIgnoreUnfixed.value} /></SettingsRow>+ <SettingsRow+ label={m.security_threat_intel_enabled_label()}+ description={m.security_threat_intel_enabled_description()}+ layout="inline"+ >+ <Switch id="vulnerabilityThreatIntelEnabledSwitch" bind:checked={formInputs.vulnerabilityThreatIntelEnabled.value} />+ </SettingsRow>+<SettingsRow label={m.security_trivy_config_label()} description={m.security_trivy_config_description()}><div class="overflow-hidden rounded-md border border-border/60"><CodeEditordiff --git a/frontend/src/lib/components/vulnerability/risk-gauge.svelte b/frontend/src/lib/components/vulnerability/risk-gauge.sveltenew file mode 100644index 000000000..7124a7854--- /dev/null+++ b/frontend/src/lib/components/vulnerability/risk-gauge.svelte@@ -0,0 +1,111 @@+<script lang="ts">+ import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';+ import { InfoIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import type { VulnerabilityRiskBand } from '#lib/types/environment.js';+ import { getRiskBandDisplay } from '#lib/utils/vulnerability.js';++ interface Props {+ /** 0-100; values outside the range are clamped. */+ score: number;+ band: VulnerabilityRiskBand;+ /** Maximum width in px; the gauge shrinks to fit narrower containers. */+ size?: number;+ stroke?: number;+ }++ let { score, band, size = 260, stroke = 14 }: Props = $props();++ let measuredWidth = $state(0);+ const clampedScore = $derived(Math.max(0, Math.min(100, score)));+ const width = $derived(measuredWidth > 0 ? Math.min(measuredWidth, size) : size);+ const radius = $derived((width - stroke) / 2);+ const svgHeight = $derived(radius + stroke);+ const arcPath = $derived(+ `M ${stroke / 2} ${radius + stroke / 2} A ${radius} ${radius} 0 0 1 ${width - stroke / 2} ${radius + stroke / 2}`+ );++ const bandStyle = $derived(getRiskBandDisplay(band));+ const large = $derived(width >= 360);+</script>++<div class="relative w-full" style="max-width: {size}px; height: {svgHeight}px;" bind:clientWidth={measuredWidth}>+ <svg {width} height={svgHeight} viewBox="0 0 {width} {svgHeight}" aria-hidden="true">+ <path d={arcPath} fill="none" stroke="currentColor" stroke-width={stroke} stroke-linecap="round" class="text-muted" />+ {#if clampedScore > 0}+ <path+ d={arcPath}+ fill="none"+ stroke="currentColor"+ stroke-width={stroke}+ stroke-linecap="round"+ pathLength="100"+ stroke-dasharray="{clampedScore} 100"+ class="gauge-fill transition-all duration-500 ease-out {bandStyle.strokeClass}"+ />+ {/if}+ </svg>+ <div class="absolute inset-x-0 bottom-0 flex flex-col items-center">+ <!-- The visible number counts up via a CSS counter; the sr-only text carries the value for assistive tech. -->+ <span+ class="gauge-number leading-none font-semibold tracking-tight tabular-nums"+ style="font-size: {Math.round(width * 0.25)}px; --gauge-score: {clampedScore};"+ aria-hidden="true"+ ></span>+ <span class="sr-only">{clampedScore}</span>+ <span class="mt-2 flex items-center gap-1.5 text-muted-foreground {large ? 'text-base' : 'text-sm'}">+ {bandStyle.label}+ <ArcaneTooltip.Root>+ <ArcaneTooltip.Trigger>+ <span class="inline-flex cursor-help items-center" aria-label={m.vuln_risk_score()}>+ <InfoIcon class="size-4 shrink-0" />+ </span>+ </ArcaneTooltip.Trigger>+ <ArcaneTooltip.Content class="max-w-64">+ <p class="mb-1 text-sm font-medium">{m.vuln_risk_score()}</p>+ <p class="text-xs text-muted-foreground">{m.vuln_risk_score_help()}</p>+ </ArcaneTooltip.Content>+ </ArcaneTooltip.Root>+ </span>+ </div>+</div>++<style>+ @property --gauge-score {+ syntax: '<integer>';+ initial-value: 0;+ inherits: false;+ }++ .gauge-number {+ counter-reset: gauge-score var(--gauge-score);+ animation: gauge-count 1.1s cubic-bezier(0.22, 1, 0.36, 1) both;+ }++ .gauge-number::after {+ content: counter(gauge-score);+ }++ .gauge-fill {+ animation: gauge-fill 1.1s cubic-bezier(0.22, 1, 0.36, 1) both;+ }++ @keyframes gauge-count {+ from {+ --gauge-score: 0;+ }+ }++ @keyframes gauge-fill {+ from {+ stroke-dasharray: 0 100;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ .gauge-number,+ .gauge-fill {+ animation: none;+ }+ }+</style>diff --git a/frontend/src/lib/components/vulnerability/risk-trend-chart.svelte b/frontend/src/lib/components/vulnerability/risk-trend-chart.sveltenew file mode 100644index 000000000..826793574--- /dev/null+++ b/frontend/src/lib/components/vulnerability/risk-trend-chart.svelte@@ -0,0 +1,169 @@+<script lang="ts">+ import { Temporal } from 'temporal-polyfill';+ import { m } from '#lib/paraglide/messages.js';+ import type { VulnerabilityRiskTrendPoint } from '#lib/types/environment.js';+ import { formatDate, plainDateToInstantString } from '#lib/utils/formatting.js';++ interface Props {+ points: VulnerabilityRiskTrendPoint[];+ /** Number of days shown, ending at the latest point. */+ days: number;+ height?: number;+ }++ let { points, days, height = 120 }: Props = $props();++ const BAND_LINES = [40, 70, 90];+ const PAD_TOP = 8;+ const PAD_BOTTOM = 4;+ const PAD_RIGHT = 24;++ let width = $state(0);+ let hoverIndex = $state<number | null>(null);++ const plotted = $derived.by(() => {+ const last = points.at(-1);+ if (!last) return [];+ const end = Temporal.PlainDate.from(last.date);+ const start = end.subtract({ days: days - 1 });+ return points+ .map((point) => {+ const date = Temporal.PlainDate.from(point.date);+ return { date, day: start.until(date).days, score: point.riskScore };+ })+ .filter((point) => point.day >= 0);+ });++ const plotWidth = $derived(Math.max(width - PAD_RIGHT, 0));+ const xFor = (day: number) => (days <= 1 ? plotWidth : (day / (days - 1)) * plotWidth);+ const yFor = (score: number) => PAD_TOP + (1 - score / 100) * (height - PAD_TOP - PAD_BOTTOM);++ // Consecutive days form a segment; a missing day breaks the line.+ const segments = $derived.by(() => {+ const result: (typeof plotted)[] = [];+ for (const point of plotted) {+ const segment = result.at(-1);+ const previous = segment?.at(-1);+ if (segment && previous && point.day - previous.day === 1) segment.push(point);+ else result.push([point]);+ }+ return result;+ });++ const linePaths = $derived(+ segments.map((segment) => segment.map((p, i) => `${i ? 'L' : 'M'}${xFor(p.day)},${yFor(p.score)}`).join(''))+ );+ const areaPaths = $derived(+ segments.flatMap((segment) => {+ const first = segment.at(0);+ const last = segment.at(-1);+ if (!first || !last || segment.length < 2) return [];+ const line = segment.map((p) => `L${xFor(p.day)},${yFor(p.score)}`).join('');+ return [`M${xFor(first.day)},${yFor(0)}${line}L${xFor(last.day)},${yFor(0)}Z`];+ })+ );++ // Single-day segments have no line, so they get a dot.+ const isolatedPoints = $derived(segments.flatMap((segment) => (segment.length === 1 ? segment : [])));+ const latest = $derived(plotted.at(-1));+ const hovered = $derived(hoverIndex === null ? undefined : plotted.at(hoverIndex));+ const summaryLabel = $derived.by(() => {+ const first = plotted.at(0);+ if (!first || !latest || plotted.length < 2) return m.security_risk_trend_empty();+ return m.security_risk_trend_summary({ from: first.score, to: latest.score, days });+ });++ function formatDay(date: Temporal.PlainDate) {+ return formatDate(plainDateToInstantString(date), { dateStyle: 'month-day' });+ }++ function handlePointerMove(event: PointerEvent) {+ if (plotted.length === 0 || plotWidth === 0) return;+ const rect = (event.currentTarget as SVGRectElement).getBoundingClientRect();+ const day = ((event.clientX - rect.left) / plotWidth) * (days - 1);+ let nearest = 0;+ let nearestDistance = Infinity;+ plotted.forEach((point, i) => {+ const distance = Math.abs(point.day - day);+ if (distance < nearestDistance) {+ nearest = i;+ nearestDistance = distance;+ }+ });+ hoverIndex = nearest;+ }+</script>++<div class="relative w-full" bind:clientWidth={width} style="height: {height}px;">+ {#if width > 0}+ <svg {width} {height} role="img" aria-label={summaryLabel} class="overflow-visible">+ {#each BAND_LINES as band (band)}+ <line+ x1="0"+ x2={plotWidth}+ y1={yFor(band)}+ y2={yFor(band)}+ stroke="currentColor"+ stroke-width="1"+ class="text-border/60"+ />+ <text x={plotWidth + 6} y={yFor(band)} dy="0.32em" class="fill-muted-foreground text-[10px] tabular-nums">{band}</text>+ {/each}+ <line x1="0" x2={plotWidth} y1={yFor(0)} y2={yFor(0)} stroke="currentColor" stroke-width="1" class="text-border" />++ {#each areaPaths as path, i (i)}+ <path d={path} fill="currentColor" class="text-primary/10" />+ {/each}+ {#each linePaths as path, i (i)}+ <path+ d={path}+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="text-primary"+ />+ {/each}+ {#each isolatedPoints as point (point.day)}+ <circle cx={xFor(point.day)} cy={yFor(point.score)} r="2.5" class="fill-primary" />+ {/each}++ {#if hovered}+ <line+ x1={xFor(hovered.day)}+ x2={xFor(hovered.day)}+ y1={PAD_TOP}+ y2={yFor(0)}+ stroke="currentColor"+ stroke-width="1"+ class="text-muted-foreground/50"+ />+ <circle cx={xFor(hovered.day)} cy={yFor(hovered.score)} r="4" class="fill-primary stroke-background" stroke-width="2" />+ {:else if latest}+ <circle cx={xFor(latest.day)} cy={yFor(latest.score)} r="4" class="fill-primary stroke-background" stroke-width="2" />+ {/if}++ <rect+ x="0"+ y="0"+ width={plotWidth}+ {height}+ fill="transparent"+ role="presentation"+ onpointermove={handlePointerMove}+ onpointerleave={() => (hoverIndex = null)}+ />+ </svg>++ {#if hovered}+ <div+ class="pointer-events-none absolute -top-2 -translate-x-1/2 -translate-y-full rounded-md border border-border/60 bg-popover px-2 py-1 text-xs whitespace-nowrap shadow-sm"+ style="left: {xFor(hovered.day)}px;"+ >+ <span class="text-muted-foreground">{formatDay(hovered.date)}</span>+ <span class="ml-1.5 font-semibold tabular-nums">{hovered.score}</span>+ </div>+ {/if}+ {/if}+</div>diff --git a/frontend/src/lib/components/vulnerability/share-bar.svelte b/frontend/src/lib/components/vulnerability/share-bar.sveltenew file mode 100644index 000000000..ee913f56a--- /dev/null+++ b/frontend/src/lib/components/vulnerability/share-bar.svelte@@ -0,0 +1,33 @@+<script lang="ts">+ import { cn } from '#lib/utils.js';+ import type { ShareBarSegment } from '#lib/utils/vulnerability.js';++ interface Props {+ segments: ShareBarSegment[];+ align?: 'start' | 'center';+ class?: string;+ }++ let { segments, align = 'start', class: className }: Props = $props();++ const visible = $derived(segments.filter((segment) => segment.count > 0));+</script>++<div class={cn('w-full space-y-3', className)}>+ <div class="flex h-2 gap-0.5">+ {#each visible as segment (segment.key)}+ <div class="h-full rounded-full {segment.barClass}" style="flex-grow: {segment.count}" title={segment.label}></div>+ {:else}+ <div class="h-full flex-1 rounded-full bg-muted"></div>+ {/each}+ </div>+ <ul class={cn('flex flex-wrap gap-x-5 gap-y-1 text-sm text-muted-foreground', align === 'center' && 'justify-center')}>+ {#each visible as segment (segment.key)}+ <li class="flex items-center gap-1.5">+ <span class="size-2 rounded-full {segment.barClass}" aria-hidden="true"></span>+ {segment.label}+ <span class="font-medium text-foreground tabular-nums">{segment.count}</span>+ </li>+ {/each}+ </ul>+</div>diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelteindex 722b11a91..2f4d10be3 100644--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte@@ -6,23 +6,36 @@import MonoCell from '#lib/components/vulnerability/mono-cell.svelte';import FixedCell from '#lib/components/vulnerability/fixed-cell.svelte';import SeverityBadge from '#lib/components/vulnerability/severity-badge.svelte';+ import RiskGauge from '#lib/components/vulnerability/risk-gauge.svelte';+ import ShareBar from '#lib/components/vulnerability/share-bar.svelte';+ import { Badge } from '#lib/components/ui/badge/index.js';import { ArcaneButton } from '#lib/components/arcane-button/index.js';import { environmentStore } from '#lib/stores/environment.store.svelte.js';import { queryKeys } from '#lib/query/query-keys.js';import { Spinner } from '#lib/components/ui/spinner/index.js';- import { Badge, type BadgeVariant } from '#lib/components/ui/badge/index.js';import { m } from '#lib/paraglide/messages.js';import { vulnerabilityService } from '#lib/services/vulnerability-service.js';import type { ColumnSpec } from '#lib/components/arcane-table/arcane-table.types.svelte.js';import type { VulnerabilityScanResult, Vulnerability as VulnType } from '#lib/types/environment.js';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';- import { ShieldCheckIcon, ShieldAlertIcon, ShieldXIcon, ScanIcon, CodeIcon, CheckIcon } from '#lib/icons/index.js';+ import {+ ShieldCheckIcon,+ ShieldAlertIcon,+ ShieldXIcon,+ ScanIcon,+ CodeIcon,+ CheckIcon,+ ActivityIcon+ } from '#lib/icons/index.js';import {buildSeveritySummary,+ getCvssScore,getSeverityBadgeVariant,getSeverityIconVariant,- getSeverityLabel+ getSeverityLabel,+ getSeveritySegments} from '#lib/utils/vulnerability.js';+ import { formatRelativeTime } from '#lib/utils/formatting.js';import { createQuery } from '@tanstack/svelte-query';import { tick } from 'svelte';@@ -57,6 +70,7 @@{ accessorKey: 'vulnerabilityId', title: 'CVE', cell: CveCol },{ accessorKey: 'pkgName', title: m.vuln_package(), cell: PackageCell },{ id: 'vulnSeverity', accessorKey: 'severity', title: m.events_col_severity(), sortable: true, cell: SeverityCell },+ { id: 'cvss', accessorFn: (row) => getCvssScore(row), title: m.vuln_cvss(), cell: CvssCell },{ accessorKey: 'installedVersion', title: m.vuln_installed_version(), cell: InstalledCell },{ accessorKey: 'fixedVersion', title: m.vuln_fixed_version(), cell: FixedCol }] satisfies ColumnSpec<VulnerabilityRow>[]);@@ -65,84 +79,12 @@{ id: 'vulnerabilityId', label: 'CVE', defaultVisible: true },{ id: 'pkgName', label: m.vuln_package(), defaultVisible: true },{ id: 'vulnSeverity', label: m.events_col_severity(), defaultVisible: true },+ { id: 'cvss', label: m.vuln_cvss(), defaultVisible: true },{ id: 'installedVersion', label: m.vuln_installed_version(), defaultVisible: false },{ id: 'fixedVersion', label: m.vuln_fixed_version(), defaultVisible: false }];- const severityBars = $derived.by(() => {- if (!resolvedSummary)- return [] as Array<{- key: string;- label: string;- count: number;- pct: number;- barClass: string;- textClass: string;- }>;- const total = Math.max(resolvedSummary.total, 1);- return [- {- key: 'critical',- label: m.vuln_severity_critical(),- count: resolvedSummary.critical,- pct: (resolvedSummary.critical / total) * 100,- barClass: 'bg-destructive',- textClass: 'text-destructive'- },- {- key: 'high',- label: m.vuln_severity_high(),- count: resolvedSummary.high,- pct: (resolvedSummary.high / total) * 100,- barClass: 'bg-orange',- textClass: 'text-orange'- },- {- key: 'medium',- label: m.vuln_severity_medium(),- count: resolvedSummary.medium,- pct: (resolvedSummary.medium / total) * 100,- barClass: 'bg-warning',- textClass: 'text-warning'- },- {- key: 'low',- label: m.vuln_severity_low(),- count: resolvedSummary.low,- pct: (resolvedSummary.low / total) * 100,- barClass: 'bg-warning',- textClass: 'text-warning'- },- {- key: 'unknown',- label: m.common_unknown(),- count: resolvedSummary.unknown,- pct: (resolvedSummary.unknown / total) * 100,- barClass: 'bg-muted-foreground',- textClass: 'text-muted-foreground'- }- ].filter((bar) => bar.count > 0);- });-- const scanStatusLabel = $derived.by(() => {- if (!resolvedSummary) return m.common_unknown();- if (resolvedSummary.total === 0) return m.vuln_clean();- if (resolvedSummary.critical > 0) return m.vuln_severity_critical();- if (resolvedSummary.high > 0) return m.vuln_severity_high();- if (resolvedSummary.medium > 0) return m.vuln_severity_medium();- if (resolvedSummary.low > 0) return m.vuln_severity_low();- return m.common_unknown();- });-- const scanStatusVariant = $derived.by((): BadgeVariant => {- if (!resolvedSummary) return 'gray';- if (resolvedSummary.total === 0) return 'green';- if (resolvedSummary.critical > 0) return 'red';- if (resolvedSummary.high > 0) return 'orange';- if (resolvedSummary.medium > 0) return 'amber';- if (resolvedSummary.low > 0) return 'lime';- return 'gray';- });+ const severitySegments = $derived(getSeveritySegments(resolvedSummary));const scanDurationLabel = $derived.by(() => {const durationMs = scan?.duration ?? 0;@@ -151,6 +93,10 @@return `${(durationMs / 1000).toFixed(1)} s`;});+ function formatCvss(score: number | undefined): string {+ return score ? score.toFixed(1) : '—';+ }+const isWorking = $derived.by(() => isScanning || scan?.status === 'scanning');const hasError = $derived.by(() => scan?.status === 'failed' || !!scan?.error);@@ -223,6 +169,10 @@<SeverityBadge severity={item.severity} />{/snippet}+{#snippet CvssCell({ item }: { item: VulnerabilityRow })}+ <span class="font-mono text-xs tabular-nums">{formatCvss(getCvssScore(item))}</span>+{/snippet}+{#snippet InstalledCell({ item }: { item: VulnerabilityRow })}<MonoCell value={item['installedVersion']} />{/snippet}@@ -254,6 +204,14 @@: null]}fields={[+ {+ label: m.vuln_cvss(),+ getValue: (item) => formatCvss(getCvssScore(item)),+ type: 'mono',+ icon: ActivityIcon,+ iconVariant: 'gray',+ show: mobileFieldVisibility['cvss'] ?? true+ },{label: m.vuln_installed_version(),getValue: (item) => item['installedVersion'],@@ -274,13 +232,10 @@/>{/snippet}-{#snippet ScanMetaChips()}- <div class="mt-4 flex flex-wrap gap-2 text-xs text-muted-foreground">- <span class="rounded-full bg-muted/50 px-2 py-1">{scanDurationLabel}</span>- {#if scan?.scannerVersion}- <span class="rounded-full bg-muted/50 px-2 py-1">Trivy {scan.scannerVersion}</span>- {/if}- </div>+{#snippet ScanMeta()}+ <p class="text-center text-xs text-muted-foreground tabular-nums">+ {scanDurationLabel}{#if scan?.scannerVersion}<span class="mx-1.5">·</span>Trivy {scan.scannerVersion}{/if}+ </p>{/snippet}{#if isWorking}@@ -294,66 +249,99 @@<p class="mb-3 text-xs text-muted-foreground">{m.vuln_report_load_failed()}: {reportError}</p>{/if}{#if summary.total === 0}- <div class="rounded-2xl border border-success/20 bg-success/5 p-6 shadow-sm">- <div class="flex items-center gap-4">- <div class="rounded-full bg-success/15 p-3">- <ShieldCheckIcon class="size-6 text-success" />- </div>- <div class="space-y-1">- <p class="text-xs font-semibold tracking-wide text-success uppercase">{m.vuln_summary()}</p>- <p class="text-lg font-semibold text-success">{m.vuln_clean()}</p>- <p class="text-sm text-success/80">{m.vuln_no_vulnerabilities()}</p>- </div>+ <div class="flex flex-col items-center gap-3 py-10 text-center">+ <ShieldCheckIcon class="size-10 text-success" />+ <div class="space-y-1">+ <p class="text-lg font-medium">{m.vuln_clean()}</p>+ <p class="text-sm text-muted-foreground">{m.vuln_no_vulnerabilities()}</p></div>- {@render ScanMetaChips()}+ {@render ScanMeta()}</div>{:else}- <div class="grid gap-4 xl:grid-cols-split-6-5">- <div class="rounded-2xl border border-border/60 bg-muted/30 p-5 shadow-sm">- <div class="flex items-center justify-between">- <p class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.vuln_summary()}</p>- <Badge variant={scanStatusVariant}>{scanStatusLabel}</Badge>- </div>- <div class="mt-5 flex items-end gap-4">- <div class="text-5xl leading-none font-semibold tracking-tight">{summary.total}</div>- <div class="space-y-1 text-xs text-muted-foreground">- <div class="tracking-wide uppercase">{m.common_total()}</div>- <div>{m.vuln_details()}</div>- </div>- </div>- <div class="mt-5 space-y-2">- {#each severityBars as bar (bar.key)}- <div class="flex items-center gap-3 text-xs">- <span class="w-24 text-muted-foreground">{bar.label}</span>- <div class="relative h-2 flex-1 overflow-hidden rounded-full bg-muted/60">- <div class={`h-full w-(--bar-width) ${bar.barClass}`} style={`--bar-width: ${bar.pct}%`}></div>+ {@const insights = scan.insights}+ <section class="mx-auto grid max-w-6xl items-center gap-10 py-8 lg:grid-cols-[minmax(0,2fr)_minmax(0,3fr)] lg:gap-0">+ <div class="flex flex-col items-center gap-6 lg:pr-12">+ {#if insights}+ <div class="flex flex-col items-center gap-3">+ <RiskGauge score={insights.riskScore} band={insights.riskBand} />+ {#if insights.knownExploitedCount > 0 || insights.exposure === 'stopped' || insights.exposure === 'unused'}+ <div class="flex flex-wrap items-center justify-center gap-2 text-xs text-muted-foreground">+ {#if insights.knownExploitedCount > 0}+ <Badge variant="red" size="xs">{m.vuln_known_exploited_count({ count: insights.knownExploitedCount })}</Badge>+ {/if}+ {#if insights.exposure === 'stopped'}+ <span>{m.vuln_exposure_stopped()}</span>+ {:else if insights.exposure === 'unused'}+ <span>{m.vuln_exposure_unused()}</span>+ {/if}</div>- <span class={`w-8 text-right font-mono ${bar.textClass}`}>{bar.count}</span>- </div>- {/each}- </div>- {@render ScanMetaChips()}+ {/if}+ </div>+ {/if}+ <ShareBar segments={severitySegments} align="center" class="max-w-72" />+ {@render ScanMeta()}</div>- <div class="grid gap-3 sm:grid-cols-2">- {#each severityBars as bar (bar.key)}- <div class="rounded-xl border border-border/60 bg-muted/30 p-4 shadow-sm">- <div class="flex items-center justify-between">- <span class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{bar.label}</span>+ <div class="space-y-10 border-t border-border/50 pt-10 lg:border-t-0 lg:border-l lg:py-2 lg:pl-12">+ <dl class="grid grid-cols-1 gap-6 sm:grid-cols-3">+ {#if insights}+ <div>+ <dt class="text-sm text-muted-foreground">{m.vuln_highest_cvss()}</dt>+ <dd class="mt-2 flex items-baseline gap-2">+ <span class="text-3xl font-semibold tabular-nums">{formatCvss(insights.highestCvss)}</span>+ {#if insights.highestVulnerabilityId}+ <CveCell vulnerabilityId={insights.highestVulnerabilityId} />+ {/if}+ </dd></div>- <div class={`mt-2 text-3xl font-semibold ${bar.textClass}`}>{bar.count}</div>- <div class="mt-3 h-1.5 rounded-full bg-muted/60">- <div class={`h-full w-(--bar-width) ${bar.barClass}`} style={`--bar-width: ${bar.pct}%`}></div>+ <div>+ <dt class="text-sm text-muted-foreground">{m.security_fixable()}</dt>+ <dd class="mt-2 flex items-baseline gap-1 tabular-nums">+ <span class="text-3xl font-semibold">{insights.fixableCount}</span>+ <span class="text-base text-muted-foreground">/ {summary.total}</span>+ </dd></div>+ {/if}+ <div>+ <dt class="text-sm text-muted-foreground">{m.security_last_scanned()}</dt>+ <dd class="mt-2 flex items-baseline">+ <span class="text-3xl font-semibold">{formatRelativeTime(scan.scanTime)}</span>+ </dd></div>- {/each}+ </dl>++ {#if insights?.topPackages.length}+ <div>+ <h4 class="mb-3 text-sm text-muted-foreground">{m.vuln_top_packages()}</h4>+ <ul class="divide-y divide-border/40">+ {#each insights.topPackages as pkg (pkg.pkgName)}+ <li+ class="-mx-3 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-1 rounded-md px-3 py-3 transition-colors hover:bg-muted/40 sm:grid-cols-[minmax(0,1fr)_auto_auto]"+ >+ <span class="flex min-w-0 items-center gap-3">+ <span class="truncate font-mono text-sm">{pkg.pkgName}</span>+ <SeverityBadge severity={pkg.severity} />+ <span class="text-xs whitespace-nowrap text-muted-foreground tabular-nums">+ {pkg.count === 1 ? m.vuln_cve_count_one() : m.vuln_cve_count({ count: pkg.count })}+ </span>+ </span>+ <span class="col-span-2 flex items-center gap-1.5 text-muted-foreground sm:col-span-1 sm:justify-self-end">+ <MonoCell value={pkg.installedVersion} />+ <span aria-hidden="true">→</span>+ <span class={pkg.fixedVersion ? 'text-foreground' : ''}><FixedCell fixedVersion={pkg.fixedVersion} /></span>+ </span>+ </li>+ {/each}+ </ul>+ </div>+ {/if}</div>- </div>+ </section>{/if}{#if resolvedSummary && resolvedSummary.total > 0}- <div class="mt-6 space-y-2">- <h4 class="text-sm font-semibold text-muted-foreground">{m.vuln_details()}</h4>+ <div class="mt-6 space-y-3">+ <h4 class="text-sm font-medium">{m.vuln_details()}</h4><div class="rounded-xl border border-border/60"><ArcaneTableitems={vulnerabilityItems}diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex 98d572824..77ea88bb1 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -180,7 +180,7 @@ export const queryKeys = {['volume-backups', environmentId, volumeName, backupId, 'has-path', path] as const},vulnerabilities: {- summaryByEnvironment: (environmentId: string) => ['vulnerabilities', 'summary', environmentId] as const,+ overviewByEnvironment: (environmentId: string) => ['vulnerabilities', 'overview', environmentId] as const,scanResult: (environmentId: string, imageId: string) => ['vulnerabilities', 'scan-result', environmentId, imageId] as const,allByEnvironment: (environmentId: string, request: SearchPaginationSortRequest) =>['vulnerabilities', 'all', environmentId, stableSerialize(request)] as const,diff --git a/frontend/src/lib/services/vulnerability-service.ts b/frontend/src/lib/services/vulnerability-service.tsindex 94d4ffce2..8920affa1 100644--- a/frontend/src/lib/services/vulnerability-service.ts+++ b/frontend/src/lib/services/vulnerability-service.ts@@ -8,7 +8,7 @@ import type {ScannerStatus,Vulnerability,VulnerabilityWithImage,- EnvironmentVulnerabilitySummary,+ VulnerabilityRiskOverview,IgnoredVulnerability,IgnoreVulnerabilityPayload,BulkVulnerabilityFilters,@@ -79,15 +79,10 @@ class VulnerabilityService extends BaseAPIService {}/**- * Get aggregated vulnerability summary for the current environment+ * Get the environment risk overview (score, trend, drivers, riskiest images, priority findings)*/- async getEnvironmentSummary(): Promise<EnvironmentVulnerabilitySummary> {- const envId = await this.resolveEnvironmentId();- return this.getEnvironmentSummaryForEnvironment(envId);- }-- async getEnvironmentSummaryForEnvironment(environmentId: string): Promise<EnvironmentVulnerabilitySummary> {- return this.handleResponse(this.api.get(`/environments/${environmentId}/vulnerabilities/summary`));+ async getRiskOverviewForEnvironment(environmentId: string): Promise<VulnerabilityRiskOverview> {+ return this.handleResponse(this.api.get(`/environments/${environmentId}/vulnerabilities/overview`));}/**diff --git a/frontend/src/lib/types/environment.ts b/frontend/src/lib/types/environment.tsindex 6959f549b..3a0652465 100644--- a/frontend/src/lib/types/environment.ts+++ b/frontend/src/lib/types/environment.ts@@ -142,6 +142,113 @@ export interface VulnerabilityWithImage extends Vulnerability {ignoreId?: string;}+export type VulnerabilityRiskBand = 'none' | 'low' | 'medium' | 'high' | 'critical';++export interface VulnerabilityPackageInsight {+ pkgName: string;+ severity: VulnerabilitySeverity;+ count: number;+ installedVersion: string;+ fixedVersion?: string;+}++export interface VulnerabilityScanInsights {+ riskScore: number;+ riskBand: VulnerabilityRiskBand;+ highestCvss: number;+ highestVulnerabilityId?: string;+ fixableCount: number;+ knownExploitedCount: number;+ exposure: VulnerabilityExposure;+ topPackages: VulnerabilityPackageInsight[];+}++export type VulnerabilityExposure = 'running' | 'stopped' | 'unused' | 'unknown';++export interface VulnerabilityRiskTrendPoint {+ date: string;+ riskScore: number;+}++export interface VulnerabilityRiskDrivers {+ knownExploited: number;+ overdueKnownExploited: number;+ highEpss: number;+ exposedCriticalHigh: number;+ fixable: number;+ findings: number;+ imagesScanned: number;+ imagesTotal: number;+}++export interface VulnerabilityRiskExposureBreakdown {+ running: number;+ stopped: number;+ unused: number;+ unknown: number;+}++export interface VulnerabilityRiskScoreDriver {+ vulnerabilityId: string;+ imageName: string;+ exposure: VulnerabilityExposure;+ knownExploited: boolean;+ risk: number;+}++export interface VulnerabilityRiskImage {+ imageId: string;+ imageName: string;+ riskScore: number;+ riskBand: VulnerabilityRiskBand;+ exposure: VulnerabilityExposure;+ runningContainers: number;+ knownExploited: number;+ critical: number;+ high: number;+ fixable: number;+ findings: number;+}++export interface VulnerabilityRiskFinding {+ vulnerabilityId: string;+ pkgName: string;+ title?: string;+ severity: VulnerabilitySeverity;+ cvss: number;+ risk: number;+ epss?: number;+ knownExploited: boolean;+ ransomware: boolean;+ kevDueDate?: string;+ imagesAffected: number;+ runningImagesAffected: number;+ fixedVersion?: string;+}++export interface VulnerabilityThreatIntelStatus {+ enabled: boolean;+ lastSyncedAt?: string;+ stale: boolean;+}++export interface VulnerabilityRiskOverview {+ riskScore: number;+ riskBand: VulnerabilityRiskBand;+ delta7d?: number;+ trend: VulnerabilityRiskTrendPoint[];+ drivers: VulnerabilityRiskDrivers;+ drivers7dAgo?: VulnerabilityRiskDrivers;+ summary: SeveritySummary;+ exposure: VulnerabilityRiskExposureBreakdown;+ scoreDriver?: VulnerabilityRiskScoreDriver;+ riskiestImages: VulnerabilityRiskImage[];+ riskiestFindings: VulnerabilityRiskFinding[];+ prevalentFindings: VulnerabilityRiskFinding[];+ threatIntel: VulnerabilityThreatIntelStatus;+ computedAt: string;+}+export interface SeveritySummary {critical: number;high: number;@@ -151,12 +258,6 @@ export interface SeveritySummary {total: number;}-export interface EnvironmentVulnerabilitySummary {- totalImages: number;- scannedImages: number;- summary?: SeveritySummary;-}-export interface VulnerabilityScanResult {imageId: string;imageName: string;@@ -170,6 +271,7 @@ export interface VulnerabilityScanResult {duration?: number;scannerVersion?: string;hasReport?: boolean;+ insights?: VulnerabilityScanInsights;}export interface VulnerabilityScanSummary {diff --git a/frontend/src/lib/types/settings.ts b/frontend/src/lib/types/settings.tsindex ee83638d0..47ad27daf 100644--- a/frontend/src/lib/types/settings.ts+++ b/frontend/src/lib/types/settings.ts@@ -92,6 +92,7 @@ export type Settings = {trivyServerUrl: string;trivyServerToken: string;trivyIgnoreUnfixed: boolean;+ vulnerabilityThreatIntelEnabled: boolean;trivyConfig: string;trivyIgnore: string;imagePatchSuffix: string;diff --git a/frontend/src/lib/utils/vulnerability.ts b/frontend/src/lib/utils/vulnerability.tsindex 9b0f8e6a9..8794848bd 100644--- a/frontend/src/lib/utils/vulnerability.ts+++ b/frontend/src/lib/utils/vulnerability.ts@@ -3,6 +3,7 @@ import type {BulkVulnerabilityFilters,SeveritySummary,Vulnerability,+ VulnerabilityRiskBand,VulnerabilityScanResult,VulnerabilityScanSummary,VulnerabilityWithImage@@ -25,12 +26,13 @@ const severityDisplay = new Map<label: () => string;badge: VulnerabilitySeverityBadgeVariant;icon: VulnerabilitySeverityIconVariant;+ barClass: string;}>([- ['CRITICAL', { key: 'critical', label: m.vuln_severity_critical, badge: 'red', icon: 'red' }],- ['HIGH', { key: 'high', label: m.vuln_severity_high, badge: 'orange', icon: 'orange' }],- ['MEDIUM', { key: 'medium', label: m.vuln_severity_medium, badge: 'amber', icon: 'amber' }],- ['LOW', { key: 'low', label: m.vuln_severity_low, badge: 'green', icon: 'emerald' }]+ ['CRITICAL', { key: 'critical', label: m.vuln_severity_critical, badge: 'red', icon: 'red', barClass: 'bg-destructive' }],+ ['HIGH', { key: 'high', label: m.vuln_severity_high, badge: 'orange', icon: 'orange', barClass: 'bg-orange' }],+ ['MEDIUM', { key: 'medium', label: m.vuln_severity_medium, badge: 'amber', icon: 'amber', barClass: 'bg-warning' }],+ ['LOW', { key: 'low', label: m.vuln_severity_low, badge: 'green', icon: 'emerald', barClass: 'bg-lime' }]]);export function buildSeveritySummary(vulnerabilities: VulnerabilitySeveritySource[]): SeveritySummary {@@ -51,6 +53,42 @@ export function getSeverityIconVariant(severity: string): VulnerabilitySeverityIreturn severityDisplay.get(severity)?.icon ?? 'gray';}+export function getSeverityBarClass(severity: string): string {+ return severityDisplay.get(severity)?.barClass ?? 'bg-muted-foreground';+}++export type ShareBarSegment = { key: string; label: string; count: number; barClass: string };++// getSeveritySegments orders a severity summary from critical to unknown for share bars and legends.+export function getSeveritySegments(summary: SeveritySummary | null | undefined): ShareBarSegment[] {+ if (!summary) return [];+ return (['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'UNKNOWN'] as const)+ .map((severity) => ({+ key: severity,+ label: getSeverityLabel(severity),+ count: summary[severity.toLowerCase() as Lowercase<typeof severity>],+ barClass: getSeverityBarClass(severity)+ }))+ .filter((segment) => segment.count > 0);+}++const riskBandDisplay: Record<VulnerabilityRiskBand, { label: () => string; strokeClass: string; barClass: string }> = {+ critical: { label: m.vuln_risk_band_critical, strokeClass: 'text-destructive', barClass: 'bg-destructive' },+ high: { label: m.vuln_risk_band_high, strokeClass: 'text-orange', barClass: 'bg-orange' },+ medium: { label: m.vuln_risk_band_medium, strokeClass: 'text-warning', barClass: 'bg-warning' },+ low: { label: m.vuln_risk_band_low, strokeClass: 'text-lime', barClass: 'bg-lime' },+ none: { label: m.vuln_clean, strokeClass: 'text-success', barClass: 'bg-success' }+};++export function getRiskBandDisplay(band: VulnerabilityRiskBand) {+ const display = riskBandDisplay[band];+ return { label: display.label(), strokeClass: display.strokeClass, barClass: display.barClass };+}++export function getCvssScore(vulnerability: Pick<Vulnerability, 'cvss'>): number | undefined {+ return vulnerability.cvss?.v3Score ?? vulnerability.cvss?.v2Score;+}+export function withVulnerabilityToggles(options: SearchPaginationSortRequest,toggles: { showIgnored: boolean; fixAvailable: boolean }diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelteindex 437557958..0324cb9ca 100644--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte@@ -337,6 +337,7 @@trivyServerUrl: settings?.trivyServerUrl || '',trivyServerToken: settings?.trivyServerToken || '',trivyIgnoreUnfixed: settings?.trivyIgnoreUnfixed ?? true,+ vulnerabilityThreatIntelEnabled: settings?.vulnerabilityThreatIntelEnabled ?? true,trivyConfig: settings?.trivyConfig || '',trivyIgnore: settings?.trivyIgnore || '',imagePatchSuffix: settings?.imagePatchSuffix || 'patched',@@ -434,6 +435,7 @@trivyServerUrl: formData.trivyServerUrl,trivyServerToken: formData.trivyServerToken,trivyIgnoreUnfixed: formData.trivyIgnoreUnfixed,+ vulnerabilityThreatIntelEnabled: formData.vulnerabilityThreatIntelEnabled,trivyConfig: formData.trivyConfig,trivyIgnore: formData.trivyIgnore,imagePatchSuffix: formData.imagePatchSuffix,diff --git a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelteindex b6d39c972..d140620e3 100644--- a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte+++ b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte@@ -149,7 +149,8 @@}function getEnabledOverride(job: JobStatus): boolean | undefined {- if (!vulnerabilityManagementEnabled && (job.id === 'vulnerability-scan' || job.id === 'auto-patch')) return false;+ if (!vulnerabilityManagementEnabled && ['vulnerability-scan', 'vulnerability-risk', 'auto-patch'].includes(job.id))+ return false;switch (job.id) {case 'scheduled-prune':return formInputs.scheduledPruneEnabled.value;diff --git a/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.ts b/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.tsindex 1ef3f832d..0b80ef4a2 100644--- a/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.ts+++ b/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.ts@@ -57,6 +57,7 @@ export const environmentFormSchema = environmentUpdateSchematrivyServerUrl: z.string(),trivyServerToken: z.string(),trivyIgnoreUnfixed: z.boolean(),+ vulnerabilityThreatIntelEnabled: z.boolean(),trivyConfig: z.string(),trivyIgnore: z.string(),imagePatchSuffix: z.string(),diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelteindex 736cce8bd..b944797cc 100644--- a/frontend/src/routes/(app)/security/+page.svelte+++ b/frontend/src/routes/(app)/security/+page.svelte@@ -7,28 +7,34 @@import { m } from '#lib/paraglide/messages.js';import { vulnerabilityService } from '#lib/services/vulnerability-service.js';import { imageService } from '#lib/services/image-service.js';- import { parallelRefresh } from '#lib/utils/api.js';+ import { extractApiErrorMessage, parallelRefresh } from '#lib/utils/api.js';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';- import type { EnvironmentVulnerabilitySummary, VulnerabilityWithImage } from '#lib/types/environment.js';+ import type { VulnerabilityRiskOverview, VulnerabilityWithImage } from '#lib/types/environment.js';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';import { onMount, onDestroy, untrack } from 'svelte';import SecurityVulnerabilityTable from './security-vulnerability-table.svelte';import SecurityPatchTable from './security-patch-table.svelte';+ import SecurityOverview from './security-overview.svelte';import type { ImagePatchTargetDto } from '#lib/types/docker.js';import { toast } from 'svelte-sonner';- import { InspectIcon, ShieldAlertIcon, ShieldCheckIcon } from '#lib/icons/index.js';+ import { ActivityIcon, InspectIcon, ShieldAlertIcon, ShieldCheckIcon } from '#lib/icons/index.js';import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';import * as Tabs from '#lib/components/ui/tabs/index.js';import { environmentStore } from '#lib/stores/environment.store.svelte.js';import { activityStore } from '#lib/stores/activity.store.svelte.js';import { hasPermission } from '#lib/utils/auth.js';- import { mapVulnerabilityPage, mapVulnerabilityRequest, withVulnerabilityToggles } from '#lib/utils/vulnerability.js';+ import {+ getSeveritySegments,+ mapVulnerabilityPage,+ mapVulnerabilityRequest,+ withVulnerabilityToggles+ } from '#lib/utils/vulnerability.js';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';let { data } = $props();let displayedEnvId = $derived(data.envId);- let summary = $derived<EnvironmentVulnerabilitySummary | null>(data.summary);+ let overview = $derived<VulnerabilityRiskOverview | null>(data.overview);type VulnerabilityRow = VulnerabilityWithImage & { id: string };let vulnerabilities = $derived<Paginated<VulnerabilityRow>>(data.vulnerabilities);@@ -47,10 +53,13 @@let isLoading = $state({ refreshing: false, scanningAll: false });let scanProgress = $state({ current: 0, total: 0 });const urlTab = useUrlTab({- validTabs: () => ['vulnerabilities', 'patches'],- defaultTab: () => 'vulnerabilities'+ validTabs: () => ['overview', 'vulnerabilities', 'patches'],+ defaultTab: () => 'overview',+ // Legacy /images/vulnerabilities?tab=ignored links open the vulnerability table.+ aliases: () => ({ ignored: 'vulnerabilities' })});const securityTabItems: TabItem[] = [+ { value: 'overview', label: m.common_overview(), icon: ActivityIcon },{ value: 'vulnerabilities', label: m.vuln_title(), icon: ShieldAlertIcon },{ value: 'patches', label: m.patches(), icon: ShieldCheckIcon }];@@ -84,37 +93,36 @@}}- const summaryCounts = $derived.by(() => ({- critical: summary?.summary?.critical ?? 0,- high: summary?.summary?.high ?? 0,- medium: summary?.summary?.medium ?? 0,- low: summary?.summary?.low ?? 0,- unknown: summary?.summary?.unknown ?? 0,- total: summary?.summary?.total ?? 0- }));-- const imagesScannedLabel = $derived.by(() => {- const total = summary?.totalImages ?? 0;- const scanned = summary?.scannedImages ?? 0;- return `${scanned}/${total}`;- });+ const severityItems = $derived(getSeveritySegments(overview?.summary));- const severityItems = $derived.by(() => {- const items = [- { key: 'critical', value: summaryCounts.critical, label: m.vuln_severity_critical(), dotClass: 'bg-destructive' },- { key: 'high', value: summaryCounts.high, label: m.vuln_severity_high(), dotClass: 'bg-orange' },- { key: 'medium', value: summaryCounts.medium, label: m.vuln_severity_medium(), dotClass: 'bg-warning' },- { key: 'low', value: summaryCounts.low, label: m.vuln_severity_low(), dotClass: 'bg-success' },- { key: 'unknown', value: summaryCounts.unknown, label: m.common_unknown(), dotClass: 'bg-muted-foreground' }- ];- return items.filter((item) => item.value > 0);- });+ async function refreshOverview() {+ const requestedEnvId = currentEnvId;+ const result = await tryCatch(vulnerabilityService.getRiskOverviewForEnvironment(requestedEnvId));+ if (result.error !== null) {+ toast.error(m.common_refresh_failed({ resource: m.security() }), { description: extractApiErrorMessage(result.error) });+ return;+ }+ if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId) overview = result.data;+ }- async function refreshAll() {+ async function showVulnerability(vulnerabilityId: string) {+ showIgnored = false;+ fixAvailable = false;+ requestOptions = {+ ...requestOptions,+ search: vulnerabilityId,+ pagination: { ...(requestOptions.pagination ?? { limit: 20 }), page: 1 }+ };+ urlTab.select('vulnerabilities');+ await refreshAll();+ }++ // reset drops retained data first so a failed reload leaves the page empty rather than stale.+ async function refreshAll(reset = false) {const requestedEnvId = currentEnvId;selectedVulnerabilityIds = [];- if (displayedEnvId !== requestedEnvId) {- summary = null;+ if (reset || displayedEnvId !== requestedEnvId) {+ overview = null;vulnerabilities = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };patchTargets = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };displayedEnvId = requestedEnvId;@@ -124,10 +132,10 @@const requestForApi = mapVulnerabilityRequest(withVulnerabilityToggles(requestOptions, { showIgnored, fixAvailable }));await parallelRefresh({- summary: {- fetch: () => vulnerabilityService.getEnvironmentSummaryForEnvironment(requestedEnvId),+ overview: {+ fetch: () => vulnerabilityService.getRiskOverviewForEnvironment(requestedEnvId),onSuccess: (data) => {- if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId) summary = data;+ if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId) overview = data;},errorMessage: m.common_refresh_failed({ resource: m.security() })},@@ -165,7 +173,7 @@const MAX_IDLE_TICKS = 3;let attempts = 0;let idleTicks = 0;- let lastScanned = summary?.scannedImages ?? 0;+ let lastScanned = overview?.drivers.imagesScanned ?? 0;stopScanPolling();@@ -185,8 +193,8 @@await refreshAll();if (destroyed || !vulnerabilityManagementEnabled) return;- const currentScanned = summary?.scannedImages ?? 0;- const currentTotal = summary?.totalImages ?? targetTotal;+ const currentScanned = overview?.drivers.imagesScanned ?? 0;+ const currentTotal = overview?.drivers.imagesTotal ?? targetTotal;if (currentTotal > 0 && currentScanned >= currentTotal) {stopScanPolling();@@ -213,6 +221,8 @@function handleTabChange(value: string) {urlTab.select(value);+ // Ignores made in the table change the overview.+ if (value === 'overview') void refreshOverview();}onMount(() => {@@ -333,13 +343,11 @@let wasFeatureEnabled = true;$effect(() => {const enabled = vulnerabilityManagementEnabled;+ // Disabled content is hidden by the template; re-enabling reloads it.if (!enabled) {stopScanPolling();- summary = null;- vulnerabilities = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };- patchTargets = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };} else if (!wasFeatureEnabled) {- untrack(() => void refreshAll());+ untrack(() => void refreshAll(true));}wasFeatureEnabled = enabled;});@@ -362,7 +370,7 @@id: 'refresh',action: 'restart',label: m.common_refresh(),- onclick: refreshAll,+ onclick: () => refreshAll(),loading: isLoading.refreshing,disabled: isLoading.refreshing || isLoading.scanningAll});@@ -379,57 +387,49 @@{#if !vulnerabilityManagementEnabled}<FeatureDisabled />{:else}- <div class="space-y-6">- <div class="rounded-lg border border-border/40 bg-muted/20 px-4 py-3">- <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">- <div class="flex items-baseline gap-4 text-xs text-muted-foreground">- <span- >{m.security_images_scanned()}:- <span class="font-medium text-foreground tabular-nums">{imagesScannedLabel}</span></span- >- <span- >{m.security_total_vulnerabilities()}:- <span class="font-medium text-foreground tabular-nums">{summaryCounts.total}</span></span- >+ <Tabs.Root value={activeTab}>+ <TabBar items={securityTabItems} value={activeTab} onValueChange={handleTabChange} />+ <Tabs.Content value="overview" class="mt-4">+ {#if overview}+ <SecurityOverview {overview} onSelectVulnerability={showVulnerability} />+ {/if}+ </Tabs.Content>+ <Tabs.Content value="vulnerabilities" class="mt-4 space-y-3">+ {#if overview}+ <div class="flex flex-wrap items-center gap-x-5 gap-y-1.5 text-xs text-muted-foreground">+ <span>+ {m.security_images_scanned()}:+ <span class="font-medium text-foreground tabular-nums"+ >{overview.drivers.imagesScanned}/{overview.drivers.imagesTotal}</span+ >+ </span>+ {#each severityItems as item (item.key)}+ <span class="flex items-center gap-1.5">+ <span class="{item.barClass} size-1.5 shrink-0 rounded-full" aria-hidden="true"></span>+ <span class="font-semibold text-foreground tabular-nums">{item.count}</span>+ {item.label}+ </span>+ {/each}</div>- {#if severityItems.length > 0}- <div class="flex flex-wrap items-center gap-x-4 gap-y-1.5">- {#each severityItems as item (item.key)}- <div class="flex items-center gap-1.5">- <span class="{item.dotClass} h-1.5 w-1.5 shrink-0 rounded-full" aria-hidden="true"></span>- <span class="text-xs text-muted-foreground">- <span class="font-semibold text-foreground tabular-nums">{item.value}</span>- <span class="ml-0.5">{item.label}</span>- </span>- </div>- {/each}- </div>- {/if}+ {/if}+ <div class="rounded-xl border border-border/60">+ <SecurityVulnerabilityTable+ bind:vulnerabilities+ bind:requestOptions+ bind:selectedIds={selectedVulnerabilityIds}+ {showIgnored}+ onToggleIgnored={toggleIgnored}+ {fixAvailable}+ onToggleFixAvailable={toggleFixAvailable}+ /></div>- </div>-- <Tabs.Root value={activeTab}>- <TabBar items={securityTabItems} value={activeTab} onValueChange={handleTabChange} />- <Tabs.Content value="vulnerabilities" class="mt-4">- <div class="rounded-xl border border-border/60">- <SecurityVulnerabilityTable- bind:vulnerabilities- bind:requestOptions- bind:selectedIds={selectedVulnerabilityIds}- {showIgnored}- onToggleIgnored={toggleIgnored}- {fixAvailable}- onToggleFixAvailable={toggleFixAvailable}- />- </div>- </Tabs.Content>- <Tabs.Content value="patches" class="mt-4">- <div class="rounded-xl border border-border/60">- <SecurityPatchTable bind:targets={patchTargets} bind:requestOptions={patchRequestOptions} />- </div>- </Tabs.Content>- </Tabs.Root>- </div>+ </Tabs.Content>+ <Tabs.Content value="patches" class="mt-4">+ <div class="rounded-xl border border-border/60">+ <SecurityPatchTable bind:targets={patchTargets} bind:requestOptions={patchRequestOptions} />+ </div>+ </Tabs.Content>+ </Tabs.Root>{/if}{/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/security/+page.ts b/frontend/src/routes/(app)/security/+page.tsindex 5ad9fc44c..1ddd3e499 100644--- a/frontend/src/routes/(app)/security/+page.ts+++ b/frontend/src/routes/(app)/security/+page.ts@@ -40,7 +40,7 @@ export const load: PageLoad = async ({ parent }) => {return {envId,featureDisabled: true,- summary: null,+ overview: null,vulnerabilities: { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } },vulnerabilityRequestOptions,patchRequestOptions@@ -49,14 +49,14 @@ export const load: PageLoad = async ({ parent }) => {const requestForApi = mapVulnerabilityRequest(vulnerabilityRequestOptions);- let summary;+ let overview;let vulnerabilities;const operationResult = await tryCatch((async () =>Promise.all([queryClient.query({- queryKey: queryKeys.vulnerabilities.summaryByEnvironment(envId),- queryFn: () => vulnerabilityService.getEnvironmentSummaryForEnvironment(envId)+ queryKey: queryKeys.vulnerabilities.overviewByEnvironment(envId),+ queryFn: () => vulnerabilityService.getRiskOverviewForEnvironment(envId)}),queryClient.query({queryKey: queryKeys.vulnerabilities.allByEnvironment(envId, requestForApi),@@ -69,13 +69,13 @@ export const load: PageLoad = async ({ parent }) => {throwPageLoadError(err, 'Failed to load security data');} else {- [summary, vulnerabilities] = operationResult.data;+ [overview, vulnerabilities] = operationResult.data;}return {envId,featureDisabled: false,- summary,+ overview,vulnerabilities: mapVulnerabilityPage(vulnerabilities, vulnerabilityRequestOptions),vulnerabilityRequestOptions,patchRequestOptionsdiff --git a/frontend/src/routes/(app)/security/security-overview.svelte b/frontend/src/routes/(app)/security/security-overview.sveltenew file mode 100644index 000000000..ef7ed3947--- /dev/null+++ b/frontend/src/routes/(app)/security/security-overview.svelte@@ -0,0 +1,366 @@+<script lang="ts">+ import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';+ import { Badge } from '#lib/components/ui/badge/index.js';+ import RiskGauge from '#lib/components/vulnerability/risk-gauge.svelte';+ import RiskTrendChart from '#lib/components/vulnerability/risk-trend-chart.svelte';+ import ShareBar from '#lib/components/vulnerability/share-bar.svelte';+ import { ArrowDownIcon, ArrowUpIcon, InfoIcon, ScanIcon } from '#lib/icons/index.js';+ import { m } from '#lib/paraglide/messages.js';+ import type { VulnerabilityRiskDrivers, VulnerabilityRiskImage, VulnerabilityRiskOverview } from '#lib/types/environment.js';+ import { formatRelativeTime } from '#lib/utils/formatting.js';+ import {+ getRiskBandDisplay,+ getSeverityBarClass,+ getSeverityLabel,+ getSeveritySegments,+ type ShareBarSegment+ } from '#lib/utils/vulnerability.js';++ interface Props {+ overview: VulnerabilityRiskOverview;+ onSelectVulnerability: (vulnerabilityId: string) => void;+ }++ let { overview, onSelectVulnerability }: Props = $props();++ let trendDays = $state('30');+ let findingRank = $state<'risk' | 'prevalence'>('risk');++ const trendPoints = $derived(overview.trend.slice(-Number(trendDays)));+ const topFindings = $derived(findingRank === 'risk' ? overview.riskiestFindings : overview.prevalentFindings);+ const severitySegments = $derived(getSeveritySegments(overview.summary));+ // One hue stepped by exposure: running findings carry full weight, unused the least.+ const exposureSegments = $derived<ShareBarSegment[]>([+ { key: 'running', label: m.security_exposure_running(), count: overview.exposure.running, barClass: 'bg-primary' },+ { key: 'stopped', label: m.security_image_stopped(), count: overview.exposure.stopped, barClass: 'bg-primary/50' },+ { key: 'unused', label: m.security_image_unused(), count: overview.exposure.unused, barClass: 'bg-muted-foreground/40' },+ { key: 'unknown', label: m.common_unknown(), count: overview.exposure.unknown, barClass: 'bg-muted-foreground/20' }+ ]);++ const intelNote = $derived.by(() => {+ const intel = overview.threatIntel;+ if (!intel.enabled) return m.security_threat_intel_disabled();+ if (!intel.lastSyncedAt) return m.security_threat_intel_pending();+ if (intel.stale) return m.security_threat_intel_stale({ time: formatRelativeTime(intel.lastSyncedAt) });+ return m.security_threat_intel_updated({ time: formatRelativeTime(intel.lastSyncedAt) });+ });++ type Driver = {+ key: keyof VulnerabilityRiskDrivers;+ label: string;+ help: string;+ // Worsening drivers show a week-over-week delta; the rest show their denominator.+ trackDelta: boolean;+ context?: string;+ };++ const drivers = $derived<Driver[]>([+ {+ key: 'knownExploited',+ label: m.security_driver_known_exploited(),+ help: m.security_driver_known_exploited_help(),+ trackDelta: true+ },+ { key: 'highEpss', label: m.security_driver_high_epss(), help: m.security_driver_high_epss_help(), trackDelta: true },+ {+ key: 'exposedCriticalHigh',+ label: m.security_driver_exposed(),+ help: m.security_driver_exposed_help(),+ trackDelta: true+ },+ {+ key: 'overdueKnownExploited',+ label: m.security_driver_overdue_kev(),+ help: m.security_driver_overdue_kev_help(),+ trackDelta: true+ },+ {+ key: 'imagesScanned',+ label: m.security_images_scanned(),+ help: m.security_driver_images_scanned_help(),+ trackDelta: false,+ context: m.security_driver_of_images({ count: overview.drivers.imagesTotal })+ }+ ]);++ function driverDelta(key: keyof VulnerabilityRiskDrivers): number | null {+ const previous = overview.drivers7dAgo;+ if (!previous) return null;+ return overview.drivers[key] - previous[key];+ }++ function imageUsageLabel(image: VulnerabilityRiskImage): string {+ switch (image.exposure) {+ case 'running':+ return m.security_running_containers({ count: image.runningContainers });+ case 'stopped':+ return m.security_image_stopped();+ case 'unused':+ return m.security_image_unused();+ default:+ return m.common_unknown();+ }+ }+</script>++{#snippet Delta(value: number | null | undefined)}+ {#if value !== null && value !== undefined && value !== 0}+ <span class="inline-flex items-center gap-0.5 text-xs text-muted-foreground tabular-nums">+ {#if value > 0}+ <ArrowUpIcon class="size-3.5 text-destructive" aria-hidden="true" />+ {:else}+ <ArrowDownIcon class="size-3.5 text-success" aria-hidden="true" />+ {/if}+ {Math.abs(value)}+ </span>+ {/if}+{/snippet}++{#snippet SegmentToggle(+ label: string,+ options: { value: string; label: string }[],+ current: string,+ onSelect: (value: string) => void+)}+ <div class="flex gap-1 text-xs" role="group" aria-label={label}>+ {#each options as option (option.value)}+ <button+ type="button"+ class="rounded-md px-2 py-1 transition-colors {current === option.value+ ? 'bg-muted font-medium text-foreground'+ : 'text-muted-foreground hover:text-foreground'}"+ aria-pressed={current === option.value}+ onclick={() => onSelect(option.value)}+ >+ {option.label}+ </button>+ {/each}+ </div>+{/snippet}++{#snippet HelpTip(title: string, body: string)}+ <ArcaneTooltip.Root>+ <ArcaneTooltip.Trigger>+ <span class="inline-flex cursor-help items-center text-muted-foreground" aria-label={title}>+ <InfoIcon class="size-3.5 shrink-0" />+ </span>+ </ArcaneTooltip.Trigger>+ <ArcaneTooltip.Content class="max-w-64">+ <p class="mb-1 text-sm font-medium">{title}</p>+ <p class="text-xs text-muted-foreground">{body}</p>+ </ArcaneTooltip.Content>+ </ArcaneTooltip.Root>+{/snippet}++{#if overview.drivers.imagesScanned === 0}+ <div class="flex flex-col items-center gap-3 py-16 text-center">+ <ScanIcon class="size-10 text-muted-foreground/50" />+ <p class="text-sm text-muted-foreground">{m.security_overview_empty()}</p>+ </div>+{:else}+ <div class="space-y-12 py-6">+ <section class="grid items-center gap-10 lg:grid-cols-4 lg:gap-12">+ <div+ class="flex flex-col items-center gap-3 lg:col-span-2 lg:justify-center lg:self-stretch lg:border-r lg:border-border/50 lg:pr-12"+ >+ <RiskGauge score={overview.riskScore} band={overview.riskBand} size={460} stroke={22} />+ {#if overview.scoreDriver}+ {@const driver = overview.scoreDriver}+ <button+ type="button"+ class="flex max-w-sm flex-col items-center gap-1.5 rounded-md px-2 py-1 text-center text-sm text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground"+ onclick={() => onSelectVulnerability(driver.vulnerabilityId)}+ >+ <span class="flex flex-wrap items-center justify-center gap-1.5">+ {m.security_score_driver({ cve: driver.vulnerabilityId, image: driver.imageName })}+ {#if driver.knownExploited}+ <Badge variant="red" size="xs">{m.vuln_kev_badge()}</Badge>+ {/if}+ </span>+ {#if driver.exposure === 'unused'}+ <span>{m.vuln_exposure_unused()}</span>+ {:else if driver.exposure === 'stopped'}+ <span>{m.vuln_exposure_stopped()}</span>+ {/if}+ </button>+ {/if}+ </div>+ <div class="min-w-0 space-y-8 lg:col-span-2">+ <div class="flex flex-wrap items-end justify-between gap-3">+ <div class="space-y-1">+ <h3 class="text-sm font-medium">{m.security_risk_trend()}</h3>+ {#if overview.delta7d !== undefined}+ <p class="flex items-center gap-1.5 text-xs text-muted-foreground">+ {#if overview.delta7d === 0}+ {m.security_risk_delta_unchanged()}+ {:else}+ {@render Delta(overview.delta7d)}+ {m.security_risk_delta_7d()}+ {/if}+ </p>+ {/if}+ </div>+ {@render SegmentToggle(+ m.security_risk_trend(),+ [+ { value: '30', label: m.security_risk_range_30d() },+ { value: '90', label: m.security_risk_range_90d() }+ ],+ trendDays,+ (value) => (trendDays = value)+ )}+ </div>+ {#if trendPoints.length > 1}+ <RiskTrendChart points={trendPoints} days={Number(trendDays)} />+ {:else}+ <p class="py-6 text-center text-sm text-muted-foreground">{m.security_risk_trend_empty()}</p>+ {/if}+ <div class="grid gap-8 sm:grid-cols-2">+ <div class="min-w-0">+ <h4 class="mb-3 text-sm text-muted-foreground">{m.security_severity_breakdown()}</h4>+ <ShareBar segments={severitySegments} />+ </div>+ <div class="min-w-0">+ <h4 class="mb-3 flex items-center gap-1.5 text-sm text-muted-foreground">+ {m.security_exposure_breakdown()}+ {@render HelpTip(m.security_exposure_breakdown(), m.security_exposure_breakdown_help())}+ </h4>+ <ShareBar segments={exposureSegments} />+ </div>+ </div>+ <p class="text-xs text-muted-foreground">{intelNote}</p>+ </div>+ </section>++ <dl+ class="grid grid-cols-2 gap-y-6 border-y border-border/50 py-6 sm:grid-cols-3 lg:grid-cols-5 lg:divide-x lg:divide-border/50"+ >+ {#each drivers as driver (driver.key)}+ <div class="flex flex-col items-center px-4 text-center">+ <dt class="flex items-center justify-center gap-1.5 text-sm text-muted-foreground">+ {driver.label}+ {@render HelpTip(driver.label, driver.help)}+ </dt>+ <dd class="mt-2 flex items-baseline justify-center gap-2">+ <span class="text-3xl font-semibold tabular-nums">{overview.drivers[driver.key]}</span>+ {#if driver.trackDelta}+ {@render Delta(driverDelta(driver.key))}+ {:else if driver.context}+ <span class="text-xs text-muted-foreground tabular-nums">{driver.context}</span>+ {/if}+ </dd>+ </div>+ {/each}+ </dl>++ <div class="grid gap-12 lg:grid-cols-2">+ <section class="min-w-0">+ <div class="mb-3 flex flex-wrap items-center justify-between gap-3">+ <h3 class="flex items-center gap-1.5 text-sm font-medium">+ {m.security_top_vulnerabilities()}+ {@render HelpTip(+ m.security_top_vulnerabilities(),+ findingRank === 'risk'+ ? m.security_top_vulnerabilities_risk_help()+ : m.security_top_vulnerabilities_prevalence_help()+ )}+ </h3>+ {@render SegmentToggle(+ m.security_top_vulnerabilities(),+ [+ { value: 'risk', label: m.security_rank_risk() },+ { value: 'prevalence', label: m.security_rank_prevalence() }+ ],+ findingRank,+ (value) => (findingRank = value === 'prevalence' ? 'prevalence' : 'risk')+ )}+ </div>+ {#if topFindings.length === 0}+ <p class="py-6 text-sm text-muted-foreground">{m.vuln_no_vulnerabilities()}</p>+ {:else}+ <ol class="divide-y divide-border/40">+ {#each topFindings as finding, index (finding.vulnerabilityId)}+ <li>+ <button+ type="button"+ class="-mx-2 grid w-[calc(100%+1rem)] grid-cols-[1.25rem_minmax(0,1fr)_auto] items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-muted/40"+ onclick={() => onSelectVulnerability(finding.vulnerabilityId)}+ >+ <span class="text-xs text-muted-foreground tabular-nums">{index + 1}</span>+ <span class="min-w-0 space-y-1">+ <span class="flex flex-wrap items-center gap-2">+ <span+ class="size-2 shrink-0 rounded-full {getSeverityBarClass(finding.severity)}"+ title={getSeverityLabel(finding.severity)}+ ></span>+ <span class="font-mono text-sm">{finding.vulnerabilityId}</span>+ {#if finding.knownExploited}+ <Badge variant="red" size="xs">{m.vuln_kev_badge()}</Badge>+ {/if}+ {#if finding.ransomware}+ <Badge variant="red" size="xs">{m.vuln_ransomware_badge()}</Badge>+ {/if}+ {#if finding.epss !== undefined && finding.epss >= 0.01}+ <Badge variant="gray" size="xs">{m.vuln_epss_value({ value: Math.round(finding.epss * 100) })}</Badge>+ {/if}+ </span>+ <span class="block truncate font-mono text-xs text-muted-foreground">+ {finding.pkgName} → {finding.fixedVersion || m.vuln_no_fix()}+ <span class="font-sans">+ · {finding.imagesAffected === 1+ ? m.security_images_affected_one()+ : m.security_images_affected({ count: finding.imagesAffected })}+ </span>+ </span>+ </span>+ <span class="text-right">+ {#if findingRank === 'risk'}+ <span class="block text-sm font-semibold tabular-nums">{finding.risk.toFixed(1)}</span>+ <span class="block text-3xs text-muted-foreground">{m.vuln_cvss()} {finding.cvss.toFixed(1)}</span>+ {:else}+ <span class="block text-sm font-semibold tabular-nums">{finding.imagesAffected}</span>+ <span class="block text-3xs text-muted-foreground"+ >{m.security_risk_value({ value: finding.risk.toFixed(1) })}</span+ >+ {/if}+ </span>+ </button>+ </li>+ {/each}+ </ol>+ {/if}+ </section>++ <section class="min-w-0">+ <h3 class="mb-3 text-sm font-medium">{m.security_riskiest_images()}</h3>+ <ul class="divide-y divide-border/40">+ {#each overview.riskiestImages as image (image.imageId)}+ {@const band = getRiskBandDisplay(image.riskBand)}+ <li>+ <a+ href="/images/{image.imageId}?tab=vulnerabilities"+ class="-mx-2 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-4 rounded-md px-2 py-3 transition-colors hover:bg-muted/40"+ >+ <span class="min-w-0 space-y-1">+ <span class="block truncate text-sm font-medium">{image.imageName}</span>+ <span class="block truncate text-xs text-muted-foreground tabular-nums">+ {imageUsageLabel(image)} · {m.security_findings_count({+ count: image.findings+ })}{#if image.knownExploited > 0}+ · {m.vuln_known_exploited_count({ count: image.knownExploited })}{/if}+ </span>+ </span>+ <span class="flex items-center gap-3">+ <span class="h-1.5 w-20 overflow-hidden rounded-full bg-muted" title={band.label}>+ <span class="block h-full rounded-full {band.barClass}" style="width: {image.riskScore}%"></span>+ </span>+ <span class="w-8 text-right text-sm font-semibold tabular-nums">{image.riskScore}</span>+ </span>+ </a>+ </li>+ {/each}+ </ul>+ </section>+ </div>+ </div>+{/if}diff --git a/tests/spec/security.spec.ts b/tests/spec/security.spec.tsindex 9b7ce13bc..3f550d1cd 100644--- a/tests/spec/security.spec.ts+++ b/tests/spec/security.spec.ts@@ -7,8 +7,8 @@ const ROUTES = {legacyVulnerabilities: '/images/vulnerabilities'};-async function navigateToSecurity(page: Page) {- await page.goto(ROUTES.page);+async function navigateToSecurity(page: Page, tab = 'vulnerabilities') {+ await page.goto(`${ROUTES.page}?tab=${tab}`);await page.waitForLoadState('load');}@@ -31,19 +31,40 @@ function vulnerabilityResponse(response: { url(): string; request(): { method():: null;}-async function mockSecurityPageData(page: Page, imageNames: string[]) {- await page.route(/\/api\/environments\/[^/]+\/vulnerabilities\/summary$/, async (route) => {+async function mockRiskOverview(page: Page) {+ await page.route(/\/api\/environments\/[^/]+\/vulnerabilities\/overview$/, async (route) => {await route.fulfill({json: {success: true,data: {- totalImages: 1,- scannedImages: 1,- summary: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0, total: 1 }+ riskScore: 75,+ riskBand: 'high',+ trend: [{ date: '2026-09-13', riskScore: 75 }],+ drivers: {+ knownExploited: 0,+ overdueKnownExploited: 0,+ highEpss: 0,+ exposedCriticalHigh: 1,+ fixable: 1,+ findings: 1,+ imagesScanned: 1,+ imagesTotal: 1+ },+ summary: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0, total: 1 },+ exposure: { running: 1, stopped: 0, unused: 0, unknown: 0 },+ riskiestImages: [],+ riskiestFindings: [],+ prevalentFindings: [],+ threatIntel: { enabled: false, stale: false },+ computedAt: '2026-09-13T10:00:00Z'}}});});+}++async function mockSecurityPageData(page: Page, imageNames: string[]) {+ await mockRiskOverview(page);await page.route(/\/api\/environments\/[^/]+\/vulnerabilities\/image-options(?:\?.*)?$/,async (route) => {@@ -89,13 +110,17 @@ test.describe('Security Page', () => {await expect(page.getByRole('heading', { name: 'Security', level: 1 })).toBeVisible();});- test('shows the vulnerabilities and patches tabs', async ({ page }) => {- await navigateToSecurity(page);+ test('opens on the overview tab and shows the vulnerabilities and patches tabs', async ({+ page+ }) => {+ await page.goto(ROUTES.page);+ await page.waitForLoadState('load');- await expect(page.getByRole('tab', { name: 'Vulnerabilities', exact: true })).toHaveAttribute(+ await expect(page.getByRole('tab', { name: 'Overview', exact: true })).toHaveAttribute('data-state','active');+ await expect(page.getByRole('tab', { name: 'Vulnerabilities', exact: true })).toBeVisible();await expect(page.getByRole('tab', { name: 'Patches', exact: true })).toBeVisible();});@@ -181,18 +206,7 @@ test.describe('Security Page', () => {let ignorePayload: unknown;let unignoreRequestCount = 0;- await page.route(/\/api\/environments\/0\/vulnerabilities\/summary$/, async (route) => {- await route.fulfill({- json: {- success: true,- data: {- totalImages: 1,- scannedImages: 1,- summary: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0, total: 1 }- }- }- });- });+ await mockRiskOverview(page);await page.route(/\/api\/environments\/0\/vulnerabilities\/all(?:\?.*)?$/, async (route) => {const showIgnored = new URL(route.request().url()).searchParams.get('ignored') === 'true';const rows =diff --git a/types/meta/job_metadata.go b/types/meta/job_metadata.goindex 21f376b06..fec508f40 100644--- a/types/meta/job_metadata.go+++ b/types/meta/job_metadata.go@@ -175,6 +175,17 @@ var jobMetadataRegistry = map[string]JobMetadata{},},},+ "vulnerability-risk": {+ ID: "vulnerability-risk",+ Name: "Vulnerability Risk",+ Description: "Refreshes CISA KEV and FIRST EPSS threat intelligence and records the daily environment risk snapshot",+ Category: "security",+ SettingsKey: "",+ ManagerOnly: false,+ IsContinuous: false,+ CanRunManually: true,+ Prerequisites: []JobPrerequisiteMetadata{},+ },"auto-patch": {ID: "auto-patch",Name: "Image Auto Patch",diff --git a/types/settings/settings.go b/types/settings/settings.goindex 170c79ac7..e6173fc8d 100644--- a/types/settings/settings.go+++ b/types/settings/settings.go@@ -199,6 +199,11 @@ type Update struct {// Required: falseVulnerabilityScanInterval *string `json:"vulnerabilityScanInterval,omitzero"`+ // VulnerabilityThreatIntelEnabled enables fetching CISA KEV and FIRST EPSS threat intelligence.+ //+ // Required: false+ VulnerabilityThreatIntelEnabled *string `json:"vulnerabilityThreatIntelEnabled,omitzero"`+// MaxImageUploadSize is the maximum size for image uploads.//// Required: falsediff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.goindex de3d69e30..795802a74 100644--- a/types/vulnerability/vulnerability.go+++ b/types/vulnerability/vulnerability.go@@ -243,6 +243,103 @@ type ScanResult struct {//// Required: falseHasReport bool `json:"hasReport,omitempty"`++ // Insights summarizes risk and remediation for completed scans with findings.+ //+ // Required: false+ Insights *ScanInsights `json:"insights,omitempty"`+}++// RiskBand is the qualitative band of a risk score, mirroring the CVSS ranges.+type RiskBand string++const (+ RiskBandNone RiskBand = "none"+ RiskBandLow RiskBand = "low"+ RiskBandMedium RiskBand = "medium"+ RiskBandHigh RiskBand = "high"+ RiskBandCritical RiskBand = "critical"+)++// ScanInsights summarizes the risk and remediation outlook of a scan.+type ScanInsights struct {+ // RiskScore is 0-100: the highest finding risk (x10) plus up to 20 points for finding volume and weight.+ //+ // Required: true+ RiskScore int `json:"riskScore"`++ // RiskBand is the qualitative band of RiskScore.+ //+ // Required: true+ RiskBand RiskBand `json:"riskBand"`++ // HighestCVSS is the highest CVSS score across findings, using a severity fallback when unscored.+ //+ // Required: true+ HighestCVSS float64 `json:"highestCvss"`++ // HighestVulnerabilityID is the ID of the finding with the highest CVSS score.+ //+ // Required: false+ HighestVulnerabilityID string `json:"highestVulnerabilityId,omitempty"`++ // FixableCount is the number of findings with a fixed version available.+ //+ // Required: true+ FixableCount int `json:"fixableCount"`++ // KnownExploitedCount is the number of findings listed in the CISA KEV catalog.+ //+ // Required: true+ KnownExploitedCount int `json:"knownExploitedCount"`++ // Exposure describes whether containers use the image, which scales finding risk.+ //+ // Required: true+ Exposure ImageExposure `json:"exposure"`++ // TopPackages lists the most severe affected packages to update.+ //+ // Required: true+ TopPackages []PackageInsight `json:"topPackages"`+}++// ImageExposure describes how containers use an image.+type ImageExposure string++const (+ ImageExposureRunning ImageExposure = "running"+ ImageExposureStopped ImageExposure = "stopped"+ ImageExposureUnused ImageExposure = "unused"+ ImageExposureUnknown ImageExposure = "unknown"+)++// PackageInsight aggregates the findings of one affected package.+type PackageInsight struct {+ // PkgName is the affected package name.+ //+ // Required: true+ PkgName string `json:"pkgName"`++ // Severity is the worst severity among the package's findings.+ //+ // Required: true+ Severity Severity `json:"severity"`++ // Count is the number of findings in the package.+ //+ // Required: true+ Count int `json:"count"`++ // InstalledVersion is the installed package version.+ //+ // Required: true+ InstalledVersion string `json:"installedVersion"`++ // FixedVersion is the version that fixes the package's findings, if known.+ //+ // Required: false+ FixedVersion string `json:"fixedVersion,omitempty"`}// ScanStatus represents the status of a vulnerability scan@@ -591,3 +688,327 @@ type BulkIgnoreResponse struct {// Required: trueAffectedCount int `json:"affectedCount"`}++// RiskOverview is the environment-wide vulnerability risk picture.+type RiskOverview struct {+ // RiskScore is the 0-100 environment risk score.+ //+ // Required: true+ RiskScore int `json:"riskScore"`++ // RiskBand is the qualitative band of RiskScore.+ //+ // Required: true+ RiskBand RiskBand `json:"riskBand"`++ // Delta7d is the score change since the snapshot from 7 days ago, when one exists.+ //+ // Required: false+ Delta7d *int `json:"delta7d,omitempty"`++ // Trend holds daily scores for up to the last 90 days, oldest first.+ //+ // Required: true+ Trend []RiskTrendPoint `json:"trend"`++ // Drivers are the current risk driver counts.+ //+ // Required: true+ Drivers RiskDrivers `json:"drivers"`++ // Drivers7dAgo are the driver counts from 7 days ago, when a snapshot exists.+ //+ // Required: false+ Drivers7dAgo *RiskDrivers `json:"drivers7dAgo,omitempty"`++ // Summary is the severity summary of non-ignored findings.+ //+ // Required: true+ Summary SeveritySummary `json:"summary"`++ // Exposure counts non-ignored findings by how containers use their image.+ //+ // Required: true+ Exposure RiskExposureBreakdown `json:"exposure"`++ // ScoreDriver is the finding that sets the peak of the risk score, when any exist.+ //+ // Required: false+ ScoreDriver *RiskScoreDriver `json:"scoreDriver,omitempty"`++ // RiskiestImages lists the highest-risk images.+ //+ // Required: true+ RiskiestImages []RiskImage `json:"riskiestImages"`++ // RiskiestFindings lists the CVEs with the highest finding risk.+ //+ // Required: true+ RiskiestFindings []RiskFinding `json:"riskiestFindings"`++ // PrevalentFindings lists the CVEs present in the most images.+ //+ // Required: true+ PrevalentFindings []RiskFinding `json:"prevalentFindings"`++ // ThreatIntel reports the state of the KEV/EPSS threat intelligence.+ //+ // Required: true+ ThreatIntel ThreatIntelStatus `json:"threatIntel"`++ // ComputedAt is when the overview was computed.+ //+ // Required: true+ ComputedAt time.Time `json:"computedAt"`+}++// RiskTrendPoint is one day of the risk trend.+type RiskTrendPoint struct {+ // Date is the snapshot day (YYYY-MM-DD).+ //+ // Required: true+ Date string `json:"date"`++ // RiskScore is the environment risk score on that day.+ //+ // Required: true+ RiskScore int `json:"riskScore"`+}++// RiskDrivers are the counts that explain the environment risk score.+type RiskDrivers struct {+ // KnownExploited is the number of unique CVEs listed in the CISA KEV catalog.+ //+ // Required: true+ KnownExploited int `json:"knownExploited"`++ // OverdueKnownExploited is the number of unique KEV CVEs past their CISA remediation due date.+ //+ // Required: true+ OverdueKnownExploited int `json:"overdueKnownExploited"`++ // HighEPSS is the number of unique CVEs with an EPSS probability of at least 10%.+ //+ // Required: true+ HighEPSS int `json:"highEpss"`++ // ExposedCriticalHigh is the number of unique critical/high CVEs in images used by running containers.+ //+ // Required: true+ ExposedCriticalHigh int `json:"exposedCriticalHigh"`++ // Fixable is the number of findings with a fixed version available.+ //+ // Required: true+ Fixable int `json:"fixable"`++ // Findings is the total number of non-ignored findings.+ //+ // Required: true+ Findings int `json:"findings"`++ // ImagesScanned is the number of current images with a completed scan.+ //+ // Required: true+ ImagesScanned int `json:"imagesScanned"`++ // ImagesTotal is the number of current images.+ //+ // Required: true+ ImagesTotal int `json:"imagesTotal"`+}++// RiskExposureBreakdown counts findings by the exposure of their image.+type RiskExposureBreakdown struct {+ // Running is the number of findings in images used by running containers.+ //+ // Required: true+ Running int `json:"running"`++ // Stopped is the number of findings in images used only by stopped containers.+ //+ // Required: true+ Stopped int `json:"stopped"`++ // Unused is the number of findings in images no container uses.+ //+ // Required: true+ Unused int `json:"unused"`++ // Unknown is the number of findings whose image exposure could not be determined.+ //+ // Required: true+ Unknown int `json:"unknown"`+}++// RiskScoreDriver identifies the finding that sets the peak of the risk score.+type RiskScoreDriver struct {+ // VulnerabilityID is the CVE or advisory ID.+ //+ // Required: true+ VulnerabilityID string `json:"vulnerabilityId"`++ // ImageName is the image holding the riskiest instance of the finding.+ //+ // Required: true+ ImageName string `json:"imageName"`++ // Exposure is how containers use that image.+ //+ // Required: true+ Exposure ImageExposure `json:"exposure"`++ // KnownExploited reports whether the CVE is in the CISA KEV catalog.+ //+ // Required: true+ KnownExploited bool `json:"knownExploited"`++ // Risk is the 0-10 finding risk.+ //+ // Required: true+ Risk float64 `json:"risk"`+}++// RiskImage is one image ranked by risk.+type RiskImage struct {+ // ImageID is the Docker image ID.+ //+ // Required: true+ ImageID string `json:"imageId"`++ // ImageName is the image name with tag.+ //+ // Required: true+ ImageName string `json:"imageName"`++ // RiskScore is the image's 0-100 risk score.+ //+ // Required: true+ RiskScore int `json:"riskScore"`++ // RiskBand is the qualitative band of RiskScore.+ //+ // Required: true+ RiskBand RiskBand `json:"riskBand"`++ // Exposure describes whether containers use the image.+ //+ // Required: true+ Exposure ImageExposure `json:"exposure"`++ // RunningContainers is the number of running containers using the image.+ //+ // Required: true+ RunningContainers int `json:"runningContainers"`++ // KnownExploited is the number of findings listed in the CISA KEV catalog.+ //+ // Required: true+ KnownExploited int `json:"knownExploited"`++ // Critical is the number of critical findings.+ //+ // Required: true+ Critical int `json:"critical"`++ // High is the number of high findings.+ //+ // Required: true+ High int `json:"high"`++ // Fixable is the number of findings with a fixed version available.+ //+ // Required: true+ Fixable int `json:"fixable"`++ // Findings is the total number of non-ignored findings.+ //+ // Required: true+ Findings int `json:"findings"`+}++// RiskFinding is one CVE aggregated across the environment's images.+type RiskFinding struct {+ // VulnerabilityID is the CVE or advisory ID.+ //+ // Required: true+ VulnerabilityID string `json:"vulnerabilityId"`++ // PkgName is the affected package.+ //+ // Required: true+ PkgName string `json:"pkgName"`++ // Title is the vulnerability title.+ //+ // Required: false+ Title string `json:"title,omitempty"`++ // Severity is the vulnerability severity.+ //+ // Required: true+ Severity Severity `json:"severity"`++ // CVSS is the CVSS score, or a severity fallback when unscored.+ //+ // Required: true+ CVSS float64 `json:"cvss"`++ // Risk is the 0-10 finding risk after threat and exposure adjustments.+ //+ // Required: true+ Risk float64 `json:"risk"`++ // EPSS is the FIRST EPSS exploit probability (0-1), when known.+ //+ // Required: false+ EPSS *float64 `json:"epss,omitempty"`++ // KnownExploited reports whether the CVE is in the CISA KEV catalog.+ //+ // Required: true+ KnownExploited bool `json:"knownExploited"`++ // Ransomware reports whether CISA lists known ransomware campaign use.+ //+ // Required: true+ Ransomware bool `json:"ransomware"`++ // KEVDueDate is the CISA remediation due date, when listed.+ //+ // Required: false+ KEVDueDate string `json:"kevDueDate,omitempty"`++ // ImagesAffected is the number of images with this CVE.+ //+ // Required: true+ ImagesAffected int `json:"imagesAffected"`++ // RunningImagesAffected is the number of affected images used by running containers.+ //+ // Required: true+ RunningImagesAffected int `json:"runningImagesAffected"`++ // FixedVersion is the version that fixes the CVE, when known.+ //+ // Required: false+ FixedVersion string `json:"fixedVersion,omitempty"`+}++// ThreatIntelStatus reports the state of the KEV/EPSS threat intelligence.+type ThreatIntelStatus struct {+ // Enabled reports whether threat intelligence is used.+ //+ // Required: true+ Enabled bool `json:"enabled"`++ // LastSyncedAt is when the feeds were last synced successfully.+ //+ // Required: false+ LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"`++ // Stale reports whether the last successful sync is older than 72 hours.+ //+ // Required: true+ Stale bool `json:"stale"`+}