Documentation
¶
Overview ¶
Package managedci exports managed-CI evidence under the canonical contract managed-ci/v2 (contracts/managed-ci/v2).
What this package is FOR: the backend classifies a managed submission by interpreting the canonical finding policy over normalized evidence FACTS. This package is the production producer of those facts. It reads the engine's own domain objects — the same evidence.Evidence the confidence scorer and the decision layer read — and reports what was OBSERVED.
What this package must never do: export a conclusion. No confidence score, no band, no tier, no status, no decision, no exit code, no blocking claim, and nothing derived from the runner's own --fail-on. The contract rejects such keys outright, and the whole point of the managed lane is that the backend, not the runner, decides. `payload_validated` exists precisely so a probe exchange never leaves the runner.
Parity: facts_test.go replays every canonical policy vector through FactsFrom and requires the exported facts to be identical to the vector's, so the exporter cannot drift from the policy the engine implements and the backend interprets.
Index ¶
- Constants
- Variables
- func AttributeFinding(finding models.Finding) (string, error)
- func BuildAnalyzers(executions map[string]Execution, counts map[string]int, version string) ([]Analyzer, []string, []Gap)
- func CeilingRefusal(err error) (string, bool)
- func CheckCeilings(body []byte) error
- func ContextFromEnv(getenv func(string) string, binding Binding) (managedRunnerContext, error)
- func CountByAnalyzer(findings []models.Finding) (map[string]int, map[string]string, error)
- func EvidenceHash(item string) string
- func FamiliesOf(engineNames []string) []string
- func SelfDigest() (string, error)
- func WriteContext(path string, runner managedRunnerContext) error
- type Analyzer
- type Binding
- type Client
- type Context
- type Coverage
- type Decision
- type Engine
- type ErrInconsistent
- type ErrNoDecision
- type ErrProvenance
- type ErrTooLarge
- type ErrUnmappable
- type Execution
- type ExportInput
- type Facts
- type Finding
- type Gap
- type Input
- type Location
- type Manifest
- type Package
- type Sanitization
- type Submission
Constants ¶
const ( AnalyzerSAST = "sast" AnalyzerSCA = "sca" AnalyzerSecrets = "secrets" AnalyzerDAST = "dast" )
The contract names ABSTRACT analyzers; the engine names concrete ones. The backend's binding policy requires `sast` and `sca`, and neither it nor the customer should have to know that SCA is three different engine analyzers.
Aggregation is pessimistic about FAILURE and honest about capability:
- any member that FAILED fails the family, because a family that broke part-way cannot vouch for the target;
- otherwise a family that ran at all is `completed`. Which concrete analyzers a runner has is engine-internal detail — the binding requires the CAPABILITY, and a stock runner without semgrep installed still performed static analysis;
- a family where nothing ran is `not_applicable` when its members had nothing to look at, and `skipped` otherwise.
The strict reading (any absent member skips the family) was tried first and is wrong: on a runner without semgrep it made `sast` permanently unobserved, so every managed scan would have been INCOMPLETE no matter how clean the code was. The engine's own report still records each analyzer's state for the customer; the manifest states what the CAPABILITY did.
const ( RuleCrossToolFlagMatchesTools = "cross_tool_flag_matches_tools" RuleProvenPathRequiresRouteAndTaint = "proven_path_requires_route_and_taint" RuleDirectObservationRequiresLive = "direct_observation_requires_live_source" RulePayloadValidationRequiresLive = "payload_validation_requires_live_source" RuleSeverityWithinPrecisionCap = "severity_within_rule_precision_cap" )
The finding policy's consistency rules, by code (contracts/managed-ci/v2/policy/finding-policy-1.0.0.json, `consistency_rules`).
The backend treats a violation as an UNCLASSIFIABLE finding: the submission is accepted, the finding is counted in no bucket, and the scan decision becomes INCOMPLETE. That is the right answer for contradictory evidence arriving from an unknown producer — but for OUR exporter it would mean the engine contradicted itself, so the export fails closed instead of shipping a finding that can only ever be unclassifiable.
consistency_test.go pins this list against the specification, so a rule added canonically cannot be silently unenforced here.
const ( APIVersion = "managed-ci/v2" ManifestSchemaVersion = "evidence-manifest/v2" ContextSchemaVersion = "managed-scan-context/v1" SanitizationProfile = "managed-ci-default/v1" CoverageContract = 1 // MaxFindings and MaxBodyBytes are INDEPENDENT ceilings. Evidence that // exceeds either one is refused; it is never truncated and never split, // because the contract has no atomic multipart submission and a partial // manifest would understate the risk while looking complete. MaxFindings = 10000 MaxBodyBytes = 8 * 1024 * 1024 MaxAnalyzers = 200 MaxCorroborating = 20 MaxEvidenceHashes = 20 MaxLocations = 20 )
Contract identity and limits (contracts/managed-ci/v2/contract-set.json). contract_test.go pins every one of these against the vendored bundle, so a canonical change cannot leave the exporter quietly out of step.
const ( LimitFindingCount = "finding count" LimitAnalyzerCount = "analyzer count" LimitRequestBody = "request body" )
The ceilings ErrTooLarge names, as its Limit field reports them.
const CeilingRefusalPrefix = "fendix: managed evidence exceeds a contract ceiling: "
CeilingRefusalPrefix opens the one line a runner prints when evidence exceeds a contract ceiling. It is stable on purpose: the Action matches it to name the ceiling in the job's error annotation and summary, instead of reporting a generic scan or submission failure.
const ( // DefaultDecisionTimeout is the contract's total decision budget. DefaultDecisionTimeout = 10 * time.Minute )
Variables ¶
var ConsistencyRules = []string{ RuleCrossToolFlagMatchesTools, RuleProvenPathRequiresRouteAndTaint, RuleDirectObservationRequiresLive, RulePayloadValidationRequiresLive, RuleSeverityWithinPrecisionCap, }
ConsistencyRules is every rule this package enforces, in specification order.
Functions ¶
func AttributeFinding ¶
AttributeFinding names the contract analyzer that produced a finding.
Attribution is STRUCTURAL, not a guess from a title or a category string: a dependency finding carries a dependency reference, a secret finding carries a secret reference, and what remains is static or live analysis by its observation source. A finding that cannot be attributed is an error — the contract requires every finding to name a reported analyzer, and a wrong attribution would misstate which analyzer attested to it.
func BuildAnalyzers ¶
func BuildAnalyzers(executions map[string]Execution, counts map[string]int, version string) ([]Analyzer, []string, []Gap)
BuildAnalyzers projects the engine's per-analyzer status onto the contract's analyzer families, and reports which families actually observed the target.
`observed` is the honest answer to "did this analyzer look?": only a family that completed is observed. The backend's required-analyzer invariant then needs both completed AND observed, so a family that skipped, failed or was not applicable can never satisfy a requirement.
func CeilingRefusal ¶
CeilingRefusal reports whether err is, or wraps, a contract-ceiling refusal, and returns the terminal line to print for it.
func CheckCeilings ¶
CheckCeilings refuses a serialized submission over any contract ceiling. Build already refuses such evidence; this repeats the check at the point where bytes would leave the runner, so a document that was edited, written by another build or assembled by hand is refused before any request too.
Only the ceilings are decided here. A body that does not parse as a submission is not this check's to judge: the backend refuses it, and that refusal is a missing decision, never a pass.
func ContextFromEnv ¶
ContextFromEnv builds the managed-scan context and a fresh submission id.
getenv is injected so the whole thing is testable without touching the process environment.
func CountByAnalyzer ¶
CountByAnalyzer attributes every finding, so the per-analyzer counts and the findings can never disagree — the contract's provenance rule holds by construction rather than by a later check.
func EvidenceHash ¶
EvidenceHash identifies one evidence item by digest. The item itself — the snippet, the probe exchange, the matched value — never leaves the runner.
func FamiliesOf ¶
FamiliesOf maps engine analyzer names onto the contract analyzers that cover them, for the `required_analyzers` the manifest RECORDS. The backend requires what the binding policy says; this list is provenance about how the run was configured, never a claim about what must be required.
func SelfDigest ¶
SelfDigest hashes the running executable, which is exactly the artifact the release publishes and the installer verifies. A digest compiled in with ldflags could not describe the binary containing it, so the binary hashes itself instead.
func WriteContext ¶
WriteContext writes the context file. 0600 because it names the tenant and Asset; it carries no credential.
Types ¶
type Analyzer ¶
type Analyzer struct {
AnalyzerID string `json:"analyzer_id"`
AnalyzerVersion string `json:"analyzer_version"`
Status string `json:"status"`
ReasonCode string `json:"reason_code"`
Attempts int `json:"attempts"`
DurationMS int `json:"duration_ms"`
FindingCount int `json:"finding_count"`
}
Analyzer is one analyzer's execution result.
type Binding ¶
Binding is what the customer configures on the Action: which tenant, which Asset, which environment. Nothing else about the run is theirs to state.
type Client ¶
type Client struct {
BaseURL string
// Token is the fxci_ credential. It is used to build one header and is
// never logged, printed or returned in an error.
Token string
HTTP *http.Client
Timeout time.Duration
// Sleep is the delay hook; tests replace it to avoid real waiting.
Sleep func(time.Duration)
// Now is the clock hook, for the same reason.
Now func() time.Time
}
Client submits evidence and polls for the decision.
func (*Client) Await ¶
Await polls until the backend reaches a terminal state or the decision budget runs out. A timeout is reported, never treated as success.
func (*Client) StatusURL ¶
StatusURL is where this client will poll for a receipt.
It is built from the CONFIGURED api-base, not from the receipt's status_url. The credential travels on every poll, and a backend that named another origin — through misconfiguration or compromise — would be telling the runner to hand that credential somewhere the workflow never approved. The receipt's own status_url is only honoured when it points at the same origin.
type Context ¶
type Context struct {
SchemaVersion string `json:"schema_version"`
ScanExecutionID string `json:"scan_execution_id"`
TenantID string `json:"tenant_id"`
AssetID string `json:"asset_id"`
Environment string `json:"environment"`
Provider string `json:"provider"`
RepositoryID string `json:"repository_id"`
RepositoryOwnerID string `json:"repository_owner_id"`
Repository string `json:"repository"`
HeadSHA string `json:"head_sha"`
BaseSHA *string `json:"base_sha"`
PullRequest *int `json:"pull_request"`
WorkflowName string `json:"workflow_name"`
WorkflowRef string `json:"workflow_ref"`
RunID string `json:"run_id"`
RunAttempt int `json:"run_attempt"`
EventName string `json:"event_name"`
}
Context is the CI identity of one workflow execution attempt. The runner supplies it; the engine copies it verbatim into the manifest and never invents any part of it. The backend compares every field with the binding the credential itself carries, so a wrong value is refused, not trusted.
type Coverage ¶
type Coverage struct {
ContractVersion int `json:"contract_version"`
RequiredAnalyzers []string `json:"required_analyzers"`
ObservedAnalyzers []string `json:"observed_analyzers"`
Gaps []Gap `json:"gaps"`
FilesConsidered *int `json:"files_considered,omitempty"`
ManifestsConsidered *int `json:"manifests_considered,omitempty"`
}
Coverage is what ran. `required_analyzers` is recorded only: the backend decides what is required from the binding policy, never from this list.
type Decision ¶
type Decision struct {
SchemaVersion string `json:"schema_version"`
ScanExecutionID string `json:"scan_execution_id"`
EvidenceSubmissionID string `json:"evidence_submission_id"`
Decision string `json:"decision"`
FailGate bool `json:"fail_gate"`
CoverageState string `json:"coverage_state"`
BackendPolicyVersion string `json:"backend_policy_version"`
ReasonCodes []string `json:"reason_codes"`
Record struct {
DecisionRecordID string `json:"decision_record_id"`
Revision int `json:"revision"`
RecordHash string `json:"record_hash"`
URL string `json:"url"`
CreatedAt string `json:"created_at"`
} `json:"record"`
}
Decision is the backend's authoritative answer.
type Engine ¶
type Engine struct {
Version string `json:"version"`
BuildDigest string `json:"build_digest"`
ReportSchemaVersion int `json:"report_schema_version"`
FindingPolicyVersion string `json:"finding_policy_version"`
}
Engine identifies the exact build that produced the evidence. The backend accepts only allowlisted (version, build_digest) pairs, which is what binds a submission to a signed release rather than to "some fendix".
type ErrInconsistent ¶
ErrInconsistent names the rule a set of facts violates. It carries no value from the scanned code — only the rule code and the finding's identity — so it is safe to print in CI output.
func (ErrInconsistent) Error ¶
func (e ErrInconsistent) Error() string
type ErrNoDecision ¶
ErrNoDecision reports that no authoritative decision was obtained. It is never a pass: the caller exits non-zero without a managed verdict.
func (ErrNoDecision) Error ¶
func (e ErrNoDecision) Error() string
type ErrProvenance ¶
type ErrProvenance struct{ Reason string }
ErrProvenance reports a manifest whose parts do not account for each other.
func (ErrProvenance) Error ¶
func (e ErrProvenance) Error() string
type ErrTooLarge ¶
ErrTooLarge reports evidence that exceeds a contract ceiling. It is a fail-closed condition: the runner reports an error and makes NO managed PASS, WARN or BLOCK claim.
func (ErrTooLarge) Error ¶
func (e ErrTooLarge) Error() string
func (ErrTooLarge) Refusal ¶
func (e ErrTooLarge) Refusal() string
Refusal is the terminal line for evidence over a ceiling. It names the ceiling, the actual size and the maximum, and states the two facts a reader of a failed job needs: nothing left the runner, and no managed decision exists for the run. Nothing is truncated or split to fit.
type ErrUnmappable ¶
ErrUnmappable reports engine state the contract vocabulary cannot express. It is returned, never guessed around: a fabricated fact would be a false attestation about the scanned code.
func (ErrUnmappable) Error ¶
func (e ErrUnmappable) Error() string
type Execution ¶
type Execution struct {
Status reporters.ScannerStatus
Duration time.Duration
}
Execution is the engine-side input for one analyzer family member.
type ExportInput ¶
type ExportInput struct {
Findings []models.Finding
Decisions []decision.Decision
// Executions is the per-engine-analyzer outcome, keyed by registry name.
Executions map[string]Execution
Context Context
// RequiredAnalyzers is recorded only. The backend requires what the
// binding policy says, never what the runner claims.
RequiredAnalyzers []string
EvidenceSubmissionID string
EngineVersion string
BuildDigest string
ReportSchemaVersion int
FindingPolicyVersion string
Workspace string
FilesConsidered *int
ManifestsConsidered *int
GeneratedAt time.Time
Configuration map[string]string
}
ExportInput is one finished scan, as the orchestrator holds it at the moment decisions are stamped: findings and their decisions are index aligned, and each decision carries the provenance-restored Evidence the scorer read.
type Facts ¶
type Facts struct {
AnalyzerImplementation string `json:"analyzer_implementation"`
AuthExpectation string `json:"auth_expectation"`
CorroboratingTools []string `json:"corroborating_tools"`
CrossToolCorroborated bool `json:"cross_tool_corroborated"`
DependencyApplicability string `json:"dependency_applicability"`
DirectObservation bool `json:"direct_observation"`
FixtureShapedValue bool `json:"fixture_shaped_value"`
InTestCode bool `json:"in_test_code"`
ObservationSource string `json:"observation_source"`
PayloadValidated bool `json:"payload_validated"`
ProvenPath bool `json:"proven_path"`
ProviderAnchoredSecret bool `json:"provider_anchored_secret"`
ReachableTaintPath bool `json:"reachable_taint_path"`
ResponseContext string `json:"response_context"`
RouteConfirmed bool `json:"route_confirmed"`
RulePrecision string `json:"rule_precision"`
UnconfirmedByLiveScan bool `json:"unconfirmed_by_live_scan"`
}
Facts is the closed 17-fact vocabulary of contracts/managed-ci/v2/schemas/evidence-facts.schema.json.
Field order is the schema's alphabetical order, so encoding/json emits a byte-identical object for identical input (Go marshals struct fields in declaration order). Every field is always emitted: the finding policy makes all 17 mandatory, and an absent fact makes the finding unclassifiable rather than "assumed false".
func FactsFrom ¶
FactsFrom reports what the engine observed about one piece of evidence.
Every fact reads exactly one engine field, and the fields are the same ones confidence.Score and decision.DecideWithOptions read, so the exported facts describe the evidence the engine itself scored. Call it AFTER ProvenanceIndex.Restore, or the internal half (probe exchange, response context, test-code and producer flags) is still detached and the facts will understate what was observed.
type Finding ¶
type Finding struct {
AnalyzerID string `json:"analyzer_id"`
Category string `json:"category"`
EvidenceFacts Facts `json:"evidence_facts"`
EvidenceHashes []string `json:"evidence_hashes"`
FindingID string `json:"finding_id"`
Fingerprint string `json:"fingerprint"`
Locations []Location `json:"locations,omitempty"`
Package *Package `json:"package,omitempty"`
RuleID string `json:"rule_id"`
Severity string `json:"severity"`
}
Finding is one normalized finding: identity, provenance and FACTS. It carries no status, no confidence and no decision of any kind.
type Gap ¶
type Gap struct {
AnalyzerID string `json:"analyzer_id"`
ReasonCode string `json:"reason_code"`
Detail string `json:"detail,omitempty"`
}
Gap is a coverage hole the runner reports about itself.
type Input ¶
type Input struct {
Context Context
Engine Engine
Analyzers []Analyzer
Coverage Coverage
Findings []Finding
GeneratedAt time.Time
RedactionCount int
EvidenceSubmissionID string
// ConfigurationInputs is the effective managed scan configuration —
// never secrets, never the target's contents. It is hashed, not sent.
ConfigurationInputs map[string]string
}
Input is everything Build needs. The caller assembles it from one scan.
type Location ¶
type Location struct {
Path string `json:"path"`
StartLine *int `json:"start_line,omitempty"`
EndLine *int `json:"end_line,omitempty"`
}
Location is bounded, repo-relative display context.
func RelativeLocation ¶
RelativeLocation normalizes an engine endpoint ("path" or "path:line") into a bounded, repository-relative location. It returns ok=false for anything absolute, parent-relative or home-prefixed: the semantic rules reject those outright, and a location is display context the manifest can simply omit.
type Manifest ¶
type Manifest struct {
Analyzers []Analyzer `json:"analyzers"`
ArtifactHash string `json:"artifact_hash"`
ConfigurationHash string `json:"configuration_hash"`
Context Context `json:"context"`
Coverage Coverage `json:"coverage"`
Engine Engine `json:"engine"`
Findings []Finding `json:"findings"`
GeneratedAt string `json:"generated_at"`
Sanitization Sanitization `json:"sanitization"`
SchemaVersion string `json:"schema_version"`
}
Manifest is the evidence document. Field order is the schema's alphabetical order so identical observations serialize to identical bytes.
`producer_diagnostics` is deliberately absent. The contract permits it as explicitly untrusted, but managed mode has no reason to send a local verdict, exit code or confidence label: they are conclusions, they are never read, and not sending them removes any doubt about what decided.
type Package ¶
type Package struct {
Ecosystem string `json:"ecosystem"`
Name string `json:"name"`
Version string `json:"version"`
AdvisoryIDs []string `json:"advisory_ids,omitempty"`
}
Package names the dependency a dependency finding is about.
type Sanitization ¶
type Sanitization struct {
Profile string `json:"profile"`
RedactionCount int `json:"redaction_count"`
SourceExcerptsIncluded bool `json:"source_excerpts_included"`
}
Sanitization records the redaction profile the producer applied.
type Submission ¶
type Submission struct {
APIVersion string `json:"api_version"`
EvidenceSubmissionID string `json:"evidence_submission_id"`
IdempotencyKey string `json:"idempotency_key"`
Manifest Manifest `json:"manifest"`
}
Submission is the exact request body the runner POSTs to /api/ci/v2/submissions.
func Build ¶
func Build(in Input) (Submission, []byte, error)
Build validates and serializes one submission.
It fails closed on anything the backend would refuse or could not classify: a finding whose facts contradict each other, a finding attributed to an analyzer that did not run, an analyzer whose count disagrees with its findings, an observed analyzer nobody reported, or evidence over either ceiling. Returning an error is always better than a document that decides nothing (INCOMPLETE) or is rejected at the door.
func Export ¶
func Export(in ExportInput) (Submission, []byte, error)
Export builds the exact request body for POST /api/ci/v2/submissions.
Everything it emits is an observation. Nothing it emits is a conclusion: the findings' Status, ConfidenceScore, ConfidenceBand, DecisionReason and the run's exit code are all left behind here, which is what makes the backend's decision the only decision.