Skip to content

Modern Docker Management, Designed for Everyone

28.7 KB
Raw Blame
package vulnerability

import (
	"time"

	"github.com/getarcaneapp/arcane/types/v2/base"
)

// ScannerStatus reports vulnerability scanner availability and version.
type ScannerStatus struct {
	Available bool   `json:"available"`
	Version   string `json:"version,omitempty"`
}

// Severity represents the severity level of a vulnerability
type Severity string

const (
	SeverityUnknown  Severity = "UNKNOWN"
	SeverityLow      Severity = "LOW"
	SeverityMedium   Severity = "MEDIUM"
	SeverityHigh     Severity = "HIGH"
	SeverityCritical Severity = "CRITICAL"

	TrivyClassOSPackages   = "os-pkgs"
	TrivyClassLangPackages = "lang-pkgs"

	RiskBandNone     RiskBand = "none"
	RiskBandLow      RiskBand = "low"
	RiskBandMedium   RiskBand = "medium"
	RiskBandHigh     RiskBand = "high"
	RiskBandCritical RiskBand = "critical"

	// ScoreStatusComplete means a score was computed.
	ScoreStatusComplete ScoreStatus = "complete"
	// ScoreStatusUnavailable means no score could be computed.
	ScoreStatusUnavailable ScoreStatus = "unavailable"

	ImageExposureRunning ImageExposure = "running"
	ImageExposureStopped ImageExposure = "stopped"
	ImageExposureUnused  ImageExposure = "unused"
	ImageExposureUnknown ImageExposure = "unknown"

	ScanStatusPending   ScanStatus = "pending"
	ScanStatusScanning  ScanStatus = "scanning"
	ScanStatusCompleted ScanStatus = "completed"
	ScanStatusFailed    ScanStatus = "failed"

	ScanPhaseCreatingContainer ScanPhase = "creating_container"
	ScanPhaseScanningImage     ScanPhase = "scanning_image"
	ScanPhaseStoringResults    ScanPhase = "storing_results"
)

// Vulnerability represents a single vulnerability found in an image
type Vulnerability struct {
	// VulnerabilityID is the unique identifier for the vulnerability (e.g., CVE-2021-1234)
	//
	// Required: true
	VulnerabilityID string `json:"vulnerabilityId"`

	// PkgName is the name of the package containing the vulnerability
	//
	// Required: true
	PkgName string `json:"pkgName"`

	// InstalledVersion is the installed version of the vulnerable package
	//
	// Required: true
	InstalledVersion string `json:"installedVersion"`

	// FixedVersion is the version where the vulnerability is fixed (empty if not fixed)
	//
	// Required: false
	FixedVersion string `json:"fixedVersion,omitempty"`

	// Severity is the severity level of the vulnerability
	//
	// Required: true
	Severity Severity `json:"severity"`

	Class string `json:"class,omitempty"`

	Type string `json:"type,omitempty"`

	// Title is the title of the vulnerability
	//
	// Required: false
	Title string `json:"title,omitempty"`

	// Description is the description of the vulnerability
	//
	// Required: false
	Description string `json:"description,omitempty"`

	// References is a list of references related to the vulnerability
	//
	// Required: false
	References []string `json:"references,omitempty"`

	// CVSS contains the CVSS score information
	//
	// Required: false
	CVSS *CVSSInfo `json:"cvss,omitempty"`

	// PublishedDate is the date when the vulnerability was published
	//
	// Required: false
	PublishedDate *time.Time `json:"publishedDate,omitempty"`

	// LastModifiedDate is the date when the vulnerability was last modified
	//
	// Required: false
	LastModifiedDate *time.Time `json:"lastModifiedDate,omitempty"`
}

// VulnerabilityWithImage represents a vulnerability with its source image context
type VulnerabilityWithImage struct {
	Vulnerability
	base.EnvironmentTag

	// Ignored marks a vulnerability the user chose to ignore. Only set when
	// the list was requested with ignored entries included.
	//
	// Required: false
	Ignored bool `json:"ignored,omitempty"`

	// IgnoreID is the ignore record's ID, used to unignore the vulnerability.
	//
	// Required: false
	IgnoreID string `json:"ignoreId,omitempty"`

	// ImageID is the Docker image ID that contains the vulnerability
	//
	// Required: true
	ImageID string `json:"imageId"`

	// ImageName is the image name with tag (e.g., nginx:latest)
	//
	// Required: true
	ImageName string `json:"imageName"`
}

// CVSSInfo contains CVSS score information
type CVSSInfo struct {
	// V2Score is the CVSS v2 score
	//
	// Required: false
	V2Score float64 `json:"v2Score,omitempty"`

	// V3Score is the CVSS v3 score
	//
	// Required: false
	V3Score float64 `json:"v3Score,omitempty"`

	// V2Vector is the CVSS v2 vector string
	//
	// Required: false
	V2Vector string `json:"v2Vector,omitempty"`

	// V3Vector is the CVSS v3 vector string
	//
	// Required: false
	V3Vector string `json:"v3Vector,omitempty"`
}

// SeveritySummary contains counts of vulnerabilities by severity
type SeveritySummary struct {
	// Critical is the count of critical vulnerabilities
	//
	// Required: true
	Critical int `json:"critical"`

	// High is the count of high severity vulnerabilities
	//
	// Required: true
	High int `json:"high"`

	// Medium is the count of medium severity vulnerabilities
	//
	// Required: true
	Medium int `json:"medium"`

	// Low is the count of low severity vulnerabilities
	//
	// Required: true
	Low int `json:"low"`

	// Unknown is the count of unknown severity vulnerabilities
	//
	// Required: true
	Unknown int `json:"unknown"`

	// Total is the total count of vulnerabilities
	//
	// Required: true
	Total int `json:"total"`
}

// EnvironmentVulnerabilitySummary contains aggregated vulnerability info for an environment
type EnvironmentVulnerabilitySummary struct {
	// TotalImages is the total number of images in the environment
	//
	// Required: true
	TotalImages int `json:"totalImages"`

	// ScannedImages is the number of images with completed scans
	//
	// Required: true
	ScannedImages int `json:"scannedImages"`

	// Summary contains the aggregated severity summary
	//
	// Required: false
	Summary *SeveritySummary `json:"summary,omitempty"`
}

// ScanResult represents the result of a vulnerability scan
type ScanResult struct {
	// ImageID is the Docker image ID that was scanned
	//
	// Required: true
	ImageID string `json:"imageId"`

	// ImageName is the image name with tag (e.g., nginx:latest)
	//
	// Required: true
	ImageName string `json:"imageName"`

	// ScanTime is the timestamp when the scan was performed
	//
	// Required: true
	ScanTime time.Time `json:"scanTime"`

	// Status is the status of the scan (scanning, completed, failed)
	//
	// Required: true
	Status ScanStatus `json:"status"`

	// ActivityID is the background activity tracking this scan, if available
	//
	// Required: false
	ActivityID *string `json:"activityId,omitempty"`

	// ScanPhase is the current phase of a running scan
	// (e.g. creating_container, scanning_image, storing_results).
	//
	// Required: false
	ScanPhase ScanPhase `json:"scanPhase,omitempty"`

	// Summary contains the severity summary of vulnerabilities found
	//
	// Required: false
	Summary *SeveritySummary `json:"summary,omitempty"`

	// Vulnerabilities is the list of vulnerabilities found
	//
	// Required: false
	Vulnerabilities []Vulnerability `json:"vulnerabilities,omitempty"`

	// Error contains the error message if the scan failed
	//
	// Required: false
	Error string `json:"error,omitempty"`

	// Duration is the duration of the scan in milliseconds
	//
	// Required: false
	Duration int64 `json:"duration,omitempty"`

	// ScannerVersion is the version of the scanner used
	//
	// Required: false
	ScannerVersion string `json:"scannerVersion,omitempty"`

	// HasReport indicates whether the raw scanner report is stored and can
	// drive report-based image patching.
	//
	// Required: false
	HasReport bool `json:"hasReport,omitempty"`

	// Insights summarizes risk and remediation for completed scans with findings.
	//
	// Required: false
	Insights *ScanInsights `json:"insights,omitempty"`
}

// RiskBand is the qualitative label of a patch priority score, mirroring the CVSS ranges.
type RiskBand string

// ScoreStatus reports how complete the data behind a patch priority score is.
type ScoreStatus string

// PatchPriority is a 0-100 risk score with its label and data status.
type PatchPriority struct {
	// RiskScore is the 0-100 patch priority. An image weighs its worst fixable findings plus their count; an environment averages images by exposure and
	// stays in the High band while a known-exploited fix is running.
	//
	// Required: true
	RiskScore int `json:"riskScore"`

	// RiskBand is the qualitative label of RiskScore.
	//
	// Required: true
	RiskBand RiskBand `json:"riskBand"`

	// ScoreStatus reports whether RiskScore is complete 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
	HighestCVSS float64 `json:"highestCvss"`

	// HighestVulnerabilityID is the ID of the finding with the highest CVSS score.
	//
	// Required: false
	HighestVulnerabilityID string `json:"highestVulnerabilityId,omitempty"`

	// FixableCount is the number of findings with a fixed version available.
	//
	// Required: true
	FixableCount int `json:"fixableCount"`

	// KnownExploitedCount is the number of findings listed in the CISA KEV catalog.
	//
	// Required: true
	KnownExploitedCount int `json:"knownExploitedCount"`

	// Exposure describes whether containers use the image, which scales finding priority.
	//
	// Required: true
	Exposure ImageExposure `json:"exposure"`

	// TopPackages lists the most severe affected packages to update.
	//
	// Required: true
	TopPackages []PackageInsight `json:"topPackages"`
}

// ImageExposure describes how containers use an image.
type ImageExposure string

// PackageInsight aggregates the findings of one affected package.
type PackageInsight struct {
	// PkgName is the affected package name.
	//
	// Required: true
	PkgName string `json:"pkgName"`

	// Severity is the worst severity among the package's findings.
	//
	// Required: true
	Severity Severity `json:"severity"`

	// Count is the number of findings in the package.
	//
	// Required: true
	Count int `json:"count"`

	// InstalledVersion is the installed package version.
	//
	// Required: true
	InstalledVersion string `json:"installedVersion"`

	// FixedVersion is the version that fixes the package's findings, if known.
	//
	// Required: false
	FixedVersion string `json:"fixedVersion,omitempty"`
}

// ScanStatus represents the status of a vulnerability scan
type ScanStatus string

// ScanPhase represents the current phase of an in-progress scan.
type ScanPhase string

// ScanSummary contains a summary of a vulnerability scan for display in lists
type ScanSummary struct {
	// ImageID is the Docker image ID that was scanned
	//
	// Required: true
	ImageID string `json:"imageId"`

	// ScanTime is the timestamp when the scan was performed
	//
	// Required: true
	ScanTime time.Time `json:"scanTime"`

	// Status is the status of the scan
	//
	// Required: true
	Status ScanStatus `json:"status"`

	// ScanPhase is the current phase of a running scan
	// (e.g. creating_container, scanning_image, storing_results).
	//
	// Required: false
	ScanPhase ScanPhase `json:"scanPhase,omitempty"`

	// Summary contains the severity summary of vulnerabilities found
	//
	// Required: false
	Summary *SeveritySummary `json:"summary,omitempty"`

	// Error contains the error message if the scan failed
	//
	// Required: false
	Error string `json:"error,omitempty"`
}

// ScanSummariesRequest is a batch request for scan summaries by image ID.
type ScanSummariesRequest struct {
	// ImageIDs is the list of Docker image IDs to fetch summaries for.
	//
	// Required: true
	ImageIDs []string `json:"imageIds"`
}

// ScanSummariesResponse wraps summaries keyed by image ID.
type ScanSummariesResponse struct {
	// Summaries maps image ID to scan summary.
	//
	// Required: true
	Summaries map[string]*ScanSummary `json:"summaries"`
}

// TrivyReport represents the JSON output structure from Trivy scanner
type TrivyReport struct {
	SchemaVersion int            `json:"SchemaVersion"`
	ArtifactName  string         `json:"ArtifactName"`
	ArtifactType  string         `json:"ArtifactType"`
	Metadata      TrivyMetadata  `json:"Metadata"`
	Results       []TrivyResults `json:"Results"`
}

// TrivyMetadata contains metadata about the scanned artifact
type TrivyMetadata struct {
	OS          *TrivyOS `json:"OS,omitempty"`
	ImageID     string   `json:"ImageID"`
	DiffIDs     []string `json:"DiffIDs"`
	RepoTags    []string `json:"RepoTags"`
	RepoDigests []string `json:"RepoDigests"`
}

// TrivyOS contains OS information
type TrivyOS struct {
	Family string `json:"Family"`
	Name   string `json:"Name"`
}

// TrivyResults contains the results for a specific target
type TrivyResults struct {
	Target          string               `json:"Target"`
	Class           string               `json:"Class"`
	Type            string               `json:"Type"`
	Vulnerabilities []TrivyVulnerability `json:"Vulnerabilities"`
}

// TrivyVulnerability represents a vulnerability in Trivy output
type TrivyVulnerability struct {
	VulnerabilityID  string               `json:"VulnerabilityID"`
	PkgID            string               `json:"PkgID"`
	PkgName          string               `json:"PkgName"`
	InstalledVersion string               `json:"InstalledVersion"`
	FixedVersion     string               `json:"FixedVersion"`
	Status           string               `json:"Status"`
	Layer            *TrivyLayer          `json:"Layer,omitempty"`
	SeveritySource   string               `json:"SeveritySource"`
	PrimaryURL       string               `json:"PrimaryURL"`
	DataSource       *TrivyDataSource     `json:"DataSource,omitempty"`
	Title            string               `json:"Title"`
	Description      string               `json:"Description"`
	Severity         string               `json:"Severity"`
	CweIDs           []string             `json:"CweIDs"`
	CVSS             map[string]TrivyCVSS `json:"CVSS"`
	References       []string             `json:"References"`
	PublishedDate    string               `json:"PublishedDate"`
	LastModifiedDate string               `json:"LastModifiedDate"`
}

// TrivyLayer contains information about the layer where the vulnerability was found
type TrivyLayer struct {
	Digest string `json:"Digest"`
	DiffID string `json:"DiffID"`
}

// TrivyDataSource contains information about the data source
type TrivyDataSource struct {
	ID   string `json:"ID"`
	Name string `json:"Name"`
	URL  string `json:"URL"`
}

// TrivyCVSS contains CVSS score information from Trivy
type TrivyCVSS struct {
	V2Vector string  `json:"V2Vector"`
	V3Vector string  `json:"V3Vector"`
	V2Score  float64 `json:"V2Score"`
	V3Score  float64 `json:"V3Score"`
}

// ConvertTrivyReportToScanResult converts a TrivyReport to a ScanResult
func ConvertTrivyReportToScanResult(report *TrivyReport, imageID string, scanTime time.Time, duration int64) *ScanResult {
	result := &ScanResult{
		ImageID:   imageID,
		ImageName: report.ArtifactName,
		ScanTime:  scanTime,
		Status:    ScanStatusCompleted,
		Duration:  duration,
		Summary: &SeveritySummary{
			Critical: 0,
			High:     0,
			Medium:   0,
			Low:      0,
			Unknown:  0,
			Total:    0,
		},
		Vulnerabilities: []Vulnerability{},
	}

	// Collect all vulnerabilities from all results
	for _, trivyResult := range report.Results {
		for _, tv := range trivyResult.Vulnerabilities {
			vuln := convertTrivyVulnerability(&tv)
			vuln.Class = trivyResult.Class
			vuln.Type = trivyResult.Type
			result.Vulnerabilities = append(result.Vulnerabilities, vuln)

			// Update severity summary
			switch vuln.Severity {
			case SeverityCritical:
				result.Summary.Critical++
			case SeverityHigh:
				result.Summary.High++
			case SeverityMedium:
				result.Summary.Medium++
			case SeverityLow:
				result.Summary.Low++
			case SeverityUnknown:
				result.Summary.Unknown++
			default:
				result.Summary.Unknown++
			}
			result.Summary.Total++
		}
	}

	return result
}

func convertTrivyVulnerability(tv *TrivyVulnerability) Vulnerability {
	vuln := Vulnerability{
		VulnerabilityID:  tv.VulnerabilityID,
		PkgName:          tv.PkgName,
		InstalledVersion: tv.InstalledVersion,
		FixedVersion:     tv.FixedVersion,
		Severity:         parseSeverity(tv.Severity),
		Title:            tv.Title,
		Description:      tv.Description,
		References:       tv.References,
	}

	// Convert CVSS scores
	if len(tv.CVSS) > 0 {
		cvss := &CVSSInfo{}
		for _, cvssData := range tv.CVSS {
			if cvssData.V3Score > 0 {
				cvss.V3Score = cvssData.V3Score
				cvss.V3Vector = cvssData.V3Vector
			}
			if cvssData.V2Score > 0 {
				cvss.V2Score = cvssData.V2Score
				cvss.V2Vector = cvssData.V2Vector
			}
		}
		if cvss.V2Score > 0 || cvss.V3Score > 0 {
			vuln.CVSS = cvss
		}
	}

	// Parse dates
	if tv.PublishedDate != "" {
		if t, err := time.Parse(time.RFC3339, tv.PublishedDate); err == nil {
			vuln.PublishedDate = &t
		}
	}
	if tv.LastModifiedDate != "" {
		if t, err := time.Parse(time.RFC3339, tv.LastModifiedDate); err == nil {
			vuln.LastModifiedDate = &t
		}
	}

	return vuln
}

func parseSeverity(s string) Severity {
	switch s {
	case "CRITICAL":
		return SeverityCritical
	case "HIGH":
		return SeverityHigh
	case "MEDIUM":
		return SeverityMedium
	case "LOW":
		return SeverityLow
	default:
		return SeverityUnknown
	}
}

// IgnorePayload represents the request to ignore a vulnerability
type IgnorePayload struct {
	// ImageID is the Docker image ID
	//
	// Required: true
	ImageID string `json:"imageId" example:"sha256:abc123"`

	// VulnerabilityID is the CVE or vulnerability identifier
	//
	// Required: true
	VulnerabilityID string `json:"vulnerabilityId" example:"CVE-2023-1234"`

	// PkgName is the package name containing the vulnerability
	//
	// Required: true
	PkgName string `json:"pkgName" example:"openssl"`

	// InstalledVersion is the version of the package with the vulnerability
	//
	// Required: false
	InstalledVersion string `json:"installedVersion,omitempty" example:"1.1.1l"`

	// Reason is an optional reason for ignoring this vulnerability
	//
	// Required: false
	Reason *string `json:"reason,omitempty" example:"False positive - not exploitable"`

	// CreatedBy is the user ID who created this ignore record (set by server from auth; do not send from client)
	//
	// Required: false
	CreatedBy string `json:"createdBy,omitempty" example:"user-123"`
}

// IgnoredVulnerability represents an ignored vulnerability record
type IgnoredVulnerability struct {
	// ID is the unique identifier for this ignore record
	ID string `json:"id"`

	// EnvironmentID is the environment where this ignore applies
	EnvironmentID string `json:"environmentId"`

	// ImageID is the Docker image ID
	ImageID string `json:"imageId"`

	// VulnerabilityID is the CVE or vulnerability identifier
	VulnerabilityID string `json:"vulnerabilityId"`

	// PkgName is the package name containing the vulnerability
	PkgName string `json:"pkgName"`

	// InstalledVersion is the version of the package with the vulnerability
	InstalledVersion string `json:"installedVersion"`

	// Reason is an optional reason for ignoring this vulnerability
	Reason *string `json:"reason,omitempty"`

	// CreatedBy is the user ID who created this ignore record
	CreatedBy string `json:"createdBy"`

	// CreatedAt is when this ignore record was created
	CreatedAt time.Time `json:"createdAt"`
}

// BulkVulnerabilityFilters mirrors the environment list filters for bulk ignore and restore requests; pagination never applies and an empty body covers every matching finding.
type BulkVulnerabilityFilters struct {
	// Search is the free-text search applied to CVE, package, version, title, and image fields
	//
	// Required: false
	Search string `json:"search,omitempty"`

	// Severity is a comma-separated severity filter
	//
	// Required: false
	Severity string `json:"severity,omitempty" example:"CRITICAL,HIGH"`

	// ImageName is a comma-separated image name substring filter
	//
	// Required: false
	ImageName string `json:"imageName,omitempty" example:"nginx"`

	// FixAvailable limits matches to vulnerabilities with a fixed version
	//
	// Required: false
	FixAvailable bool `json:"fixAvailable,omitempty"`
}

// BulkIgnoreResponse reports how many ignore records the request created or removed.
type BulkIgnoreResponse struct {
	// AffectedCount is the number of ignore records actually created or removed
	//
	// Required: true
	AffectedCount int `json:"affectedCount"`
}

// RiskOverview is the environment-wide vulnerability patch priority picture.
type RiskOverview struct {
	PatchPriority

	// Delta7d is the score change since the snapshot from 7 days ago, when one exists.
	//
	// Required: false
	Delta7d *int `json:"delta7d,omitempty"`

	// Trend holds daily scores for up to the last 90 days, oldest first.
	//
	// Required: true
	Trend []RiskTrendPoint `json:"trend"`

	// Drivers are the current risk driver counts.
	//
	// Required: true
	Drivers RiskDrivers `json:"drivers"`

	// Drivers7dAgo are the driver counts from 7 days ago, when a snapshot exists.
	//
	// Required: false
	Drivers7dAgo *RiskDrivers `json:"drivers7dAgo,omitempty"`

	// Summary is the severity summary of non-ignored findings.
	//
	// Required: true
	Summary SeveritySummary `json:"summary"`

	// Exposure counts non-ignored findings by how containers use their image.
	//
	// Required: true
	Exposure RiskExposureBreakdown `json:"exposure"`

	// ScoreDriver is the highest-priority fixable finding occurrence, when any exist.
	//
	// Required: false
	ScoreDriver *RiskScoreDriver `json:"scoreDriver,omitempty"`

	// RiskiestImages lists the images with the highest patch priority.
	//
	// Required: true
	RiskiestImages []RiskImage `json:"riskiestImages"`

	// RiskiestFindings lists the CVEs with the highest finding priority.
	//
	// Required: true
	RiskiestFindings []RiskFinding `json:"riskiestFindings"`

	// PrevalentFindings lists the CVEs present in the most images.
	//
	// Required: true
	PrevalentFindings []RiskFinding `json:"prevalentFindings"`

	// ThreatIntel reports the state of the KEV/EPSS threat intelligence.
	//
	// Required: true
	ThreatIntel ThreatIntelStatus `json:"threatIntel"`

	// ComputedAt is when the overview was computed.
	//
	// Required: true
	ComputedAt time.Time `json:"computedAt"`
}

// RiskTrendPoint is one day of the patch priority trend.
type RiskTrendPoint struct {
	// Date is the snapshot day (YYYY-MM-DD).
	//
	// Required: true
	Date string `json:"date"`

	// RiskScore is the environment patch priority on that day.
	//
	// Required: true
	RiskScore int `json:"riskScore"`
}

// 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.
	//
	// Required: true
	KnownExploited int `json:"knownExploited"`

	// OverdueKnownExploited is the number of unique KEV CVEs past their CISA remediation due date.
	//
	// Required: true
	OverdueKnownExploited int `json:"overdueKnownExploited"`

	// HighEPSS is the number of unique CVEs with an EPSS probability of at least 10%.
	//
	// Required: true
	HighEPSS int `json:"highEpss"`

	// ExposedCriticalHigh is the number of unique critical/high CVEs in images used by running containers.
	//
	// Required: true
	ExposedCriticalHigh int `json:"exposedCriticalHigh"`

	// Fixable is the number of findings with a fixed version available.
	//
	// Required: true
	Fixable int `json:"fixable"`

	// Findings is the total number of non-ignored findings.
	//
	// Required: true
	Findings int `json:"findings"`

	// ImagesScanned is the number of current images with a completed scan.
	//
	// Required: true
	ImagesScanned int `json:"imagesScanned"`

	// ImagesTotal is the number of current images.
	//
	// Required: true
	ImagesTotal int `json:"imagesTotal"`

	// ScoredImages is the number of scanned images that enter the patch priority score.
	//
	// Required: true
	ScoredImages int `json:"scoredImages"`
}

// RiskExposureBreakdown counts findings by the exposure of their image.
type RiskExposureBreakdown struct {
	// Running is the number of findings in images used by running containers.
	//
	// Required: true
	Running int `json:"running"`

	// Stopped is the number of findings in images used only by stopped containers.
	//
	// Required: true
	Stopped int `json:"stopped"`

	// Unused is the number of findings in images no container uses.
	//
	// Required: true
	Unused int `json:"unused"`

	// Unknown is the number of findings whose image exposure could not be determined.
	//
	// Required: true
	Unknown int `json:"unknown"`
}

// RiskScoreDriver identifies the highest-priority fixable finding occurrence; every field describes that one occurrence.
type RiskScoreDriver struct {
	// VulnerabilityID is the CVE or advisory ID.
	//
	// Required: true
	VulnerabilityID string `json:"vulnerabilityId"`

	// ImageName is the image holding the occurrence.
	//
	// Required: true
	ImageName 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
	Exposure ImageExposure `json:"exposure"`

	// KnownExploited reports whether the CVE is in the CISA KEV catalog.
	//
	// Required: true
	KnownExploited bool `json:"knownExploited"`

	// Risk is the 0-10 finding priority (patch priority / 10).
	//
	// Required: true
	Risk float64 `json:"risk"`
}

// RiskImage is one image ranked by patch priority.
type RiskImage struct {
	PatchPriority

	// ImageID is the Docker image ID.
	//
	// Required: true
	ImageID string `json:"imageId"`

	// ImageName is the image name with tag.
	//
	// Required: true
	ImageName string `json:"imageName"`

	// Exposure describes whether containers use the image.
	//
	// Required: true
	Exposure ImageExposure `json:"exposure"`

	// RunningContainers is the number of running containers using the image.
	//
	// Required: true
	RunningContainers int `json:"runningContainers"`

	// KnownExploited is the number of findings listed in the CISA KEV catalog.
	//
	// Required: true
	KnownExploited int `json:"knownExploited"`

	// Critical is the number of critical findings.
	//
	// Required: true
	Critical int `json:"critical"`

	// High is the number of high findings.
	//
	// Required: true
	High int `json:"high"`

	// Fixable is the number of findings with a fixed version available.
	//
	// Required: true
	Fixable int `json:"fixable"`

	// Findings is the total number of non-ignored findings.
	//
	// Required: true
	Findings int `json:"findings"`
}

// RiskFinding is one CVE aggregated across the environment's images.
type RiskFinding struct {
	// VulnerabilityID is the CVE or advisory ID.
	//
	// Required: true
	VulnerabilityID string `json:"vulnerabilityId"`

	// PkgName is the affected package.
	//
	// Required: true
	PkgName string `json:"pkgName"`

	// Title is the vulnerability title.
	//
	// Required: false
	Title string `json:"title,omitempty"`

	// Severity is the vulnerability severity.
	//
	// Required: true
	Severity Severity `json:"severity"`

	// CVSS is the CVSS score, or a severity fallback when unscored.
	//
	// Required: true
	CVSS float64 `json:"cvss"`

	// Risk is the 0-10 finding priority (patch priority / 10) after threat and usage adjustments.
	//
	// Required: true
	Risk float64 `json:"risk"`

	// EPSS is the FIRST EPSS exploit probability (0-1), when known.
	//
	// Required: false
	EPSS *float64 `json:"epss,omitempty"`

	// KnownExploited reports whether the CVE is in the CISA KEV catalog.
	//
	// Required: true
	KnownExploited bool `json:"knownExploited"`

	// Ransomware reports whether CISA lists known ransomware campaign use.
	//
	// Required: true
	Ransomware bool `json:"ransomware"`

	// KEVDueDate is the CISA remediation due date, when listed.
	//
	// Required: false
	KEVDueDate string `json:"kevDueDate,omitempty"`

	// ImagesAffected is the number of images with this CVE.
	//
	// Required: true
	ImagesAffected int `json:"imagesAffected"`

	// RunningImagesAffected is the number of affected images used by running containers.
	//
	// Required: true
	RunningImagesAffected int `json:"runningImagesAffected"`

	// FixedVersion is the version that fixes the CVE, when known.
	//
	// Required: false
	FixedVersion string `json:"fixedVersion,omitempty"`
}

// ThreatIntelStatus reports the state of the KEV/EPSS threat intelligence.
type ThreatIntelStatus struct {
	// Enabled reports whether threat intelligence is used.
	//
	// Required: true
	Enabled bool `json:"enabled"`

	// LastSyncedAt is when the feeds were last synced successfully.
	//
	// Required: false
	LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"`

	// Stale reports whether the last successful sync is older than 72 hours.
	//
	// Required: true
	Stale bool `json:"stale"`
}

// ThreatIntelEntry is the cached CISA KEV and FIRST EPSS data of one CVE.
type ThreatIntelEntry struct {
	CVEID          string
	KnownExploited bool
	KEVDateAdded   string
	KEVDueDate     string
	KEVRansomware  bool
	EPSSScore      *float64
	EPSSPercentile *float64
	EPSSCheckedAt  *time.Time
	UpdatedAt      *time.Time
}