From af3c43af85f816571e021cbb2e06af4e42b53a33 Mon Sep 17 00:00:00 2001 From: Rokibul Hasan Date: Wed, 3 Apr 2024 11:45:36 +0600 Subject: [PATCH] Sort images by vulnerabilities count (#292) Signed-off-by: Rokibul Hasan --- pkg/registry/scanner/reports/storage.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/pkg/registry/scanner/reports/storage.go b/pkg/registry/scanner/reports/storage.go index 2c17d5f73..13ddf6a68 100644 --- a/pkg/registry/scanner/reports/storage.go +++ b/pkg/registry/scanner/reports/storage.go @@ -299,7 +299,7 @@ func GenerateReports(images map[string]kmapi.ImageInfo, results map[string]resul } return &reportsapi.CVEReportResponse{ - Images: sortImageInfosByImageName(imginfos), + Images: sortImageInfosByVulnerabilities(imginfos), Vulnerabilities: reportsapi.VulnerabilityInfo{ Stats: getVulnerabilityStats(totalOccurrence, vuls), CVEs: getCVEsFromVulnerabilityInfoMap(vuls), @@ -412,17 +412,27 @@ func getVulnerabilityStats(totalOccurrence map[string]int, vuls map[string]trivy return stats } -func sortImageInfosByImageName(imginfos map[string]reportsapi.ImageInfo) []reportsapi.ImageInfo { +func sortImageInfosByVulnerabilities(imginfos map[string]reportsapi.ImageInfo) []reportsapi.ImageInfo { images := make([]reportsapi.ImageInfo, 0, len(imginfos)) for _, ii := range imginfos { images = append(images, ii) } sort.Slice(images, func(i, j int) bool { - return images[i].Image.Name < images[j].Image.Name + return calculateVulnerabilities(images[i].Stats) < calculateVulnerabilities(images[j].Stats) }) return images } +func calculateVulnerabilities(stats map[string]reportsapi.RiskStats) int { + count := 0 + for _, key := range []string{"HIGH", "LOW", "MEDIUM", "CRITICAL", "UNKNOWN"} { + if val, ok := stats[key]; ok { + count += val.Count + } + } + return count +} + func getCVEsFromVulnerabilityInfoMap(vuls map[string]trivy.VulnerabilityInfo) []trivy.VulnerabilityInfo { cves := make([]trivy.VulnerabilityInfo, 0, len(vuls)) for _, vul := range vuls {