Documentation
¶
Overview ¶
Package validation defines the Stage-4 contract: WHAT gets validated, WHAT counts as evidence, WHO gates it — but NOT HOW a technique runs.
Architectural note: OpenCTEM is agent-based. The API is an ORCHESTRATOR, not an executor. Actual exploit execution, cloud probes, and adversary emulation run on the agent that lives in the tenant's network, has tenant-local credentials, and can legally reach the target.
This package therefore holds:
- Data shapes (TechniqueID, Target, Evidence, Outcome)
- The attacker-profile gate (API-side policy)
- The Dispatcher contract (API submits a job → agent executes → agent posts Evidence back via the ingest API)
- EvidenceStore + Redactor (API persists, redacts secrets)
What this package does NOT hold:
- Any direct call to AWS / Atomic Red Team / Caldera / Nuclei. Those belong to the agent repo.
Index ¶
- Constants
- Variables
- func DowngradePct(downgraded, validated int) float64
- func Enforce(c ValidationCoverage, t CoverageThresholds) error
- func ValidDetectionStatus(d DetectionStatus) bool
- type AgentAvailability
- type AgentCapability
- type AssetLookup
- type AttackerProfile
- type CommandCreator
- type CommandDispatcher
- type CoverageThresholds
- type DefaultSelector
- type DetectionCorrelator
- type DetectionStatus
- type DetectionVerdict
- type Evidence
- func (e Evidence) Executor() stringdeprecated
- type EvidenceIngestService
- type EvidenceRepository
- type EvidenceStore
- func (s *EvidenceStore) ListForFinding(ctx context.Context, tenantID, findingID shared.ID) ([]StoredEvidence, error)
- func (s *EvidenceStore) Record(ctx context.Context, tenantID, findingID shared.ID, simulationRunID *shared.ID, ...) (StoredEvidence, error)
- func (s *EvidenceStore) SetDetectionCorrelator(c *DetectionCorrelator)
- type ExecutorKind
- type FindingLookup
- type FindingMutator
- type IngestResult
- type JobDispatcher
- type NucleiAvailability
- type Outcome
- type ProofOfFixService
- type Redactor
- type RetestNotifier
- type RunService
- func (s *RunService) DispatchSimulationCheck(ctx context.Context, tenantID, simRunID, assetID shared.ID, technique string) (shared.ID, error)
- func (s *RunService) SetAgentAvailability(a AgentAvailability)
- func (s *RunService) SetNucleiAvailability(a NucleiAvailability)
- func (s *RunService) ValidateFinding(ctx context.Context, tenantID, findingID shared.ID) (shared.ID, error)
- type Selector
- type SeverityCoverage
- type StoredEvidence
- type Target
- type TechniqueID
- type TelemetryProbe
- type ValidateCommandPayload
- type ValidateResultPayload
- type ValidateTargetPayload
- type ValidationCoverage
- type ValidationDispatcher
- type ValidationJob
- type Verdict
- type VerdictRecorder
Constants ¶
const ( DetectionPostWindow = 5 * time.Minute DetectionPreGrace = 30 * time.Second )
Correlation window.
postWindow — how long AFTER the probe ends we keep accepting telemetry as caused by it. 5 minutes: EDR/XDR agents batch and forward on a timer (CrowdStrike/Defender/osquery forwarders are typically seconds to ~2 min; SIEM relay adds more), so anything shorter turns normal pipeline latency into fabricated detection gaps. Longer buys little: a sensor that takes >5 min is not providing actionable detection anyway.
preGrace — how long BEFORE the recorded start we accept. Small (30s) and exists only to absorb clock skew between the agent host and the API, plus the gap between the command being issued and the probe firing.
Failure modes, stated plainly:
- FALSE NEGATIVE (reported not_observed though a control did fire): telemetry that arrives later than postWindow, e.g. an hourly batch forwarder. Mitigated by correlation_id, which is time-independent — a stamped event matches whenever it lands, as long as it lands before this evaluation runs.
- FALSE POSITIVE (reported observed though nothing detected us): unrelated telemetry on the same asset inside the window. This is the real risk of time-based matching on a busy host. Mitigated two ways: (a) heuristic matching is restricted to event types a network probe could plausibly cause, and (b) every verdict records its match_mode, so an "observed" reached heuristically is auditable and never silently equated with an exact match.
const AgentCapabilityValidate = "validate"
AgentCapabilityValidate is the capability string a validate-capable agent advertises and the one a validate command requires for routing. It is the single source of truth shared by the dispatch payload (RequiredCapabilities) and the pre-flight availability gate (RunService.ensureAgentAvailable) so the two never drift: the gate opens exactly when a queued command can be routed.
const AgentCapabilityValidateNuclei = "validate:nuclei"
AgentCapabilityValidateNuclei is the capability a nuclei-re-verify-capable agent advertises (RFC-011.2 Phase 2b). It is strictly deeper than AgentCapabilityValidate: an agent that can run a single detection template advertises BOTH, and a KindNuclei command requires this one so it is only ever routed to an agent that can execute it — never a safe-check-only agent. The gate that decides whether to route KindNuclei (NucleiAvailability) queries for exactly this capability, so the two never drift.
Variables ¶
var DefaultThresholds = CoverageThresholds{
P0: 100,
P1: 100,
P2: 80,
P3: 0,
}
DefaultThresholds matches the commitment: full coverage on P0/P1, 80% on P2, optional on P3.
var ErrCoverageBelowSLO = errors.New("validation coverage below SLO")
ErrCoverageBelowSLO is returned by Enforce when any class is under its threshold. Message enumerates the offending classes so the operator sees exactly which P0s are missing evidence.
var ErrInvalidOutcome = fmt.Errorf("%w: invalid evidence outcome", shared.ErrValidation)
ErrInvalidOutcome is returned when the evidence outcome is not a known value.
var ErrNoExecutor = errors.New("no executor available")
ErrNoExecutor is returned by Selector.Select when nothing in the available list matches the policy.
var ErrNoValidationAgent = fmt.Errorf("%w: no validation-capable agent is online for this tenant; deploy a validation agent to run this check", shared.ErrValidation)
ErrNoValidationAgent is returned when a validation job would be dispatched but no validation-capable agent is currently online for the tenant. This makes the dispatch capability-gated exactly like scan dispatch (agent.AgentSelector.CheckAgentAvailability): the platform must never enqueue a validate command that no agent can consume, which would sit in the queue forever (the "silently inert" defect) and, for a live simulation, strand its run in "running". Callers treat it as an expected skip: the auto-proof-of-fix path logs once and moves on, the live-simulation path falls back to its clearly-labeled synthetic result, and the manual endpoint tells the operator to deploy a validation agent. It wraps ErrValidation so the HTTP layer surfaces a 400 with the message rather than a 500. The gate is self-arming: the moment a tenant registers an agent advertising the "validate" capability, dispatch begins — no code change or redeploy.
var ErrNotNetworkAddressable = fmt.Errorf("%w: asset is not network-addressable for a safe-check re-check", shared.ErrValidation)
ErrNotNetworkAddressable is returned when a finding's asset has no network address a safe-check reachability probe can dial (e.g. a code repository, container image, or cloud-account finding). Callers that auto-dispatch validation (e.g. proof-of-fix on fix_applied) treat it as an expected skip, not a failure.
Functions ¶
func DowngradePct ¶ added in v0.6.0
DowngradePct computes the CTEM "downgrade %" outcome metric: of the findings that have been validated, the share that a validation re-check downgraded (verdict not_reproducible on a still-open finding). Returns 0 when nothing has been validated yet — an honest "0% measured", distinct from the pre-2a "not measured" blank. Result is clamped to [0,100].
func Enforce ¶
func Enforce(c ValidationCoverage, t CoverageThresholds) error
Enforce returns nil when every class meets its threshold, else ErrCoverageBelowSLO wrapped with a human-readable breakdown. Used by the cycle-close handler: no close if coverage is under.
func ValidDetectionStatus ¶ added in v0.5.0
func ValidDetectionStatus(d DetectionStatus) bool
ValidDetectionStatus mirrors the DB CHECK constraint.
Types ¶
type AgentAvailability ¶ added in v0.6.0
type AgentAvailability interface {
HasValidationAgent(ctx context.Context, tenantID shared.ID) (bool, error)
}
AgentAvailability reports whether a validation-capable agent is currently online for a tenant. It is the validation-side mirror of the scan dispatch pre-flight capability check: a real implementation asks the agent registry for online, in-capacity agents advertising the "validate" capability (AgentCapabilityValidate); the test stub returns a fixed answer. Optional on RunService — a nil gate preserves the pre-gate behavior (always dispatch).
type AgentCapability ¶
type AgentCapability interface {
AvailableExecutorKinds(ctx context.Context, tenantID shared.ID) ([]ExecutorKind, error)
}
AgentCapability lets the service ask "which ExecutorKinds are currently available for this tenant?" before selecting. A real implementation looks at agent registrations; the test stub returns a static slice.
type AssetLookup ¶ added in v0.3.0
type AssetLookup interface {
GetByID(ctx context.Context, tenantID, assetID shared.ID) (*asset.Asset, error)
}
AssetLookup is the narrow read seam over the asset repository.
type AttackerProfile ¶
type AttackerProfile struct {
ID shared.ID
Name string
Capabilities []string // "external-unauth" | "credentialed" | "network-pivot" | ...
}
AttackerProfile is the narrow subset of the full profile that the API-side selection / gating logic needs. It never travels to the agent — the agent receives the already-approved executor kind and technique.
type CommandCreator ¶ added in v0.3.0
type CommandCreator interface {
Create(ctx context.Context, cmd *commanddom.Command) error
}
CommandCreator is the narrow seam over the command repository used to enqueue a validation job. Implemented by *postgres.CommandRepository.
type CommandDispatcher ¶ added in v0.3.0
type CommandDispatcher struct {
// contains filtered or unexported fields
}
CommandDispatcher implements JobDispatcher by creating a CommandTypeValidate command that a validate-capable agent polls and executes.
func NewCommandDispatcher ¶ added in v0.3.0
func NewCommandDispatcher(commands CommandCreator, log *logger.Logger) *CommandDispatcher
NewCommandDispatcher wires the dispatcher over the command repository.
func (*CommandDispatcher) Dispatch ¶ added in v0.3.0
func (d *CommandDispatcher) Dispatch(ctx context.Context, job ValidationJob) (shared.ID, error)
Dispatch enqueues the job as a tenant command and returns the command ID.
type CoverageThresholds ¶
CoverageThresholds define the SLO targets per priority class. Exported so tenants can override later (per-tenant-config).
type DefaultSelector ¶
type DefaultSelector struct{}
DefaultSelector applies a conservative mapping:
- safe-check is preferred when available — cheapest + legally safest
- nuclei is next for web-reachable targets
- atomic-red-team / caldera require a non-empty profile capability set (waiver + adversary emulation opt-in)
func (DefaultSelector) Select ¶
func (DefaultSelector) Select( tid TechniqueID, profile *AttackerProfile, available []ExecutorKind, ) (ExecutorKind, error)
Select picks the first available executor that fits the policy.
type DetectionCorrelator ¶ added in v0.5.0
type DetectionCorrelator struct {
// contains filtered or unexported fields
}
DetectionCorrelator turns a completed validation plus the telemetry stream into a DetectionStatus. Safe to construct with a nil probe — it then reports DetectionNotEvaluated rather than guessing.
func NewDetectionCorrelator ¶ added in v0.5.0
func NewDetectionCorrelator(probe TelemetryProbe) *DetectionCorrelator
NewDetectionCorrelator wires the correlator. probe may be nil, in which case every verdict is DetectionNotEvaluated.
func (*DetectionCorrelator) Evaluate ¶ added in v0.5.0
func (c *DetectionCorrelator) Evaluate( ctx context.Context, tenantID shared.ID, ev Evidence, correlationID shared.ID, ) DetectionVerdict
Evaluate decides whether anything observed the validation described by ev. correlationID may be zero (no producer stamped anything).
Order of checks is deliberate and is the safety property of this function: we refuse to say "not_observed" until we have positively established that telemetry is flowing for this tenant. Every earlier return is a form of "we don't know", never a control indictment.
type DetectionStatus ¶ added in v0.5.0
type DetectionStatus string
DetectionStatus is the verdict on whether anything observed a validation. Deliberately disjoint from Outcome — see file header.
const ( // DetectionObserved: telemetry correlated to this validation // arrived. Something in the stack saw it. DetectionObserved DetectionStatus = "observed" // DetectionNotObserved: the tenant IS shipping telemetry, but none // of it correlated to this validation. This is the only value that // asserts a real detection gap. DetectionNotObserved DetectionStatus = "not_observed" // DetectionNoTelemetrySource: no telemetry is reaching the platform // for this tenant at all. The honest reading is UNKNOWN — we did // not look at a control, so we cannot grade one. DetectionNoTelemetrySource DetectionStatus = "no_telemetry_source" // DetectionNotApplicable: the validation did not execute (error or // skipped), so there was no attack to detect. Grading detection // here would punish a control for our own failure to run. DetectionNotApplicable DetectionStatus = "not_applicable" // DetectionNotEvaluated: correlation did not run for this record // (probe unwired, or the row predates this feature). Never means // "no detection". DetectionNotEvaluated DetectionStatus = "not_evaluated" )
func (DetectionStatus) IsConclusive ¶ added in v0.5.0
func (d DetectionStatus) IsConclusive() bool
IsConclusive reports whether the verdict is based on an actual look at telemetry. no_telemetry_source / not_applicable / not_evaluated are all "we did not or could not look".
func (DetectionStatus) IsDetectionGap ¶ added in v0.5.0
func (d DetectionStatus) IsDetectionGap() bool
IsDetectionGap reports whether the status asserts a genuine control failure. Only DetectionNotObserved qualifies. Dashboards MUST use this rather than `!= observed`, or "no telemetry configured" gets rendered as "controls failed" — the exact misreport this feature exists to prevent.
type DetectionVerdict ¶ added in v0.5.0
type DetectionVerdict struct {
Status DetectionStatus
Detail map[string]any
}
DetectionVerdict is the correlator's output: the status plus enough detail for an operator to audit how it was reached.
type Evidence ¶
type Evidence struct {
// ExecutorKind identifies which agent-side tool produced this
// evidence. Enforced by the ingest handler against the
// ExecutorKind declared on the job.
ExecutorKind string
Technique TechniqueID
Target Target
StartedAt time.Time
EndedAt time.Time
Outcome Outcome
Summary string
Artifacts []string // attachment IDs (screenshots, PCAPs)
RawMeta map[string]any
// CorrelationID ties this execution to runtime telemetry that a
// producer stamped with the same id, giving an exact,
// time-independent detection match. Zero when nothing stamped
// anything — the correlator then falls back to an asset+window
// heuristic. See detection.go.
CorrelationID shared.ID
}
Evidence is everything a reviewer needs to judge whether the technique was executed and what it produced. Produced by the agent and POSTed back through the validation-ingest endpoint.
type EvidenceIngestService ¶ added in v0.3.0
type EvidenceIngestService struct {
// contains filtered or unexported fields
}
EvidenceIngestService records validation evidence submitted out-of-band — an agent that finished an async validation job, or a pentest retest reporting a result — and reconciles the finding status from the evidence outcome.
This is the activation seam that makes CTEM Stage-4 (Validation) functional without a synchronous in-process dispatcher: agent executes the technique → POSTs Evidence to the ingest endpoint → this service persists it (redacted) and applies the outcome to the finding.
func NewEvidenceIngestService ¶ added in v0.3.0
func NewEvidenceIngestService(store *EvidenceStore, finding FindingMutator, notifier RetestNotifier, recorder VerdictRecorder, log *logger.Logger) *EvidenceIngestService
NewEvidenceIngestService wires the ingest service. notifier and recorder may be nil (recorder-nil skips the durable verdict stamp that feeds downgrade %).
func (*EvidenceIngestService) Ingest ¶ added in v0.3.0
func (s *EvidenceIngestService) Ingest( ctx context.Context, tenantID, findingID shared.ID, simRunID *shared.ID, ev Evidence, ) (IngestResult, error)
Ingest persists the evidence (after redaction) and applies its outcome to the finding. The evidence is the source of truth and is always recorded first; if the finding cannot legally transition from its current state (e.g. already closed) that is logged but NOT fatal — the recorded evidence still surfaces.
func (*EvidenceIngestService) ListForFinding ¶ added in v0.3.0
func (s *EvidenceIngestService) ListForFinding(ctx context.Context, tenantID, findingID shared.ID) ([]StoredEvidence, error)
ListForFinding returns the evidence recorded for a finding (UI detail page).
type EvidenceRepository ¶
type EvidenceRepository interface {
Create(ctx context.Context, ev StoredEvidence) error
ListByFinding(ctx context.Context, tenantID, findingID shared.ID) ([]StoredEvidence, error)
}
EvidenceRepository persists StoredEvidence. Implemented by a postgres-backed type; tests use an in-memory fake.
type EvidenceStore ¶
type EvidenceStore struct {
// contains filtered or unexported fields
}
EvidenceStore is the app-layer facade. Calls redact → persist → returns the stored record so callers can surface it.
func NewEvidenceStore ¶
func NewEvidenceStore(repo EvidenceRepository) *EvidenceStore
NewEvidenceStore wires defaults. Detection correlation is off until SetDetectionCorrelator is called — until then every record is stored as DetectionNotEvaluated, never as a detection gap.
func (*EvidenceStore) ListForFinding ¶
func (s *EvidenceStore) ListForFinding( ctx context.Context, tenantID, findingID shared.ID, ) ([]StoredEvidence, error)
ListForFinding returns every evidence record attached to a finding in chronological order. The UI uses this on the finding detail page.
func (*EvidenceStore) Record ¶
func (s *EvidenceStore) Record( ctx context.Context, tenantID, findingID shared.ID, simulationRunID *shared.ID, ev Evidence, ) (StoredEvidence, error)
Record persists the evidence after redaction. Returns the stored envelope with ID populated. Errors from the repo are propagated.
func (*EvidenceStore) SetDetectionCorrelator ¶ added in v0.5.0
func (s *EvidenceStore) SetDetectionCorrelator(c *DetectionCorrelator)
SetDetectionCorrelator enables "did our controls react?" evaluation. Called from services bootstrap after both the store and the telemetry probe exist — mirrors RuntimeTelemetryHandler.SetCorrelator and avoids a wiring-order cycle.
type ExecutorKind ¶
type ExecutorKind string
ExecutorKind enumerates the validation tool the AGENT will run. The API uses this string to route jobs to agents that declare they support it. The API does not import or call the tool itself.
const ( KindSafeCheck ExecutorKind = "safe-check" KindAtomicRedTeam ExecutorKind = "atomic-red-team" KindCaldera ExecutorKind = "caldera" KindNuclei ExecutorKind = "nuclei" )
type FindingLookup ¶ added in v0.3.0
type FindingLookup interface {
GetByID(ctx context.Context, tenantID, id shared.ID) (*vulnerability.Finding, error)
}
FindingLookup is the narrow read seam over the finding repository.
type FindingMutator ¶
type FindingMutator interface {
Get(ctx context.Context, tenantID, findingID shared.ID) (*vulnerability.Finding, error)
Update(ctx context.Context, f *vulnerability.Finding) error
}
FindingMutator is the narrow contract for loading + saving a finding during the transition.
type IngestResult ¶ added in v0.3.0
type IngestResult struct {
Stored StoredEvidence
StatusChanged bool // the finding moved to resolved (the fix stood)
// Downgraded is true when a not_reproducible verdict downgraded a
// still-open finding to validated_fixed (feeds the downgrade % metric).
Downgraded bool
}
IngestResult summarizes what an evidence ingestion did.
type JobDispatcher ¶ added in v0.3.0
type JobDispatcher interface {
Dispatch(ctx context.Context, job ValidationJob) (shared.ID, error)
}
JobDispatcher enqueues a validation job for an agent to execute and returns the command ID it was queued under. It is fire-and-forget: the agent reports the result later and the command-completion hook maps that result back into Evidence via EvidenceIngestService. (This is the async counterpart to the synchronous ValidationDispatcher.Submit contract, which does not fit the platform's poll/complete queue.)
type NucleiAvailability ¶ added in v0.6.0
type NucleiAvailability interface {
HasNucleiValidationAgent(ctx context.Context, tenantID shared.ID) (bool, error)
}
NucleiAvailability reports whether a nuclei-validation-capable agent is currently online for a tenant. It is the deeper-rung sibling of AgentAvailability: a `validate:nuclei`-advertising agent implies a `validate`-advertising one, but not vice-versa, so the two gates are distinct. Optional on RunService — a nil gate means the fleet advertises no nuclei executor, so routing stays safe-check-only (Phase 2a behavior). This keeps 2b inert-safe: with no nuclei agent, dispatch is byte-for-byte what it is today.
type ProofOfFixService ¶
type ProofOfFixService struct {
// contains filtered or unexported fields
}
ProofOfFixService orchestrates the retest.
func NewProofOfFixService ¶
func NewProofOfFixService( dispatcher ValidationDispatcher, capability AgentCapability, evStore *EvidenceStore, findingRepo FindingMutator, notifier RetestNotifier, ) *ProofOfFixService
NewProofOfFixService wires dependencies.
func (*ProofOfFixService) Retest ¶
func (s *ProofOfFixService) Retest( ctx context.Context, tenantID, findingID shared.ID, tid TechniqueID, target Target, priorKind ExecutorKind, profile *AttackerProfile, ) (Evidence, bool, error)
Retest dispatches a validation job and reconciles the finding. Returns the Evidence the agent produced, a boolean indicating whether the fix stood (true = finding moved to resolved), and any error.
Passing priorKind routes to the same executor that produced the original validation when that kind is still available in the fleet. Falling back to Selector.Select when it is not.
func (*ProofOfFixService) SetVerdictRecorder ¶ added in v0.6.0
func (s *ProofOfFixService) SetVerdictRecorder(r VerdictRecorder)
SetVerdictRecorder wires the durable verdict recorder (validation_outcome / downgraded_at). Optional — without it the state transitions still apply.
type Redactor ¶
type Redactor struct {
// contains filtered or unexported fields
}
Redactor scrubs common secret patterns from the evidence before it is persisted.
func NewRedactor ¶
func NewRedactor() *Redactor
NewRedactor returns a Redactor with the default pattern set. Patterns are conservative — we would rather redact too much than too little. Operators can extend via AddPattern.
func (*Redactor) AddPattern ¶
AddPattern registers an additional regex. Panics on a bad regex (programmer error — regex is a const at the call site).
type RetestNotifier ¶
type RetestNotifier interface {
NotifyFixRejected(ctx context.Context, tenantID, findingID shared.ID, reason string) error
}
RetestNotifier posts a message to the assignee when the retest refutes the fix. Nil notifier is acceptable — the status revert still happens.
type RunService ¶ added in v0.3.0
type RunService struct {
// contains filtered or unexported fields
}
RunService turns "validate this finding" into a dispatched validation job. It resolves the finding's asset into a Target, picks an executor kind via the Selector against the fleet's available kinds, and hands the job to the dispatcher. Evidence returns asynchronously through EvidenceIngestService.
func NewRunService ¶ added in v0.3.0
func NewRunService( findings FindingLookup, assets AssetLookup, dispatcher JobDispatcher, selector Selector, available []ExecutorKind, log *logger.Logger, ) *RunService
NewRunService wires the run service. available is the set of executor kinds the agent fleet supports; the MVP passes {KindSafeCheck}.
func (*RunService) DispatchSimulationCheck ¶ added in v0.4.0
func (s *RunService) DispatchSimulationCheck(ctx context.Context, tenantID, simRunID, assetID shared.ID, technique string) (shared.ID, error)
DispatchSimulationCheck dispatches a real safe-check probe for an attack-simulation run (RFC-012 Phase 1b). Unlike ValidateFinding it is not finding-scoped: the job carries the simulation run id, and the completion hook finalizes the run from the agent's outcome. Returns ErrNotNetworkAddressable when the target asset cannot be reachability-probed, or a selector error when the technique is not safe-checkable — in both cases the caller falls back to the (clearly-labeled) synthetic path.
func (*RunService) SetAgentAvailability ¶ added in v0.6.0
func (s *RunService) SetAgentAvailability(a AgentAvailability)
SetAgentAvailability installs the per-tenant capability gate. When set, a dispatch is skipped with ErrNoValidationAgent whenever no validation-capable agent is online for the tenant, so a validate command is only ever queued for an agent that can execute it. Optional: leaving it unset keeps every dispatch unconditional (the pre-gate behavior), which is what the unit tests exercise.
func (*RunService) SetNucleiAvailability ¶ added in v0.6.0
func (s *RunService) SetNucleiAvailability(a NucleiAvailability)
SetNucleiAvailability installs the deeper-rung nuclei capability gate. When set, ValidateFinding upgrades a re-verify from safe-check to KindNuclei only when a `validate:nuclei`-capable agent is online for the tenant AND the finding carries a usable, non-destructive detection signature. Leaving it unset keeps routing safe-check-only (Phase 2a behavior) — the inert-safe default: no nuclei agent, no behavior change.
func (*RunService) ValidateFinding ¶ added in v0.3.0
func (s *RunService) ValidateFinding(ctx context.Context, tenantID, findingID shared.ID) (shared.ID, error)
ValidateFinding dispatches a validation job for the given finding and returns the command ID it was queued under.
type Selector ¶
type Selector interface {
Select(tid TechniqueID, profile *AttackerProfile, available []ExecutorKind) (ExecutorKind, error)
}
Selector owns the API-side policy: given a technique + attacker profile + a list of executor kinds the agent fleet supports, pick the appropriate kind.
type SeverityCoverage ¶ added in v0.3.0
type SeverityCoverage struct {
Severity string `json:"severity"`
Total int `json:"total"`
Validated int `json:"validated"`
}
SeverityCoverage is validation coverage for one severity band: how many of a tenant's findings at that severity have at least one validation evidence record. Answers the operator question "how much of my exposure has actually been re-checked?" (the CTEM Validation KPI), keyed on the always-present severity rather than the computed priority class.
func (SeverityCoverage) Pct ¶ added in v0.3.0
func (s SeverityCoverage) Pct() float64
Pct returns the validated ratio in [0,100]; zero total is reported as 0 so an empty band does not inflate the headline (unlike the SLO Pct, which treats "nothing to cover" as trivially met for gate purposes).
type StoredEvidence ¶
type StoredEvidence struct {
ID shared.ID
TenantID shared.ID
FindingID shared.ID // the finding this execution validated
SimulationRunID *shared.ID // optional; populated when evidence is part of a scheduled simulation
Evidence Evidence
CreatedAt time.Time
// DetectionStatus answers "did any control observe this?" — a
// SEPARATE question from Evidence.Outcome ("is the exposure still
// reachable?"). Defaults to DetectionNotEvaluated so a record never
// implies a control failed just because correlation did not run.
DetectionStatus DetectionStatus
// DetectionDetail records how the verdict was reached (match mode,
// window, pipeline liveness) so an operator can audit it.
DetectionDetail map[string]any
}
StoredEvidence is the persistence shape. Adds tenant_id + finding linkage to the in-memory Evidence struct. Persisted into the simulation_evidence table (migration lives in a companion PR).
type Target ¶
type Target struct {
AssetID shared.ID
Type string // "host" | "web_url" | "api_endpoint" | "cloud_resource"
Address string // host:port, URL, ARN, etc.
Metadata map[string]any
}
Target identifies what we are validating against. The executor kind determines which fields it uses.
type TechniqueID ¶
type TechniqueID string
TechniqueID is the MITRE ATT&CK technique identifier. The API does not interpret it — it is passed to the agent unchanged.
type TelemetryProbe ¶ added in v0.5.0
type TelemetryProbe interface {
// PipelineLive reports whether ANY telemetry (of any kind) has
// arrived for the tenant since `since`. This is the guard that
// separates "no detection" from "no telemetry pipeline".
PipelineLive(ctx context.Context, tenantID shared.ID, since time.Time) (bool, error)
// CountByCorrelationID counts events a producer explicitly stamped
// with this validation's correlation id. Exact; no time bounds.
CountByCorrelationID(ctx context.Context, tenantID, correlationID shared.ID) (int, error)
// CountNearTarget counts events on the given asset between from and
// to whose event_type is in eventTypes. The heuristic fallback for
// producers that cannot stamp a correlation id.
CountNearTarget(ctx context.Context, tenantID, assetID shared.ID, from, to time.Time, eventTypes []string) (int, error)
}
TelemetryProbe is the read side of the telemetry stream that the correlator needs. Implemented by postgres; faked in tests.
type ValidateCommandPayload ¶ added in v0.3.0
type ValidateCommandPayload struct {
JobID string `json:"job_id"`
FindingID string `json:"finding_id"`
// SimulationRunID is set when the job backs an attack-simulation run
// (RFC-012). The agent ignores it; the server completion hook uses it to
// finalize the run. Empty for plain finding proof-of-fix jobs.
SimulationRunID string `json:"simulation_run_id,omitempty"`
ExecutorKind string `json:"executor_kind"`
Technique string `json:"technique"`
Target ValidateTargetPayload `json:"target"`
TimeoutSeconds int `json:"timeout_seconds"`
// TemplateID / CVEID carry the finding's own detection signature for a
// KindNuclei job (RFC-011.2 Phase 2b): the agent re-runs this single template
// (`nuclei -id <template_id|cve_id>`), never a full scan. Both empty for a
// safe-check job, which the agent then handles as today.
TemplateID string `json:"template_id,omitempty"`
CVEID string `json:"cve_id,omitempty"`
// RequiredCapabilities lets the platform route the job only to agents that
// advertise the validation capability (mirrors the scan command payload).
RequiredCapabilities []string `json:"required_capabilities"`
}
ValidateCommandPayload is the JSON payload embedded in a CommandTypeValidate command. It is the wire contract between the API (producer) and the agent executor (consumer); the agent replies with a ValidateResultPayload.
type ValidateResultPayload ¶ added in v0.3.0
type ValidateResultPayload struct {
Outcome string `json:"outcome"`
Summary string `json:"summary"`
Evidence map[string]any `json:"evidence,omitempty"`
}
ValidateResultPayload is what an agent reports back in the command result for a validate command. Kept small and stable; RawMeta carries probe detail.
type ValidateTargetPayload ¶ added in v0.3.0
type ValidateTargetPayload struct {
AssetID string `json:"asset_id"`
Type string `json:"type"`
Address string `json:"address"`
}
ValidateTargetPayload is the target section of a validate command payload.
type ValidationCoverage ¶
type ValidationCoverage struct {
P0Total int
P0WithEvidence int
P1Total int
P1WithEvidence int
P2Total int
P2WithEvidence int
P3Total int
P3WithEvidence int
}
ValidationCoverage aggregates per-priority coverage for a tenant or cycle window.
func (ValidationCoverage) Pct ¶
func (c ValidationCoverage) Pct(class string) float64
Pct returns the coverage ratio for a priority class in [0, 100]. Zero-total returns 100 (nothing to cover = trivially met).
type ValidationDispatcher ¶
type ValidationDispatcher interface {
Submit(ctx context.Context, job ValidationJob) (Evidence, error)
}
ValidationDispatcher submits a job for an agent and returns the resulting Evidence when the agent has reported back. Concrete implementations plug into the platform-job queue (Redis / Postgres).
Submit is expected to BLOCK until the agent finishes OR the context deadline fires — callers choose the deadline. In practice the implementation is queue + subscribe, not a synchronous call.
type ValidationJob ¶
type ValidationJob struct {
JobID shared.ID
TenantID shared.ID
FindingID shared.ID
// SimulationRunID links this job to an attack-simulation run (RFC-012). A
// job carries a finding, a simulation run, or both; the completion hook
// reconciles whichever is present.
SimulationRunID shared.ID
ExecutorKind ExecutorKind
Technique TechniqueID
Target Target
ProfileID shared.ID
TimeoutSeconds int
// TemplateID / CVEID carry the finding's own detection signature for the
// KindNuclei executor (RFC-011.2 Phase 2b). TemplateID is a nuclei template
// id (nuclei-native findings); CVEID is a CVE→template candidate for
// cross-scanner findings. Both empty for safe-check jobs.
TemplateID string
CVEID string
}
ValidationJob is the payload the API queues for an agent. Agents long-poll for jobs that match their advertised ExecutorKinds. Result is delivered via POST /api/v1/validation/evidence.
type Verdict ¶ added in v0.6.0
type Verdict string
Verdict is the persisted finding-level validation verdict value. It is the enum stored in findings.validation_outcome (see migration 000209).
const ( // VerdictReproducible: the validation re-check still observed the exposure // condition. The finding stays open ("still exploitable"). VerdictReproducible Verdict = "reproducible" // VerdictNotReproducible: the validation re-check no longer observed the // exposure condition — the input to a confirm-or-downgrade decision. VerdictNotReproducible Verdict = "not_reproducible" )
type VerdictRecorder ¶ added in v0.6.0
type VerdictRecorder interface {
RecordVerdict(ctx context.Context, tenantID, findingID shared.ID, verdict Verdict, downgradedAt *time.Time) error
}
VerdictRecorder durably stamps the validation verdict on a finding. It is a narrow side-write next to the status transition: the status change rides the finding entity's normal Update, while validation_outcome / downgraded_at are columns the entity round-trip does not carry, so they are written directly.
downgradedAt is non-nil ONLY when a still-open finding is being downgraded to validated_fixed; implementations must preserve any existing downgraded_at when it is nil (a later reproducible verdict must not erase the downgrade history the metric depends on).
A nil VerdictRecorder is tolerated by the verdict logic (the state transition still happens); the metric simply is not fed.