engine

package
v0.187.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 40 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package engine orchestrates a run: it expands a Saga into scan jobs (controllers × components), executes them with bounded parallelism, and aggregates each control's results. Content-hash caching and the full describe→publish pipeline build on this.

Index

Constants

View Source
const MaliciousPackageRule = "malicious-package"

MaliciousPackageRule is the rule a finding about a package flagged as malicious is reported under. Draugr's own, because the statement carries no advisory identifier to report it under.

View Source
const MaliciousPackageTool = "deps.dev"

MaliciousPackageTool is the source named on such a finding: the service that answered the lookup, which relays the OSSF Malicious Packages Project's list.

Variables

This section is empty.

Functions

func Waivable added in v0.52.0

func Waivable(control string) bool

Waivable reports whether a failure under this control name is one --allow-scan-errors can accept.

The flag means "a scanner could not run and I accept a partial result". The reader has other controls that did run and is choosing to proceed on those. A planning failure is not a scanner: it is the run saying there was nothing to do at all, so there is no partial result to accept. Treating the two alike turns the flag into "pass anyway", and a PASS that means "we did not look" is the worst thing this tool can print.

(sbom) stays waivable on purpose. A missing SBOM is missing evidence, not a missing check, the controls still ran and their verdict still means something.

Types

type AnalyzerReachability added in v0.102.0

type AnalyzerReachability struct {
	// Analyzer names the tool, e.g. "govulncheck".
	Analyzer string
	// Reachable, Unreachable and Unknown count findings this analyzer decided.
	Reachable   int
	Unreachable int
	Unknown     int
	// Contributed counts findings this analyzer reported that no other scanner did, and which
	// are therefore kept as findings in their own right rather than folded away.
	Contributed int
}

AnalyzerReachability is one analyzer's contribution.

type DataRefresh added in v0.152.0

type DataRefresh struct {
	// Scanner is the scanner's name, and Data the names its ScannerInfo gives what it refreshes,
	// such as "vulnerability database". Data is empty for a scanner that declares none.
	Scanner string
	Data    []string
	Took    time.Duration
	// Failed is true where the refresh returned an error. The run continues with whatever is on
	// disk, as it always has, and the time spent trying is still time the run took.
	Failed bool
}

DataRefresh is one scanner's warm-up: the data it refreshes and how long that took.

type DependencyHealthResolver added in v0.128.0

type DependencyHealthResolver func(ctx context.Context, purls []string) error

DependencyHealthResolver answers what is known about the packages a run found.

A function rather than a client, so pkg/engine holds no opinion about where the answer comes from and no HTTP. The caller supplies one that reaches a service, or one that reads a fixture.

type EffectConsent added in v0.161.0

type EffectConsent struct {
	// Declared is config.allowEffects in the merged descriptor, sorted and deduplicated.
	Declared []plugin.EffectKind
	// Allowed is what the run accepted: Declared together with --allow-effects, sorted and
	// deduplicated.
	Allowed []plugin.EffectKind
}

EffectConsent is which scanner effects a run accepted, beside what its descriptor declared.

Both are kept because they answer different questions. The descriptor is what was reviewed; the run is what was in force, and --allow-effects accepts an effect for one invocation that no reviewed file names. A record holding only one of the two cannot show that they differ.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine plans and runs scans against a registry of controllers and scanners.

func New

func New(reg *Registry, opts ...Option) *Engine

New creates an Engine over the given registry. By default it runs as many jobs at once as toolexec.DefaultJobs gives for this machine.

func (*Engine) Plan

func (e *Engine) Plan(model saga.Model) ([]PlannedJob, error)

Plan expands the model into scan jobs. Only registered controllers that are enabled (project-level for project-scoped controllers, per-component for component-scoped ones) are planned. Controllers are visited in name order for determinism.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, model saga.Model) (Result, error)

Run plans and executes scans with bounded concurrency, then aggregates per control. Scan errors do not abort the run; they are collected and returned (joined) alongside whatever results succeeded. Honors ctx cancellation.

type FailedScan added in v0.165.3

type FailedScan struct {
	// Scanner and Version name the scanner that failed. Version is what it reported through
	// plugin.CacheVersioner, or its static version, and is empty where neither said anything.
	Scanner string
	Version string
	// Control and Component are the job's; Component is empty for a project-wide control.
	Control   string
	Component string
	// Kind and Target name the target as Targets names it, so the two can be read together. Both
	// are empty for a job with no target.
	Kind   string
	Target string
	// Detail is the scanner's error, the same text as the control's ScanErrors entry for it.
	Detail string
}

FailedScan is one job whose scanner returned an error, and which scanner it was.

type InputCoverage added in v0.133.0

type InputCoverage struct {
	Component string
	Control   string
	// Scanners are the scanners that accounted for what they read, sorted. A scanner that does not
	// account says nothing either way and is not named.
	Scanners []string
	// Read counts the dependency files at least one of them took packages from, the files read in
	// part included.
	Read int
	// Unread are the files none of them did, by repository and path, and the files they read in
	// part, which Read counts too and which are marked Partly.
	Unread []UnreadInput
	// Missed are the files a scanner took no packages from where another scanner of the control
	// took some, one entry per file and scanner, by repository, path and scanner. Read counts them,
	// and Unread does not list them.
	Missed []MissedInput
}

InputCoverage is what the dependency scans of one component read for one control: how many dependency files at least one scanner took packages from, and the ones none did.

Unread is per control and not per scanner, because a file one scanner skips and another reads was read: it is the caveat, and what the gate counts. A file an analysis could not cover (sarif.Input.Analysis), such as a Go module govulncheck could not load, is listed whoever read its packages, because reading them is not the analysis. What each scanner missed of a file another read is kept apart, in Missed, as a record of which scanner a finding from that file could have come from.

type JobMemory added in v0.178.0

type JobMemory struct {
	// Scanner, Control and Component are the job's; Component is empty for a project-wide control.
	Scanner   string
	Control   string
	Component string
	// Kind and Target name the target as Targets names it. Both are empty for a job with no target.
	Kind   string
	Target string
	// PeakBytes is the largest resident memory of one of the job's tool processes.
	PeakBytes uint64
}

JobMemory is the largest resident memory, in bytes, one tool process of a job reached, with the processes that process waited for, such as a Go build's compile processes or Semgrep's workers.

type MissedInput added in v0.166.0

type MissedInput struct {
	Repository string
	Path       string
	// Scanner is the scanner that read no packages from it.
	Scanner string
	// Reason is that scanner's reason, in the words UnreadInput.Reason uses.
	Reason string
}

MissedInput is a dependency file one scanner of a control read no packages from while another scanner of the control read it.

type MissingTool added in v0.154.0

type MissingTool struct {
	Control string
	// Tool is the executable as it was looked up, "trivy".
	Tool string
	// Provisionable is whether `draugr tools install` fetches it.
	Provisionable bool
	// Message is the control's ScanErrors entry for this failure.
	Message string
}

MissingTool is a control that could not run a scanner because its executable is not installed.

type ModuleResolver added in v0.142.2

type ModuleResolver func(ctx context.Context, url, revision string, workingTree bool, manifest string, paths []string) ([]string, error)

ModuleResolver lists the directories holding manifest that a job over paths has to analyze whole, read at revision or, for a working-tree scan, from the files on disk. Nil, with no error, means the paths need no widening or the layout cannot be read, and the job keeps its paths.

Injected for the reason WithTreeResolver is: answering means reading the repository, and the engine knows nothing about how one is fetched.

type Option

type Option func(*Engine)

Option configures an Engine.

func WithAllowedEffects added in v0.45.0

func WithAllowedEffects(kinds []string) Option

WithAllowedEffects accepts scanner effects for this invocation, on top of whatever the Saga accepts. Backs the --allow-effects flag.

func WithCache

func WithCache(c cache.Cache) Option

WithCache enables result caching: a cache hit for a job's key reuses the stored report instead of re-scanning. A nil cache disables caching (the default).

func WithCacheableTarget added in v0.61.0

func WithCacheableTarget(fn func(plugin.Target) bool) Option

WithCacheableTarget restricts caching to targets the predicate accepts.

Draugr's cache is content-addressed, which holds only while a target's identity is its content. A container image named by a mutable tag breaks that: the name is stable while the bytes behind it are not. This is the hook for a caller that would rather re-scan than be wrong about one.

Nil accepts everything, which is the default.

func WithConcurrency

func WithConcurrency(n int) Option

WithConcurrency sets the maximum number of scan jobs running at once. Values < 1 are ignored (the default is used).

func WithConsulted added in v0.107.0

func WithConsulted(feeds []sarif.Consulted) Option

WithConsulted records which exploitability datasets the prioritizer could answer from, so the result can say so whether or not any of them moved a finding.

Separate from WithPrioritization because the prioritizer is a function: what it consults is closed over and cannot be read back out. A caller that enriches without calling this produces a run whose evidence cannot distinguish "not on KEV" from "KEV was never loaded". Which is the distinction that makes a band explainable.

func WithContextFloors added in v0.162.0

func WithContextFloors(controls []string) Option

WithContextFloors names the controls whose findings the prioritizer ranks at a context tier of their own, whatever the component declares, so the result can say a floor applied whether or not it raised anything.

Separate from WithPrioritization for the reason WithConsulted is: which controls the prioritizer floors is closed over and cannot be read back out. A run that ranks with a floor and does not record it reports a floor that raised nothing exactly as it reports one that never applied.

func WithDependencyHealth added in v0.128.0

func WithDependencyHealth(resolve DependencyHealthResolver, src *dephealth.Source) Option

WithDependencyHealth supplies the resolver and the source it fills.

Both, because the source is handed to the prioritizer before a scan and filled after one: the packages are not known until the scanners have run. The engine calls the resolver once, between aggregation and ranking, and rebands what it changed.

func WithLocalImages added in v0.170.0

func WithLocalImages(fn func(ctx context.Context, ref string) bool) Option

WithLocalImages lets the engine ask whether the local Docker daemon holds an image, so an image a registry refused says when it was built here and never pushed. Asked after the scans, only for refused images. Nil leaves the question unanswered.

func WithModuleResolver added in v0.142.2

func WithModuleResolver(fn ModuleResolver) Option

WithModuleResolver supplies the module directories a scoped job has to analyze whole. See ModuleResolver.

Without one, a scanner that analyzes whole modules reads a component's paths as written, which works for a component holding its own module and leaves nothing that compiles for one holding part of a module.

func WithPrioritization added in v0.5.0

func WithPrioritization(p Prioritizer) Option

WithPrioritization stamps each finding with a priority band computed by p. Priority is applied per run (never cached), since it depends on the component's current classification.

func WithProgress added in v0.76.0

func WithProgress(fn ProgressFunc) Option

WithProgress reports what a run is doing while it does it.

A scan plans one job per repository, image, host and cluster and runs them concurrently, and the slow ones are the interesting ones, an image pulling, a benchmark Job waiting to be scheduled. Without this a run that is working and a run that is stuck are indistinguishable for as long as they last, which on a first scan is minutes.

func WithRegistryCredentials added in v0.162.0

func WithRegistryCredentials(fn func(ctx context.Context, host string) (bool, error)) Option

WithRegistryCredentials supplies how to find out whether this machine holds a credential for a container registry, so an image the registry refused says whether a login was missing.

Asked after the scans, once for each registry that refused an image, and never for one that did not. Injected rather than built in, because the answer comes from the machine's own container configuration, which can mean running a credential helper. Nil leaves the question unanswered, and the refusal is reported without it.

func WithRemoteResolver added in v0.70.0

func WithRemoteResolver(r RemoteResolver) Option

WithRemoteResolver names local checkouts by the repository they came from.

func WithRevisionResolver added in v0.117.0

func WithRevisionResolver(fn func(ctx context.Context, url, revision string) (string, error)) Option

WithRevisionResolver lets the engine learn which commit a repository's revision names.

A cache entry has to be keyed on what was scanned. A revision like `main`, or none at all, names whatever the branch points at now, so an entry stored under it outlives the commit it described and the next run at any commit is served the previous one's findings. The direction that shows up is a stale failure; the direction that does not is a clean answer about a commit that introduced something.

Injected rather than built in, because resolving means running git, and the engine deliberately knows nothing about how a repository is fetched. Without one, an unpinned repository is scanned normally and not cached: a slower run is a fair price, and a wrong answer is not.

func WithSBOM added in v0.41.0

func WithSBOM(g sbom.Generator) Option

WithSBOM supplies the generator used when a Saga enables config.sbom. Injected rather than imported so pkg/engine stays free of a concrete tool, exactly as it does for scanners. Nil (the default) means a Saga asking for SBOMs gets an error rather than silence.

func WithScope added in v0.71.0

func WithScope(sc Scope) Option

WithScope narrows the run to named components and controls. The zero Scope scans everything.

func WithTreeResolver added in v0.123.0

func WithTreeResolver(fn func(ctx context.Context, url, commit string, paths []string) (string, error)) Option

WithTreeResolver supplies the identity of a scoped job's own subtree at a commit.

Without one, every job over a repository is keyed on that repository's commit, so a monorepo commit touching one component invalidates every other component's cached result. A monorepo takes a commit every few minutes, which is where the cache was going to matter most.

func WithVEX added in v0.100.0

func WithVEX(set vex.Set) Option

WithVEX supplies exploitability claims somebody else made, already resolved.

Takes documents rather than descriptor sources because resolving a source can mean fetching a URL or cloning a repository, and an engine that did either would be reaching the network on its own account, the one thing the prewarm and the deterministic-core rule exist to keep out of it. The caller reads them; the engine only applies them.

func WithWorkingTree added in v0.64.0

func WithWorkingTree() Option

WithWorkingTree scans repositories as they are on disk, uncommitted work included, instead of at their committed revision.

Also refuses to cache what it scans. A working tree's content changes between two runs at the same revision, so a content-addressed cache keyed on the revision would serve the previous edit's findings. Which is the exact opposite of what somebody iterating on a fix needs.

func WithoutPrewarm added in v0.56.0

func WithoutPrewarm() Option

WithoutPrewarm skips the pre-run warm-up of shared scanner state.

For a run that must make no network calls. The scan still happens against whatever each tool already has on disk, and a tool with nothing on disk reports that itself. Which is a more specific message than the engine could produce on its behalf.

type PlannedJob

type PlannedJob struct {
	Control string
	Job     plugin.ScanJob
	// Component names the part of the application being scanned, empty for a project-scoped
	// control. Carried alongside the classification rather than derived from it: exposure and
	// criticality say what a component is worth, and a reader also has to know which one it was.
	Component   string
	Exposure    saga.Exposure
	Criticality saga.Criticality
	// Labels are what the component declares about itself, carried onto every finding it produces.
	Labels map[string]string
	// UpgradePolicy is the largest version step the fix list may propose for this component's
	// dependency findings, empty where it is the default of major.
	UpgradePolicy saga.UpgradeStep
	// UpgradePolicyFrom is the descriptor key that set UpgradePolicy, `config.fixes.upgrade` or the
	// component's own. Empty with UpgradePolicy.
	UpgradePolicyFrom string
	// contains filtered or unexported fields
}

PlannedJob is a scan job tagged with the control that produced it and the risk classification of the component it targets (empty for project-scoped controls).

type Prioritizer added in v0.5.0

type Prioritizer func(control string, exposure saga.Exposure, criticality saga.Criticality, res sarif.Result) Priority

Prioritizer computes a finding's priority band from its control and its component's risk classification. Injected via WithPrioritization so the engine stays decoupled from the prioritization matrices and per-control minimum severities; nil disables priority stamping.

type Priority added in v0.56.0

type Priority struct {
	// Band is the action band, P1–P4. Empty leaves the finding unstamped.
	Band string
	// Escalation is set when exploitability data raised the severity the band was computed
	// from. Nil when the scanner's own rating stood.
	Escalation *sarif.Escalation
	// Exploited is the catalog of observed exploitation that lists the finding, whether or not it
	// raised the severity. Nil where none does.
	Exploited *sarif.Match
	// CVELookup is the CVE an advisory database lists for a finding that names none itself, the one
	// KEV and EPSS were asked about. Nil where the finding names its CVE or nothing was found.
	CVELookup *sarif.CVELookup
	// Floor explains a band that the component's classification alone does not account for,
	// because the control declared that exposure does not bound its findings. Empty when the
	// matrices' own answer stood.
	Floor string
	// RankedAs is the severity the band was computed from when reachability analysis lowered it.
	// Empty when nothing lowered it, which is every finding that is reachable, unanalyzed, or
	// already at the bottom band.
	RankedAs sarif.Severity
	// SeverityFloor is the control's minimum severity, set only where it raised the rating the band
	// was computed from. Empty where the control declares no floor or the rating was already at or
	// above it.
	SeverityFloor sarif.Severity
	// Cap explains a band held below what the severity and context gave, as sarif.Result.PriorityCap
	// records it. Empty when nothing held it down.
	Cap string
}

Priority is what a Prioritizer decided, and why where there is a why.

A struct rather than a bare band because the band alone states a conclusion and withholds its premise, and because the next thing worth explaining about a ranking will not be the last.

type ProgressEvent added in v0.76.0

type ProgressEvent struct {
	// Total is how many jobs were planned, and Complete how many have finished. Including those that
	// failed, were served from cache, or shared a scan with an identical job. A reader watching this
	// wants to know when it ends, and every one of those ends it.
	Total    int
	Complete int
	// Running names what is in flight as "control/scanner", sorted so the line does not reorder
	// itself between updates for reasons that mean nothing.
	Running []string
	// Steps is the same run broken down by what is doing the work, so a display can show a
	// scanner finishing rather than vanishing. Sorted by name, so it does not reorder itself
	// between updates for reasons that mean nothing to a reader watching it.
	Steps []ProgressStep
	// Failed is how many jobs have failed so far.
	//
	// Reported while the run continues because the answer changes what a reader does with the
	// next twenty seconds. A scan whose every image job is failing to authenticate is one to
	// stop and fix, and learning that only from the report means waiting out a run that was
	// never going to cover them.
	Failed int
	// Refreshing names the scanner data being refreshed before the jobs start, such as "trivy
	// vulnerability database", and is empty once the jobs have begun. On a first run that refresh
	// can be most of the wait, and a display showing no job moving cannot say why without it.
	Refreshing string
}

ProgressEvent is what a run is doing at one moment: how much is done, and what is in flight.

A snapshot rather than a stream of starts and stops, because the consumer renders a line and a line shows a state. Reconstructing that state from events is work every consumer would repeat, and get subtly differently.

type ProgressFunc added in v0.76.0

type ProgressFunc func(ProgressEvent)

ProgressFunc receives a snapshot whenever a job starts or finishes.

Called while the run holds its lock, so it must not block: it exists to update a display, and a display that stalls the scan it describes is worse than no display.

type ProgressStep added in v0.96.0

type ProgressStep struct {
	// Control and Scanner name the work. Together they are how a reader recognizes it.
	Control string
	Scanner string
	// Total is how many jobs this pair has, and the rest is where they have got to.
	Total   int
	Done    int
	Failed  int
	Running int
	// RunningSince is when this step's earliest still-running job started, zero when none is.
	//
	// A time rather than a duration, so a display can recompute the elapsed figure whenever it
	// repaints. Progress is reported when a job starts or finishes, and a step with one slow job
	// produces no events at all while it runs. Which is exactly when somebody is asking whether it is
	// working.
	RunningSince time.Time
}

ProgressStep is one control/scanner pair and how its jobs are going.

Planned up front rather than discovered as work starts, so the display can show what has not begun as well as what has: a reader watching a list that only grows cannot tell a scanner that is slow from one that has not been reached.

func (ProgressStep) Name added in v0.96.0

func (s ProgressStep) Name() string

Name is how the step is identified in a display.

type ReachabilitySummary added in v0.101.0

type ReachabilitySummary struct {
	// Analyzers are the per-tool breakdowns, ordered by name. Empty when none ran.
	Analyzers []AnalyzerReachability
	// Reachable, Unreachable and Unknown are the totals across every analyzer.
	Reachable   int
	Unreachable int
	Unknown     int
}

ReachabilitySummary counts what reachability analysis concluded, so a reader can see the analysis happened and how far it got.

Unknown is reported rather than folded into a total, because it is the number that says how much of the answer is missing. A run reporting forty unreachable and nothing unknown is a different claim from one reporting four and thirty-six, and a single "unreachable" count cannot tell them apart.

Broken down per analyzer rather than summed, because more than one can run: they cover different ecosystems and reach their answers by different methods, and a single total would present a framework heuristic and a call graph as one number. It is also the shape that cannot silently pick a winner, one analyzer named for a run that used two is a report that is right about half of itself.

func (ReachabilitySummary) Ran added in v0.102.0

func (r ReachabilitySummary) Ran() bool

Ran reports whether any reachability analyzer contributed to this run.

type Refusal added in v0.162.0

type Refusal struct {
	// Registry is the image's registry, as `docker login` names it: `docker.io` for Docker Hub.
	Registry string `json:"registry"`
	// Status is the HTTP status the refusal amounts to: 401 when the registry asked for a
	// credential, 403 when it declined the request it was given.
	Status int `json:"status"`
	// Credential is whether the machine held a credential for Registry where the scanners read one,
	// asked after the scans. Absent when the run did not ask, or the configuration could not be read.
	Credential *bool `json:"credential,omitempty"`
	// LocalDaemon is whether the local Docker daemon held the image, asked after the scans. An image
	// built here and never pushed is one a registry has nothing of, so its answer is not the
	// problem, and logging in does not change it.
	LocalDaemon bool `json:"localDaemon,omitempty"`
}

Refusal is a container registry declining to serve an image to the machine that ran the scan.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds the controllers and scanners available to the engine, keyed by name.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) CheckExclusive added in v0.166.2

func (r *Registry) CheckExclusive(known ...string) error

CheckExclusive reports a registered scanner whose ScannerInfo.Exclusive is not one of known. Two scanners meant to share a resource and naming it differently would each take a lock of their own and run beside each other, so this is for a test over the real registry, given the declared resource constants, rather than for a run.

func (*Registry) CheckReadsAfter added in v0.166.2

func (r *Registry) CheckReadsAfter() error

CheckReadsAfter reports a registered scanner whose ScannerInfo.ReadsAfter names a scanner the registry does not hold, or declarations across the registry that form a cycle. Both are a programming error in whoever declared them, so this is for a test over the real registry rather than for a run, which tolerates the first (nothing of an unknown scanner is ever planned) and reports the second.

func (*Registry) Controller

func (r *Registry) Controller(name string) (plugin.Controller, bool)

Controller returns the named controller, if registered.

func (*Registry) Controllers added in v0.18.0

func (r *Registry) Controllers() []plugin.Controller

Controllers returns all registered controllers, sorted by Info().Name for stable output.

func (*Registry) RegisterController

func (r *Registry) RegisterController(c plugin.Controller)

RegisterController adds a controller, keyed by its Info().Name.

func (*Registry) RegisterScanner

func (r *Registry) RegisterScanner(s plugin.Scanner)

RegisterScanner adds a scanner, keyed by its Info().Name.

func (*Registry) Scanner

func (r *Registry) Scanner(name string) (plugin.Scanner, bool)

Scanner returns the named scanner, if registered.

func (*Registry) Scanners added in v0.7.0

func (r *Registry) Scanners() []plugin.Scanner

Scanners returns all registered scanners, sorted by Info().Name for stable output.

type RemoteResolver added in v0.70.0

type RemoteResolver func(path string) string

RemoteResolver reports the repository a local checkout was cloned from, or "" when the path is not a local checkout, has no remote, or should not be resolved.

Injected because resolving one means running git, which lives in internal/, the same arrangement as the SBOM generator. It also makes "do not resolve" expressible by simply not supplying one, which is what a vendored copy or an air-gapped mirror wants: there the path is the more truthful answer, because the remote is absent or names something the tree no longer matches.

type Result

type Result struct {
	Controls map[string]plugin.ControlResult
	Stats    Stats
	// Scope is what the run was narrowed to, empty when it was not narrowed at all.
	//
	// Carried on the result rather than left with the caller because every artifact a result
	// becomes has to be able to say so. A scoped report.json shaped exactly like an unscoped one
	// is a partial answer that anything downstream will read as a complete one.
	Scope Scope
	// Suppressed counts findings a config.exclude rule matched. They are still present in the
	// reports, marked with their justification. This is how many stopped counting.
	Suppressed int
	// LapsedExclusions are exclusions past their expiry date, which no longer suppress anything.
	// Reported so a finding that used to be accepted does not simply reappear with nothing to
	// say why.
	LapsedExclusions []saga.ExcludeRule
	// UnmatchedExclusions are rules that matched no finding in this run. Reported because an
	// exclusion doing nothing is indistinguishable from one that is working: it is usually a
	// typo, a rule id that moved, or a finding someone already fixed and forgot to stop excusing.
	UnmatchedExclusions []saga.ExcludeRule
	// Silenced counts findings the scanner set aside on its own: a directive in the source such as
	// a Semgrep `nosem`, or a rule in the scanner's own configuration such as a `.trivyignore`
	// line.
	//
	// Counted apart from Suppressed and Imported because it is the weakest of the three and the
	// only one nobody reviewed. A descriptor rule was written where whoever owns the descriptor
	// can see it; a supplier's claim is answerable by the supplier. This one was written wherever
	// it was convenient, possibly to get a build green, and folding it into either total would let
	// that hide inside a stronger answer.
	//
	// One count for both of the scanner's own, because what the number is for is true of each. The
	// finding itself carries which of the two it was.
	Silenced int
	// Imported counts findings excused by a claim somebody else made, a supplier's VEX document
	// rather than a rule in this descriptor. Counted apart from Suppressed because they answer the
	// auditor's question differently: one says we accepted this, the other says our supplier states
	// it does not apply, and a single total can only report the weaker of the two.
	Imported int
	// DevDependencies counts findings in development dependencies that a component's
	// config.controls.sca.devDependencies set aside. Apart from Suppressed because nobody judged
	// these findings: the setting names a kind of finding, and each carries OriginSetting.
	DevDependencies int
	// ProvidedDependencies counts findings in dependencies the runtime provides that a component's
	// config.controls.sca.providedDependencies set aside, apart from Suppressed for the reason
	// DevDependencies is.
	ProvidedDependencies int
	// CPEMatches counts findings a scanner matched only through a CPE that a component's
	// sca or images cpeMatches set aside, apart from Suppressed for the reason DevDependencies is.
	CPEMatches int
	// OwnPackages counts findings about the project's own package that a component's
	// config.controls.sca.ownPackages set aside, apart from Suppressed for the reason DevDependencies
	// is.
	OwnPackages int
	// NonShipping counts findings under documentation, examples or tests that a component's
	// nonShippingPaths, under sast, iac or sca, set aside, apart from Suppressed for the reason
	// DevDependencies is. The findings it counted are not here: they carry the mark and count.
	NonShipping int
	// DetectSecretsBaselines counts findings on the hashes a detect-secrets baseline records that a
	// component's config.controls.secrets.detectSecretsBaselines set aside, apart from Suppressed
	// for the reason DevDependencies is.
	DetectSecretsBaselines int
	// VEX is the supplier documents this run read, with what each contributed. Present even when
	// a document excused nothing, which is the case worth seeing: a document matching no finding
	// looks exactly like one that was never configured.
	VEX []vex.Resolved
	// UnmatchedClaims are supplier statements nothing in this run matched, for the same reason
	// UnmatchedExclusions exists. Usually it means the supplier and the scanner name a package
	// differently, which is a real finding about the document rather than a quiet no-op.
	UnmatchedClaims []vex.Claim
	// Effects records what this run did to its targets beyond reading them, deduplicated. Only
	// scans that actually executed count: a cache hit means the traffic was not sent this time,
	// and a record of effects has to describe what happened rather than what was configured.
	Effects []plugin.Effect
	// Consent is which effects the run accepted, after --allow-effects, beside what the
	// descriptor's config.allowEffects declared.
	Consent EffectConsent
	// Skipped are jobs that were planned and then not run, because the scanner could not answer
	// the question the target asked. Reported because a scanner that quietly does not run is
	// indistinguishable, in the output, from one that ran and found nothing.
	Skipped []SkippedJob
	// FailedScans are the jobs whose scanner returned an error, one per job, each with the scanner's
	// version and the target it was reading. A failed job leaves no report and so no provenance, and
	// without this a scanner that ran and failed reads the same, in an account of what ran, as one
	// that was never configured.
	FailedScans []FailedScan
	// Reported names, per control, the scanners whose jobs returned a report, sorted: from a scan,
	// from the cache or from a scan shared with another job. Beside FailedScans it says which of a
	// control's scanners its counts come from when another of them failed. Recorded here rather than
	// read off the reports' provenance, which a scanner reporting no version does not leave.
	Reported map[string][]string
	// Targets is what became of each distinct target the run planned: read, failed or skipped, and
	// the components that declared it. A count of what was declared beside what was reached is the
	// one thing a reader of the report cannot otherwise get without parsing scanner text.
	Targets []TargetOutcome
	// Inputs is what the dependency scans read, per component and control, with the dependency
	// files in the tree that none of them read. Reported because a scan that could not read a
	// manifest finds nothing in it, and that reads as a clean result.
	Inputs []InputCoverage
	// UnreadChecks are the checks a scan could not evaluate, by component and service, each with
	// the reason. Reported because a check whose read was denied can pass, fail or say nothing, and
	// none of those is a result.
	UnreadChecks []UnreadChecks
	// Scanners names every scanner this run used, deduplicated and sorted.
	//
	// Recorded because a report has to be able to say which tools produced its findings. The SARIF
	// driver name is the tool's own and does not identify the scanner Draugr selected, so nothing
	// downstream could work it out. Cache hits count: the key includes the tool version, so a hit
	// describes the same build as the run that stored it.
	Scanners []string
	// SBOMs are the Software Bills of Materials produced when the Saga enables config.sbom.
	// Evidence rather than judgement: they carry no findings and never affect the verdict.
	SBOMs []sbom.Document
	// SBOMFailures are the documents config.sbom asked for and the run did not produce, each with
	// its reason. Each one is also a ScanErrors entry under (sbom); this is the same failure with
	// the target it was about.
	SBOMFailures []SBOMFailure
	// Consulted names the exploitability datasets this run had loaded, whether or not any of
	// them moved a finding. Carried for the same reason VEX documents are carried even when they
	// excused nothing: a dataset that fired for nothing looks exactly like one nobody loaded.
	Consulted []sarif.Consulted
	// ContextFloors names the controls whose findings this run ranked at a context tier of their
	// own, whatever the component declares: the controls a report's floor row is about. Empty when
	// the caller did not say, which a report reads as no floor applied.
	ContextFloors []string
	// ScanErrors records, per control, what stopped it completing, a missing scanner binary, a tool
	// that exited badly, a plan that couldn't be built. A control listed here checked less than it
	// was asked to, so its absence of findings is not evidence of absence, and callers that treat an
	// empty report as "clean" would be wrong.
	ScanErrors map[string][]string
	// MissingTools names the scan errors that are a tool absent from this machine, one entry per
	// control and tool, sorted. Each entry's Message is the ScanErrors entry it explains, word for
	// word, so a renderer can say it more briefly without losing the rest.
	MissingTools []MissingTool
	// Reachability summarizes what a reachability analyzer concluded about this run's dependency
	// findings, and is zero when none ran.
	Reachability ReachabilitySummary
	// Correlated counts flaws that more than one scanner reported, and which are therefore
	// counted once rather than once per scanner. Zero when no two scanners agreed on anything,
	// which includes every run with one scanner per control.
	Correlated int
}

Result is the outcome of a run: one aggregated ControlResult per control, plus run statistics.

func (Result) Incomplete added in v0.165.4

func (r Result) Incomplete(control string) bool

Incomplete reports whether a scan error was recorded against control: a job of it failed, or it could not be planned. A report decides that a control is in error from this, so the console's ERROR and report.json's verdict for one control rest on the same fact.

func (Result) Partial added in v0.165.4

func (r Result) Partial(control string) (reported, failed []string)

Partial splits an incomplete control's scanners into the ones that reported and the ones that failed, each sorted. reported holds only scanners that failed no job of the control, so the two never name one scanner. Both are empty unless the control has a scanner on each side, so a control whose every scanner failed a job, or whose one scanner read one target and failed on another, names nothing.

type SBOMFailure added in v0.161.0

type SBOMFailure struct {
	// Scope is the document that failed: saga.SBOMScopeComponent for one target's inventory, and
	// saga.SBOMScopeProject for the document assembled from them.
	Scope saga.SBOMScope
	// Component and Target name the target whose inventory failed, as a document taken from it
	// names it (sbom.TargetName). Both are empty on a project document, and on a failure that
	// belongs to no one target: no generator configured, or the run canceled.
	Component string
	Target    string
	// Format is the format that was asked for.
	Format saga.SBOMFormat
	// Reason is what stopped it, in the generator's words, the same text ScanErrors records under
	// (sbom).
	Reason string
}

SBOMFailure is an SBOM document config.sbom asked for that the run did not produce.

type ScannerData added in v0.152.0

type ScannerData struct {
	// Tool is the executable that reads the data, or the scanner's name for one Draugr runs itself.
	Tool string
	plugin.DataState
}

ScannerData is one data source a run read, and the tool that reads it.

func DataStates added in v0.152.0

func DataStates(ctx context.Context, scanners []plugin.Scanner) []ScannerData

DataStates asks each scanner that reports its data (plugin.DataStater) for that data's state, in the order given, and keeps one entry per tool and data source: the database four Trivy scanners share appears once.

type Scope added in v0.71.0

type Scope struct {
	Components []string
	Controls   []string
	// Labels, Exposure and Criticality select components by what they are rather than by name.
	//
	// A monorepo is the case they exist for. A team knows the label it files under; it does not
	// know which of two hundred component names carry that label this week, and a list written out
	// by hand goes stale the first time somebody adds one.
	//
	// All three resolve into Components before a run starts, so everything downstream sees a
	// concrete set and nothing else has to learn a second way of being narrowed.
	//
	// Labels are `key=value` over the component's own metadata, which is the organization's
	// vocabulary: Draugr reads no key here and attaches no meaning to one. Exposure and
	// Criticality are Draugr's own, a closed set, so a value that is not one of them is rejected by
	// name rather than left to match nothing.
	//
	// Within a selector the values are alternatives, and across selectors they narrow together:
	// `Labels: ["team=web"], Exposure: ["public"]` is the web team's public components.
	Labels      []string
	Exposure    []saga.Exposure
	Criticality []saga.Criticality
	// SkippedComponents are the declared components this scope leaves out, filled in by Resolve.
	//
	// Carried rather than recomputed because the descriptor is not available everywhere the scope is
	// read. A rendered report knows what ran, not what was declared. Naming them rather than
	// counting them: "10 not scanned" tells a reader they are missing something and not which thing,
	// and the answer is one the run already had.
	SkippedComponents []string
}

Scope narrows a run to named components and controls, without changing the descriptor.

The distinction it exists for: `config.controls` records a decision. This project does not need `dast`. And a filter is a view over one run. Editing the first to get the second is how a temporary change gets committed, and how a control ends up disabled in main because somebody was debugging.

The zero value scans everything, so a caller that never sets one is unaffected. An empty list means "no restriction on this axis", not "nothing": `Scope{Components: []string{"app"}}` runs every control against one component.

A scoped run is still gated and still produces a verdict. The alternative is answering "is my fix good?" with "no verdict", which sends the reader back to a full scan and makes the filter useless for the loop it exists for. What a scoped run must never do is look like an unscoped one, so the scope travels with the result and into every artifact that result becomes.

func (Scope) Empty added in v0.71.0

func (s Scope) Empty() bool

Empty reports whether this scope restricts nothing, which is the ordinary case.

Read after Resolve, where a selector has become a component list. Before it, a scope that selects restricts something even though Components is still empty.

func (Scope) IncludesComponent added in v0.71.0

func (s Scope) IncludesComponent(name string) bool

IncludesComponent reports whether a component is in scope.

Exported because the report has the same question to answer: a component the scope left out must be rendered as not scanned rather than as passing, and only this type knows which those are.

func (Scope) Resolve added in v0.71.0

func (s Scope) Resolve(model saga.Model) Scope

Resolve returns a copy of this scope with the selectors turned into component names and SkippedComponents filled in from the descriptor, so everything downstream can say what ran and what was left out without needing the descriptor again.

Selecting by label or by classification produces a concrete list here rather than staying a rule evaluated later. Two things depend on that and neither would be obvious from the flag: the scope a report states is what was actually covered, and the SARIF automation id a run publishes under is built from the component list, so two teams scanning one commit stay in separate categories instead of replacing each other's alerts.

func (Scope) Selectors added in v0.123.0

func (s Scope) Selectors() []Selector

Selectors is what was asked for, for a report that has to state the request as well as the result. Empty where the scope named components outright.

func (Scope) Validate added in v0.71.0

func (s Scope) Validate(model saga.Model, controls []string) error

Validate rejects a scope naming something the descriptor or the registry does not have.

A misspelling is the whole failure this guards: `--components frontnd` matches nothing, scans nothing, and passes. The same "we did not look" verdict a filter is otherwise careful not to produce, reached by typo. The error lists what is available, because the reader is one character away from the answer and should not have to go and find it.

type Selector added in v0.123.0

type Selector struct{ Key, Value string }

Selector is one narrowing a caller asked for by what a component is rather than by its name.

type SkippedJob added in v0.79.0

type SkippedJob struct {
	Control   string
	Scanner   string
	Component string
	// Reason is a sentence a reader can act on, or decide not to.
	Reason string
	// contains filtered or unexported fields
}

SkippedJob is a job that was planned and then not run, because the scanner cannot answer the question the target asks.

Recorded rather than dropped. A scanner that quietly does not run is the same thing as one that found nothing, and the report has no way to tell them apart. Which is the failure this whole codebase is built to avoid. The alternative that was tried first, refusing the descriptor, is worse: it makes a reader hand-write an exception to state something Draugr already knows.

type Stats

type Stats struct {
	Jobs      int
	Scans     int
	CacheHits int
	// UnpinnedCacheHits names the targets whose result came from a cache entry that could not be
	// content-addressed, today, images the descriptor identifies by a tag alone. Sorted and
	// deduplicated.
	//
	// A hit like that is right about its key and possibly wrong about the image: the tag can have
	// been rebuilt and repushed since, and nothing about the reused report would say so. Draugr
	// cannot know without asking the registry, so it reports which results rest on that
	// assumption instead of presenting them as though they did not.
	UnpinnedCacheHits []string
	// OldestCacheHit is when the oldest reused entry was written, zero when nothing was reused
	// or the cache cannot say. An instant rather than an age: a duration is only true at the
	// moment it is computed, and a kept report is read later.
	OldestCacheHit time.Time
	// OldestCacheAge is that same entry's age at the moment it was reused, for the console, which
	// is read now and where a date is a thing to subtract rather than a thing to know. Recorded
	// here because rendering holds no clock: the console is a pure function of this struct, which
	// is what lets a golden test pin it.
	OldestCacheAge time.Duration
	// Cache describes the cache this run was given, and is nil when it was given none. That
	// distinction is the one the counts cannot carry: a run told not to cache and a run whose
	// every entry had expired both report zero hits.
	Cache *cache.Description
	// Deduped counts jobs that reused an identical scan already running/completed in this run
	// (in-run singleflight), rather than scanning or hitting the persistent cache.
	Deduped int
	// Concurrency is the maximum number of scan jobs run in parallel for this run (the
	// effective value after applying WithConcurrency or the machine default).
	Concurrency int
	// PeakToolMemory is the largest resident memory, in bytes, that any single tool process
	// reached, read from the operating system once the jobs and SBOMs are done. One process, not a
	// sum across those that ran at once. Zero where the platform does not report it.
	//
	// Recorded because a run that came close to exhausting the machine otherwise finishes looking
	// like any other, and the next, larger one is the run that fails.
	PeakToolMemory uint64
	// PeakOwnMemory is the largest resident memory, in bytes, Draugr's own process reached, read
	// with PeakToolMemory and leaving the tools out. Zero where the platform does not report it.
	// Draugr holds what the tools report, and reads and decodes their output, so a run's memory is
	// this as well as the tools'.
	PeakOwnMemory uint64
	// MemoryLimit is the memory, in bytes, this process may use: the machine's, or the lowest
	// cgroup limit above it where that is lower. Zero where neither is known. Beside the two peaks
	// so a reader can tell a run that came close to being killed from one that did not.
	MemoryLimit uint64
	// JobMemory is, for each job that ran a tool, the largest resident memory one of its tool
	// processes reached, with the processes that process waited for, sorted by scanner, then
	// target. A job served from the cache, or by another job's identical scan, ran none and has no
	// entry.
	JobMemory []JobMemory
	// Duration is wall-clock for the whole run, and ByControl is how long each control's jobs
	// took summed across them. Reported because "why is this slow" is a question a job count
	// cannot answer: with concurrency the parts do not add up to the whole, and the control
	// worth attention is the slowest one rather than the one with the most jobs.
	Duration  time.Duration
	ByControl map[string]time.Duration
	// Unscanned names what each component has that none of its jobs read: one entry per component
	// and target, carrying the failed job that was going to look at it. A target two components
	// declare appears once for each of them, and a target-level count reads Targets instead.
	//
	// Recorded per target rather than only per control, because a control's error says a scan
	// failed and not what went unexamined. A component whose every image failed to pull has had
	// nothing looked at, and a report that cannot say so has to describe it as passing.
	Unscanned []Unscanned
	// Failures are the failed jobs behind each target no scanner reached, every one of them rather
	// than one per target, leaving out a job whose tool was not installed. Each carries the error its control reports, so a renderer that names the
	// target once can leave that error out of the control's own; a failure on a target another
	// scanner read is not here, and stays the control's error alone.
	Failures []Unscanned

	// ToolWaits is time the run spent queueing for a tool's own cache rather than scanning,
	// summed per tool. Reported because a run that took three times as long deserves a reason,
	// and because these waits are Draugr's own doing: it plans concurrent jobs that share one
	// tool cache, so the contention is a cost of the scheduling rather than a fault of the tool.
	ToolWaits map[string]time.Duration

	// OrderWaits is time a scanner's jobs spent waiting for other jobs' work, summed per waiting
	// scanner: for the jobs it reads after on the same target to finish (ScannerInfo.ReadsAfter),
	// and for the job holding a resource it uses whole to end (ScannerInfo.Exclusive), which may be
	// a job of the same scanner on another target. Kept apart from ToolWaits, which the console
	// words as a wait for that tool's own cache: an ordering wait is for other jobs' work, and the
	// waiting scanner has no cache of its own being contended.
	OrderWaits map[string]time.Duration

	// DataRefresh is how long each scanner took to refresh its data before the jobs started, in
	// the order the scanners were warmed. The run's duration includes it, and on a run that
	// downloaded a database it is most of the difference from the run before, so a reader asking
	// why this one took longer gets the answer rather than a slower total.
	DataRefresh []DataRefresh

	// Data is the state of each data source the run's scanners read, as the tools report it after
	// the warm-up: its version, when it was published and when this machine downloaded it. One
	// entry per tool and data source, so the database four Trivy scanners share appears once.
	Data []ScannerData
}

Stats summarizes execution, including cache effectiveness.

type TargetOutcome added in v0.144.0

type TargetOutcome struct {
	Kind   string       `json:"kind"`
	Target string       `json:"target"`
	Status TargetStatus `json:"status"`
	// Detail is why the target was not reached: the first failure in the scanner's words, or the
	// reason it was skipped. Empty when it was reached.
	Detail string `json:"detail,omitempty"`
	// Components are the components that declared it, so a target that was not reached can be
	// read as the components it leaves unscanned.
	Components []string `json:"components,omitempty"`
	// Refusal is the registry's answer when the target is an image its registry declined to serve,
	// and nil otherwise.
	Refusal *Refusal `json:"refusal,omitempty"`
}

TargetOutcome is what became of one distinct target the run planned.

Identified the way `draugr doctor` identifies targets, so a target doctor checked and the same target in a run's report match: a repository by its source and revision, an image by its pinned reference, a host by its URL and a cluster by its name.

type TargetStatus added in v0.144.0

type TargetStatus string

TargetStatus is what became of a target a run planned.

const (
	// TargetReached is a target at least one job read.
	TargetReached TargetStatus = "reached"
	// TargetFailed is a target every job for it tried and failed to read.
	TargetFailed TargetStatus = "failed"
	// TargetSkipped is a target no job was run for, for a reason the run states: the scanner could
	// not honor its scope, or the tool was not installed.
	TargetSkipped TargetStatus = "skipped"
)

The outcomes a planned target can have.

type UnreadChecks added in v0.145.0

type UnreadChecks struct {
	Component string
	Control   string
	// Group is what the checks read, the cloud service, such as "compute".
	Group string
	// Checks are the identifiers of the checks with no result, sorted.
	Checks []string
	// PartlyRead are the identifiers of the checks that returned results from the reads they were
	// allowed, sorted. Their findings are in the report, and they are not decided.
	PartlyRead []string
	// Reason is why, the first stated for the group: "denied compute.instances.list".
	Reason string
	// Kind is the reason's kind, sarif.UncheckedDenied or sarif.UncheckedPrecondition, or empty where
	// the scanner does not say: what clears the group, a grant or a scan from another account.
	Kind string
}

UnreadChecks are the checks of one service a component's scan could not evaluate, or evaluate in full, and why.

Grouped by service because that is what a reader acts on: a denied read is fixed by granting the permission it needs, once, and it clears every check that reads the service.

type UnreadInput added in v0.133.0

type UnreadInput struct {
	Repository string
	Path       string
	// Reason is why it contributed nothing: "no lockfile", "no pinned versions", "no packages
	// read", or for a file Trivy failed to parse "not parsed: " and the parser's error, as
	// `not parsed: JSON decode error: json: cannot unmarshal JSON string into Go
	// map[string]interface {} within "/packages/left-pad"`. For a Terraform file the module blocks
	// not loaded, as `module "vpc" not loaded`, and for a Terraform root module the calls not
	// evaluated, as `32 of 33 module calls checked; "zbad" skipped`. For a Helm chart's Chart.yaml,
	// what stopped Trivy rendering the chart, as `run helm dependency build; redis not in
	// charts/`. For a file searched for
	// secrets, "archive extension, not read" and what to do about it, or at the repository root
	// "no files read". For a source file Semgrep skipped or did not finish, `over 1 MB, not scanned`
	// and what to do about it, or the rules that
	// timed out on it, as `1 rule timed out, not checked: "x"`. For a go.mod, why govulncheck could
	// not load the module.
	//
	// For a requirements file read in part, the requirements not read, as `1 requirement not
	// pinned: urllib3`, and for a pom.xml Trivy did not resolve, `2 dependency versions not
	// resolved, run mvn dependency:resolve` or `transitive dependencies not resolved, run mvn
	// dependency:resolve`. For a file whose packages the license scan read with no license for any,
	// `records no licenses for 12 packages`, or `licenses of 12 packages not read, run dotnet
	// restore` (or `run go mod download`) where a command fills the cache the licenses are read from.
	Reason string
	// Kind is the scanner's name for the file's format (sarif.Input.Kind), empty where none said.
	Kind string
	// Partly marks a file a scan took some packages from and not all, which Read counts as read.
	Partly bool
}

UnreadInput is a dependency file no scan of a control read packages from.

type Unscanned added in v0.96.0

type Unscanned struct {
	// Control and Scanner say which check did not happen.
	Control string
	Scanner string
	// Component is the part of the application it belonged to, empty for a project-wide control.
	Component string
	// Kind is the target kind, "image", "repository", "host", and Target names the instance. Together
	// they are what a reader needs to know what went unexamined.
	Kind   string
	Target string
	// Detail is why the job produced nothing, in the scanner's words.
	Detail string
	// contains filtered or unexported fields
}

Unscanned is one job that did not produce a report, and the target it was for.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL