Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: improve risk score model (#4205)
Kyle Mendell0238e1414138
diff --git a/backend/internal/imageupdate/service_test.go b/backend/internal/imageupdate/service_test.goindex e014971db..b9e11c8d3 100644--- a/backend/internal/imageupdate/service_test.go+++ b/backend/internal/imageupdate/service_test.go@@ -594,6 +594,23 @@ func TestImageUpdateService_InspectLocalImageSnapshot_NoRepoDigestsRemainsLocal(assert.Equal(t, "sha256:local-only-image", snapshot.PrimaryDigest)}+// registryPingInternal answers the /v2/ version check every registry client sends before its first request.+func registryPingInternal(w http.ResponseWriter, r *http.Request) bool {+ if r.URL.Path != "/v2/" {+ return false+ }+ w.WriteHeader(http.StatusOK)+ return true+}++// writeManifestHeadInternal answers a manifest HEAD with the headers a client needs to trust the digest without a body.+func writeManifestHeadInternal(w http.ResponseWriter, digest string) {+ w.Header().Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")+ w.Header().Set("Content-Length", "0")+ w.Header().Set("Docker-Content-Digest", digest)+ w.WriteHeader(http.StatusOK)+}+func newImageUpdateFallbackServer(t *testing.T, repositoryTag, localDigest, remoteDigest string) *httptest.Server {t.Helper()@@ -630,8 +647,9 @@ func newImageUpdateFallbackServer(t *testing.T, repositoryTag, localDigest, remo}returncase r.URL.Path == manifestPath:- w.Header().Set("Docker-Content-Digest", remoteDigest)- w.WriteHeader(http.StatusOK)+ writeManifestHeadInternal(w, remoteDigest)+ return+ case registryPingInternal(w, r):returndefault:http.NotFound(w, r)@@ -662,8 +680,9 @@ func newImageUpdateRegistryOnlyServer(t *testing.T, repositoryTag, remoteDigesthttp.Error(w, "not found", http.StatusNotFound)returncase r.URL.Path == manifestPath:- w.Header().Set("Docker-Content-Digest", remoteDigest)- w.WriteHeader(http.StatusOK)+ writeManifestHeadInternal(w, remoteDigest)+ return+ case registryPingInternal(w, r):returndefault:http.NotFound(w, r)@@ -2475,6 +2494,9 @@ func TestContainerTagChecksPersistIndependentPoliciesInternal(t *testing.T) {db := setupImageUpdateRegistryTestDBInternal(t)var tagListings atomic.Int64registryServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if registryPingInternal(w, r) {+ return+ }if !strings.HasSuffix(r.URL.Path, "/tags/list") {http.NotFound(w, r)return@@ -2575,6 +2597,9 @@ func TestContainerTagChecksPersistIndependentPoliciesInternal(t *testing.T) {func TestContainerTagChecksSeparateMonitoringFromInstallationInternal(t *testing.T) {db := setupImageUpdateRegistryTestDBInternal(t)registryServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if registryPingInternal(w, r) {+ return+ }if !strings.HasSuffix(r.URL.Path, "/tags/list") {http.NotFound(w, r)return@@ -2676,6 +2701,9 @@ func TestContainerTagChecksUseRegistryTagTimeoutInternal(t *testing.T) {t.Setenv("REGISTRY_TAG_TIMEOUT", tt.tagTimeout)settingsService := newImageUpdateTestSettingsServiceInternal(t, "1", "30")registryServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if registryPingInternal(w, r) {+ return+ }if !strings.HasSuffix(r.URL.Path, "/tags/list") {http.NotFound(w, r)return@@ -2731,6 +2759,7 @@ func TestContainerTagChecksPersistResultsFinishedBeforeScanDeadlineInternal(t *tsettingsService := newImageUpdateTestSettingsServiceInternal(t, "30", "30")registryServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch {+ case registryPingInternal(w, r):case strings.HasSuffix(r.URL.Path, "/team/fast/tags/list"):w.Header().Set("Content-Type", "application/json")require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/fast", "tags": []string{"1.0.0", "1.1.0"}}))diff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.goindex 986390cde..067d01f01 100644--- a/backend/internal/project/service_test.go+++ b/backend/internal/project/service_test.go@@ -7611,6 +7611,10 @@ type serviceTagTransportInternal struct {}func (s *serviceTagTransportInternal) RoundTrip(request *http.Request) (*http.Response, error) {+ // The /v2/ version check precedes every listing and is not a tag call.+ if request.URL.Path == "/v2/" {+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: http.NoBody, Request: request}, nil+ }s.calls++payload, err := json.Marshal(map[string]any{"name": "library/app", "tags": s.tags})if err != nil {diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.goindex 3d8b9a230..8d3a309e2 100644--- a/backend/internal/registry/service.go+++ b/backend/internal/registry/service.go@@ -29,6 +29,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation""github.com/getarcaneapp/arcane/types/v2/containerregistry"+ "github.com/google/go-containerregistry/pkg/v1/remote/transport"dockerregistry "github.com/moby/moby/api/types/registry""github.com/moby/moby/client""go.getarcane.app/sys/crypto"@@ -1343,6 +1344,10 @@ func isUnauthorizedRegistryErrorInternal(err error) bool {if cerrdefs.IsUnauthorized(err) || cerrdefs.IsPermissionDenied(err) {return true}+ var registryErr *transport.Error+ if errors.As(err, ®istryErr) {+ return registryErr.StatusCode == http.StatusUnauthorized || registryErr.StatusCode == http.StatusForbidden+ }// Fallback: some Docker daemon versions return plain-text errors without// a typed wrapper. These known substrings cover Docker Hub, GHCR, anddiff --git a/backend/internal/registry/service_test.go b/backend/internal/registry/service_test.goindex ecf1d0a69..9f110a13f 100644--- a/backend/internal/registry/service_test.go+++ b/backend/internal/registry/service_test.go@@ -4,7 +4,6 @@ import ("context""encoding/base64""encoding/json"- "io""net/http""net/http/httptest""net/url"@@ -94,10 +93,39 @@ func (f *fakeRegistryDaemonClient) DistributionInspect(ctx context.Context, imagreturn f.distributionInspectFn(ctx, imageRef, options)}+const dockerHubChallengeInternal = `Bearer realm="https://auth.docker.io/token",service="registry.docker.io"`++// registryPingInternal answers the /v2/ version check every registry client sends first: a bearer challenge when set, else OK.+func registryPingInternal(w http.ResponseWriter, r *http.Request, challenge string) bool {+ if r.URL.Path != "/v2/" {+ return false+ }+ if challenge != "" {+ w.Header().Set("WWW-Authenticate", challenge)+ w.WriteHeader(http.StatusUnauthorized)+ return true+ }+ w.WriteHeader(http.StatusOK)+ return true+}++// writeManifestHeadInternal answers a manifest HEAD with the headers a client needs to trust the digest without a body.+func writeManifestHeadInternal(w http.ResponseWriter, digest string) {+ w.Header().Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")+ w.Header().Set("Content-Length", "0")+ w.Header().Set("Docker-Content-Digest", digest)+ w.WriteHeader(http.StatusOK)+}+func newDockerHubRateLimitTestClient(t *testing.T, handler http.HandlerFunc) *http.Client {t.Helper()- server := httptest.NewTLSServer(handler)+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if registryPingInternal(w, r, dockerHubChallengeInternal) {+ return+ }+ handler(w, r)+ }))t.Cleanup(server.Close)targetURL, err := url.Parse(server.URL)@@ -237,7 +265,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_AnonymousDockerHubLimit(t_, _ = w.Write([]byte(`{"token":"anonymous-token"}`))case r.Method == http.MethodHead && r.URL.Path == "/v2/ratelimitpreview/test/manifests/latest":if r.Header.Get("Authorization") != "Bearer anonymous-token" {- w.Header().Set("WWW-Authenticate", `Bearer realm="https://auth.docker.io/token",service="registry.docker.io"`)+ w.Header().Set("WWW-Authenticate", dockerHubChallengeInternal)w.WriteHeader(http.StatusUnauthorized)return}@@ -289,7 +317,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_UsesDockerHubCredential(t_, _ = w.Write([]byte(`{"token":"credential-token"}`))case r.Method == http.MethodHead && r.URL.Path == "/v2/ratelimitpreview/test/manifests/latest":if r.Header.Get("Authorization") != "Bearer credential-token" {- w.Header().Set("WWW-Authenticate", `Bearer realm="https://auth.docker.io/token",service="registry.docker.io"`)+ w.Header().Set("WWW-Authenticate", dockerHubChallengeInternal)w.WriteHeader(http.StatusUnauthorized)return}@@ -328,7 +356,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_CredentialErrorIsNonFatalcase r.URL.Path == "/token":w.WriteHeader(http.StatusUnauthorized)case r.Method == http.MethodHead && r.URL.Path == "/v2/ratelimitpreview/test/manifests/latest":- w.Header().Set("WWW-Authenticate", `Bearer realm="https://auth.docker.io/token",service="registry.docker.io"`)+ w.Header().Set("WWW-Authenticate", dockerHubChallengeInternal)w.WriteHeader(http.StatusUnauthorized)default:if !assert.Failf(t, "unexpected failure", "unexpected request %s %s", r.Method, r.URL.Path) {@@ -344,7 +372,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_CredentialErrorIsNonFatalregistry := result.Registries[0]assert.Equal(t, "credential", registry.AuthMethod)assert.Equal(t, "docker-user", registry.AuthUsername)- assert.Contains(t, registry.Error, "token request failed with status: 401")+ assert.Contains(t, registry.Error, "401 Unauthorized")}func TestContainerRegistryService_RecordImagePull_IncrementsObservedRegistryCount(t *testing.T) {@@ -981,6 +1009,10 @@ func TestContainerRegistryService_InspectImageDigest_FallbackUsesStoredCredentia}, nil)svc.distributionHTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ // The version check never carries credentials; only manifest requests count.+ if req.URL.Path == "/v2/" {+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: http.NoBody}, nil+ }authorization := req.Header.Get("Authorization")if authorization == "" {anonymousCalls++@@ -989,8 +1021,11 @@ func TestContainerRegistryService_InspectImageDigest_FallbackUsesStoredCredentiaassert.Equal(t, "Basic "+base64.StdEncoding.EncodeToString([]byte("ghcr-user:ghcr-token")), authorization)return &http.Response{StatusCode: http.StatusOK,- Header: http.Header{"Docker-Content-Digest": []string{wantDigest}},- Body: io.NopCloser(strings.NewReader("")),+ Header: http.Header{+ "Docker-Content-Digest": []string{wantDigest},+ "Content-Type": []string{"application/vnd.docker.distribution.manifest.v2+json"},+ },+ Body: http.NoBody,}, nil}),}@@ -1008,9 +1043,11 @@ func TestContainerRegistryService_InspectImageDigest_FallsBackWhenDistributionNowantDigest := digest.FromString("fallback-not-found").String()server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if registryPingInternal(w, r, "") {+ return+ }if r.URL.Path == "/v2/team/app/manifests/1.2.3" {- w.Header().Set("Docker-Content-Digest", wantDigest)- w.WriteHeader(http.StatusOK)+ writeManifestHeadInternal(w, wantDigest)return}http.NotFound(w, r)@@ -1045,9 +1082,11 @@ func TestContainerRegistryService_InspectImageDigest_FallsBackWhenDistributionFowantDigest := digest.FromString("fallback-forbidden").String()server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if registryPingInternal(w, r, "") {+ return+ }if r.URL.Path == "/v2/team/app/manifests/1.2.3" {- w.Header().Set("Docker-Content-Digest", wantDigest)- w.WriteHeader(http.StatusOK)+ writeManifestHeadInternal(w, wantDigest)return}http.NotFound(w, r)@@ -1085,25 +1124,21 @@ func TestContainerRegistryService_InspectImageDigest_RetriesStoredCredentialsAftvar authHeaders []stringvar tokenURL stringhandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ challenge := `Bearer realm="` + tokenURL + `",service="registry.example.com"`+ if registryPingInternal(w, r, challenge) {+ return+ }switch r.URL.Path {case "/v2/team/app/manifests/1.2.3":authHeaders = append(authHeaders, r.Header.Get("Authorization"))- switch len(authHeaders) {- case 1:- w.Header().Set("WWW-Authenticate", `Bearer realm="`+tokenURL+`",service="registry.example.com"`)- w.WriteHeader(http.StatusUnauthorized)- case 2:+ switch r.Header.Get("Authorization") {+ case "Bearer credential-token":w.WriteHeader(http.StatusForbidden)- case 3:- w.Header().Set("WWW-Authenticate", `Bearer realm="`+tokenURL+`",service="registry.example.com"`)- w.WriteHeader(http.StatusUnauthorized)- case 4:- w.Header().Set("Docker-Content-Digest", wantDigest)- w.WriteHeader(http.StatusOK)+ case "Bearer anonymous-token":+ writeManifestHeadInternal(w, wantDigest)default:- if !assert.Failf(t, "unexpected failure", "unexpected manifest call %d", len(authHeaders)) {- return- }+ w.Header().Set("WWW-Authenticate", challenge)+ w.WriteHeader(http.StatusUnauthorized)}case "/token":username, password, ok := r.BasicAuth()@@ -1154,11 +1189,7 @@ func TestContainerRegistryService_InspectImageDigest_RetriesStoredCredentialsAftrequire.NoError(t, err)assert.Equal(t, wantDigest, result.Digest)// Stored credentials go first; only after rejection does the lookup retry anonymously.- require.Len(t, authHeaders, 4)- assert.Equal(t, "Basic c3RvcmVkLXVzZXI6c3RvcmVkLXRva2Vu", authHeaders[0])- assert.Equal(t, "Bearer credential-token", authHeaders[1])- assert.Empty(t, authHeaders[2])- assert.Equal(t, "Bearer anonymous-token", authHeaders[3])+ assert.Equal(t, []string{"Bearer credential-token", "Bearer anonymous-token"}, authHeaders)assert.Equal(t, "anonymous", result.AuthMethod)assert.False(t, result.UsedCredential)}@@ -1215,9 +1246,13 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthorivar tokenURL stringserver := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ challenge := `Bearer realm="` + tokenURL + `",service="registry.example.com"`+ if registryPingInternal(w, r, challenge) {+ return+ }switch r.URL.Path {case "/v2/team/app/manifests/1.2.3":- w.Header().Set("WWW-Authenticate", `Bearer realm="`+tokenURL+`",service="registry.example.com"`)+ w.Header().Set("WWW-Authenticate", challenge)w.WriteHeader(http.StatusUnauthorized)case "/token":if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{@@ -1249,7 +1284,7 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthorirequire.NotNil(t, result)assert.Equal(t, "anonymous", result.AuthMethod)assert.Contains(t, err.Error(), "anonymous access unauthorized")- assert.Contains(t, err.Error(), "status: 401")+ assert.Contains(t, err.Error(), "401 Unauthorized")assert.Contains(t, err.Error(), "failed to load enabled registries")}diff --git a/backend/internal/registry/tags_test.go b/backend/internal/registry/tags_test.goindex 24eace92b..a768d253c 100644--- a/backend/internal/registry/tags_test.go+++ b/backend/internal/registry/tags_test.go@@ -2,6 +2,7 @@ package registryimport ("context"+ "encoding/base64""io""net/http""strings"@@ -30,8 +31,11 @@ func TestListImageTagsCredentialsInternal(t *testing.T) {createTestPullRegistryInternal(t, db, "https://index.docker.io/v1/", "stored-user", "stored-token")calls := 0client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {- calls++assert.Equal(t, "registry-1.docker.io", req.URL.Host)+ if req.URL.Path == "/v2/" {+ return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Header: http.Header{}}, nil+ }+ calls++assert.Equal(t, "/v2/library/nginx/tags/list", req.URL.Path)user, password, _ := req.BasicAuth()assert.Equal(t, tt.wantUser, user)@@ -48,15 +52,24 @@ func TestListImageTagsCredentialsInternal(t *testing.T) {}func TestListImageTagsDoesNotFallBackOnRateLimitInternal(t *testing.T) {- calls := 0+ // The registry client retries 429s itself, so count credentialed and anonymous listings rather than requests.+ credentialed, anonymous := 0, 0svc := NewContainerRegistryService(nil, nil, nil, &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {- calls++- return &http.Response{StatusCode: http.StatusTooManyRequests, Body: io.NopCloser(strings.NewReader("")), Header: http.Header{}}, nil+ if req.URL.Path == "/v2/" {+ return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Header: http.Header{}}, nil+ }+ if req.Header.Get("Authorization") == "" {+ anonymous+++ } else {+ credentialed+++ }+ return &http.Response{StatusCode: http.StatusTooManyRequests, Body: http.NoBody, Header: http.Header{}}, nil})})tags, err := svc.ListImageTags(t.Context(), "registry.test/team/app:1.0.0", []containerregistry.Credential{{URL: "registry.test", Username: "user", Token: "token", Enabled: true}})require.Error(t, err)assert.Nil(t, tags)- assert.Equal(t, 1, calls)+ assert.Positive(t, credentialed)+ assert.Zero(t, anonymous, "a rate-limited credential must not spend the anonymous quota")}func TestListImageTagsCancellationInternal(t *testing.T) {@@ -68,25 +81,34 @@ func TestListImageTagsCancellationInternal(t *testing.T) {}func TestListImageTagsRejectedCredentialFallbackInternal(t *testing.T) {+ basic := "Basic " + base64.StdEncoding.EncodeToString([]byte("user:token"))for _, tt := range []struct {- name string- host string- wantError bool- wantCalls int+ name string+ host string+ wantError bool+ wantTokenAuth []string}{- {name: "private registry public image", host: "registry.test", wantCalls: 3},- {name: "docker hub preserves quota", host: "docker.io", wantError: true, wantCalls: 2},+ {name: "private registry public image", host: "registry.test", wantTokenAuth: []string{basic, ""}},+ {name: "docker hub preserves quota", host: "docker.io", wantError: true, wantTokenAuth: []string{basic}},} {t.Run(tt.name, func(t *testing.T) {- calls := 0+ // The registry challenges at /v2/ and its token endpoint rejects the stored credential but serves anonymous tokens.+ var tokenAuth []stringsvc := NewContainerRegistryService(nil, nil, nil, &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {- calls++- response := &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"tags":["1.0.1"]}`)), Header: http.Header{}}- if req.URL.Path == "/token" {- response.StatusCode = http.StatusUnauthorized- } else if req.Header.Get("Authorization") != "" {+ response := &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Header: http.Header{}}+ switch req.URL.Path {+ case "/v2/":response.StatusCode = http.StatusUnauthorizedresponse.Header.Set("WWW-Authenticate", `Bearer realm="https://auth.test/token"`)+ case "/token":+ tokenAuth = append(tokenAuth, req.Header.Get("Authorization"))+ if req.Header.Get("Authorization") != "" {+ response.StatusCode = http.StatusUnauthorized+ } else {+ response.Body = io.NopCloser(strings.NewReader(`{"token":"anonymous-token"}`))+ }+ default:+ response.Body = io.NopCloser(strings.NewReader(`{"tags":["1.0.1"]}`))}return response, nil})})@@ -98,7 +120,7 @@ func TestListImageTagsRejectedCredentialFallbackInternal(t *testing.T) {require.NoError(t, err)assert.Equal(t, []string{"1.0.1"}, tags)}- assert.Equal(t, tt.wantCalls, calls)+ assert.Equal(t, tt.wantTokenAuth, tokenAuth)})}}diff --git a/backend/internal/vulnerability/model.go b/backend/internal/vulnerability/model.goindex dfb4caf7a..4bb20b307 100644--- a/backend/internal/vulnerability/model.go+++ b/backend/internal/vulnerability/model.go@@ -108,9 +108,10 @@ func (VulnerabilityThreatIntel) TableName() string {return "vulnerability_threat_intel"}-// VulnerabilityRiskSnapshot stores one day of environment risk for the trend.+// VulnerabilityRiskSnapshot stores one day of environment patch priority for the trend.type VulnerabilityRiskSnapshot struct {SnapshotDate string `gorm:"column:snapshot_date;primaryKey"`+ ScoringVersion int `gorm:"column:scoring_version"`RiskScore int `gorm:"column:risk_score"`RiskBand string `gorm:"column:risk_band"`CriticalCount int `gorm:"column:critical_count"`@@ -126,6 +127,7 @@ type VulnerabilityRiskSnapshot struct {FixableCount int `gorm:"column:fixable_count"`ImagesScanned int `gorm:"column:images_scanned"`ImagesTotal int `gorm:"column:images_total"`+ ScoredImages int `gorm:"column:scored_images"`CreatedAt time.Time `gorm:"column:created_at;autoCreateTime"`UpdatedAt *time.Time `gorm:"column:updated_at"`}diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.goindex 23ade1335..3ffc08846 100644--- a/backend/internal/vulnerability/service_test.go+++ b/backend/internal/vulnerability/service_test.go@@ -716,14 +716,15 @@ func TestBuildScanInsightsInternal(t *testing.T) {{VulnerabilityID: "CVE-MED", PkgName: "curl", InstalledVersion: "8.0.0", Severity: vulnerability.SeverityMedium},}- insights := buildScanInsightsInternal(vulns, nil, vulnerability.ImageExposureUnknown)+ insights := buildScanInsightsInternal(vulns, nil, vulnerability.ImageExposureUnknown, false)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)+ // Only the two fixable findings enter the average: (37.5 + 39) / 2 with no threat data and unknown usage.+ require.Equal(t, 38, insights.RiskScore)+ require.Equal(t, vulnerability.RiskBandLow, insights.RiskBand)+ require.Equal(t, vulnerability.ScoreStatusProvisional, insights.ScoreStatus)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])@@ -731,66 +732,142 @@ func TestBuildScanInsightsInternal(t *testing.T) {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},- })+func TestBuildScanInsightsInternal_VolumeDoesNotInflateScore(t *testing.T) {+ kev := func(n int) ([]vulnerability.Vulnerability, map[string]VulnerabilityThreatIntel) {+ vulns := make([]vulnerability.Vulnerability, 0, n)+ intel := map[string]VulnerabilityThreatIntel{}+ for i := range n {+ id := fmt.Sprintf("CVE-%d", i)+ vulns = append(vulns, vulnerability.Vulnerability{VulnerabilityID: id, PkgName: fmt.Sprintf("pkg-%d", i), FixedVersion: "1.0.1", Severity: vulnerability.SeverityCritical, CVSS: &vulnerability.CVSSInfo{V3Score: 9.8}})+ intel[id] = VulnerabilityThreatIntel{CVEID: id, KnownExploited: true}+ }+ return vulns, intel+ }++ oneVulns, oneIntel := kev(1)+ manyVulns, manyIntel := kev(8)+ one := buildScanInsightsInternal(oneVulns, oneIntel, vulnerability.ImageExposureRunning, false)+ many := buildScanInsightsInternal(manyVulns, manyIntel, vulnerability.ImageExposureRunning, false)+ // Identical findings average to the same priority regardless of how many there are.+ require.Equal(t, 98, one.RiskScore)+ require.Equal(t, one.RiskScore, many.RiskScore)+ require.Equal(t, vulnerability.RiskBandCritical, many.RiskBand)+ require.Equal(t, vulnerability.ScoreStatusComplete, many.ScoreStatus)+ require.Len(t, many.TopPackages, topPackageInsightLimit)+}++func TestBuildScanInsightsInternal_NoFixableFindings(t *testing.T) {+ vulns := []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-KEV", PkgName: "openssl", Severity: vulnerability.SeverityCritical, CVSS: &vulnerability.CVSSInfo{V3Score: 9.8}},+ }+ intel := map[string]VulnerabilityThreatIntel{"CVE-KEV": {CVEID: "CVE-KEV", KnownExploited: true}}++ insights := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureRunning, false)++ // An unfixable KEV stays visible but does not set a patch priority.+ require.Equal(t, 1, insights.KnownExploitedCount)+ require.Zero(t, insights.RiskScore)+ require.Equal(t, vulnerability.RiskBandNone, insights.RiskBand)+ require.Equal(t, vulnerability.ScoreStatusComplete, insights.ScoreStatus)+}++func TestBuildScanInsightsInternal_DeduplicatesFixableFindings(t *testing.T) {+ vulns := []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-DUP", PkgName: "libssl", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V3Score: 8}},+ {VulnerabilityID: "CVE-DUP", PkgName: "openssl", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V3Score: 8}},+ {VulnerabilityID: "CVE-DUP", PkgName: "openssl-dev", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V3Score: 8}},+ {VulnerabilityID: "CVE-LOW", PkgName: "zlib", FixedVersion: "1.3", Severity: vulnerability.SeverityLow, CVSS: &vulnerability.CVSSInfo{V3Score: 2}},+ }+ intel := map[string]VulnerabilityThreatIntel{+ "CVE-DUP": {CVEID: "CVE-DUP", EPSSScore: new(0.0)},+ "CVE-LOW": {CVEID: "CVE-LOW", EPSSScore: new(0.0)},+ }++ insights := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureRunning, false)++ // CVE-DUP counts once at 40 and CVE-LOW at 10: the three package rows do not triple its weight.+ require.Equal(t, 25, insights.RiskScore)+ require.Equal(t, 3, insights.FixableCount)+ require.Equal(t, vulnerability.ScoreStatusComplete, insights.ScoreStatus)+}++func TestBuildScanInsightsInternal_UnknownSeverity(t *testing.T) {+ unscored := []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-UNK", PkgName: "foo", FixedVersion: "2.0", Severity: vulnerability.SeverityUnknown},}+ insights := buildScanInsightsInternal(unscored, nil, vulnerability.ImageExposureRunning, false)+ require.Equal(t, vulnerability.ScoreStatusUnavailable, insights.ScoreStatus)+ require.Zero(t, insights.RiskScore)- insights := buildScanInsightsInternal(vulns, nil, vulnerability.ImageExposureUnknown)+ mixed := append(unscored, vulnerability.Vulnerability{VulnerabilityID: "CVE-KEV", PkgName: "bar", FixedVersion: "1.1", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 6}})+ intel := map[string]VulnerabilityThreatIntel{"CVE-KEV": {CVEID: "CVE-KEV", KnownExploited: true}}+ insights = buildScanInsightsInternal(mixed, intel, vulnerability.ImageExposureRunning, false)+ // The unscored finding is left out of the average but marks the score provisional.+ require.Equal(t, 60, insights.RiskScore)+ require.Equal(t, vulnerability.ScoreStatusProvisional, insights.ScoreStatus)+}++func TestBuildScanInsightsInternal_StaleIntelIsProvisional(t *testing.T) {+ vulns := []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-KEV", PkgName: "openssl", FixedVersion: "3.0.1", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 6}},+ }+ intel := map[string]VulnerabilityThreatIntel{"CVE-KEV": {CVEID: "CVE-KEV", KnownExploited: true}}- require.Equal(t, 100, insights.RiskScore)- require.Equal(t, vulnerability.RiskBandCritical, insights.RiskBand)- require.Len(t, insights.TopPackages, topPackageInsightLimit)+ fresh := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureRunning, false)+ stale := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureRunning, true)+ require.Equal(t, vulnerability.ScoreStatusComplete, fresh.ScoreStatus)+ require.Equal(t, vulnerability.ScoreStatusProvisional, stale.ScoreStatus)+ require.Equal(t, fresh.RiskScore, stale.RiskScore)}-func TestFindingRiskInternal(t *testing.T) {- lowEPSS, highEPSS := 0.01, 0.97+func TestFindingPriorityInternal(t *testing.T) {+ zeroEPSS, lowEPSS, highEPSS := 0.0, 0.01, 0.97tests := []struct {- name string- base float64- knownExploited bool- epss *float64- exposure vulnerability.ImageExposure- want float64+ name string+ base float64+ knownExploited bool+ epss *float64+ exposure vulnerability.ImageExposure+ want float64+ wantProvisional bool}{- {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},+ {name: "no intel running", base: 7.5, exposure: vulnerability.ImageExposureRunning, want: 37.5, wantProvisional: true},+ {name: "epss zero is complete", base: 7.5, epss: &zeroEPSS, exposure: vulnerability.ImageExposureRunning, want: 37.5},+ {name: "unknown exposure is provisional", base: 7.5, epss: &zeroEPSS, exposure: vulnerability.ImageExposureUnknown, want: 37.5, wantProvisional: true},+ {name: "known exploited", base: 6, knownExploited: true, exposure: vulnerability.ImageExposureRunning, want: 60},+ {name: "low epss", base: 7.5, epss: &lowEPSS, exposure: vulnerability.ImageExposureRunning, want: 41.25},+ {name: "high epss", base: 6, epss: &highEPSS, exposure: vulnerability.ImageExposureRunning, want: 60 * (0.5 + 0.5*math.Sqrt(0.97))},+ {name: "stopped", base: 5, knownExploited: true, exposure: vulnerability.ImageExposureStopped, want: 40},+ {name: "unused", base: 9.8, knownExploited: true, exposure: vulnerability.ImageExposureUnused, want: 49},+ {name: "maximum", base: 10, knownExploited: true, exposure: vulnerability.ImageExposureRunning, want: 100},}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)+ got, provisional := findingPriorityInternal(tt.base, tt.knownExploited, tt.epss, tt.exposure)+ require.InDelta(t, tt.want, got, 0.001)+ require.Equal(t, tt.wantProvisional, provisional)})}}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}},+ {VulnerabilityID: "CVE-KEV", PkgName: "openssl", FixedVersion: "3.0.1", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 6}},+ {VulnerabilityID: "CVE-OTHER", PkgName: "zlib", FixedVersion: "1.3", 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)+ running := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureRunning, false)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)+ // (60 + 15) / 2; CVE-OTHER has no threat data so the score is provisional.+ require.Equal(t, 38, running.RiskScore)+ require.Equal(t, vulnerability.ScoreStatusProvisional, running.ScoreStatus)- unused := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureUnused)+ unused := buildScanInsightsInternal(vulns, intel, vulnerability.ImageExposureUnused, false)+ require.Equal(t, 19, unused.RiskScore)require.Less(t, unused.RiskScore, running.RiskScore)- require.Equal(t, vulnerability.RiskBandMedium, unused.RiskBand)}func riskTestServiceInternal(t *testing.T) (*VulnerabilityService, *settings.SettingsService, *database.DB) {@@ -822,6 +899,8 @@ func seedRiskScansInternal(t *testing.T, svc *VulnerabilityService) {{VulnerabilityID: "GHSA-xxxx", PkgName: "lodash", InstalledVersion: "4.0.0", Severity: vulnerability.SeverityLow},},},+ {ImageID: "sha256:clean", ImageName: "clean:1", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now()},+ {ImageID: "sha256:broken", ImageName: "broken:1", Status: vulnerability.ScanStatusFailed, ScanTime: time.Now(), Error: "scanner exploded"},}for _, scan := range scans {require.NoError(t, svc.saveScanResult(t.Context(), scan))@@ -844,44 +923,74 @@ func TestVulnerabilityService_GetRiskOverview(t *testing.T) {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.Equal(t, 3, overview.Drivers.ImagesScanned, "the failed scan is not a scanned image")+ require.Equal(t, 3, overview.Drivers.ScoredImages, "the clean image is scored at zero")require.True(t, overview.ThreatIntel.Enabled)require.True(t, overview.ThreatIntel.Stale)+ // The highlighted fix is the highest-priority fixable occurrence: the KEV in db:16, not the unfixable copy in web.+ require.NotNil(t, overview.ScoreDriver)+ require.Equal(t, vulnerability.RiskScoreDriver{VulnerabilityID: "CVE-2024-0002", ImageName: "db:16", PkgName: "curl", FixedVersion: "8.1.0", Exposure: vulnerability.ImageExposureUnknown, KnownExploited: true, Risk: 5.3}, *overview.ScoreDriver)+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]+ kev := overview.RiskiestFindings[0]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.InDelta(t, 5.3, kev.Risk, 0.001)+ require.Equal(t, "CVE-2024-0001", overview.RiskiestFindings[1].VulnerabilityID)+ require.InDelta(t, 3.8, overview.RiskiestFindings[1].Risk, 0.001, "no threat data halves the priority")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)+ // web averages its single fixable finding (37.5), db its KEV (53), clean contributes 0: 90.5 / 3.+ require.Equal(t, 30, overview.RiskScore)+ require.Equal(t, vulnerability.RiskBandLow, overview.RiskBand)+ require.Equal(t, vulnerability.ScoreStatusProvisional, overview.ScoreStatus, "unknown usage and missing threat data")require.Len(t, overview.RiskiestImages, 2)- require.Equal(t, "web:latest", overview.RiskiestImages[0].ImageName)+ require.Equal(t, "db:16", overview.RiskiestImages[0].ImageName)+ require.Equal(t, 53, overview.RiskiestImages[0].RiskScore)+ require.Equal(t, vulnerability.ScoreStatusProvisional, overview.RiskiestImages[0].ScoreStatus)+ require.Equal(t, "web:latest", overview.RiskiestImages[1].ImageName)+ require.Equal(t, 38, overview.RiskiestImages[1].RiskScore, "the unfixable CVE-2024-0002 in web does not enter its average")require.Len(t, overview.Trend, 1)require.Nil(t, overview.Delta7d)}+func TestVulnerabilityService_GetRiskOverview_ImageScoreMatchesInsights(t *testing.T) {+ svc, _, db := riskTestServiceInternal(t)+ seedRiskScansInternal(t, svc)+ require.NoError(t, db.Create(&VulnerabilityThreatIntel{CVEID: "CVE-2024-0001", EPSSScore: new(0.25)}).Error)++ overview, err := svc.GetRiskOverview(t.Context(), "0")+ require.NoError(t, err)+ scan, err := svc.GetScanResult(t.Context(), "0", "sha256:web")+ require.NoError(t, err)+ require.NotNil(t, scan.Insights)++ var ranked *vulnerability.RiskImage+ for i := range overview.RiskiestImages {+ if overview.RiskiestImages[i].ImageID == "sha256:web" {+ ranked = &overview.RiskiestImages[i]+ }+ }+ require.NotNil(t, ranked)+ require.Equal(t, scan.Insights.RiskScore, ranked.RiskScore)+ require.Equal(t, scan.Insights.ScoreStatus, ranked.ScoreStatus)+}+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},+ {SnapshotDate: now.AddDate(0, 0, -500).Format(riskDateLayout), ScoringVersion: riskScoringVersion, RiskScore: 10, RiskBand: "low"},+ {SnapshotDate: now.AddDate(0, 0, -7).Format(riskDateLayout), ScoringVersion: riskScoringVersion, RiskScore: 60, RiskBand: "medium", KnownExploitedCount: 3},+ {SnapshotDate: now.AddDate(0, 0, -3).Format(riskDateLayout), ScoringVersion: 1, RiskScore: 95, RiskBand: "critical"},}).Error)require.NoError(t, svc.RecordRiskSnapshot(t.Context()))@@ -889,13 +998,16 @@ func TestVulnerabilityService_RecordRiskSnapshot(t *testing.T) {var snapshots []VulnerabilityRiskSnapshotrequire.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)+ require.Len(t, snapshots, 3, "old snapshot pruned and same-day runs upserted")+ today := snapshots[2]+ require.Equal(t, now.Format(riskDateLayout), today.SnapshotDate)+ require.Equal(t, riskScoringVersion, today.ScoringVersion)+ require.Equal(t, 5, today.FindingsCount)+ require.Equal(t, 3, today.ScoredImages)overview, err := svc.GetRiskOverview(t.Context(), "0")require.NoError(t, err)- require.Len(t, overview.Trend, 2)+ require.Len(t, overview.Trend, 2, "the older scoring version stays out of the trend")require.Equal(t, now.Format(riskDateLayout), overview.Trend[1].Date)require.NotNil(t, overview.Delta7d)require.Equal(t, overview.RiskScore-60, *overview.Delta7d)diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.goindex 8ece0958e..e5043cf33 100644--- a/backend/internal/vulnerability/vulnerability_query.go+++ b/backend/internal/vulnerability/vulnerability_query.go@@ -39,7 +39,8 @@ func (s *VulnerabilityService) GetScanResult(ctx context.Context, envID, imageIDreturn nil, errors.WrapIf(err, "failed to filter ignored vulnerabilities")}intel := map[string]VulnerabilityThreatIntel{}- if s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true) {+ intelStatus := s.threatIntelStatusInternal(ctx)+ if intelStatus.Enabled {cveIDs := make([]string, 0, len(vulns))for i := range vulns {cveIDs = append(cveIDs, vulns[i].VulnerabilityID)@@ -53,7 +54,7 @@ func (s *VulnerabilityService) GetScanResult(ctx context.Context, envID, imageID}}usage, usageOK := s.containerUsageInternal(ctx)- result.Insights = buildScanInsightsInternal(vulns, intel, imageExposureInternal(usage, usageOK, result.ImageID))+ result.Insights = buildScanInsightsInternal(vulns, intel, imageExposureInternal(usage, usageOK, result.ImageID), intelStatus.Stale)return result, nil}@@ -768,15 +769,12 @@ type riskFindingRowInternal struct {}type riskImageAggInternal struct {- image vulnerability.RiskImage- peak, load float64+ image vulnerability.RiskImage+ mean priorityMeanInternal}type riskFindingAggInternal struct {- finding vulnerability.RiskFinding- // peakImage and peakExposure describe the riskiest instance of the CVE.- peakImage string- peakExposure vulnerability.ImageExposure+ finding vulnerability.RiskFindingimages map[string]struct{}runningImages map[string]struct{}}@@ -790,16 +788,18 @@ func boolToIntInternal(b bool) int {// 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+ today string+ intelStale bool+ scannedImageIDs []string+ overview *vulnerability.RiskOverview+ images map[string]*riskImageAggInternal+ findings map[string]*riskFindingAggInternal+ driverPriority float64}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@@ -836,12 +836,15 @@ func (a *riskAccumulatorInternal) addInternal(row *riskFindingRowInternal, exposa.images[row.ImageID] = img}img.image.Findings++- img.peak = max(img.peak, risk)- img.load += (risk / 10) * (risk / 10)+ priority := img.mean.addFindingInternal(row.VulnerabilityID, fixable, base, row.KnownExploited, row.EPSSScore, exposure)+ risk := priority / 10img.image.Critical += boolToIntInternal(severity == vulnerability.SeverityCritical)img.image.High += boolToIntInternal(severity == vulnerability.SeverityHigh)img.image.KnownExploited += boolToIntInternal(row.KnownExploited)img.image.Fixable += boolToIntInternal(fixable)+ if fixable && base > 0 {+ a.considerDriverInternal(row, exposure, priority)+ }agg, ok := a.findings[row.VulnerabilityID]if !ok {@@ -863,11 +866,10 @@ func (a *riskAccumulatorInternal) addInternal(row *riskFindingRowInternal, exposif exposure == vulnerability.ImageExposureRunning {agg.runningImages[row.ImageID] = struct{}{}}- // The riskiest instance of a CVE describes it; any fixed version beats none.+ // The highest-priority 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, severityagg.finding.PkgName, agg.finding.Title = row.PkgName, row.Title- agg.peakImage, agg.peakExposure = row.ImageName, exposureif fixable {agg.finding.FixedVersion = row.FixedVersion}@@ -877,36 +879,48 @@ func (a *riskAccumulatorInternal) addInternal(row *riskFindingRowInternal, expos}}-// finishInternal derives the drivers and score, and ranks findings and images.+// considerDriverInternal keeps the highest-priority fixable occurrence so its package, image, fix and score match.+func (a *riskAccumulatorInternal) considerDriverInternal(row *riskFindingRowInternal, exposure vulnerability.ImageExposure, priority float64) {+ current := a.overview.ScoreDriver+ if current != nil {+ order := cmp.Or(+ cmp.Compare(priority, a.driverPriority),+ cmp.Compare(boolToIntInternal(row.KnownExploited), boolToIntInternal(current.KnownExploited)),+ strings.Compare(current.VulnerabilityID, row.VulnerabilityID),+ strings.Compare(current.ImageName, row.ImageName),+ )+ if order <= 0 {+ return+ }+ }+ a.driverPriority = priority+ a.overview.ScoreDriver = &vulnerability.RiskScoreDriver{+ VulnerabilityID: row.VulnerabilityID,+ ImageName: row.ImageName,+ PkgName: row.PkgName,+ FixedVersion: row.FixedVersion,+ Exposure: exposure,+ KnownExploited: row.KnownExploited,+ Risk: math.Round(priority) / 10,+ }+}++// finishInternal derives the drivers and averages, and ranks findings and images.func (a *riskAccumulatorInternal) finishInternal() {overview := a.overviewoverview.Drivers.Findings = overview.Summary.Total- peak, load := 0.0, 0.0findings := make([]*riskFindingAggInternal, 0, len(a.findings))for _, agg := range a.findings {f := &agg.findingf.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 {@@ -940,10 +954,18 @@ func (a *riskAccumulatorInternal) finishInternal() {overview.RiskiestFindings = top(byRisk)overview.PrevalentFindings = top(byPrevalence)+ // Every scanned image weighs the same; clean images count as zero and unavailable ones leave the denominator.+ var environment priorityMeanInternaloverview.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)+ for _, id := range a.scannedImageIDs {+ img, ok := a.images[id]+ if !ok {+ environment.addScoreInternal(id, 0, vulnerability.ScoreStatusComplete)+ continue+ }+ mean, priority := img.mean.scoreInternal(a.intelStale)+ img.image.PatchPriority = priority+ environment.addScoreInternal(id, mean, priority.ScoreStatus)overview.RiskiestImages = append(overview.RiskiestImages, img.image)}slices.SortFunc(overview.RiskiestImages, func(a, b vulnerability.RiskImage) int {@@ -955,16 +977,32 @@ func (a *riskAccumulatorInternal) finishInternal() {)})overview.RiskiestImages = overview.RiskiestImages[:min(len(overview.RiskiestImages), riskiestImageLimit)]++ _, overview.PatchPriority = environment.scoreInternal(false)+ overview.Drivers.ScoredImages = len(environment.scores)+ if overview.Drivers.ScoredImages == 0 {+ overview.ScoreStatus = vulnerability.ScoreStatusUnavailable+ }}-// computeRiskInternal scores every non-ignored finding of current images; the trend, deltas and intel status are left to callers.+// computeRiskInternal scores every non-ignored finding of current images; the trend and deltas are left to callers.func (s *VulnerabilityService) computeRiskInternal(ctx context.Context, envID string) (*vulnerability.RiskOverview, error) {- intelEnabled := s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true)+ intelStatus := s.threatIntelStatusInternal(ctx)usage, usageOK := s.containerUsageInternal(ctx)imageIDs, imageIDsOK := s.currentImageIDsInternal(ctx)+ // Completed scans are listed first and findings loaded only for them, so a scan finishing in between is absent from both.+ scanQuery := s.db.WithContext(ctx).Model(&VulnerabilityScanRecord{}).Where("status = ?", ScanStatusCompleted)+ if imageIDsOK {+ scanQuery = scanQuery.Where("id IN ?", imageIDs)+ }+ var scannedIDs []string+ if err := scanQuery.Pluck("id", &scannedIDs).Error; err != nil {+ return nil, errors.WrapIf(err, "failed to list scanned images")+ }+var rows []riskFindingRowInternal- err := scanItemsQueryInternal(ctx, s.db.DB, envID, false, mo.TupleToOption(imageIDs, imageIDsOK)).+ err := scanItemsQueryInternal(ctx, s.db.DB, envID, false, mo.Some(scannedIDs)).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",@@ -980,29 +1018,22 @@ func (s *VulnerabilityService) computeRiskInternal(ctx context.Context, envID streturn 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)+ today: s.riskNowInternal().Format(riskDateLayout),+ intelStale: intelStatus.Stale,+ scannedImageIDs: scannedIDs,+ overview: &vulnerability.RiskOverview{Trend: []vulnerability.RiskTrendPoint{}, ThreatIntel: intelStatus},+ images: map[string]*riskImageAggInternal{},+ findings: map[string]*riskFindingAggInternal{},+ }+ acc.overview.Drivers.ImagesScanned = len(scannedIDs)+ acc.overview.Drivers.ImagesTotal = len(scannedIDs)if imageIDsOK {acc.overview.Drivers.ImagesTotal = len(imageIDs)}for i := range rows {row := &rows[i]- if !intelEnabled {+ if !intelStatus.Enabled {row.KnownExploited, row.KEVRansomware, row.KEVDueDate, row.EPSSScore = false, false, "", nil}acc.addInternal(row, imageExposureInternal(usage, usageOK, row.ImageID), usage[row.ImageID].running)@@ -1021,7 +1052,7 @@ func (s *VulnerabilityService) riskNowInternal() time.Time {return time.Now().In(s.config.GetLocation())}-// GetRiskOverview returns the environment risk score with its trend, drivers, riskiest images and top findings.+// GetRiskOverview returns the environment patch priority with its trend, drivers, prioritized 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@@ -1036,6 +1067,7 @@ func (s *VulnerabilityService) GetRiskOverview(ctx context.Context, envID stringtoday := now.Format(riskDateLayout)var snapshots []VulnerabilityRiskSnapshotif err := s.db.WithContext(ctx).+ Where("scoring_version = ?", riskScoringVersion).Where("snapshot_date >= ?", now.AddDate(0, 0, -(riskTrendDays-1)).Format(riskDateLayout)).Order("snapshot_date ASC").Find(&snapshots).Error; err != nil {@@ -1061,17 +1093,11 @@ func (s *VulnerabilityService) GetRiskOverview(ctx context.Context, envID stringFindings: snap.FindingsCount,ImagesScanned: snap.ImagesScanned,ImagesTotal: snap.ImagesTotal,+ ScoredImages: snap.ScoredImages,}}}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, nildiff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.goindex c10f0a596..11ef2f294 100644--- a/backend/internal/vulnerability/vulnerability_store.go+++ b/backend/internal/vulnerability/vulnerability_store.go@@ -535,12 +535,12 @@ func buildSeveritySummaryFromVulnerabilitiesInternal(vulns []vulnerability.Vulne}const (- topPackageInsightLimit = 5- threatFactorKEV = 1.4- exposureFactorStopped = 0.8- exposureFactorUnused = 0.5- imageRiskLoadScale = 5.0- environmentRiskLoadScale = 50.0+ topPackageInsightLimit = 5+ threatFactorNoData = 0.5+ usageFactorStopped = 0.8+ usageFactorUnused = 0.5+ // riskScoringVersion tags snapshots; trends only read the current formula.+ riskScoringVersion = 2)// rawCVSSInternal returns the CVSS v3 score, else v2, else 0.@@ -575,27 +575,92 @@ func baseScoreInternal(cvss float64, severity vulnerability.Severity) float64 {}}-// 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)+// findingPriorityInternal maps a 0-10 severity onto a 0-100 patch priority using exploitation evidence and container usage.+// provisional reports that threat data was missing or usage was unknown.+func findingPriorityInternal(base float64, knownExploited bool, epss *float64, exposure vulnerability.ImageExposure) (priority float64, provisional bool) {+ threat := threatFactorNoData+ switch {+ case knownExploited:+ threat = 1+ case epss != nil:+ threat = 0.5 + 0.5*math.Sqrt(*epss)+ default:+ provisional = true}+ usage := 1.0switch exposure {case vulnerability.ImageExposureStopped:- threat *= exposureFactorStopped+ usage = usageFactorStoppedcase vulnerability.ImageExposureUnused:- threat *= exposureFactorUnused- case vulnerability.ImageExposureRunning, vulnerability.ImageExposureUnknown:+ usage = usageFactorUnused+ case vulnerability.ImageExposureUnknown:+ provisional = true+ case vulnerability.ImageExposureRunning:+ }+ return min(100, 10*base*threat*usage), provisional+}++// priorityMeanInternal averages member scores keyed by ID: distinct fixable findings for an image, scanned images for an environment.+type priorityMeanInternal struct {+ scores map[string]float64+ unscored map[string]struct{}+ provisional bool+}++// addFindingInternal scores one finding occurrence, records it when fixable, and returns its 0-100 priority.+func (p *priorityMeanInternal) addFindingInternal(vulnerabilityID string, fixable bool, base float64, knownExploited bool, epss *float64, exposure vulnerability.ImageExposure) float64 {+ priority, provisional := findingPriorityInternal(base, knownExploited, epss, exposure)+ if !fixable {+ return priority+ }+ status := vulnerability.ScoreStatusComplete+ switch {+ case base <= 0:+ status = vulnerability.ScoreStatusUnavailable+ case provisional:+ status = vulnerability.ScoreStatusProvisional+ }+ p.addScoreInternal(vulnerabilityID, priority, status)+ return priority+}++// addScoreInternal records a member's score; the highest score per ID wins and unavailable members stay out of the denominator.+func (p *priorityMeanInternal) addScoreInternal(id string, score float64, status vulnerability.ScoreStatus) {+ if p.scores == nil {+ p.scores, p.unscored = map[string]float64{}, map[string]struct{}{}}- return min(10, base*threat)+ if status == vulnerability.ScoreStatusUnavailable {+ if _, ok := p.scores[id]; !ok {+ p.unscored[id] = struct{}{}+ }+ return+ }+ delete(p.unscored, id)+ if current, ok := p.scores[id]; !ok || score > current {+ p.scores[id] = score+ }+ p.provisional = p.provisional || status == vulnerability.ScoreStatusProvisional}-// 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)))))+// scoreInternal returns the unrounded 0-100 mean and the rounded API score; only unscorable members make it unavailable.+func (p *priorityMeanInternal) scoreInternal(intelStale bool) (float64, vulnerability.PatchPriority) {+ sum := 0.0+ for _, score := range p.scores {+ sum += score+ }+ mean := 0.0+ if len(p.scores) > 0 {+ mean = sum / float64(len(p.scores))+ }+ result := vulnerability.PatchPriority{RiskScore: int(math.Round(mean)), ScoreStatus: vulnerability.ScoreStatusComplete}+ result.RiskBand = riskBandInternal(result.RiskScore)+ switch {+ case len(p.scores) == 0 && len(p.unscored) > 0:+ result.ScoreStatus = vulnerability.ScoreStatusUnavailable+ case len(p.scores) > 0 && (p.provisional || intelStale || len(p.unscored) > 0):+ result.ScoreStatus = vulnerability.ScoreStatusProvisional+ }+ return mean, result}func riskBandInternal(score int) vulnerability.RiskBand {@@ -623,14 +688,14 @@ func isNewerFixedVersionInternal(candidate, current string) bool {}// 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 {+func buildScanInsightsInternal(vulns []vulnerability.Vulnerability, intel map[string]VulnerabilityThreatIntel, exposure vulnerability.ImageExposure, intelStale bool) *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+ var mean priorityMeanInternalpackages := map[string]*vulnerability.PackageInsight{}var packageOrder []string@@ -644,13 +709,11 @@ func buildScanInsightsInternal(vulns []vulnerability.Vulnerability, intel map[stif 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++}+ mean.addFindingInternal(v.VulnerabilityID, fixedVersion != "", base, threat.KnownExploited, threat.EPSSScore, exposure)pkg, ok := packages[v.PkgName]if !ok {@@ -664,8 +727,7 @@ func buildScanInsightsInternal(vulns []vulnerability.Vulnerability, intel map[st}}- insights.RiskScore = riskScoreInternal(peak, load, imageRiskLoadScale)- insights.RiskBand = riskBandInternal(insights.RiskScore)+ _, insights.PatchPriority = mean.scoreInternal(intelStale)for _, name := range packageOrder {insights.TopPackages = append(insights.TopPackages, *packages[name])@@ -935,6 +997,18 @@ func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveID}).Create(&batch).Error, "failed to store EPSS scores")}+// threatIntelStatusInternal reports whether threat intelligence is enabled and when it last synced.+func (s *VulnerabilityService) threatIntelStatusInternal(ctx context.Context) vulnerability.ThreatIntelStatus {+ status := vulnerability.ThreatIntelStatus{Enabled: s.settingsService.GetBoolSetting(ctx, threatIntelSettingKey, true)}+ if !status.Enabled {+ return status+ }+ state := s.loadThreatIntelStateInternal(ctx)+ status.LastSyncedAt = state.LastSyncedAt+ status.Stale = state.LastSyncedAt == nil || time.Since(*state.LastSyncedAt) > threatIntelStaleAfter+ return status+}+// 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) {@@ -948,6 +1022,7 @@ func (s *VulnerabilityService) RecordRiskSnapshot(ctx context.Context) error {now := s.riskNowInternal()snapshot := VulnerabilityRiskSnapshot{SnapshotDate: now.Format(riskDateLayout),+ ScoringVersion: riskScoringVersion,RiskScore: overview.RiskScore,RiskBand: string(overview.RiskBand),CriticalCount: overview.Summary.Critical,@@ -963,12 +1038,13 @@ func (s *VulnerabilityService) RecordRiskSnapshot(ctx context.Context) error {FixableCount: overview.Drivers.Fixable,ImagesScanned: overview.Drivers.ImagesScanned,ImagesTotal: overview.Drivers.ImagesTotal,+ ScoredImages: overview.Drivers.ScoredImages,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"}),+ DoUpdates: clause.AssignmentColumns([]string{"scoring_version", "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", "scored_images", "updated_at"}),}).Create(&snapshot).Error; err != nil {return errors.WrapIf(err, "failed to store risk snapshot")}diff --git a/backend/resources/migrations/postgres/089_add_vulnerability_scoring_version.sql b/backend/resources/migrations/postgres/089_add_vulnerability_scoring_version.sqlnew file mode 100644index 000000000..d51911f30--- /dev/null+++ b/backend/resources/migrations/postgres/089_add_vulnerability_scoring_version.sql@@ -0,0 +1,7 @@+-- +goose Up+ALTER TABLE vulnerability_risk_snapshots ADD COLUMN IF NOT EXISTS scoring_version INTEGER NOT NULL DEFAULT 1;+ALTER TABLE vulnerability_risk_snapshots ADD COLUMN IF NOT EXISTS scored_images INTEGER NOT NULL DEFAULT 0;++-- +goose Down+ALTER TABLE vulnerability_risk_snapshots DROP COLUMN IF EXISTS scored_images;+ALTER TABLE vulnerability_risk_snapshots DROP COLUMN IF EXISTS scoring_version;diff --git a/backend/resources/migrations/sqlite/089_add_vulnerability_scoring_version.sql b/backend/resources/migrations/sqlite/089_add_vulnerability_scoring_version.sqlnew file mode 100644index 000000000..c06a51263--- /dev/null+++ b/backend/resources/migrations/sqlite/089_add_vulnerability_scoring_version.sql@@ -0,0 +1,7 @@+-- +goose Up+ALTER TABLE vulnerability_risk_snapshots ADD COLUMN scoring_version INTEGER NOT NULL DEFAULT 1;+ALTER TABLE vulnerability_risk_snapshots ADD COLUMN scored_images INTEGER NOT NULL DEFAULT 0;++-- +goose Down+ALTER TABLE vulnerability_risk_snapshots DROP COLUMN scored_images;+ALTER TABLE vulnerability_risk_snapshots DROP COLUMN scoring_version;diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex e309ba5cf..0e36ea27c 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -988,12 +988,18 @@"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_risk_score": "Patch priority",+ "vuln_risk_band_low": "Low priority",+ "vuln_risk_band_medium": "Medium priority",+ "vuln_risk_band_high": "High priority",+ "vuln_risk_band_critical": "Critical priority",+ "vuln_risk_score_help": "Average priority of this image's fixable findings, from 0 to 100. Each finding's severity is weighted by known exploitation, exploit probability and container usage. Findings without a fix stay listed but do not enter the average.",+ "vuln_priority_none": "No fixable findings",+ "vuln_priority_unavailable": "Priority unavailable",+ "vuln_score_denominator": "/100",+ "vuln_score_provisional": "Provisional",+ "vuln_score_provisional_title": "Provisional score",+ "vuln_score_provisional_help": "Threat data or container usage is missing or out of date. The score may change once it is available.","vuln_highest_cvss": "Highest CVSS","vuln_cvss": "CVSS","vuln_top_packages": "Top packages to update",@@ -1003,11 +1009,9 @@"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_trend": "Priority trend",+ "security_risk_trend_summary": "Patch priority went from {from} to {to} over the last {days} days",+ "security_risk_trend_empty": "The trend fills in as daily priority 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",@@ -1016,35 +1020,39 @@"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_exposed": "Running critical/high",+ "security_driver_exposed_help": "Critical and high CVEs in images used by running containers. A running container is not necessarily reachable from the internet.","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_driver_unavailable": "Unavailable until threat data has synced",+ "security_score_driver": "Highest-priority fix: {cve} in {image}",+ "security_patch_priority_help": "Average patch priority of fixable findings across scanned images, from 0 to 100. Every scanned image counts equally and images with no fixable findings count as 0. An average describes the current mix of findings, so it can rise when lower-priority findings are removed while urgent findings stay listed below.",+ "security_patch_priority_basis": "Average across {count} scanned images",+ "security_patch_priority_basis_one": "Based on 1 scanned 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_breakdown_help": "Findings in images used by running containers carry full weight; 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_risk_help": "Ranked by priority: severity weighted by known exploitation, exploit probability and container usage. Findings without a fix stay listed here but do not enter the patch priority average.","security_top_vulnerabilities_prevalence_help": "Ranked by how many images contain the CVE, then by risk.",- "security_rank_risk": "Risk",+ "security_rank_risk": "Priority","security_rank_prevalence": "Prevalence",- "security_risk_value": "Risk {value}",- "security_riskiest_images": "Riskiest images",+ "security_risk_value": "Priority {value}",+ "security_riskiest_images": "Images to prioritize","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_overview_empty": "Scan your images to see the environment patch priority.","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_disabled": "Threat intelligence is off; scores use severity and container usage only and stay provisional","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",diff --git a/frontend/src/lib/components/vulnerability/risk-gauge.svelte b/frontend/src/lib/components/vulnerability/risk-gauge.svelteindex 04ed215e1..a4741d342 100644--- a/frontend/src/lib/components/vulnerability/risk-gauge.svelte+++ b/frontend/src/lib/components/vulnerability/risk-gauge.svelte@@ -1,23 +1,28 @@<script lang="ts">import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';import { InfoIcon } from '#lib/icons/index.js';+ import { Badge } from '#lib/components/ui/badge/index.js';import { m } from '#lib/paraglide/messages.js';- import type { VulnerabilityRiskBand } from '#lib/types/environment.js';+ import type { VulnerabilityRiskBand, VulnerabilityScoreStatus } 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;+ status: VulnerabilityScoreStatus;+ /** Tooltip body explaining what the score averages. */+ help?: string;/** 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 { score, band, status, help = m.vuln_risk_score_help(), size = 260, stroke = 14 }: Props = $props();let measuredWidth = $state(0);- const clampedScore = $derived(Math.max(0, Math.min(100, score)));+ const unavailable = $derived(status === 'unavailable');+ const clampedScore = $derived(unavailable ? 0 : 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);@@ -25,7 +30,7 @@`M ${stroke / 2} ${radius + stroke / 2} A ${radius} ${radius} 0 0 1 ${width - stroke / 2} ${radius + stroke / 2}`);- const bandStyle = $derived(getRiskBandDisplay(band));+ const bandStyle = $derived(getRiskBandDisplay(band, status));const large = $derived(width >= 360);</script>@@ -50,13 +55,23 @@{/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 text-(length:--gauge-font-size) leading-none font-semibold tracking-tight tabular-nums"- style="--gauge-font-size: {Math.round(width * 0.25)}px; --gauge-score: {clampedScore};"- aria-hidden="true"- ></span>- <span class="sr-only">{clampedScore}</span>+ <span class="flex items-baseline" style="--gauge-font-size: {Math.round(width * 0.25)}px;">+ {#if unavailable}+ <span+ class="text-(length:--gauge-font-size) leading-none font-semibold tracking-tight text-muted-foreground"+ aria-label={m.vuln_priority_unavailable()}>–</span+ >+ {:else}+ <!-- The visible number counts up via a CSS counter; the sr-only text carries the value for assistive tech. -->+ <span+ class="gauge-number text-(length:--gauge-font-size) leading-none font-semibold tracking-tight tabular-nums"+ style="--gauge-score: {clampedScore};"+ aria-hidden="true"+ ></span>+ <span class="sr-only">{clampedScore}</span>+ <span class="text-muted-foreground {large ? 'text-xl' : 'text-base'}">{m.vuln_score_denominator()}</span>+ {/if}+ </span><span class="mt-2 flex items-center gap-1.5 text-muted-foreground {large ? 'text-base' : 'text-sm'}">{bandStyle.label}<ArcaneTooltip.Root>@@ -67,9 +82,20 @@</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>+ <p class="text-xs">{help}</p></ArcaneTooltip.Content></ArcaneTooltip.Root>+ {#if status === 'provisional'}+ <ArcaneTooltip.Root>+ <ArcaneTooltip.Trigger>+ <Badge variant="gray" size="xs">{m.vuln_score_provisional()}</Badge>+ </ArcaneTooltip.Trigger>+ <ArcaneTooltip.Content side="bottom" class="max-w-56">+ <p class="mb-1 text-sm font-medium">{m.vuln_score_provisional_title()}</p>+ <p class="text-xs">{m.vuln_score_provisional_help()}</p>+ </ArcaneTooltip.Content>+ </ArcaneTooltip.Root>+ {/if}</span></div></div>diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelteindex 2c7f5b53f..56a4b7b21 100644--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte@@ -263,18 +263,9 @@<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>+ <RiskGauge score={insights.riskScore} band={insights.riskBand} status={insights.scoreStatus} />+ {#if insights.knownExploitedCount > 0}+ <Badge variant="red" size="xs">{m.vuln_known_exploited_count({ count: insights.knownExploitedCount })}</Badge>{/if}</div>{/if}diff --git a/frontend/src/lib/types/environment.ts b/frontend/src/lib/types/environment.tsindex 3a0652465..277352891 100644--- a/frontend/src/lib/types/environment.ts+++ b/frontend/src/lib/types/environment.ts@@ -143,6 +143,7 @@ export interface VulnerabilityWithImage extends Vulnerability {}export type VulnerabilityRiskBand = 'none' | 'low' | 'medium' | 'high' | 'critical';+export type VulnerabilityScoreStatus = 'complete' | 'provisional' | 'unavailable';export interface VulnerabilityPackageInsight {pkgName: string;@@ -155,6 +156,7 @@ export interface VulnerabilityPackageInsight {export interface VulnerabilityScanInsights {riskScore: number;riskBand: VulnerabilityRiskBand;+ scoreStatus: VulnerabilityScoreStatus;highestCvss: number;highestVulnerabilityId?: string;fixableCount: number;@@ -179,6 +181,7 @@ export interface VulnerabilityRiskDrivers {findings: number;imagesScanned: number;imagesTotal: number;+ scoredImages: number;}export interface VulnerabilityRiskExposureBreakdown {@@ -191,6 +194,8 @@ export interface VulnerabilityRiskExposureBreakdown {export interface VulnerabilityRiskScoreDriver {vulnerabilityId: string;imageName: string;+ pkgName: string;+ fixedVersion: string;exposure: VulnerabilityExposure;knownExploited: boolean;risk: number;@@ -201,6 +206,7 @@ export interface VulnerabilityRiskImage {imageName: string;riskScore: number;riskBand: VulnerabilityRiskBand;+ scoreStatus: VulnerabilityScoreStatus;exposure: VulnerabilityExposure;runningContainers: number;knownExploited: number;@@ -235,6 +241,7 @@ export interface VulnerabilityThreatIntelStatus {export interface VulnerabilityRiskOverview {riskScore: number;riskBand: VulnerabilityRiskBand;+ scoreStatus: VulnerabilityScoreStatus;delta7d?: number;trend: VulnerabilityRiskTrendPoint[];drivers: VulnerabilityRiskDrivers;diff --git a/frontend/src/lib/utils/vulnerability.ts b/frontend/src/lib/utils/vulnerability.tsindex 8794848bd..d0a4ffcca 100644--- a/frontend/src/lib/utils/vulnerability.ts+++ b/frontend/src/lib/utils/vulnerability.ts@@ -5,6 +5,7 @@ import type {Vulnerability,VulnerabilityRiskBand,VulnerabilityScanResult,+ VulnerabilityScoreStatus,VulnerabilityScanSummary,VulnerabilityWithImage} from '#lib/types/environment.js';@@ -72,16 +73,25 @@ export function getSeveritySegments(summary: SeveritySummary | null | undefined).filter((segment) => segment.count > 0);}-const riskBandDisplay: Record<VulnerabilityRiskBand, { label: () => string; strokeClass: string; barClass: string }> = {+type RiskBandDisplay = { label: () => string; strokeClass: string; barClass: string };++const riskBandDisplay: Record<VulnerabilityRiskBand, RiskBandDisplay> = {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' }+ none: { label: m.vuln_priority_none, strokeClass: 'text-success', barClass: 'bg-success' }+};++const unavailableDisplay: RiskBandDisplay = {+ label: m.vuln_priority_unavailable,+ strokeClass: 'text-muted-foreground',+ barClass: 'bg-muted-foreground/40'};-export function getRiskBandDisplay(band: VulnerabilityRiskBand) {- const display = riskBandDisplay[band];+// An unavailable score must never read as clean, so it overrides the band.+export function getRiskBandDisplay(band: VulnerabilityRiskBand, status: VulnerabilityScoreStatus) {+ const display = status === 'unavailable' ? unavailableDisplay : riskBandDisplay[band];return { label: display.label(), strokeClass: display.strokeClass, barClass: display.barClass };}diff --git a/frontend/src/routes/(app)/security/security-overview.svelte b/frontend/src/routes/(app)/security/security-overview.svelteindex 901fcf2d7..438f526d4 100644--- a/frontend/src/routes/(app)/security/security-overview.svelte+++ b/frontend/src/routes/(app)/security/security-overview.svelte@@ -52,16 +52,32 @@// Worsening drivers show a week-over-week delta; the rest show their denominator.trackDelta: boolean;context?: string;+ // Threat-data counters are unavailable, not zero, until the feeds have synced.+ unavailable?: boolean;};+ const threatDataUnavailable = $derived(!overview.threatIntel.enabled || !overview.threatIntel.lastSyncedAt);+ const scoreBasis = $derived(+ overview.drivers.scoredImages === 1+ ? m.security_patch_priority_basis_one()+ : m.security_patch_priority_basis({ count: overview.drivers.scoredImages })+ );+const drivers = $derived<Driver[]>([{key: 'knownExploited',label: m.security_driver_known_exploited(),help: m.security_driver_known_exploited_help(),- trackDelta: true+ trackDelta: true,+ unavailable: threatDataUnavailable+ },+ {+ key: 'highEpss',+ label: m.security_driver_high_epss(),+ help: m.security_driver_high_epss_help(),+ trackDelta: true,+ unavailable: threatDataUnavailable},- { key: 'highEpss', label: m.security_driver_high_epss(), help: m.security_driver_high_epss_help(), trackDelta: true },{key: 'exposedCriticalHigh',label: m.security_driver_exposed(),@@ -72,7 +88,8 @@key: 'overdueKnownExploited',label: m.security_driver_overdue_kev(),help: m.security_driver_overdue_kev_help(),- trackDelta: true+ trackDelta: true,+ unavailable: threatDataUnavailable},{key: 'imagesScanned',@@ -147,7 +164,7 @@</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>+ <p class="text-xs">{body}</p></ArcaneTooltip.Content></ArcaneTooltip.Root>{/snippet}@@ -163,7 +180,15 @@<divclass="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} />+ <RiskGauge+ score={overview.riskScore}+ band={overview.riskBand}+ status={overview.scoreStatus}+ help={m.security_patch_priority_help()}+ size={460}+ stroke={22}+ />+ <p class="text-xs text-muted-foreground">{scoreBasis}</p>{#if overview.scoreDriver}{@const driver = overview.scoreDriver}<button@@ -177,11 +202,7 @@<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}+ <span class="font-mono text-xs">{driver.pkgName} → {driver.fixedVersion}</span></button>{/if}</div>@@ -242,11 +263,15 @@{@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 driver.unavailable}+ <span class="text-3xl font-semibold text-muted-foreground" aria-label={m.security_driver_unavailable()}>–</span>+ {:else}+ <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}{/if}</dd></div>@@ -315,12 +340,12 @@</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-sm font-semibold tabular-nums">{Math.round(finding.risk * 10)}</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+ >{m.security_risk_value({ value: Math.round(finding.risk * 10) })}</span>{/if}</span>@@ -335,7 +360,7 @@<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)}+ {@const band = getRiskBandDisplay(image.riskBand, image.scoreStatus)}<li><ahref="/images/{image.imageId}?tab=vulnerabilities"@@ -357,7 +382,13 @@style="--risk-width: {image.riskScore}%"></span></span>- <span class="w-8 text-right text-sm font-semibold tabular-nums">{image.riskScore}</span>+ <span class="w-8 text-right text-sm font-semibold tabular-nums">+ {#if image.scoreStatus === 'unavailable'}+ <span class="text-muted-foreground" aria-label={band.label}>–</span>+ {:else}+ {image.riskScore}+ {/if}+ </span></span></a></li>diff --git a/tests/spec/security.spec.ts b/tests/spec/security.spec.tsindex 3f550d1cd..486060a90 100644--- a/tests/spec/security.spec.ts+++ b/tests/spec/security.spec.ts@@ -39,6 +39,7 @@ async function mockRiskOverview(page: Page) {data: {riskScore: 75,riskBand: 'high',+ scoreStatus: 'complete',trend: [{ date: '2026-09-13', riskScore: 75 }],drivers: {knownExploited: 0,@@ -48,7 +49,8 @@ async function mockRiskOverview(page: Page) {fixable: 1,findings: 1,imagesScanned: 1,- imagesTotal: 1+ imagesTotal: 1,+ scoredImages: 1},summary: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0, total: 1 },exposure: { running: 1, stopped: 0, unused: 0, unknown: 0 },diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.goindex 795802a74..f1fb92d2d 100644--- a/types/vulnerability/vulnerability.go+++ b/types/vulnerability/vulnerability.go@@ -250,7 +250,7 @@ type ScanResult struct {Insights *ScanInsights `json:"insights,omitempty"`}-// RiskBand is the qualitative band of a risk score, mirroring the CVSS ranges.+// RiskBand is the qualitative label of a patch priority score, mirroring the CVSS ranges.type RiskBand stringconst (@@ -261,18 +261,40 @@ const (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.+// ScoreStatus reports how complete the data behind a patch priority score is.+type ScoreStatus string++const (+ // ScoreStatusComplete means every contributing finding had threat and usage data.+ ScoreStatusComplete ScoreStatus = "complete"+ // ScoreStatusProvisional means threat data was missing or stale, usage was unknown, or some fixable findings could not be scored.+ ScoreStatusProvisional ScoreStatus = "provisional"+ // ScoreStatusUnavailable means no score could be computed.+ ScoreStatusUnavailable ScoreStatus = "unavailable"+)++// PatchPriority is a 0-100 average of finding priorities with its label and data status.+type PatchPriority struct {+ // RiskScore is the 0-100 patch priority: for an image the mean of its distinct fixable finding priorities, for an environment the mean of its scored images.//// Required: trueRiskScore int `json:"riskScore"`- // RiskBand is the qualitative band of RiskScore.+ // RiskBand is the qualitative label of RiskScore.//// Required: trueRiskBand RiskBand `json:"riskBand"`+ // ScoreStatus reports whether RiskScore is complete, provisional or unavailable.+ //+ // Required: true+ ScoreStatus ScoreStatus `json:"scoreStatus"`+}++// ScanInsights summarizes the patch priority and remediation outlook of a scan.+type ScanInsights struct {+ PatchPriority+// HighestCVSS is the highest CVSS score across findings, using a severity fallback when unscored.//// Required: true@@ -293,7 +315,7 @@ type ScanInsights struct {// Required: trueKnownExploitedCount int `json:"knownExploitedCount"`- // Exposure describes whether containers use the image, which scales finding risk.+ // Exposure describes whether containers use the image, which scales finding priority.//// Required: trueExposure ImageExposure `json:"exposure"`@@ -689,17 +711,9 @@ type BulkIgnoreResponse struct {AffectedCount int `json:"affectedCount"`}-// RiskOverview is the environment-wide vulnerability risk picture.+// RiskOverview is the environment-wide vulnerability patch priority 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"`+ PatchPriority// Delta7d is the score change since the snapshot from 7 days ago, when one exists.//@@ -731,17 +745,17 @@ type RiskOverview struct {// Required: trueExposure RiskExposureBreakdown `json:"exposure"`- // ScoreDriver is the finding that sets the peak of the risk score, when any exist.+ // ScoreDriver is the highest-priority fixable finding occurrence, when any exist.//// Required: falseScoreDriver *RiskScoreDriver `json:"scoreDriver,omitempty"`- // RiskiestImages lists the highest-risk images.+ // RiskiestImages lists the images with the highest patch priority.//// Required: trueRiskiestImages []RiskImage `json:"riskiestImages"`- // RiskiestFindings lists the CVEs with the highest finding risk.+ // RiskiestFindings lists the CVEs with the highest finding priority.//// Required: trueRiskiestFindings []RiskFinding `json:"riskiestFindings"`@@ -762,20 +776,20 @@ type RiskOverview struct {ComputedAt time.Time `json:"computedAt"`}-// RiskTrendPoint is one day of the risk trend.+// RiskTrendPoint is one day of the patch priority trend.type RiskTrendPoint struct {// Date is the snapshot day (YYYY-MM-DD).//// Required: trueDate string `json:"date"`- // RiskScore is the environment risk score on that day.+ // RiskScore is the environment patch priority on that day.//// Required: trueRiskScore int `json:"riskScore"`}-// RiskDrivers are the counts that explain the environment risk score.+// RiskDrivers are the counts that explain the environment patch priority.type RiskDrivers struct {// KnownExploited is the number of unique CVEs listed in the CISA KEV catalog.//@@ -816,6 +830,11 @@ type RiskDrivers struct {//// Required: trueImagesTotal int `json:"imagesTotal"`++ // ScoredImages is the number of scanned images that enter the patch priority average.+ //+ // Required: true+ ScoredImages int `json:"scoredImages"`}// RiskExposureBreakdown counts findings by the exposure of their image.@@ -841,18 +860,28 @@ type RiskExposureBreakdown struct {Unknown int `json:"unknown"`}-// RiskScoreDriver identifies the finding that sets the peak of the risk score.+// RiskScoreDriver identifies the highest-priority fixable finding occurrence; every field describes that one occurrence.type RiskScoreDriver struct {// VulnerabilityID is the CVE or advisory ID.//// Required: trueVulnerabilityID string `json:"vulnerabilityId"`- // ImageName is the image holding the riskiest instance of the finding.+ // ImageName is the image holding the occurrence.//// Required: trueImageName string `json:"imageName"`+ // PkgName is the affected package in that image.+ //+ // Required: true+ PkgName string `json:"pkgName"`++ // FixedVersion is the package version that fixes the finding.+ //+ // Required: true+ FixedVersion string `json:"fixedVersion"`+// Exposure is how containers use that image.//// Required: true@@ -863,14 +892,16 @@ type RiskScoreDriver struct {// Required: trueKnownExploited bool `json:"knownExploited"`- // Risk is the 0-10 finding risk.+ // Risk is the 0-10 finding priority (patch priority / 10).//// Required: trueRisk float64 `json:"risk"`}-// RiskImage is one image ranked by risk.+// RiskImage is one image ranked by patch priority.type RiskImage struct {+ PatchPriority+// ImageID is the Docker image ID.//// Required: true@@ -881,16 +912,6 @@ type RiskImage struct {// Required: trueImageName 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@@ -954,7 +975,7 @@ type RiskFinding struct {// Required: trueCVSS float64 `json:"cvss"`- // Risk is the 0-10 finding risk after threat and exposure adjustments.+ // Risk is the 0-10 finding priority (patch priority / 10) after threat and usage adjustments.//// Required: trueRisk float64 `json:"risk"`