Skip to content

Modern Docker Management, Designed for Everyone

29.3 KB
Raw Blame
package scan

import (
	"cmp"
	"context"
	"errors"
	"fmt"
	"log/slog"
	"maps"
	"slices"
	"strings"
	"sync"
	"time"

	activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
	"github.com/getarcaneapp/arcane/types/v2/features"
	usertypes "github.com/getarcaneapp/arcane/types/v2/user"
	"github.com/getarcaneapp/arcane/types/v2/vulnerability"
	"github.com/moby/moby/api/types/registry"
	"github.com/moby/moby/client"
	"github.com/samber/mo"
	kit "go.getarcane.app/kit/pkg"

	"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
	"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/event"
	"github.com/getarcaneapp/arcane/backend/v2/internal/kv"
	"github.com/getarcaneapp/arcane/backend/v2/internal/notification"
	"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
	"github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability/children/scan/children/trivy"
	activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
)

const (
	scansTable          = "vulnerability_scans"
	scanStaleTimeout    = 30 * time.Minute
	scheduledScanMaxAge = 7 * 24 * time.Hour
	// scanPoolIdle removes shared scan containers left behind by a scan that never finalized.
	scanPoolIdle = 2 * time.Minute
	// scanPoolSetupTimeout bounds creating the shared scan containers, including pulling the scanner image.
	scanPoolSetupTimeout = 10 * time.Minute
)

// scheduledScanUser is the actor recorded for scheduled scans.
var scheduledScanUser = usertypes.Actor{Username: "System"}

// Records updates scan records, whose model the vulnerability domain owns.
type Records struct {
	MarkStatus   func(ctx context.Context, imageID string, status vulnerability.ScanStatus) (bool, error)
	MarkFailed   func(ctx context.Context, imageID, message string, duration int64) (bool, error)
	SetImageName func(ctx context.Context, imageID, imageName string) error
}

// Dependencies are the services and hooks scans run on.
type Dependencies struct {
	DB                  *database.DB
	Records             Records
	Config              *config.Config
	KV                  *kv.KVService
	RegistryAuthConfigs func(ctx context.Context) (map[string]registry.AuthConfig, error)
	SaveReport          func(ctx context.Context, imageID, data string) error
	Docker              *docker.DockerClientService
	Settings            *settings.SettingsService
	Events              *event.EventService
	Notifications       *notification.NotificationService
	Activity            *activity.ActivityService
	SaveResult          func(ctx context.Context, result *vulnerability.ScanResult) error
	SaveScheduledResult func(ctx context.Context, result *vulnerability.ScanResult) error
	EnsureSummary       func(result *vulnerability.ScanResult) *vulnerability.SeveritySummary
	FilterIgnored       func(ctx context.Context, envID, imageID string, vulns []vulnerability.Vulnerability) ([]vulnerability.Vulnerability, error)
}

// Service runs manual and scheduled image scans and tracks their live phases.
type Service struct {
	db                  *database.DB
	records             Records
	trivy               *trivy.Service
	dockerService       *docker.DockerClientService
	settingsService     *settings.SettingsService
	eventService        *event.EventService
	notificationService *notification.NotificationService
	activityService     *activity.ActivityService
	saveResult          func(ctx context.Context, result *vulnerability.ScanResult) error
	saveScheduledResult func(ctx context.Context, result *vulnerability.ScanResult) error
	ensureSummary       func(result *vulnerability.ScanResult) *vulnerability.SeveritySummary
	filterIgnored       func(ctx context.Context, envID, imageID string, vulns []vulnerability.Vulnerability) ([]vulnerability.Vulnerability, error)
	scanPhases          sync.Map // map[string]vulnerability.ScanPhase
	poolMu              sync.Mutex
	pool                *scanPool
	liveContainers      map[string]struct{}
}

type (
	// Target is one image a scheduled scan covers.
	Target struct {
		ImageID        string `json:"imageId"`
		ImageName      string `json:"imageName"`
		ScannerVersion string `json:"scannerVersion,omitempty"`
	}

	// Fixable summarizes one image's fixable findings for the scan notification.
	Fixable struct {
		Total    int            `json:"total,omitempty"`
		Severity map[string]int `json:"severity,omitempty"`
		CVEs     []string       `json:"cves,omitempty"`
	}

	// scanPool is the set of long-running Trivy containers scheduled scans exec
	// into. Scan tasks share it across deliveries until finalize or idleness removes it.
	scanPool struct {
		containers chan string
		files      map[string][]byte
		cleanup    func()
		users      int
		idle       *time.Timer
		// retired closes when a container could not be stopped; waiting scans then retry on a fresh pool.
		retired chan struct{}
	}
)

func NewService(deps Dependencies) *Service {
	var s *Service
	s = &Service{
		db:      deps.DB,
		records: deps.Records,
		trivy: trivy.NewService(deps.Config, deps.Docker, deps.Settings, deps.KV, deps.RegistryAuthConfigs, deps.SaveReport, func(imageID string, phase vulnerability.ScanPhase) {
			s.setScanPhase(imageID, phase)
		}),
		dockerService:       deps.Docker,
		settingsService:     deps.Settings,
		eventService:        deps.Events,
		notificationService: deps.Notifications,
		activityService:     deps.Activity,
		saveResult:          deps.SaveResult,
		saveScheduledResult: deps.SaveScheduledResult,
		ensureSummary:       deps.EnsureSummary,
		filterIgnored:       deps.FilterIgnored,
		liveContainers:      map[string]struct{}{},
	}
	return s
}

// scanStateRow is the freshness projection of a scan record.
type scanStateRow struct {
	ID             string    `gorm:"column:id"`
	ImageName      string    `gorm:"column:image_name"`
	Status         string    `gorm:"column:status"`
	ScanTime       time.Time `gorm:"column:scan_time"`
	ScannerVersion string    `gorm:"column:scanner_version"`
	ScanPolicy     string    `gorm:"column:scan_policy"`
}

func (s *Service) setScanPhase(imageID string, phase vulnerability.ScanPhase) {
	if imageID == "" || phase == "" {
		return
	}
	s.scanPhases.Store(imageID, phase)
}

// resolveScanPhase reports the live phase of an in-progress scan, falling back to one implied by its status.
func (s *Service) resolveScanPhase(imageID string, status vulnerability.ScanStatus) vulnerability.ScanPhase {
	if status != vulnerability.ScanStatusPending && status != vulnerability.ScanStatusScanning {
		return ""
	}
	if phase, ok := s.scanPhases.Load(imageID); ok {
		if typed, isPhase := phase.(vulnerability.ScanPhase); isPhase && typed != "" {
			return typed
		}
	}
	return kit.Ternary(status == vulnerability.ScanStatusPending, vulnerability.ScanPhaseCreatingContainer, vulnerability.ScanPhaseScanningImage)
}

// ScanImage queues a Trivy scan of an image and runs it in the background.
func (s *Service) ScanImage(ctx context.Context, envID, imageID string, user usertypes.Actor) (*vulnerability.ScanResult, error) {
	if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {
		return nil, err
	}
	scanCtx := utils.ActivityRuntimeContext(ctx, nil)

	imageInspect, err := s.dockerService.Call(scanCtx, func(ctx context.Context, cli *client.Client) (client.ImageInspectResult, error) {
		return cli.ImageInspect(ctx, imageID)
	})
	if err != nil {
		return nil, common.ClassifyDockerError(fmt.Errorf("failed to inspect image: %w", err))
	}
	imageName := slices.Concat(imageInspect.RepoTags, imageInspect.RepoDigests, []string{imageID})[0]

	slotID, releaseSlot, err := s.trivy.AcquireSlot(scanCtx, imageID, false)
	if err != nil {
		return nil, err
	}
	status := kit.Ternary(releaseSlot != nil, vulnerability.ScanStatusScanning, vulnerability.ScanStatusPending)
	slog.InfoContext(scanCtx, "vulnerability scan queued", "environmentId", envID, "imageId", imageID, "imageName", imageName)

	activityID := func() string {
		scanActivity, startErr := s.activityService.StartActivity(scanCtx, activity.StartActivityRequest{
			EnvironmentID: envID,
			Type:          activitytypes.TypeVulnerabilityScan,
			ResourceType:  new("image"),
			ResourceID:    &imageID,
			ResourceName:  &imageName,
			StartedBy:     &user,
			Progress:      new(0),
			Step:          string(vulnerability.ScanPhaseCreatingContainer),
			LatestMessage: "Vulnerability scan queued",
		})
		if startErr != nil {
			slog.WarnContext(scanCtx, "failed to create vulnerability scan activity", "error", startErr, "imageId", imageID)
			return ""
		}
		return scanActivity.ID
	}()
	activityRef := mo.EmptyableToOption(activityID).ToPointer()
	// Cancelling the activity cancels scanCtx, which stops the Trivy container wait and tears it down.
	scanCtx = s.activityService.Track(scanCtx, activityID)
	s.setScanPhase(imageID, vulnerability.ScanPhaseCreatingContainer)

	pendingResult := &vulnerability.ScanResult{
		ImageID:    imageID,
		ImageName:  imageName,
		ScanTime:   time.Now(),
		Status:     status,
		ActivityID: activityRef,
		ScanPhase:  s.resolveScanPhase(imageID, status),
		Summary:    &vulnerability.SeveritySummary{},
	}
	if saveErr := s.markOrSaveResult(scanCtx, pendingResult, func(ctx context.Context) (bool, error) {
		return s.records.MarkStatus(ctx, imageID, status)
	}); saveErr != nil {
		slog.WarnContext(scanCtx, "failed to save pending scan result", "error", saveErr, "imageId", imageID, "imageName", imageName)
	}

	go func() {
		var runErr error
		if releaseSlot == nil {
			slotID, releaseSlot, runErr = s.trivy.AcquireSlot(scanCtx, imageID, true)
		}
		if releaseSlot != nil {
			defer releaseSlot()
			if _, updateErr := s.records.MarkStatus(scanCtx, imageID, vulnerability.ScanStatusScanning); updateErr != nil {
				slog.WarnContext(scanCtx, "failed to mark queued scan as running", "imageId", imageID, "error", updateErr)
			}
		}
		defer s.scanPhases.Delete(imageID)
		// fail records a failed scan; a scan that never started carries no duration.
		fail := func(message string, duration int64) {
			s.setScanPhase(imageID, vulnerability.ScanPhaseStoringResults)
			s.updateVulnerabilityScanActivity(scanCtx, activityID, vulnerability.ScanPhaseStoringResults, 90, "Storing failed scan result")
			if saveErr := s.markOrSaveResult(context.WithoutCancel(scanCtx), &vulnerability.ScanResult{
				ImageID:    imageID,
				ImageName:  imageName,
				ScanTime:   time.Now(),
				Status:     vulnerability.ScanStatusFailed,
				ActivityID: activityRef,
				Error:      message,
				Duration:   duration,
			}, func(ctx context.Context) (bool, error) {
				return s.records.MarkFailed(ctx, imageID, message, duration)
			}); saveErr != nil {
				slog.WarnContext(scanCtx, "failed to save failed scan result", "error", saveErr)
			}
			slog.WarnContext(scanCtx, "background vulnerability scan failed", "environmentId", envID, "imageId", imageID, "imageName", imageName, "error", message)
			s.completeVulnerabilityScanActivity(scanCtx, activityID, false, message)
		}

		s.setScanPhase(imageID, vulnerability.ScanPhaseCreatingContainer)
		s.updateVulnerabilityScanActivity(scanCtx, activityID, vulnerability.ScanPhaseCreatingContainer, 10, "Preparing vulnerability scanner")
		var scannerImage string
		if runErr == nil {
			scannerImage, runErr = s.trivy.EnsureImage(scanCtx)
		}
		if runErr != nil {
			fail(kit.Ternary(errors.Is(runErr, common.ErrFeatureDisabled), runErr.Error(), "Trivy scanner is not available: "+runErr.Error()), 0)
			return
		}

		if featureErr := s.settingsService.RequireFeature(scanCtx, features.VulnerabilityManagement); featureErr != nil {
			fail(featureErr.Error(), 0)
			return
		}
		s.setScanPhase(imageID, vulnerability.ScanPhaseScanningImage)
		s.updateVulnerabilityScanActivity(scanCtx, activityID, vulnerability.ScanPhaseScanningImage, 45, "Scanning image for vulnerabilities")
		startTime := time.Now()
		scanned, runErr := s.trivy.Scan(scanCtx, scannerImage, imageName, imageID, slotID)
		duration := time.Since(startTime).Milliseconds()
		if runErr != nil {
			s.logScanEvent(scanCtx, event.EventTypeImageScan, "vulnerability_scan", envID, imageID, imageName, user, runErr.Error())
			fail(runErr.Error(), duration)
			return
		}

		if featureErr := s.settingsService.RequireFeature(scanCtx, features.VulnerabilityManagement); featureErr != nil {
			fail(featureErr.Error(), duration)
			return
		}
		result := &vulnerability.ScanResult{ //exhaustruct:enforce
			ImageID:         scanned.ImageID,
			ImageName:       scanned.ImageName,
			ScanTime:        scanned.ScanTime,
			Status:          scanned.Status,
			ActivityID:      activityRef,
			ScanPhase:       scanned.ScanPhase,
			Summary:         s.ensureSummary(scanned),
			Vulnerabilities: scanned.Vulnerabilities,
			Error:           scanned.Error,
			Duration:        duration,
			ScannerVersion:  scanned.ScannerVersion,
			HasReport:       scanned.HasReport,
			Insights:        scanned.Insights,
		}
		s.setScanPhase(imageID, vulnerability.ScanPhaseStoringResults)
		s.updateVulnerabilityScanActivity(scanCtx, activityID, vulnerability.ScanPhaseStoringResults, 90, "Storing vulnerability results")
		if saveErr := s.saveResult(scanCtx, result); saveErr != nil {
			slog.WarnContext(scanCtx, "failed to save scan result", "error", saveErr)
		}
		slog.InfoContext(scanCtx, "background vulnerability scan completed",
			"environmentId", envID, "imageId", imageID, "imageName", imageName, "durationMs", duration, "vulnerabilities", result.Summary.Total)
		s.logScanEvent(scanCtx, event.EventTypeImageScan, "vulnerability_scan", envID, imageID, imageName, user, "")
		s.completeVulnerabilityScanActivity(scanCtx, activityID, true, "")
	}()

	return pendingResult, nil
}

func (s *Service) markOrSaveResult(ctx context.Context, result *vulnerability.ScanResult, mark func(context.Context) (bool, error)) error {
	marked, err := mark(ctx)
	if err != nil || marked {
		return err
	}
	return s.saveResult(ctx, result)
}

// markStale fails a pending or scanning scan that outlived scanStaleTimeout
// and returns the failure message and duration.
func (s *Service) markStale(ctx context.Context, imageID string, status vulnerability.ScanStatus, scanTime time.Time) (string, int64, bool) {
	if status != vulnerability.ScanStatusScanning && status != vulnerability.ScanStatusPending {
		return "", 0, false
	}
	if time.Since(scanTime) <= scanStaleTimeout {
		return "", 0, false
	}

	errMsg := "Scan timed out or was interrupted. Please retry."
	duration := time.Since(scanTime).Milliseconds()
	s.scanPhases.Delete(imageID)
	if _, err := s.records.MarkFailed(ctx, imageID, errMsg, duration); err != nil {
		slog.WarnContext(ctx, "failed to mark stale scan as failed", "error", err, "scanId", imageID)
	}
	return errMsg, duration, true
}

// RefreshSummary fails stale in-progress scans and attaches the live scan phase.
func (s *Service) RefreshSummary(ctx context.Context, summary *vulnerability.ScanSummary) {
	if summary == nil {
		return
	}
	errMsg, _, stale := s.markStale(ctx, summary.ImageID, summary.Status, summary.ScanTime)
	status := kit.Ternary(stale, vulnerability.ScanStatusFailed, summary.Status)
	*summary = vulnerability.ScanSummary{ //exhaustruct:enforce
		ImageID:   summary.ImageID,
		ScanTime:  summary.ScanTime,
		Status:    status,
		ScanPhase: s.resolveScanPhase(summary.ImageID, status),
		Summary:   summary.Summary,
		Error:     kit.Ternary(stale, errMsg, summary.Error),
	}
}

// RefreshResult fails stale in-progress scans and attaches the live scan phase.
func (s *Service) RefreshResult(ctx context.Context, result *vulnerability.ScanResult) {
	if result == nil {
		return
	}
	errMsg, duration, stale := s.markStale(ctx, result.ImageID, result.Status, result.ScanTime)
	status := kit.Ternary(stale, vulnerability.ScanStatusFailed, result.Status)
	*result = vulnerability.ScanResult{ //exhaustruct:enforce
		ImageID:         result.ImageID,
		ImageName:       result.ImageName,
		ScanTime:        result.ScanTime,
		Status:          status,
		ActivityID:      result.ActivityID,
		ScanPhase:       s.resolveScanPhase(result.ImageID, status),
		Summary:         result.Summary,
		Vulnerabilities: result.Vulnerabilities,
		Error:           kit.Ternary(stale, errMsg, result.Error),
		Duration:        kit.Ternary(stale, duration, result.Duration),
		ScannerVersion:  result.ScannerVersion,
		HasReport:       result.HasReport,
		Insights:        result.Insights,
	}
}

func (s *Service) updateVulnerabilityScanActivity(ctx context.Context, activityID string, phase vulnerability.ScanPhase, progress int, message string) {
	if activityID == "" {
		return
	}
	if _, err := s.activityService.AppendMessage(ctx, activityID, activity.AppendActivityMessageRequest{
		Level:    activitytypes.MessageLevelInfo,
		Message:  message,
		Progress: &progress,
		Step:     string(phase),
	}); err != nil {
		slog.DebugContext(ctx, "failed to append vulnerability scan activity message", "activityId", activityID, "error", err)
	}
}

func (s *Service) completeVulnerabilityScanActivity(ctx context.Context, activityID string, success bool, errMessage string) {
	if activityID == "" {
		return
	}
	status, message, errorPtr := func() (activitytypes.Status, string, *string) {
		switch {
		case success:
			return activitytypes.StatusSuccess, "Vulnerability scan completed", nil
		case activitylib.CancelledByContext(ctx):
			return activitytypes.StatusCancelled, "Vulnerability scan cancelled", nil
		default:
			return activitytypes.StatusFailed, cmp.Or(errMessage, "Vulnerability scan failed"), mo.EmptyableToOption(errMessage).ToPointer()
		}
	}()
	if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errorPtr); err != nil {
		slog.DebugContext(ctx, "failed to complete vulnerability scan activity", "activityId", activityID, "error", err)
	}
}

// logScanEvent records a manual or scheduled scan event; an empty errMsg means it succeeded.
func (s *Service) logScanEvent(ctx context.Context, eventType event.EventType, action, envID, imageID, imageName string, user usertypes.Actor, errMsg string) {
	metadata := database.JSON{"action": action, "imageId": imageID, "imageName": imageName, "success": errMsg == ""}
	if errMsg != "" {
		metadata["error"] = errMsg
	}
	if err := s.eventService.LogImageEvent(ctx, eventType, imageID, imageName, user.ID, user.Username, cmp.Or(envID, "0"), metadata); err != nil {
		slog.WarnContext(ctx, "failed to log vulnerability scan event", "action", action, "error", err)
	}
}

// Policy describes the scan settings a stored result was produced with.
func (s *Service) Policy() string {
	serverURL, _ := s.trivy.ServerConfig()
	return fmt.Sprintf("ignoreUnfixed=%t;server=%s", s.trivy.IgnoreUnfixed(), serverURL)
}

// Targets lists the images due for a scheduled scan, skipping completed results
// from the last week with the same scanner version and policy.
func (s *Service) Targets(ctx context.Context) ([]Target, error) {
	if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {
		return nil, err
	}
	images, err := s.dockerService.ListImages(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to list images: %w", err)
	}
	scannerVersion := s.trivy.Version(ctx)
	targets := make([]Target, 0, len(images))
	ids := make([]string, 0, len(images))
	for _, img := range images {
		imageName := slices.Concat(img.RepoTags, img.RepoDigests, []string{img.ID})[0]
		// Skip intermediate and dangling images with no usable name.
		if imageName != "<none>:<none>" && imageName != img.ID {
			targets = append(targets, Target{
				ImageID:        img.ID,
				ImageName:      imageName,
				ScannerVersion: scannerVersion,
			})
			ids = append(ids, img.ID)
		}
	}
	if len(targets) == 0 {
		return targets, nil
	}

	var records []scanStateRow
	if queryErr := s.db.WithContext(ctx).
		Table(scansTable).
		Select("id", "image_name", "status", "scan_time", "scanner_version", "scan_policy").
		Where("id IN ?", ids).
		Find(&records).Error; queryErr != nil {
		return nil, fmt.Errorf("failed to load existing scan records: %w", queryErr)
	}
	cutoff := time.Now().Add(-scheduledScanMaxAge)
	policy := s.Policy()
	recent := make(map[string]scanStateRow, len(records))
	for _, record := range records {
		if record.Status == string(vulnerability.ScanStatusCompleted) && record.ScannerVersion == scannerVersion && record.ScanPolicy == policy && record.ScanTime.After(cutoff) {
			recent[record.ID] = record
		}
	}
	targets = slices.DeleteFunc(targets, func(target Target) bool {
		record, ok := recent[target.ImageID]
		if ok && record.ImageName != target.ImageName {
			if renameErr := s.records.SetImageName(ctx, target.ImageID, target.ImageName); renameErr != nil {
				slog.WarnContext(ctx, "failed to refresh scan record image name", "imageId", target.ImageID, "error", renameErr)
			}
		}
		return ok
	})
	if len(recent) > 0 {
		slog.InfoContext(ctx, "scheduled vulnerability scan: skipping recently scanned images", "skipped", len(recent), "maxAge", scheduledScanMaxAge.String())
	}
	return targets, nil
}

// joinPool returns the shared scan containers, creating them on first use; leave must be called when the scan ends.
func (s *Service) joinPool(ctx context.Context) (*scanPool, func(), error) {
	s.poolMu.Lock()
	if s.pool == nil {
		// Setup stays cancelable and bounded, since later scans wait on poolMu; removing the containers detaches on its own.
		setupCtx, cancelSetup := context.WithTimeout(ctx, scanPoolSetupTimeout)
		containerIDs, files, cleanup, err := s.trivy.SetupBatchContainers(setupCtx, s.trivy.ConcurrentScanContainers(), slices.Collect(maps.Keys(s.liveContainers)))
		cancelSetup()
		if err != nil {
			s.poolMu.Unlock()
			return nil, nil, common.Classify(common.ErrUnavailable, fmt.Errorf("prepare scan containers: %w", err))
		}
		s.pool = &scanPool{
			containers: make(chan string, len(containerIDs)),
			files:      files,
			cleanup: func() {
				cleanup()
				s.poolMu.Lock()
				for _, containerID := range containerIDs {
					delete(s.liveContainers, containerID)
				}
				s.poolMu.Unlock()
			},
			retired: make(chan struct{}),
		}
		for _, containerID := range containerIDs {
			s.liveContainers[containerID] = struct{}{}
			s.pool.containers <- containerID
		}
	}
	pool := s.pool
	if pool.idle != nil {
		pool.idle.Stop()
		pool.idle = nil // keep: the pool is shared with in-flight scans under poolMu
	}
	pool.users++
	s.poolMu.Unlock()
	return pool, func() {
		s.poolMu.Lock()
		pool.users--
		idle, retired := pool.users == 0 && s.pool == pool, pool.users == 0 && s.pool != pool
		// An interrupted last scan, such as at shutdown, removes the pool now; the idle timer would not outlive the process.
		if idle && ctx.Err() != nil {
			s.pool, idle, retired = nil, false, true
		}
		if idle {
			pool.idle = time.AfterFunc(scanPoolIdle, s.ReleaseScanPool) // keep: the pool is shared with in-flight scans under poolMu
		}
		s.poolMu.Unlock()
		// The last scan out of a retired pool removes its containers, the unstoppable one included.
		if retired {
			pool.cleanup()
		}
	}, nil
}

// ScanTarget scans one image in the shared scan containers and saves its result.
// It returns common.ErrFeatureDisabled, without saving, once the feature is off.
func (s *Service) ScanTarget(ctx context.Context, envID string, target Target) (Fixable, error) {
	pool, leave, err := s.joinPool(ctx)
	if err != nil {
		return Fixable{}, err
	}
	defer leave()

	slog.InfoContext(ctx, "scheduled vulnerability scan: scanning image", "image", target.ImageName, "imageId", target.ImageID)
	startTime := time.Now()
	slotID, releaseSlot, err := s.trivy.AcquireSlot(ctx, target.ImageID, true)
	if err != nil {
		return Fixable{}, err
	}
	defer releaseSlot()
	var containerID string
	select {
	case containerID = <-pool.containers:
	case <-pool.retired:
		return Fixable{}, common.Classify(common.ErrUnavailable, errors.New("scan containers were replaced; retrying"))
	case <-ctx.Done():
		return Fixable{}, ctx.Err()
	}
	defer func() {
		// A cancel only detaches from the exec, so the container is restarted to stop Trivy before another scan reuses it.
		if ctx.Err() != nil {
			restartCtx := context.WithoutCancel(ctx)
			_, clientErr := s.dockerService.Call(restartCtx, func(ctx context.Context, cli *client.Client) (client.ContainerRestartResult, error) {
				return cli.ContainerRestart(ctx, containerID, client.ContainerRestartOptions{})
			})
			if clientErr != nil {
				// Without this container the pool cannot serve scans, so later scans start a fresh one.
				slog.WarnContext(restartCtx, "scheduled vulnerability scan: failed to stop a canceled scan; retiring its scan containers", "containerId", containerID, "error", clientErr)
				s.poolMu.Lock()
				select {
				case <-pool.retired:
				default:
					close(pool.retired)
				}
				if s.pool == pool {
					s.pool = nil
				}
				s.poolMu.Unlock()
				return
			}
		}
		pool.containers <- containerID
	}()
	if featureErr := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); featureErr != nil {
		return Fixable{}, featureErr
	}
	scanned, err := s.trivy.ExecScan(ctx, containerID, target.ImageName, target.ImageID, target.ScannerVersion, slotID, pool.files)
	duration := time.Since(startTime).Milliseconds()
	if err != nil {
		if saveErr := s.markOrSaveResult(context.WithoutCancel(ctx), &vulnerability.ScanResult{
			ImageID:   target.ImageID,
			ImageName: target.ImageName,
			ScanTime:  time.Now(),
			Status:    vulnerability.ScanStatusFailed,
			Error:     err.Error(),
			Duration:  duration,
		}, func(ctx context.Context) (bool, error) {
			return s.records.MarkFailed(ctx, target.ImageID, err.Error(), duration)
		}); saveErr != nil {
			slog.WarnContext(ctx, "failed to save failed scan result", "error", saveErr)
		}
		s.logScanEvent(ctx, event.EventTypeImageVulnerabilityScan, "scheduled_vulnerability_scan", envID, target.ImageID, target.ImageName, scheduledScanUser, err.Error())
		return Fixable{}, err
	}
	result := &vulnerability.ScanResult{ //exhaustruct:enforce
		ImageID:         scanned.ImageID,
		ImageName:       scanned.ImageName,
		ScanTime:        scanned.ScanTime,
		Status:          scanned.Status,
		ActivityID:      scanned.ActivityID,
		ScanPhase:       scanned.ScanPhase,
		Summary:         s.ensureSummary(scanned),
		Vulnerabilities: scanned.Vulnerabilities,
		Error:           scanned.Error,
		Duration:        duration,
		ScannerVersion:  scanned.ScannerVersion,
		HasReport:       scanned.HasReport,
		Insights:        scanned.Insights,
	}
	if saveErr := s.saveScheduledResult(ctx, result); saveErr != nil {
		return Fixable{}, common.Classify(common.ErrUnavailable, fmt.Errorf("save scan result for %s: %w", target.ImageName, saveErr))
	}
	s.logScanEvent(ctx, event.EventTypeImageVulnerabilityScan, "scheduled_vulnerability_scan", envID, target.ImageID, target.ImageName, scheduledScanUser, "")

	if result.Status != vulnerability.ScanStatusCompleted || len(result.Vulnerabilities) == 0 {
		return Fixable{Severity: map[string]int{}}, nil
	}
	vulnerabilities, err := s.filterIgnored(ctx, envID, result.ImageID, result.Vulnerabilities)
	if err != nil {
		slog.WarnContext(ctx, "failed to filter ignored vulnerabilities for notifications", "error", err)
		vulnerabilities = result.Vulnerabilities
	}
	total, severity := 0, map[string]int{}
	var cves []string
	for _, v := range vulnerabilities {
		if strings.TrimSpace(v.FixedVersion) == "" {
			continue
		}
		total++
		severity[strings.ToUpper(strings.TrimSpace(string(v.Severity)))]++
		if cveID := strings.TrimSpace(v.VulnerabilityID); cveID != "" && len(cves) < 5 && !slices.Contains(cves, cveID) {
			cves = append(cves, cveID)
		}
	}
	return Fixable{
		Total:    total,
		Severity: severity,
		CVEs:     cves,
	}, nil
}

// ReleaseScanPool removes the shared scan containers once no scan is using them.
func (s *Service) ReleaseScanPool() {
	s.poolMu.Lock()
	pool := s.pool
	if pool == nil || pool.users > 0 {
		s.poolMu.Unlock()
		return
	}
	s.pool = nil
	if pool.idle != nil {
		pool.idle.Stop()
	}
	s.poolMu.Unlock()
	pool.cleanup()
}

// NotifySummary sends the scheduled scan's daily summary of fixable findings.
func (s *Service) NotifySummary(ctx context.Context, scanned int, fixables []Fixable) {
	if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
		return
	}
	severity := map[string]int{"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "UNKNOWN": 0}
	var total, images int
	var sampleCVEs []string
	for _, fixable := range fixables {
		if fixable.Total == 0 {
			continue
		}
		images++
		total += fixable.Total
		for sev, count := range fixable.Severity {
			if _, known := severity[sev]; !known {
				sev = "UNKNOWN"
			}
			severity[sev] += count
		}
		for _, cveID := range fixable.CVEs {
			if len(sampleCVEs) < 5 && !slices.Contains(sampleCVEs, cveID) {
				sampleCVEs = append(sampleCVEs, cveID)
			}
		}
	}
	if total == 0 {
		return
	}
	payload := notification.VulnerabilityNotificationPayload{
		CVEID:        "Daily Summary - " + time.Now().UTC().Format("2006-01-02"),
		Severity:     fmt.Sprintf("Critical:%d High:%d Medium:%d Low:%d Unknown:%d", severity["CRITICAL"], severity["HIGH"], severity["MEDIUM"], severity["LOW"], severity["UNKNOWN"]),
		ImageName:    fmt.Sprintf("%d image(s) scanned, %d with fixable vulnerabilities", scanned, images),
		FixedVersion: fmt.Sprintf("%d fixable vulnerability record(s)", total),
		PkgName:      strings.Join(sampleCVEs, ", "),
	}
	if err := s.notificationService.SendVulnerabilityNotification(ctx, payload); err != nil {
		slog.WarnContext(ctx, "failed to send daily vulnerability summary notification", "error", err)
	}
}