Skip to content

Modern Docker Management, Designed for Everyone

56.3 KB
Raw Blame
package query

import (
	"cmp"
	"context"
	"encoding/csv"
	"encoding/json/v2"
	"errors"
	"fmt"
	"io"
	"iter"
	"log/slog"
	"math"
	"net/url"
	"slices"
	"sort"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/getarcaneapp/arcane/types/v2"
	"github.com/getarcaneapp/arcane/types/v2/base"
	"github.com/getarcaneapp/arcane/types/v2/features"
	"github.com/getarcaneapp/arcane/types/v2/vulnerability"
	"github.com/moby/moby/api/types/container"
	"github.com/samber/mo"
	"go.getarcane.app/kit/pkg"
	"golang.org/x/sync/singleflight"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	"github.com/getarcaneapp/arcane/backend/v2/internal/common"
	"github.com/getarcaneapp/arcane/backend/v2/internal/config"
	"github.com/getarcaneapp/arcane/backend/v2/internal/database"
	"github.com/getarcaneapp/arcane/backend/v2/internal/docker"
	"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
)

const (
	scansTable       = "vulnerability_scans"
	scanItemsTable   = "vulnerability_scan_items"
	threatIntelTable = "vulnerability_threat_intel"

	// riskOverviewCacheTTL bounds staleness from changes that do not invalidate
	// the cache, such as containers starting or threat intel refreshing.
	riskOverviewCacheTTL     = 5 * time.Second
	riskOverviewBuildTimeout = 30 * time.Second
)

// Service answers vulnerability result, listing, export, and risk queries.
type Service struct {
	db                *database.DB
	config            *config.Config
	dockerService     *docker.DockerClientService
	settingsService   *settings.SettingsService
	loadResult        func(ctx context.Context, imageID string) (*vulnerability.ScanResult, error)
	refreshSummary    func(ctx context.Context, summary *vulnerability.ScanSummary)
	threatIntelStatus func(ctx context.Context) vulnerability.ThreatIntelStatus
	filterIgnored     func(ctx context.Context, envID, imageID string, vulns []vulnerability.Vulnerability) ([]vulnerability.Vulnerability, error)

	// riskFlight and riskCache share one risk overview build per environment;
	// riskGen is bumped by InvalidateRiskOverview to drop cached overviews.
	riskFlight singleflight.Group
	riskCache  sync.Map // envID -> *riskOverviewCacheEntry
	riskGen    atomic.Uint64
}

type riskOverviewCacheEntry struct {
	overview *vulnerability.RiskOverview
	builtAt  time.Time
	gen      uint64
}

func NewService(
	db *database.DB,
	cfg *config.Config,
	dockerService *docker.DockerClientService,
	settingsService *settings.SettingsService,
	loadResult func(ctx context.Context, imageID string) (*vulnerability.ScanResult, error),
	refreshSummary func(ctx context.Context, summary *vulnerability.ScanSummary),
	threatIntelStatus func(ctx context.Context) vulnerability.ThreatIntelStatus,
	filterIgnored func(ctx context.Context, envID, imageID string, vulns []vulnerability.Vulnerability) ([]vulnerability.Vulnerability, error),
) *Service {
	return &Service{
		db:                db,
		config:            cfg,
		dockerService:     dockerService,
		settingsService:   settingsService,
		loadResult:        loadResult,
		refreshSummary:    refreshSummary,
		threatIntelStatus: threatIntelStatus,
		filterIgnored:     filterIgnored,
	}
}

// scanSummaryRow is the summary projection of a scan record.
type scanSummaryRow struct {
	ID            string    `gorm:"column:id"`
	ScanTime      time.Time `gorm:"column:scan_time"`
	Status        string    `gorm:"column:status"`
	CriticalCount int       `gorm:"column:critical_count"`
	HighCount     int       `gorm:"column:high_count"`
	MediumCount   int       `gorm:"column:medium_count"`
	LowCount      int       `gorm:"column:low_count"`
	UnknownCount  int       `gorm:"column:unknown_count"`
	TotalCount    int       `gorm:"column:total_count"`
	Error         *string   `gorm:"column:error"`
}

// scanImageRow is the image projection of a scan record.
type scanImageRow struct {
	ID        string `gorm:"column:id"`
	ImageName string `gorm:"column:image_name"`
}

// threatIntelRow is the insight projection of a cached threat intel row.
type threatIntelRow struct {
	CVEID          string   `gorm:"column:cve_id"`
	KnownExploited bool     `gorm:"column:known_exploited"`
	EPSSScore      *float64 `gorm:"column:epss_score"`
}

// GetScanResult retrieves the most recent scan result for an image, with risk insights for completed scans.
func (s *Service) GetScanResult(ctx context.Context, envID, imageID string) (*vulnerability.ScanResult, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return nil, nil
	}
	result, err := s.loadResult(ctx, imageID)
	if err != nil || result == nil || result.Status != vulnerability.ScanStatusCompleted || len(result.Vulnerabilities) == 0 {
		return result, err
	}

	vulns, err := s.filterIgnored(ctx, envID, result.ImageID, result.Vulnerabilities)
	if err != nil {
		return nil, fmt.Errorf("failed to filter ignored vulnerabilities: %w", err)
	}
	intel := map[string]vuln.ThreatIntel{}
	if s.threatIntelStatus(ctx).Enabled {
		cveIDs := make([]string, 0, len(vulns))
		for i := range vulns {
			cveIDs = append(cveIDs, vulns[i].VulnerabilityID)
		}
		var rows []threatIntelRow
		if loadThreatIntelErr := s.db.WithContext(ctx).Table(threatIntelTable).Where("cve_id IN ?", cveIDs).Find(&rows).Error; loadThreatIntelErr != nil {
			slog.WarnContext(ctx, "failed to load threat intel for image insights", "error", loadThreatIntelErr)
		}
		for _, row := range rows {
			intel[row.CVEID] = vuln.ThreatIntel{KnownExploited: row.KnownExploited, EPSS: row.EPSSScore}
		}
	}
	usage, usageOK := s.containerUsage(ctx)
	return &vulnerability.ScanResult{ //exhaustruct:enforce
		ImageID:         result.ImageID,
		ImageName:       result.ImageName,
		ScanTime:        result.ScanTime,
		Status:          result.Status,
		ActivityID:      result.ActivityID,
		ScanPhase:       result.ScanPhase,
		Summary:         result.Summary,
		Vulnerabilities: result.Vulnerabilities,
		Error:           result.Error,
		Duration:        result.Duration,
		ScannerVersion:  result.ScannerVersion,
		HasReport:       result.HasReport,
		Insights:        vuln.BuildScanInsights(vulns, intel, imageExposure(usage, usageOK, result.ImageID)),
	}, nil
}

// GetScanSummary retrieves just the summary for an image (for list views)
func (s *Service) GetScanSummary(ctx context.Context, imageID string) (*vulnerability.ScanSummary, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return nil, nil
	}

	var record scanSummaryRow
	err := s.db.WithContext(ctx).
		Table(scansTable).
		Select("id", "scan_time", "status", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "total_count", "error").
		Where("id = ?", imageID).
		First(&record).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to get scan summary: %w", err)
	}

	summary := &vulnerability.ScanSummary{
		ImageID:  record.ID,
		ScanTime: record.ScanTime,
		Status:   vulnerability.ScanStatus(record.Status),
		Summary: &vulnerability.SeveritySummary{
			Critical: record.CriticalCount,
			High:     record.HighCount,
			Medium:   record.MediumCount,
			Low:      record.LowCount,
			Unknown:  record.UnknownCount,
			Total:    record.TotalCount,
		},
		Error: mo.PointerToOption(record.Error).OrEmpty(),
	}
	s.refreshSummary(ctx, summary)

	return summary, nil
}

// ListVulnerabilities returns a paginated, filtered list of vulnerabilities for an image.
func (s *Service) ListVulnerabilities(ctx context.Context, imageID string, params pagination.QueryParams) ([]vulnerability.Vulnerability, pagination.Response, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return nil, pagination.Response{}, common.ErrVulnerabilityScanNotFound
	}
	result, err := s.loadResult(ctx, imageID)
	if err != nil {
		return nil, pagination.Response{}, fmt.Errorf("failed to get scan result: %w", err)
	}
	if result == nil {
		return nil, pagination.Response{}, common.ErrVulnerabilityScanNotFound
	}

	paginationConfig := pagination.Config[vulnerability.Vulnerability]{
		SearchAccessors: []pagination.SearchAccessor[vulnerability.Vulnerability]{
			func(item vulnerability.Vulnerability) (string, error) { return item.VulnerabilityID, nil },
			func(item vulnerability.Vulnerability) (string, error) { return item.PkgName, nil },
			func(item vulnerability.Vulnerability) (string, error) { return item.InstalledVersion, nil },
			func(item vulnerability.Vulnerability) (string, error) { return item.FixedVersion, nil },
			func(item vulnerability.Vulnerability) (string, error) { return item.Title, nil },
		},
		SortBindings: []pagination.SortBinding[vulnerability.Vulnerability]{
			{
				Key: "vulnerabilityId",
				Fn: func(a, b vulnerability.Vulnerability) int {
					return strings.Compare(a.VulnerabilityID, b.VulnerabilityID)
				},
			},
			{
				Key: "pkgName",
				Fn:  func(a, b vulnerability.Vulnerability) int { return strings.Compare(a.PkgName, b.PkgName) },
			},
			{
				Key: "severity",
				Fn: func(a, b vulnerability.Vulnerability) int {
					return vuln.SeverityRank(a.Severity) - vuln.SeverityRank(b.Severity)
				},
			},
			{
				Key: "installedVersion",
				Fn: func(a, b vulnerability.Vulnerability) int {
					return strings.Compare(a.InstalledVersion, b.InstalledVersion)
				},
			},
			{
				Key: "fixedVersion",
				Fn:  func(a, b vulnerability.Vulnerability) int { return strings.Compare(a.FixedVersion, b.FixedVersion) },
			},
		},
		FilterAccessors: []pagination.FilterAccessor[vulnerability.Vulnerability]{
			{
				Key: "severity",
				Fn: func(item vulnerability.Vulnerability, value string) bool {
					return strings.EqualFold(string(item.Severity), value)
				},
			},
		},
	}

	filtered := paginationConfig.SearchOrderAndPaginate(result.Vulnerabilities, params)
	return filtered.Items, pagination.BuildResponse(filtered.TotalCount, filtered.TotalAvailable, params), nil
}

// GetEnvironmentSummary returns aggregated vulnerability counts across all images.
func (s *Service) GetEnvironmentSummary(ctx context.Context) (*vulnerability.EnvironmentVulnerabilitySummary, error) {
	images, counts, imagesErr := s.dockerService.GetAllImages(ctx)
	if imagesErr != nil {
		slog.WarnContext(ctx, "failed to list images for vulnerability summary", "error", imagesErr)
	}
	currentImageIDs := make([]string, 0, len(images))
	for i := range images {
		currentImageIDs = append(currentImageIDs, images[i].ID)
	}

	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return &vulnerability.EnvironmentVulnerabilitySummary{
			TotalImages: kit.Ternary(imagesErr == nil, counts.Total, 0),
			Summary:     &vulnerability.SeveritySummary{},
		}, nil
	}

	type aggregate struct {
		Critical int `gorm:"column:critical"`
		High     int `gorm:"column:high"`
		Medium   int `gorm:"column:medium"`
		Low      int `gorm:"column:low"`
		Unknown  int `gorm:"column:unknown"`
		Total    int `gorm:"column:total"`
		Scanned  int `gorm:"column:scanned"`
	}

	var agg aggregate
	aggQuery := s.db.WithContext(ctx).
		Table(scansTable).
		Select(
			"COALESCE(SUM(critical_count), 0) AS critical",
			"COALESCE(SUM(high_count), 0) AS high",
			"COALESCE(SUM(medium_count), 0) AS medium",
			"COALESCE(SUM(low_count), 0) AS low",
			"COALESCE(SUM(unknown_count), 0) AS unknown",
			"COALESCE(SUM(total_count), 0) AS total",
			"COUNT(*) AS scanned",
		).
		Where("status = ?", string(vulnerability.ScanStatusCompleted))
	if imagesErr == nil {
		aggQuery = aggQuery.Where("id IN ?", currentImageIDs)
	}
	err := aggQuery.Scan(&agg).Error
	if err != nil {
		return nil, fmt.Errorf("failed to aggregate vulnerability summary: %w", err)
	}

	return &vulnerability.EnvironmentVulnerabilitySummary{
		TotalImages:   kit.Ternary(imagesErr == nil, counts.Total, 0),
		ScannedImages: agg.Scanned,
		Summary: &vulnerability.SeveritySummary{
			Critical: agg.Critical,
			High:     agg.High,
			Medium:   agg.Medium,
			Low:      agg.Low,
			Unknown:  agg.Unknown,
			Total:    agg.Total,
		},
	}, nil
}

// currentImageIDs lists daemon image IDs so queries skip scans of images removed outside Arcane; ok is false when the daemon could not be listed.
func (s *Service) currentImageIDs(ctx context.Context) (ids []string, ok bool) {
	images, err := s.dockerService.ListImages(ctx)
	if err != nil {
		slog.WarnContext(ctx, "failed to list images for vulnerability query", "error", err)
		return nil, false
	}
	ids = make([]string, 0, len(images))
	for i := range images {
		ids = append(ids, images[i].ID)
	}
	return ids, true
}

// ActionableCountExcludingIgnored counts critical and high severity vulnerabilities
// across all completed scans, excluding any that have been ignored. This is used by the dashboard
// to show an accurate action item count that reflects ignore decisions.
//
// Without ignore records the count comes from the indexed critical_count/
// high_count columns; with ignore records it is a single COUNT over the
// per-CVE item rows.
func (s *Service) ActionableCountExcludingIgnored(ctx context.Context) (int, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return 0, nil
	}

	var ignoreCount int64
	if err := s.db.WithContext(ctx).Table("vulnerability_ignores").Count(&ignoreCount).Error; err != nil {
		return 0, fmt.Errorf("failed to count ignore records: %w", err)
	}
	currentImageIDs, haveCurrentImages := s.currentImageIDs(ctx)

	if ignoreCount == 0 {
		var indexedCount int64
		sumQuery := s.db.WithContext(ctx).
			Table(scansTable).
			Select("COALESCE(SUM(critical_count + high_count), 0)").
			Where("status = ?", string(vulnerability.ScanStatusCompleted))
		if haveCurrentImages {
			sumQuery = sumQuery.Where("id IN ?", currentImageIDs)
		}
		if err := sumQuery.Scan(&indexedCount).Error; err != nil {
			return 0, fmt.Errorf("failed to sum vulnerability counts: %w", err)
		}
		return int(indexedCount), nil
	}

	countQuery := s.db.WithContext(ctx).
		Table(scanItemsTable).
		Joins("JOIN vulnerability_scans ON vulnerability_scans.id = vulnerability_scan_items.image_id AND vulnerability_scans.status = ?", string(vulnerability.ScanStatusCompleted)).
		Where("vulnerability_scan_items.severity IN ?", []string{string(vulnerability.SeverityCritical), string(vulnerability.SeverityHigh)})
	if haveCurrentImages {
		countQuery = countQuery.Where("vulnerability_scan_items.image_id IN ?", currentImageIDs)
	}
	var count int64
	err := countQuery.Where(
		"NOT EXISTS (SELECT 1 FROM vulnerability_ignores WHERE vulnerability_ignores.image_id = " +
			"vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = " +
			"vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = " +
			"vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = " +
			"vulnerability_scan_items.installed_version)",
	).
		Count(&count).Error
	if err != nil {
		return 0, fmt.Errorf("failed to count actionable vulnerabilities: %w", err)
	}
	return int(count), nil
}

type vulnerabilityScanItemRow struct {
	ImageID          string  `gorm:"column:image_id"`
	VulnerabilityID  string  `gorm:"column:vulnerability_id"`
	PkgName          string  `gorm:"column:pkg_name"`
	InstalledVersion string  `gorm:"column:installed_version"`
	FixedVersion     string  `gorm:"column:fixed_version"`
	Severity         string  `gorm:"column:severity"`
	PkgClass         string  `gorm:"column:pkg_class"`
	PkgType          string  `gorm:"column:pkg_type"`
	Title            string  `gorm:"column:title"`
	Details          *string `gorm:"column:details"`
	ImageName        string  `gorm:"column:image_name"`
	IgnoreID         string  `gorm:"column:ignore_id"`
}

var listAllVulnerabilitySortColumns = map[string]string{
	"vulnerabilityId":  "vulnerability_scan_items.vulnerability_id",
	"pkgName":          "vulnerability_scan_items.pkg_name",
	"severity":         "vulnerability_scan_items.severity_rank",
	"installedVersion": "vulnerability_scan_items.installed_version",
	"fixedVersion":     "vulnerability_scan_items.fixed_version",
	"imageName":        "vulnerability_scans.image_name",
}

// scanItemsQuery joins scan items to completed scans and their ignore records, keeping ignored or active rows for the given images.
func scanItemsQuery(ctx context.Context, db *gorm.DB, envID string, onlyIgnored bool, imageIDs mo.Option[[]string]) *gorm.DB {
	query := db.WithContext(ctx).
		Table(scanItemsTable).
		Joins("JOIN vulnerability_scans ON vulnerability_scans.id = vulnerability_scan_items.image_id AND vulnerability_scans.status = ?", string(vulnerability.ScanStatusCompleted)).
		Joins(
			"LEFT JOIN vulnerability_ignores ON vulnerability_ignores.environment_id = ? AND "+
				"vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND "+
				"vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND "+
				"vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND "+
				"vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version",
			envID,
		)
	if onlyIgnored {
		query = query.Where("vulnerability_ignores.id IS NOT NULL")
	} else {
		query = query.Where("vulnerability_ignores.id IS NULL")
	}
	if ids, ok := imageIDs.Get(); ok {
		query = query.Where("vulnerability_scan_items.image_id IN ?", ids)
	}
	return query
}

// listAllVulnerabilitiesQuery returns the base query used for counts and the filtered, ordered query on db; it clears params.Sort once ordering is applied.
func (s *Service) listAllVulnerabilitiesQuery(ctx context.Context, db *gorm.DB, envID string, params *pagination.QueryParams) (*gorm.DB, *gorm.DB) {
	// "ignored" flips the list from active to ignored vulnerabilities, the same
	// way the projects list swaps to archived projects.
	onlyIgnored := params.Filters["ignored"] == "true"
	delete(params.Filters, "ignored")

	countQuery := scanItemsQuery(ctx, db, envID, onlyIgnored, mo.TupleToOption(s.currentImageIDs(ctx))).
		Select("vulnerability_scan_items.*", "vulnerability_scans.image_name AS image_name", "COALESCE(vulnerability_ignores.id, '') AS ignore_id").
		Session(&gorm.Session{})

	q := pagination.ApplyFilter(countQuery, "vulnerability_scan_items.severity", strings.ToUpper(params.Filters["severity"]))
	if params.Filters["fixAvailable"] == "true" {
		q = q.Where("vulnerability_scan_items.fixed_version <> ''")
	}
	if imageNameParts := kit.TrimNonEmpty(strings.Split(params.Filters["imageName"], ",")); len(imageNameParts) > 0 {
		clauses := make([]string, 0, len(imageNameParts))
		args := make([]any, 0, len(imageNameParts))
		for _, part := range imageNameParts {
			clauses = append(clauses, "LOWER(vulnerability_scans.image_name) LIKE ?")
			args = append(args, "%"+strings.ToLower(part)+"%")
		}
		q = q.Where("("+strings.Join(clauses, " OR ")+")", args...)
	}
	q = pagination.ApplyLikeSearch(q, strings.ToLower(params.Search),
		"(LOWER(vulnerability_scan_items.vulnerability_id) LIKE ? OR "+
			"LOWER(vulnerability_scan_items.pkg_name) LIKE ? OR "+
			"LOWER(vulnerability_scan_items.installed_version) LIKE ? OR "+
			"LOWER(vulnerability_scan_items.fixed_version) LIKE ? OR LOWER(vulnerability_scan_items.title) LIKE "+
			"? OR LOWER(vulnerability_scans.image_name) LIKE ? OR LOWER(vulnerability_scan_items.image_id) LIKE "+
			"?)")
	if col, ok := listAllVulnerabilitySortColumns[params.Sort]; ok {
		q = q.Order(clause.OrderByColumn{Column: clause.Column{Name: col, Raw: true}, Desc: strings.EqualFold(string(params.Order), "desc")})
	}
	*params = pagination.QueryParams{
		Search:    params.Search,
		Order:     params.Order,
		Start:     params.Start,
		Limit:     params.Limit,
		SkipCount: params.SkipCount,
		Filters:   params.Filters,
	}

	return countQuery, q
}

// ListAllVulnerabilities returns a paginated list of vulnerabilities across all scanned images.
func (s *Service) ListAllVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.VulnerabilityWithImage, pagination.Response, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return []vulnerability.VulnerabilityWithImage{}, pagination.BuildResponse(0, 0, params), nil
	}

	countQuery, q := s.listAllVulnerabilitiesQuery(ctx, s.db.DB, envID, &params)

	var totalAvailable int64
	if err := countQuery.Count(&totalAvailable).Error; err != nil {
		return nil, pagination.Response{}, fmt.Errorf("failed to count vulnerabilities: %w", err)
	}

	var rows []vulnerabilityScanItemRow
	response, err := pagination.PaginateAndSortDB(params, q, &rows)
	if err != nil {
		return nil, pagination.Response{}, fmt.Errorf("failed to list vulnerabilities: %w", err)
	}

	items := make([]vulnerability.VulnerabilityWithImage, 0, len(rows))
	for i := range rows {
		row := &rows[i]
		details := func() vulnerability.Vulnerability {
			var decoded vulnerability.Vulnerability
			if kit.FromPtr(row.Details) == "" || json.Unmarshal([]byte(*row.Details), &decoded) != nil {
				return vulnerability.Vulnerability{}
			}
			return decoded
		}()
		items = append(items, vulnerability.VulnerabilityWithImage{
			VulnerabilityID:  row.VulnerabilityID,
			PkgName:          row.PkgName,
			InstalledVersion: row.InstalledVersion,
			FixedVersion:     row.FixedVersion,
			Severity:         vulnerability.Severity(row.Severity),
			Class:            row.PkgClass,
			Type:             row.PkgType,
			Title:            row.Title,
			Description:      details.Description,
			References:       details.References,
			CVSS:             details.CVSS,
			PublishedDate:    details.PublishedDate,
			LastModifiedDate: details.LastModifiedDate,
			Ignored:          row.IgnoreID != "",
			IgnoreID:         row.IgnoreID,
			ImageID:          row.ImageID,
			ImageName:        row.ImageName,
		})
	}

	return items, pagination.Response{ //exhaustruct:enforce
		TotalPages:      response.TotalPages,
		TotalItems:      response.TotalItems,
		CurrentPage:     response.CurrentPage,
		ItemsPerPage:    response.ItemsPerPage,
		GrandTotalItems: totalAvailable,
	}, nil
}

func (s *Service) AggregateVulnerabilities(ctx context.Context, params pagination.QueryParams) (base.Paginated[vulnerability.VulnerabilityWithImage], error) {
	collection, err := httpx.CollectEnvironments[base.Paginated[vulnerability.VulnerabilityWithImage]](ctx, url.Values{"start": {"0"}, "limit": {"-1"}})
	if err != nil {
		return base.Paginated[vulnerability.VulnerabilityWithImage]{}, fmt.Errorf("collect environment vulnerabilities: %w", err)
	}
	pages := make([]pagination.EnvironmentPage[vulnerability.VulnerabilityWithImage], 0, len(collection.Results))
	for _, result := range collection.Results {
		pages = append(pages, pagination.EnvironmentPage[vulnerability.VulnerabilityWithImage]{
			Environment:    result.Environment,
			Items:          result.Value.Data,
			TotalAvailable: cmp.Or(result.Value.Pagination.GrandTotalItems, result.Value.Pagination.TotalItems),
		})
	}
	items, resp := pagination.MergeEnvironmentPages(pagination.Config[vulnerability.VulnerabilityWithImage]{
		SortBindings: []pagination.SortBinding[vulnerability.VulnerabilityWithImage]{
			{Key: "imageId", Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
				return cmp.Or(
					strings.Compare(a.ImageName, b.ImageName),
					strings.Compare(a.ImageID, b.ImageID),
					strings.Compare(a.PkgName, b.PkgName),
					strings.Compare(a.InstalledVersion, b.InstalledVersion),
					strings.Compare(a.VulnerabilityID, b.VulnerabilityID),
				)
			}},
			{Key: "vulnerabilityId", Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
				return strings.Compare(a.VulnerabilityID, b.VulnerabilityID)
			}},
			{Key: "pkgName", Fn: func(a, b vulnerability.VulnerabilityWithImage) int { return strings.Compare(a.PkgName, b.PkgName) }},
			{Key: "severity", Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
				return cmp.Compare(vuln.SeverityRank(a.Severity), vuln.SeverityRank(b.Severity))
			}},
			{Key: "installedVersion", Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
				return strings.Compare(a.InstalledVersion, b.InstalledVersion)
			}},
			{Key: "fixedVersion", Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
				return strings.Compare(a.FixedVersion, b.FixedVersion)
			}},
			{Key: "imageName", Fn: func(a, b vulnerability.VulnerabilityWithImage) int { return strings.Compare(a.ImageName, b.ImageName) }},
		},
	}, pages, params)
	return base.Paginated[vulnerability.VulnerabilityWithImage]{
		Success:            true,
		Data:               items,
		Pagination:         handlerutil.PaginationResponse(resp),
		FailedEnvironments: collection.Failures,
	}, nil
}

// ExportVulnerabilities opens a cursor over every vulnerability matching params and yields rows one at a time in the requested order.
func (s *Service) ExportVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) (iter.Seq2[vulnerability.VulnerabilityWithImage, error], error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return func(func(vulnerability.VulnerabilityWithImage, error) bool) {}, nil
	}

	_, q := s.listAllVulnerabilitiesQuery(ctx, s.db.DB, envID, &params)
	rows, err := q.Rows()
	if err != nil {
		return nil, fmt.Errorf("failed to export vulnerabilities: %w", err)
	}

	return func(yield func(vulnerability.VulnerabilityWithImage, error) bool) {
		defer func() {
			if closeErr := rows.Close(); closeErr != nil {
				slog.WarnContext(ctx, "failed to close vulnerability export cursor", "error", closeErr)
			}
		}()

		for rows.Next() {
			var row vulnerabilityScanItemRow
			if scanRowsErr := q.ScanRows(rows, &row); scanRowsErr != nil {
				yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", scanRowsErr))
				return
			}
			item := vulnerability.VulnerabilityWithImage{
				VulnerabilityID:  row.VulnerabilityID,
				PkgName:          row.PkgName,
				InstalledVersion: row.InstalledVersion,
				FixedVersion:     row.FixedVersion,
				Severity:         vulnerability.Severity(row.Severity),
				Class:            row.PkgClass,
				Type:             row.PkgType,
				Title:            row.Title,
				Ignored:          row.IgnoreID != "",
				IgnoreID:         row.IgnoreID,
				ImageID:          row.ImageID,
				ImageName:        row.ImageName,
			}
			if !yield(item, nil) {
				return
			}
		}
		if iterateExportRowsErr := rows.Err(); iterateExportRowsErr != nil {
			yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", iterateExportRowsErr))
		}
	}, nil
}

const (
	threatIntelSettingKey     = "vulnerabilityThreatIntelEnabled"
	highEPSSThreshold         = 0.1
	riskTrendDays             = 90
	riskDeltaDays             = 7
	riskDeltaToleranceDays    = 3
	riskSnapshotRetentionDays = 400
	riskiestImageLimit        = 5
	topFindingLimit           = 10
	riskDateLayout            = "2006-01-02"
)

// ListAllVulnerabilityImageOptions returns unique image names (or image IDs when name is empty)
// for vulnerability filtering, optionally constrained by severity.
func (s *Service) ListAllVulnerabilityImageOptions(ctx context.Context, severityFilter string) ([]string, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return []string{}, nil
	}

	query := s.db.WithContext(ctx).
		Table(scansTable).
		Select("id", "image_name").
		Where("status = ?", string(vulnerability.ScanStatusCompleted)).
		Where("total_count > 0")
	if currentImageIDs, ok := s.currentImageIDs(ctx); ok {
		query = query.Where("id IN ?", currentImageIDs)
	}

	if strings.TrimSpace(severityFilter) != "" {
		filtered, hasPossibleMatches := applyListAllVulnerabilityRecordPrefilters(query, map[string]string{
			"severity": severityFilter,
		}).Get()
		if !hasPossibleMatches {
			return []string{}, nil
		}
		query = filtered
	}

	var records []scanImageRow
	if err := query.Find(&records).Error; err != nil {
		return nil, fmt.Errorf("failed to list vulnerability image options: %w", err)
	}

	options := make([]string, 0, len(records))
	for _, record := range records {
		options = append(options, cmp.Or(record.ImageName, record.ID))
	}
	options = kit.Unique(kit.TrimNonEmpty(options))
	sort.Strings(options)
	return options, nil
}

func (s *Service) AggregateImageOptions(ctx context.Context) (base.ApiResponse[[]string], error) {
	collection, err := httpx.CollectEnvironments[base.ApiResponse[[]string]](ctx, nil)
	if err != nil {
		return base.ApiResponse[[]string]{}, fmt.Errorf("collect environment vulnerability image options: %w", err)
	}
	options := make([]string, 0)
	for _, result := range collection.Results {
		options = append(options, result.Value.Data...)
	}
	slices.Sort(options)
	return base.ApiResponse[[]string]{
		Success:            true,
		Data:               slices.Compact(options),
		FailedEnvironments: collection.Failures,
	}, nil
}

// GetScanSummariesByImageIDs retrieves scan summaries for multiple images
func (s *Service) GetScanSummariesByImageIDs(ctx context.Context, imageIDs []string) (map[string]*vulnerability.ScanSummary, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || len(imageIDs) == 0 {
		return make(map[string]*vulnerability.ScanSummary), nil
	}

	var records []scanSummaryRow
	err := s.db.WithContext(ctx).
		Table(scansTable).
		Select("id", "scan_time", "status", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "total_count", "error").
		Where("id IN ?", imageIDs).
		Find(&records).Error
	if err != nil {
		return nil, fmt.Errorf("failed to get scan summaries: %w", err)
	}

	result := make(map[string]*vulnerability.ScanSummary, len(records))
	for _, record := range records {
		result[record.ID] = &vulnerability.ScanSummary{
			ImageID:  record.ID,
			ScanTime: record.ScanTime,
			Status:   vulnerability.ScanStatus(record.Status),
			Summary: &vulnerability.SeveritySummary{
				Critical: record.CriticalCount,
				High:     record.HighCount,
				Medium:   record.MediumCount,
				Low:      record.LowCount,
				Unknown:  record.UnknownCount,
				Total:    record.TotalCount,
			},
			Error: kit.FromPtr(record.Error),
		}
		s.refreshSummary(ctx, result[record.ID])
	}

	return result, nil
}

type imageUsage struct {
	running int
	stopped int
}

// containerUsage counts running and stopped containers per image ID; ok is false when the daemon could not be listed.
func (s *Service) containerUsage(ctx context.Context) (map[string]imageUsage, bool) {
	containers, err := s.dockerService.ListContainers(ctx)
	if err != nil {
		slog.WarnContext(ctx, "failed to list containers for vulnerability risk", "error", err)
		return nil, false
	}
	usage := make(map[string]imageUsage, len(containers))
	for i := range containers {
		entry := usage[containers[i].ImageID]
		switch containers[i].State {
		case container.StateRunning, container.StatePaused, container.StateRestarting:
			entry.running++
		case container.StateCreated, container.StateRemoving, container.StateExited, container.StateDead:
			entry.stopped++
		default:
			entry.stopped++
		}
		usage[containers[i].ImageID] = entry
	}
	return usage, true
}

func imageExposure(usage map[string]imageUsage, ok bool, imageID string) vulnerability.ImageExposure {
	switch {
	case !ok:
		return vulnerability.ImageExposureUnknown
	case usage[imageID].running > 0:
		return vulnerability.ImageExposureRunning
	case usage[imageID].stopped > 0:
		return vulnerability.ImageExposureStopped
	default:
		return vulnerability.ImageExposureUnused
	}
}

type riskFindingRow struct {
	ImageID         string   `gorm:"column:image_id"`
	ImageName       string   `gorm:"column:image_name"`
	VulnerabilityID string   `gorm:"column:vulnerability_id"`
	PkgName         string   `gorm:"column:pkg_name"`
	FixedVersion    string   `gorm:"column:fixed_version"`
	Severity        string   `gorm:"column:severity"`
	Title           string   `gorm:"column:title"`
	CVSSScore       *float64 `gorm:"column:cvss_score"`
	KnownExploited  bool     `gorm:"column:known_exploited"`
	KEVRansomware   bool     `gorm:"column:kev_ransomware"`
	KEVDueDate      string   `gorm:"column:kev_due_date"`
	EPSSScore       *float64 `gorm:"column:epss_score"`
}

type riskImageAgg struct {
	image vulnerability.RiskImage
	score vuln.RiskScore
}

type riskFindingAgg struct {
	finding       vulnerability.RiskFinding
	images        map[string]struct{}
	runningImages map[string]struct{}
}

// riskAccumulator aggregates scored findings into environment, per-image and per-CVE totals.
type riskAccumulator struct {
	today           string
	scannedImageIDs []string
	exposures       map[string]vulnerability.ImageExposure
	images          map[string]*riskImageAgg
	findings        map[string]*riskFindingAgg
	summary         vulnerability.SeveritySummary
	exposure        vulnerability.RiskExposureBreakdown
	fixable         int
	scoreDriver     *vulnerability.RiskScoreDriver
	driverPriority  float64
}

func (a *riskAccumulator) add(row *riskFindingRow, exposure vulnerability.ImageExposure, runningContainers int) {
	severity := vulnerability.Severity(row.Severity)
	baseScore := vuln.BaseScore(*cmp.Or(row.CVSSScore, new(0.0)), severity)
	fixable := strings.TrimSpace(row.FixedVersion) != ""

	switch severity {
	case vulnerability.SeverityCritical:
		a.summary.Critical++
	case vulnerability.SeverityHigh:
		a.summary.High++
	case vulnerability.SeverityMedium:
		a.summary.Medium++
	case vulnerability.SeverityLow:
		a.summary.Low++
	case vulnerability.SeverityUnknown:
		a.summary.Unknown++
	default:
		a.summary.Unknown++
	}
	a.summary.Total++

	switch exposure {
	case vulnerability.ImageExposureRunning:
		a.exposure.Running++
	case vulnerability.ImageExposureStopped:
		a.exposure.Stopped++
	case vulnerability.ImageExposureUnused:
		a.exposure.Unused++
	case vulnerability.ImageExposureUnknown:
		a.exposure.Unknown++
	}

	img, ok := a.images[row.ImageID]
	if !ok {
		img = &riskImageAgg{
			image: vulnerability.RiskImage{
				ImageID:           row.ImageID,
				ImageName:         row.ImageName,
				Exposure:          exposure,
				RunningContainers: runningContainers,
			},
		}
		a.images[row.ImageID] = img
	}
	img.image.Findings++
	priority := img.score.AddFinding(row.VulnerabilityID, fixable, baseScore, vuln.ThreatIntel{KnownExploited: row.KnownExploited, EPSS: row.EPSSScore}, exposure)
	risk := priority / 10
	if severity == vulnerability.SeverityCritical {
		img.image.Critical++
	}
	if severity == vulnerability.SeverityHigh {
		img.image.High++
	}
	if row.KnownExploited {
		img.image.KnownExploited++
	}
	if fixable {
		img.image.Fixable++
		a.fixable++
	}
	if fixable && baseScore > 0 {
		a.considerDriver(row, exposure, priority)
	}

	agg, ok := a.findings[row.VulnerabilityID]
	if !ok {
		agg = &riskFindingAgg{
			finding: vulnerability.RiskFinding{
				VulnerabilityID: row.VulnerabilityID,
				KnownExploited:  row.KnownExploited,
				Ransomware:      row.KEVRansomware,
				KEVDueDate:      row.KEVDueDate,
				EPSS:            row.EPSSScore,
				Risk:            -1,
			},
			images:        map[string]struct{}{},
			runningImages: map[string]struct{}{},
		}
		a.findings[row.VulnerabilityID] = agg
	}
	agg.images[row.ImageID] = struct{}{}
	if exposure == vulnerability.ImageExposureRunning {
		agg.runningImages[row.ImageID] = struct{}{}
	}
	// The highest-priority instance of a CVE describes it; any fixed version beats none.
	better := risk > agg.finding.Risk
	*agg = riskFindingAgg{ //exhaustruct:enforce
		finding: vulnerability.RiskFinding{ //exhaustruct:enforce
			VulnerabilityID:       agg.finding.VulnerabilityID,
			PkgName:               kit.Ternary(better, row.PkgName, agg.finding.PkgName),
			Title:                 kit.Ternary(better, row.Title, agg.finding.Title),
			Severity:              kit.Ternary(better, severity, agg.finding.Severity),
			CVSS:                  kit.Ternary(better, baseScore, agg.finding.CVSS),
			Risk:                  kit.Ternary(better, risk, agg.finding.Risk),
			EPSS:                  agg.finding.EPSS,
			KnownExploited:        agg.finding.KnownExploited,
			Ransomware:            agg.finding.Ransomware,
			KEVDueDate:            agg.finding.KEVDueDate,
			ImagesAffected:        agg.finding.ImagesAffected,
			RunningImagesAffected: agg.finding.RunningImagesAffected,
			FixedVersion:          kit.Ternary(fixable && (better || agg.finding.FixedVersion == ""), row.FixedVersion, agg.finding.FixedVersion),
		},
		images:        agg.images,
		runningImages: agg.runningImages,
	}
}

// considerDriver keeps the highest-priority fixable occurrence so its package, image, fix and score match.
func (a *riskAccumulator) considerDriver(row *riskFindingRow, exposure vulnerability.ImageExposure, priority float64) {
	current := a.scoreDriver
	if current != nil {
		switch {
		case priority != a.driverPriority:
			if priority < a.driverPriority {
				return
			}
		case row.KnownExploited != current.KnownExploited:
			if !row.KnownExploited {
				return
			}
		default:
			if cmp.Or(strings.Compare(current.VulnerabilityID, row.VulnerabilityID), strings.Compare(current.ImageName, row.ImageName)) <= 0 {
				return
			}
		}
	}
	a.driverPriority = priority
	a.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,
	}
}

// finish derives the drivers and scores, and ranks findings and images.
func (a *riskAccumulator) finish(threatIntel vulnerability.ThreatIntelStatus, imagesTotal int) *vulnerability.RiskOverview {
	var knownExploited, overdueKnownExploited, highEPSS, exposedCriticalHigh int
	findings := make([]vulnerability.RiskFinding, 0, len(a.findings))
	for _, agg := range a.findings {
		if agg.finding.KnownExploited {
			knownExploited++
			if agg.finding.KEVDueDate != "" && agg.finding.KEVDueDate < a.today {
				overdueKnownExploited++
			}
		}
		if kit.FromPtr(agg.finding.EPSS) >= highEPSSThreshold {
			highEPSS++
		}
		if len(agg.runningImages) > 0 && (agg.finding.Severity == vulnerability.SeverityCritical || agg.finding.Severity == vulnerability.SeverityHigh) {
			exposedCriticalHigh++
		}
		findings = append(findings, vulnerability.RiskFinding{ //exhaustruct:enforce
			VulnerabilityID:       agg.finding.VulnerabilityID,
			PkgName:               agg.finding.PkgName,
			Title:                 agg.finding.Title,
			Severity:              agg.finding.Severity,
			CVSS:                  agg.finding.CVSS,
			Risk:                  agg.finding.Risk,
			EPSS:                  agg.finding.EPSS,
			KnownExploited:        agg.finding.KnownExploited,
			Ransomware:            agg.finding.Ransomware,
			KEVDueDate:            agg.finding.KEVDueDate,
			ImagesAffected:        len(agg.images),
			RunningImagesAffected: len(agg.runningImages),
			FixedVersion:          agg.finding.FixedVersion,
		})
	}

	byRisk := slices.Clone(findings)
	slices.SortFunc(byRisk, func(a, b vulnerability.RiskFinding) int {
		if a.Risk != b.Risk {
			return cmp.Compare(b.Risk, a.Risk)
		}
		if a.KnownExploited != b.KnownExploited {
			return kit.Ternary(b.KnownExploited, 1, -1)
		}
		return cmp.Or(
			cmp.Compare(b.RunningImagesAffected, a.RunningImagesAffected),
			cmp.Compare(*cmp.Or(b.EPSS, new(0.0)), *cmp.Or(a.EPSS, new(0.0))),
			strings.Compare(a.VulnerabilityID, b.VulnerabilityID),
		)
	})
	byPrevalence := slices.Clone(findings)
	slices.SortFunc(byPrevalence, func(a, b vulnerability.RiskFinding) int {
		return cmp.Or(
			cmp.Compare(b.ImagesAffected, a.ImagesAffected),
			cmp.Compare(b.RunningImagesAffected, a.RunningImagesAffected),
			cmp.Compare(b.Risk, a.Risk),
			strings.Compare(a.VulnerabilityID, b.VulnerabilityID),
		)
	})
	top := func(sorted []vulnerability.RiskFinding) []vulnerability.RiskFinding {
		out := make([]vulnerability.RiskFinding, 0, min(len(sorted), topFindingLimit))
		for _, finding := range sorted[:min(len(sorted), topFindingLimit)] {
			out = append(out, vulnerability.RiskFinding{ //exhaustruct:enforce
				VulnerabilityID:       finding.VulnerabilityID,
				PkgName:               finding.PkgName,
				Title:                 finding.Title,
				Severity:              finding.Severity,
				CVSS:                  finding.CVSS,
				Risk:                  math.Round(finding.Risk*10) / 10,
				EPSS:                  finding.EPSS,
				KnownExploited:        finding.KnownExploited,
				Ransomware:            finding.Ransomware,
				KEVDueDate:            finding.KEVDueDate,
				ImagesAffected:        finding.ImagesAffected,
				RunningImagesAffected: finding.RunningImagesAffected,
				FixedVersion:          finding.FixedVersion,
			})
		}
		return out
	}

	// Images average by exposure, clean ones at zero; unavailable images stay out.
	var environment vuln.RiskScore
	riskiestImages := make([]vulnerability.RiskImage, 0, len(a.images))
	for _, id := range a.scannedImageIDs {
		img, ok := a.images[id]
		if !ok {
			environment.AddImage(id, 0, vulnerability.ScoreStatusComplete, a.exposures[id], false)
			continue
		}
		score, priority := img.score.ImageScore()
		environment.AddImage(id, score, priority.ScoreStatus, img.image.Exposure, img.score.ExploitedRunning())
		riskiestImages = append(riskiestImages, vulnerability.RiskImage{ //exhaustruct:enforce
			PatchPriority:     priority,
			ImageID:           img.image.ImageID,
			ImageName:         img.image.ImageName,
			Exposure:          img.image.Exposure,
			RunningContainers: img.image.RunningContainers,
			KnownExploited:    img.image.KnownExploited,
			Critical:          img.image.Critical,
			High:              img.image.High,
			Fixable:           img.image.Fixable,
			Findings:          img.image.Findings,
		})
	}
	slices.SortFunc(riskiestImages, func(a, b vulnerability.RiskImage) int {
		return cmp.Or(
			cmp.Compare(b.RiskScore, a.RiskScore),
			cmp.Compare(b.KnownExploited, a.KnownExploited),
			cmp.Compare(b.Critical, a.Critical),
			strings.Compare(a.ImageName, b.ImageName),
		)
	})

	_, patchPriority := environment.EnvironmentScore()
	return &vulnerability.RiskOverview{ //exhaustruct:enforce
		PatchPriority: vulnerability.PatchPriority{
			RiskScore:   patchPriority.RiskScore,
			RiskBand:    patchPriority.RiskBand,
			ScoreStatus: kit.Ternary(environment.Scored() == 0, vulnerability.ScoreStatusUnavailable, patchPriority.ScoreStatus),
		},
		Delta7d: nil,
		Trend:   []vulnerability.RiskTrendPoint{},
		Drivers: vulnerability.RiskDrivers{ //exhaustruct:enforce
			KnownExploited:        knownExploited,
			OverdueKnownExploited: overdueKnownExploited,
			HighEPSS:              highEPSS,
			ExposedCriticalHigh:   exposedCriticalHigh,
			Fixable:               a.fixable,
			Findings:              a.summary.Total,
			ImagesScanned:         len(a.scannedImageIDs),
			ImagesTotal:           imagesTotal,
			ScoredImages:          environment.Scored(),
		},
		Drivers7dAgo:      nil,
		Summary:           a.summary,
		Exposure:          a.exposure,
		ScoreDriver:       a.scoreDriver,
		RiskiestImages:    riskiestImages[:min(len(riskiestImages), riskiestImageLimit)],
		RiskiestFindings:  top(byRisk),
		PrevalentFindings: top(byPrevalence),
		ThreatIntel:       threatIntel,
		ComputedAt:        time.Time{},
	}
}

// computeRisk scores every non-ignored finding of current images; the trend and deltas are left to callers.
func (s *Service) computeRisk(ctx context.Context, envID string) (*vulnerability.RiskOverview, error) {
	intelStatus := s.threatIntelStatus(ctx)
	usage, usageOK := s.containerUsage(ctx)
	imageIDs, imageIDsOK := s.currentImageIDs(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).Table(scansTable).Where("status = ?", string(vulnerability.ScanStatusCompleted))
	if imageIDsOK {
		scanQuery = scanQuery.Where("id IN ?", imageIDs)
	}
	var scannedIDs []string
	if err := scanQuery.Pluck("id", &scannedIDs).Error; err != nil {
		return nil, fmt.Errorf("failed to list scanned images: %w", err)
	}

	var rows []riskFindingRow
	err := scanItemsQuery(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",
			"vulnerability_scan_items.pkg_name", "vulnerability_scan_items.fixed_version", "vulnerability_scan_items.severity",
			"vulnerability_scan_items.title", "vulnerability_scan_items.cvss_score",
			"COALESCE(vulnerability_threat_intel.known_exploited, FALSE) AS known_exploited",
			"COALESCE(vulnerability_threat_intel.kev_ransomware, FALSE) AS kev_ransomware",
			"COALESCE(vulnerability_threat_intel.kev_due_date, '') AS kev_due_date",
			"vulnerability_threat_intel.epss_score",
		).
		Scan(&rows).Error
	if err != nil {
		return nil, fmt.Errorf("failed to load vulnerability risk findings: %w", err)
	}

	acc := &riskAccumulator{
		today:           s.riskNow().Format(riskDateLayout),
		scannedImageIDs: scannedIDs,
		exposures:       make(map[string]vulnerability.ImageExposure, len(scannedIDs)),
		images:          map[string]*riskImageAgg{},
		findings:        map[string]*riskFindingAgg{},
	}
	for _, id := range scannedIDs {
		acc.exposures[id] = imageExposure(usage, usageOK, id)
	}
	for _, row := range rows {
		if !intelStatus.Enabled {
			row = riskFindingRow{ //exhaustruct:enforce
				ImageID:         row.ImageID,
				ImageName:       row.ImageName,
				VulnerabilityID: row.VulnerabilityID,
				PkgName:         row.PkgName,
				FixedVersion:    row.FixedVersion,
				Severity:        row.Severity,
				Title:           row.Title,
				CVSSScore:       row.CVSSScore,
				KnownExploited:  false,
				KEVRansomware:   false,
				KEVDueDate:      "",
				EPSSScore:       nil,
			}
		}
		acc.add(&row, acc.exposures[row.ImageID], usage[row.ImageID].running)
	}

	return acc.finish(intelStatus, kit.Ternary(imageIDsOK, len(imageIDs), len(scannedIDs))), nil
}

// riskNow returns the current time in the configured timezone, which defines snapshot days.
func (s *Service) riskNow() time.Time {
	return time.Now().In(s.config.GetLocation())
}

// GetRiskOverview returns the environment patch priority with its trend, drivers, prioritized images and top findings.
// Concurrent callers share one build, and the result is reused briefly. Callers must not mutate it.
func (s *Service) GetRiskOverview(ctx context.Context, envID string) (*vulnerability.RiskOverview, error) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return nil, common.ErrFeatureDisabled
	}
	if overview, ok := s.cachedRiskOverview(envID); ok {
		return overview, nil
	}

	// Keying the build by generation keeps a request that follows an invalidation off an older build.
	gen := s.riskGen.Load()
	results := s.riskFlight.DoChan(envID+":"+strconv.FormatUint(gen, 10), func() (any, error) {
		// A caller that queued behind the winner finds the fresh entry here.
		if overview, ok := s.cachedRiskOverview(envID); ok {
			return overview, nil
		}
		buildCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), riskOverviewBuildTimeout)
		defer cancel()
		overview, buildErr := s.buildRiskOverview(buildCtx, envID)
		if buildErr != nil {
			return nil, buildErr
		}
		s.riskCache.Store(envID, &riskOverviewCacheEntry{
			overview: overview,
			builtAt:  time.Now(),
			gen:      gen,
		})
		return overview, nil
	})
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case result := <-results:
		if result.Err != nil {
			return nil, result.Err
		}
		overview, ok := result.Val.(*vulnerability.RiskOverview)
		if !ok {
			return nil, errors.New("risk overview cache returned unexpected type")
		}
		return overview, nil
	}
}

// InvalidateRiskOverview drops cached risk overviews. Call it after a scan or ignore change commits.
func (s *Service) InvalidateRiskOverview() {
	s.riskGen.Add(1)
}

func (s *Service) cachedRiskOverview(envID string) (*vulnerability.RiskOverview, bool) {
	value, ok := s.riskCache.Load(envID)
	if !ok {
		return nil, false
	}
	entry, ok := value.(*riskOverviewCacheEntry)
	if !ok || entry.gen != s.riskGen.Load() || time.Since(entry.builtAt) >= riskOverviewCacheTTL {
		return nil, false
	}
	return entry.overview, true
}

func (s *Service) buildRiskOverview(ctx context.Context, envID string) (*vulnerability.RiskOverview, error) {
	overview, err := s.computeRisk(ctx, envID)
	if err != nil {
		return nil, err
	}

	now := s.riskNow()
	today := now.Format(riskDateLayout)
	var snapshots []VulnerabilityRiskSnapshot
	if loadSnapshotsErr := s.db.WithContext(ctx).
		Where("scoring_version = ?", vuln.ScoringVersion).
		Where("snapshot_date >= ?", now.AddDate(0, 0, -(riskTrendDays-1)).Format(riskDateLayout)).
		Order("snapshot_date ASC").
		Find(&snapshots).Error; loadSnapshotsErr != nil {
		return nil, fmt.Errorf("failed to load risk snapshots: %w", loadSnapshotsErr)
	}

	deltaDay := now.AddDate(0, 0, -riskDeltaDays).Format(riskDateLayout)
	deltaFloor := now.AddDate(0, 0, -(riskDeltaDays + riskDeltaToleranceDays)).Format(riskDateLayout)
	trend := overview.Trend
	delta7d, drivers7dAgo := overview.Delta7d, overview.Drivers7dAgo
	for i := range snapshots {
		snap := &snapshots[i]
		if snap.SnapshotDate == today {
			continue
		}
		trend = append(trend, vulnerability.RiskTrendPoint{Date: snap.SnapshotDate, RiskScore: snap.RiskScore})
		if snap.SnapshotDate <= deltaDay && snap.SnapshotDate >= deltaFloor {
			delta7d = new(overview.RiskScore - snap.RiskScore)
			drivers7dAgo = &vulnerability.RiskDrivers{
				KnownExploited:        snap.KnownExploitedCount,
				OverdueKnownExploited: snap.OverdueKnownExploitedCount,
				HighEPSS:              snap.HighEPSSCount,
				ExposedCriticalHigh:   snap.ExposedCriticalHighCount,
				Fixable:               snap.FixableCount,
				Findings:              snap.FindingsCount,
				ImagesScanned:         snap.ImagesScanned,
				ImagesTotal:           snap.ImagesTotal,
				ScoredImages:          snap.ScoredImages,
			}
		}
	}

	return &vulnerability.RiskOverview{ //exhaustruct:enforce
		PatchPriority:     overview.PatchPriority,
		Delta7d:           delta7d,
		Trend:             append(trend, vulnerability.RiskTrendPoint{Date: today, RiskScore: overview.RiskScore}),
		Drivers:           overview.Drivers,
		Drivers7dAgo:      drivers7dAgo,
		Summary:           overview.Summary,
		Exposure:          overview.Exposure,
		ScoreDriver:       overview.ScoreDriver,
		RiskiestImages:    overview.RiskiestImages,
		RiskiestFindings:  overview.RiskiestFindings,
		PrevalentFindings: overview.PrevalentFindings,
		ThreatIntel:       overview.ThreatIntel,
		ComputedAt:        time.Now(),
	}, nil
}

var vulnerabilityCSVHeader = []string{"CVE", "Severity", "Package", "Installed Version", "Fixed Version", "Image", "Ignored"}

// WriteVulnerabilitiesCSV streams items to w as a BOM-prefixed, CRLF-terminated CSV with formula-safe cells.
func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.VulnerabilityWithImage, error]) error {
	if _, err := io.WriteString(w, "\xEF\xBB\xBF"); err != nil {
		return fmt.Errorf("failed to write csv: %w", err)
	}
	writer := csv.NewWriter(w)
	writer.UseCRLF = true // keep: csv.Writer carries unexported state that only csv.NewWriter can build
	if err := writer.Write(vulnerabilityCSVHeader); err != nil {
		return fmt.Errorf("failed to write csv: %w", err)
	}
	for item, err := range items {
		if err != nil {
			return err
		}
		image := cmp.Or(item.ImageName, item.ImageID)
		record := []string{item.VulnerabilityID, string(item.Severity), item.PkgName, item.InstalledVersion, item.FixedVersion, image, strconv.FormatBool(item.Ignored)}
		for j, value := range record {
			record[j] = kit.Ternary(value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])), "'"+value, value)
		}
		if writeErr := writer.Write(record); writeErr != nil {
			return fmt.Errorf("failed to write csv: %w", writeErr)
		}
	}
	writer.Flush()
	if err := writer.Error(); err != nil {
		return fmt.Errorf("failed to write csv: %w", err)
	}
	return nil
}

// RecordRiskSnapshot upserts today's environment risk snapshot and prunes snapshots past retention.
func (s *Service) RecordRiskSnapshot(ctx context.Context) error {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return nil
	}
	overview, err := s.computeRisk(ctx, types.LocalDockerEnvironmentID)
	if err != nil {
		return err
	}

	now := s.riskNow()
	snapshot := VulnerabilityRiskSnapshot{
		SnapshotDate:               now.Format(riskDateLayout),
		ScoringVersion:             vuln.ScoringVersion,
		RiskScore:                  overview.RiskScore,
		RiskBand:                   string(overview.RiskBand),
		CriticalCount:              overview.Summary.Critical,
		HighCount:                  overview.Summary.High,
		MediumCount:                overview.Summary.Medium,
		LowCount:                   overview.Summary.Low,
		UnknownCount:               overview.Summary.Unknown,
		FindingsCount:              overview.Drivers.Findings,
		KnownExploitedCount:        overview.Drivers.KnownExploited,
		OverdueKnownExploitedCount: overview.Drivers.OverdueKnownExploited,
		HighEPSSCount:              overview.Drivers.HighEPSS,
		ExposedCriticalHighCount:   overview.Drivers.ExposedCriticalHigh,
		FixableCount:               overview.Drivers.Fixable,
		ImagesScanned:              overview.Drivers.ImagesScanned,
		ImagesTotal:                overview.Drivers.ImagesTotal,
		ScoredImages:               overview.Drivers.ScoredImages,
		UpdatedAt:                  &now,
	}
	return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
		if storeSnapshotErr := tx.Clauses(clause.OnConflict{
			Columns: []clause.Column{{Name: "snapshot_date"}},
			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; storeSnapshotErr != nil {
			return fmt.Errorf("failed to store risk snapshot: %w", storeSnapshotErr)
		}
		if pruneSnapshotsErr := tx.Where("snapshot_date < ?", now.AddDate(0, 0, -riskSnapshotRetentionDays).Format(riskDateLayout)).
			Delete(&VulnerabilityRiskSnapshot{}).Error; pruneSnapshotsErr != nil {
			return fmt.Errorf("failed to prune risk snapshots: %w", pruneSnapshotsErr)
		}
		return nil
	})
}

// ActiveItemsQuery returns the filtered, ordered finding query the list and
// export use, so bulk ignore operations act on exactly the listed findings.
func (s *Service) ActiveItemsQuery(ctx context.Context, db *gorm.DB, envID string, params *pagination.QueryParams) *gorm.DB {
	_, q := s.listAllVulnerabilitiesQuery(ctx, db, envID, params)
	return q
}

func severityCountColumnsForFilter(value string) []string {
	parts := kit.TrimNonEmpty(strings.Split(value, ","))
	if len(parts) == 0 {
		return nil
	}

	columns := make([]string, 0, len(parts))
	for _, part := range parts {
		var col string
		switch {
		case strings.EqualFold(part, string(vulnerability.SeverityCritical)):
			col = "critical_count"
		case strings.EqualFold(part, string(vulnerability.SeverityHigh)):
			col = "high_count"
		case strings.EqualFold(part, string(vulnerability.SeverityMedium)):
			col = "medium_count"
		case strings.EqualFold(part, string(vulnerability.SeverityLow)):
			col = "low_count"
		case strings.EqualFold(part, string(vulnerability.SeverityUnknown)):
			col = "unknown_count"
		default:
			continue
		}

		columns = append(columns, col)
	}

	return kit.Unique(columns)
}

func applyListAllVulnerabilityRecordPrefilters(query *gorm.DB, filters map[string]string) mo.Option[*gorm.DB] {
	if query == nil || len(filters) == 0 {
		return mo.Some(query)
	}

	if severityFilter, ok := filters["severity"]; ok {
		severityColumns := severityCountColumnsForFilter(severityFilter)
		if len(severityColumns) == 0 {
			return mo.None[*gorm.DB]()
		}

		parts := make([]string, 0, len(severityColumns))
		args := make([]any, 0, len(severityColumns))
		for _, col := range severityColumns {
			parts = append(parts, col+" > ?")
			args = append(args, 0)
		}
		query = query.Where("("+strings.Join(parts, " OR ")+")", args...)
	}

	if imageNameFilter, ok := filters["imageName"]; ok {
		imageNameParts := kit.TrimNonEmpty(strings.Split(imageNameFilter, ","))
		if len(imageNameParts) == 0 {
			return mo.None[*gorm.DB]()
		}

		clauses := make([]string, 0, len(imageNameParts))
		args := make([]any, 0, len(imageNameParts))
		for _, part := range imageNameParts {
			clauses = append(clauses, "LOWER(image_name) LIKE ?")
			args = append(args, "%"+strings.ToLower(part)+"%")
		}
		query = query.Where("("+strings.Join(clauses, " OR ")+")", args...)
	}

	return mo.Some(query)
}