models

package
v0.0.0-...-a02776c Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 12 Imported by: 0 modules, 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 models defines the core data types shared across Fendix. Finding, Severity, Confidence, and Source are the primary types used by both Go and Python engines via the IPC contract.

Index

Constants

View Source
const (
	AuthTypeBearer = "bearer"
	AuthTypeAPIKey = "apikey"
	// AuthTypeAPIKeyQuery places the API key in a query-string parameter
	// rather than a request header. Param name comes from AuthContext.Header
	// (a small overload — Header doubles as the query-param name in this
	// mode); defaults to "api_key" if unset.
	AuthTypeAPIKeyQuery = "apikey-query"
	AuthTypeBasic       = "basic"
	AuthTypeCookie      = "cookie"

	EnvAuth       = "FENDIX_AUTH"
	EnvAuthType   = "FENDIX_AUTH_TYPE"
	EnvAuthHeader = "FENDIX_AUTH_HEADER"

	DefaultAuthHeader       = "Authorization"
	DefaultAPIKeyQueryParam = "api_key"
)
View Source
const DefaultProfileName = "default"

DefaultProfileName is the profile loaded when no --profile is specified.

View Source
const FingerprintAlgorithm = "fendix/v2"

FingerprintAlgorithm names the identity scheme this build produces. It is part of Fendix's public behaviour: a baseline, a `.fendix-ignore` `fingerprint:` rule and a GitHub Code Scanning alert are all keyed on it, so a change here re-identifies findings for every existing consumer and must be versioned, announced, and never made silently.

v1 was sha1(Category|Endpoint|Title) — see FingerprintV1. v2 is the semantic scheme below.

View Source
const ReachableMult = 1.5

ReachableMult is the multiplier applied when the engine proved intra-function dataflow from a request source to a dangerous sink (Finding.Reachable=true). Per docs/example_plan.md §3.5: "(1.5 if reachable_code else 1.0)". Translates to ~one severity-level bump on the discrete CRITICAL/HIGH/MEDIUM/LOW/INFO scale.

TASK-125: lifts the multiplier from "an idea in the plan doc" to a first-class factor in CalculateSeverity. The correlator already applies a discrete escalateSeverity for the correlated-reachable case (TASK-114); this lets non-correlated whitebox findings with reachable=true also benefit, via the orchestrator's escalateNonCorrelatedReachable step.

Variables

View Source
var ConfidenceMult = map[Confidence]float64{
	ConfidenceHigh:   1.0,
	ConfidenceMedium: 0.75,
	ConfidenceLow:    0.5,
}

ConfidenceMult maps confidence levels to score multipliers.

View Source
var ImpactBase = map[string]float64{
	"auth_bypass":     10.0,
	"injection":       9.5,
	"secrets":         9.0,
	"ssrf":            8.5,
	"idor":            8.5,
	"method_tamper":   7.0,
	"data_exposure":   7.0,
	"cors":            6.5,
	"host_header":     6.5,
	"redirect":        5.0,
	"graphql":         4.0,
	"headers":         4.0,
	"cookie":          4.0,
	"rate_limiting":   4.0,
	"info_disclosure": 2.0,
}

ImpactBase maps finding categories to their base impact scores.

Part of the REFERENCE MODEL (see the file header): Score = Base × ConfidenceMult × SourceMult. Consumed only by CalculateSeverity* and the derivation of MaxSeverityForConfidence — not by any scanner.

View Source
var SourceMult = map[Source]float64{
	SourceCorrelated: 1.1,
	SourceBlackbox:   1.0,
	SourceWhitebox:   0.9,
}

SourceMult maps finding sources to score multipliers. Correlated findings get a boost because both engines agree.

Functions

func DetectAuthType

func DetectAuthType(value string) string

DetectAuthType infers the authentication scheme from the credential value. "Bearer ..." → bearer, "Basic ..." → basic, key=value → cookie, else → bearer.

func Fingerprint

func Fingerprint(f Finding) string

Fingerprint returns the long-lived semantic identity of a finding: a stable answer to "which vulnerability is this?" It is independent of volatile coordinates and of what Fendix currently believes about the finding, while retaining the artifact and operation needed to distinguish security claims.

Identity versus location

The v1 scheme hashed Category|Endpoint|Title, and for whitebox findings Endpoint is "path:line". One unrelated line inserted above a vulnerability therefore gave it a new identity — which silently broke baseline tracking, new-vs-existing detection, suppressions and PR annotations, because every one of those asks "have I seen this before?" and the answer flipped to no whenever the file was edited above the finding.

v2 splits volatile coordinates from semantic location. Line and column numbers are reporting details: they say where to look today. The containing file or manifest, code symbol and operation, or HTTP method and path identify the affected artifact and claim; changing one of those can change identity.

What is deliberately excluded

Title, Evidence prose, Fix and reference text are PRESENTATION — RC-6 re-titles findings as their evidence strengthens ("Potential SSRF" → "SSRF"), and a wording change must never re-file a vulnerability as new.

Severity, Confidence, ConfidenceScore, ConfidenceBand, Status, DecisionReason, DecisionPolicy and Applicability are all EVOLVING JUDGEMENTS ABOUT a vulnerability, not part of which vulnerability it is. A finding that moves BLOCK → WARN, or whose applicability resolves unknown → evidence_against, is the same vulnerability better understood; that is the whole point of keeping a long-lived record.

Line and column numbers, timestamps and run identifiers are excluded because they encode the moment rather than the finding. Emitters are expected to provide repository-relative paths: this package normalizes separators and a leading "./", but cannot safely remove an arbitrary absolute worktree prefix.

Credential material — raw or digested — is excluded unconditionally. See SecretRef for why a hash is not an acceptable substitute here.

Partial evidence

Analyzers differ in what they can prove, so every semantic component is optional and each is emitted as a labelled key so an absent component cannot be confused with a present one. Where nothing semantic is available the scheme degrades to rule + artifact, which merges repeat occurrences of one rule in one file rather than inventing a discriminator out of location.

func FingerprintIdentityComponents

func FingerprintIdentityComponents(f Finding) []string

FingerprintIdentityComponents exposes the labelled semantic inputs used by Fingerprint for contract documentation and drift tests. The returned slice is a copy; callers cannot mutate the identity calculation. This package is internal, so the helper does not expand the public engine API.

func FingerprintV1

func FingerprintV1(f Finding) string

FingerprintV1 is the retired sha1(Category|Endpoint|Title) scheme, kept so migration tooling can compute both keys for the same finding and report how existing findings map onto v2. Nothing in the scan path may call it.

func IsTestPath

func IsTestPath(endpoint string) bool

IsTestPath reports whether a finding endpoint points at test / fixture code.

The endpoint may be a bare path ("tests/test_auth.py"), a path with a line suffix ("tests/test_auth.py:42"), or a Windows-separated path — all three normalise to the same answer.

URL-SHAPED ENDPOINTS ARE NEVER TEST CODE, and the guard for that is load bearing rather than cosmetic. The marker regex matches a `tests?` or `testing` path segment anywhere, so without the guard a perfectly real live route — `GET /tests`, `GET /api/test`, `GET /api/testing/run`, `GET /fixtures/team` — classifies as test code and its DAST findings get de-escalated to INFO. A route is a deployed attack surface no matter what it is named; only a *source file* can be test code.

Pure and deterministic: the same endpoint always yields the same answer, with no filesystem access. That matters because this feeds the confidence / decision layer, which must be reproducible (Constitution Rule 8).

func ParseFailOn

func ParseFailOn(value string) (string, error)

ParseFailOn normalises a --fail-on threshold.

Empty means "no threshold": nothing blocks, every MEDIUM+ finding warns. A severity name is accepted in any case and with surrounding space, so "high", "High" and "HIGH" are the same threshold. Anything else is an error.

It used to be that an unrecognised value only logged a warning, and the scan then ran with NO threshold. `--fail-on high` therefore silently disabled the gate it asked for: a HIGH finding warned and the run exited 0. An unrecognised threshold must refuse the run, never weaken it.

func ProfileLoader

func ProfileLoader(name string) func() *AuthContext

ProfileLoader returns a function suitable for passing to ResolveAuth that loads the named profile. If name is empty, uses "default".

A load failure yields nil (the scan continues unauthenticated) but is now LOGGED rather than discarded: swallowing it meant a malformed or wrongly-nested profile silently degraded every authenticated check, and the operator's only clue was an implausible pile of 401-shaped findings.

func ProfilesDir

func ProfilesDir() (string, error)

ProfilesDir returns the path to ~/.fendix/profiles/.

func SeverityRank

func SeverityRank(s Severity) int

SeverityRank returns a numeric rank for severity comparison. Higher values indicate more severe findings.

func StampIdentity

func StampIdentity(f *Finding)

StampIdentity sets both identity keys on a finding: the canonical v2 fingerprint and the retired v1 key that lets downstream consumers recognise a finding they first tracked under the old scheme.

Called once, centrally, in the orchestrator before ID assignment. Keeping the pair in one place is what stops a future caller stamping the canonical key and silently omitting the bridge.

Types

type Applicability

type Applicability string

Applicability is what Fendix established about whether a vulnerable dependency's AFFECTED COMPONENT is actually used by the scanned project — as distinct from whether the vulnerable VERSION is installed, which is what the finding itself asserts.

Three states, and exactly three, because three is what the analyzer can actually produce (scanner/deps/applicability.resolve):

Unknown         the advisory names no importable component, or the import
                grep overran its budget and failed open. NOT a claim.
Applicable      at least one affected component IS imported by the tree.
EvidenceAgainst no affected component is imported anywhere in the tree.

The previous model was a single bool, ComponentNotImported, whose false conflated "the component IS imported" with "we never evaluated this" — two states that must drive different decisions.

DELIBERATELY NOT a fourth "ConfirmedNonApplicable" state. The backing evidence is a static import grep, and dynamic import forms (importlib.import_module, plugin registries, reflection) mean absence of an import is EVIDENCE against applicability, never proof of it. Naming the state after what it is — evidence — keeps that honest at every call site.

Symmetrically, Applicable means "the component is imported", not "the vulnerable function is reached": Fendix does not build a dependency call graph. It is evidence FOR applicability, which is why it restores normal policy rather than escalating beyond it.

const (
	// ApplicabilityUnknown — not evaluated, or evaluation was incomplete.
	ApplicabilityUnknown Applicability = ""
	// ApplicabilityApplicable — an affected component is imported.
	ApplicabilityApplicable Applicability = "applicable"
	// ApplicabilityEvidenceAgainst — no affected component is imported.
	ApplicabilityEvidenceAgainst Applicability = "evidence_against"
)

type AuthContext

type AuthContext struct {
	Type   string // bearer | apikey | basic | cookie
	Value  string
	Header string // default: Authorization
}

AuthContext holds authentication credentials for scan requests. Credentials are masked as [REDACTED] in all report output.

func LoadProfile

func LoadProfile(name string) (*AuthContext, error)

LoadProfile reads a named profile from ~/.fendix/profiles/<name>.yaml. Returns nil (not an error) if the profile file does not exist.

func LoadProfileFrom

func LoadProfileFrom(path string) (*AuthContext, error)

LoadProfileFrom reads a profile from an explicit file path. Returns nil (not an error) if the file does not exist.

func NormalizeAuth

func NormalizeAuth(auth *AuthContext) *AuthContext

NormalizeAuth fills in defaults: sets the header to Authorization if empty, auto-detects auth type if not specified, and overrides header for cookie (always "Cookie") and apikey-query (defaults to "api_key" unless user set it explicitly). The apikey-query default is applied AFTER the empty-header fallback so the user's explicit `--auth-header api_secret` wins.

func ResolveAuth

func ResolveAuth(flagAuth *AuthContext, profileLoader func() *AuthContext) *AuthContext

ResolveAuth resolves authentication from multiple sources in priority order:

  1. CLI flags (provided AuthContext)
  2. Environment variables (FENDIX_AUTH, FENDIX_AUTH_TYPE, FENDIX_AUTH_HEADER)
  3. Config file (~/.fendix/profiles/) — resolved via ProfileLoader if provided

Returns nil if no auth source is available.

func (*AuthContext) ApplyToRequest

func (a *AuthContext) ApplyToRequest(req *http.Request)

ApplyToRequest sets the authentication on an HTTP request — either as a header (default) or as a query-string parameter (apikey-query mode). Safe to call on a nil receiver.

func (*AuthContext) Redacted

func (a *AuthContext) Redacted() string

Redacted returns "[REDACTED]" for any non-empty credential. Auth credentials must never appear in report output.

func (*AuthContext) RedactedHeader

func (a *AuthContext) RedactedHeader() (string, string)

RedactedHeader returns the header name and a masked value, safe for logging.

type AuthExpectation

type AuthExpectation string

AuthExpectation is what Fendix ESTABLISHED about whether an endpoint is supposed to require authentication — independently of what it actually did when probed.

The zero value is UNKNOWN and that is load-bearing. A target scanned with no spec and no static route analysis has no expectation, and "we never established one" must never render as "this endpoint is declared public". Collapsing unknown into public would silently suppress real bypasses; collapsing it into required would flag every public endpoint as CRITICAL, which is the RC-2 defect. It is its own state, and the decision layer treats it as evidence in neither direction.

const (
	// AuthExpectationUnknown — never evaluated. NOT a claim in either direction.
	AuthExpectationUnknown AuthExpectation = ""
	// AuthExpectationPublic — a source of truth declares anonymous access
	// intentional (OpenAPI `security: []` or `security: [{}]`).
	AuthExpectationPublic AuthExpectation = "public"
	// AuthExpectationRequired — a source of truth declares authentication
	// required: an operation-level `security` requirement, or an inherited
	// global one the operation does not override.
	AuthExpectationRequired AuthExpectation = "required"
)

type Confidence

type Confidence string

Confidence represents how certain we are about a finding.

const (
	ConfidenceHigh   Confidence = "HIGH"
	ConfidenceMedium Confidence = "MEDIUM"
	ConfidenceLow    Confidence = "LOW"
)

type ConfidenceReason

type ConfidenceReason struct {
	Delta int    `json:"delta"`
	Code  string `json:"code"`
	Text  string `json:"text"`
}

ConfidenceReason is one scoring rule's contribution to a confidence score. confidence.Reason is an alias of this type; it is declared HERE because it has to sit on Finding, and the confidence package imports models — so the dependency can only point one way.

type DependencyRef

type DependencyRef struct {
	Ecosystem string `json:"ecosystem,omitempty"` // PyPI, npm, Go, …
	Package   string `json:"package,omitempty"`
	Version   string `json:"version,omitempty"`
	Manifest  string `json:"manifest,omitempty"` // requirements.txt, package-lock.json, …
}

DependencyRef is the semantic identity of the package a dependency finding is about: which ecosystem, which package, which manifest declared it.

It exists because that identity used to live only in the rendered Title ("Vulnerable dependency: requests==2.28.0 (CVE-…)"), which made the dependency's identity a substring of a human-readable string. Version is carried for reporting but is deliberately NOT an identity input — a package bumped from one vulnerable version to another is the same unresolved vulnerability, and churning its fingerprint would file it as "fixed, plus a new one" on every patch release.

type Finding

type Finding struct {
	ID string `json:"id"`
	// Fingerprint is the fendix/v2 semantic, run-stable identity for the
	// finding: SHA-256 over labelled identity components, truncated to 20
	// bytes. Unlike ID (a positional SEC-NNN reassigned every run) it excludes
	// line/column coordinates and presentation text, so .fendix-ignore rules and
	// baselines keep matching across line shifts and rewording. The containing
	// file/manifest or HTTP method+path remains part of identity. Stamped
	// centrally in the orchestrator before ID assignment.
	Fingerprint string `json:"fingerprint,omitempty"`
	// FingerprintV1 is the RETIRED sha1(Category|Endpoint|Title) identity for
	// this same finding, published purely as a migration bridge.
	//
	// It is not an identity and nothing may key on it: v1 moved whenever a
	// line was inserted above a finding, which is the defect v2 exists to fix.
	// Its only job is to let a consumer that tracked this finding under v1
	// recognise it after the re-key, instead of reading the transition as
	// "the old finding vanished and a new one appeared" — which is how the
	// hosted backend ended up with two Issues, and two SEC ids, for one
	// vulnerability.
	//
	// Computed here rather than downstream so the mapping is produced by the
	// side that owns both algorithms and cannot drift from either.
	FingerprintV1 string `json:"fingerprint_v1,omitempty"`
	// RuleID is the precise rule/check that fired (e.g. "python.ssrf.taint",
	// "secrets/aws-access-key", or a CVE id for a dependency advisory). It is
	// the single most stable identity input a finding has: unlike Title it is
	// not prose, and unlike Endpoint it does not move when the code does.
	//
	// It has always existed on evidence.Evidence; it was dropped by
	// ToFinding, which is precisely why fingerprinting had nothing semantic
	// left to hash and fell back on Category|Endpoint|Title.
	RuleID string `json:"rule_id,omitempty"`
	// Dependency is the package identity behind a `deps` finding. Nil for
	// every other family.
	Dependency *DependencyRef `json:"dependency,omitempty"`
	// Secret is the safe identity of a committed credential behind a
	// `secrets` finding. Nil for every other family. Never holds credential
	// material — see SecretRef.
	Secret *SecretRef `json:"secret,omitempty"`
	// Sink is the normalized vulnerable OPERATION a code finding is about —
	// "requests.get(url)", "cursor.execute(q)", "open(name)". It is the
	// operation's identity, and it is what separates two vulnerabilities of
	// the same rule in the same symbol.
	//
	// Carried explicitly rather than read off the end of TaintChain, because a
	// chainless finding has no chain to read and would otherwise fall back to
	// its evidence text. Those are different strings, so the fallback made
	// identity move the moment an analyzer learned to PROVE a flow it had only
	// observed — turning an evidence improvement into a new vulnerability. The
	// analyzer knows the sink either way; this is where it says so.
	Sink string `json:"sink,omitempty"`
	// Symbol is the enclosing function or method a code finding sits in.
	//
	// Distinct from Route.Handler on purpose. A Route is bound only when the
	// analyzer PROVED a taint chain and the enclosing function is a registered
	// handler, so route availability tracks how much was proven rather than
	// tracking the code. Identity must not inherit that dependency: the
	// symbol is the same symbol whether or not the flow was proven, and
	// keying on Route.Handler made a finding change identity the moment its
	// chain became provable.
	Symbol            string   `json:"symbol,omitempty"`
	Title             string   `json:"title"`
	Severity          Severity `json:"severity"`
	Source            Source   `json:"source"`
	Category          string   `json:"category"`
	Endpoint          string   `json:"endpoint"`
	AffectedEndpoints []string `json:"affected_endpoints,omitempty"`
	// Occurrences lists every distinct security occurrence this finding
	// presents: one entry per (endpoint, occurrence fingerprint). A finding is
	// a PRESENTATION group; an occurrence is the unit of security identity.
	// Baselines, `.fendix-ignore` rules and lifecycle tracking act on
	// occurrences, never on the group, so a new occurrence that joins an old
	// group can never inherit the group's suppression or disposition. The
	// finding's own Fingerprint is the primary occurrence's fingerprint and
	// always appears here. Emitted for every scanned finding; absent only on
	// reports produced before this field existed.
	Occurrences []Occurrence `json:"occurrences,omitempty"`
	Evidence    string       `json:"evidence"`
	Fix         string       `json:"fix"`
	References  []string     `json:"references"`
	Confidence  Confidence   `json:"confidence"`
	Line        *string      `json:"line"`
	TaintChain  []TaintLink  `json:"taint_chain,omitempty"`
	Reachable   bool         `json:"reachable,omitempty"`
	// SourceTier records the analysis engine tier (Proven Path v1). Empty
	// for blackbox / pre-field findings. See SourceTier doc.
	SourceTier SourceTier `json:"source_tier,omitempty"`
	// Route binds the finding to its HTTP route (Proven Path v1). Empty
	// when unbound. A non-empty Route + a TaintChain is the v1 "proof":
	// route → handler → source→sink taint path.
	Route *Route `json:"route,omitempty"`
	// RouteConfirmed is set by the correlator when a blackbox endpoint was
	// matched to this finding's Route.Pattern (the highest-priority match
	// strategy). It means the live scan actually hit the route the taint
	// chain reaches — not merely a fuzzy URL overlap.
	RouteConfirmed bool `json:"route_confirmed,omitempty"`
	// ProvenPath is the Proven Path v1 signal: set ONLY when RouteConfirmed
	// AND Reachable are both true (and the source tier cleared the F1 gate).
	// It marks the "DAST hit + SAST taint path + the exact route that reaches
	// it" case and forces the finding to CRITICAL. Never set from
	// RouteConfirmed alone.
	ProvenPath bool `json:"proven_path,omitempty"`

	// --- v0.24 Decision Reports (additive, omitempty) -------------------
	// These surface the internal Decision + Confidence Engine in the public
	// report. Stamped once by the orchestrator from the finalized finding
	// set; absent (and byte-identical to pre-v0.24) when a reporter is
	// called without the orchestrator's decision pass.
	//
	// Status is the decision verdict: BLOCK / WARN / INFO.
	Status string `json:"status,omitempty"`
	// ConfidenceScore is the deterministic 0–100 confidence score (v0.23).
	ConfidenceScore int `json:"confidence_score,omitempty"`
	// ConfidenceBand is the score-derived HIGH/MEDIUM/LOW band. It is
	// intentionally distinct from the existing `confidence` enum (which
	// scanners/correlation set): `confidence` is unchanged for backward
	// compat; `confidence_band` is the v0.23 scorer's bucket and may equal it.
	ConfidenceBand string `json:"confidence_band,omitempty"`
	// ConfidenceReasons is the plain-text, per-rule breakdown of the score
	// (the "no black boxes" contract).
	ConfidenceReasons []string `json:"confidence_reasons,omitempty"`

	// ConfidenceBreakdown is ConfidenceReasons in machine-readable form,
	// index-for-index aligned with it: one entry per scoring rule that fired,
	// carrying a stable Code and the signed Delta it contributed.
	//
	// It exists so a consumer — the SARIF export above all — can key off a
	// rule identity instead of parsing a presentation string whose wording is
	// free to change. The deltas sum to ConfidenceScore, so the score is
	// reconstructable without a parser.
	ConfidenceBreakdown []ConfidenceReason `json:"confidence_breakdown,omitempty"`
	// DecisionReason is the plain-text justification for Status, verbatim from
	// decision.Decision.Reason.
	DecisionReason string `json:"decision_reason,omitempty"`
	// DecisionPolicy names which policy produced Status: "enforced" (the
	// shipped evidence-gated policy) or "relaxed" (the legacy severity-only
	// mapping restored by --enforce-confidence=false).
	DecisionPolicy string `json:"decision_policy,omitempty"`
	// PolicyOverride is true only when the relaxed policy produced a BLOCK the
	// shipped policy would NOT have produced — i.e. an unconfirmed finding
	// gated the build because the operator switched the evidence requirement
	// off.
	//
	// omitempty is deliberate: the marker's PRESENCE is the signal. Publishing
	// "policy_override": false on every normal result would be noise, and noise
	// is how a genuine override goes unnoticed.
	PolicyOverride bool `json:"policy_override,omitempty"`
	// IndependentSignals / SelfEvidentSignals are the two corroboration classes
	// behind Status (decision.corroborate). Only Independent may lift a band to
	// BLOCK; both are published so a reader can reconstruct the verdict without
	// re-running the engine.
	//
	// STAMPED, NOT PROJECTED — same reasoning as the corroboration pair below:
	// engine.stampDecisions writes them from the post-Restore evidence, so they
	// reflect the merged group rather than whichever duplicate won findingLess.
	IndependentSignals []string `json:"independent_signals,omitempty"`
	SelfEvidentSignals []string `json:"self_evident_signals,omitempty"`
	// AuthExpectation is what a source of truth declared about authentication
	// for this endpoint (unknown / public / required). Published because the
	// DECISION depends on it: a "contradicted authentication requirement" is an
	// independent corroborating signal, and an auditable decision cannot cite a
	// field the report withholds. Empty (unknown) is omitted, which is the
	// honest encoding — see the type doc.
	AuthExpectation AuthExpectation `json:"auth_expectation,omitempty"`
	// Applicability is the dependency-applicability verdict. Published for the
	// same reason as AuthExpectation: the decision policy reads it, and an
	// auditable verdict cannot cite a field the report withholds. Unknown is
	// omitted, which is the honest encoding of "not evaluated".
	Applicability Applicability `json:"applicability,omitempty"`

	// --- Cross-tool corroboration (SARIF import) ------------------------
	// CrossToolCorroborated / CorroboratingTools publish the verdict of
	// engine.CorrelateCrossTool: an INDEPENDENT tool reported the same
	// normalized weakness at the same normalized location. Both omitempty,
	// so a report with no corroboration is byte-identical to one produced
	// before these fields existed. Their additive introduction did not require
	// a schema-version bump.
	//
	// STAMPED, NOT PROJECTED. evidence.ToFinding deliberately does NOT carry
	// them; engine.stampDecisions writes them from the post-Restore evidence
	// so the published value is the PROOF-UNION over the dedup group rather
	// than whichever duplicate happened to win findingLess and become the
	// group primary. Projecting them through the render block would silently
	// reintroduce the erasure the proof-union fold exists to prevent — on a
	// public surface. TestPublicCorroborationSurvivesUncorroboratedDuplicate
	// locks this.
	CrossToolCorroborated bool     `json:"cross_tool_corroborated,omitempty"`
	CorroboratingTools    []string `json:"corroborating_tools,omitempty"`
}

Finding represents a single security finding produced by either engine. This struct is the shared data contract between Go and Python.

AffectedEndpoints is populated by the orchestrator's deduplication pass (TASK-088) when N findings of the same (Title, Category, Severity) collapse into one. The slice contains every affected endpoint including the primary one in `Endpoint`. When the finding represents a single occurrence, AffectedEndpoints is nil (omitted from JSON via omitempty).

TaintChain and Reachable are populated by the white-box AST analyzer when it can prove an intra-function dataflow path from a request-input source to a dangerous sink (TASK-114). The correlator promotes a blackbox+whitebox match to Source=correlated AND Reachable=true when the whitebox half carries a chain — that's the "DAST + SAST agree AND we can show the path" case worth a build-failing exit code.

func EnforceSeverityConsistency

func EnforceSeverityConsistency(f Finding) (Finding, bool)

EnforceSeverityConsistency returns f with severity downgraded to MaxSeverityForConfidence(f.Confidence) when the original severity exceeds that cap. The boolean return indicates whether a downgrade happened, so callers can log or count violations.

type Occurrence

type Occurrence struct {
	Endpoint    string `json:"endpoint"`
	Fingerprint string `json:"fingerprint"`
}

Occurrence is one security occurrence inside a (possibly grouped) finding: where it is, and its own fendix/v2 fingerprint. The fingerprint is computed from that occurrence alone, before any grouping, so it is independent of which other occurrences share its presentation group and of how their paths sort.

type Route

type Route struct {
	Method  string `json:"method,omitempty"`  // GET, POST, … ("" = any/unknown)
	Pattern string `json:"pattern,omitempty"` // URL pattern, e.g. /users/<id>
	Handler string `json:"handler,omitempty"` // handler symbol, e.g. views.get_user
	File    string `json:"file,omitempty"`    // file the route is declared in
	Line    int    `json:"line,omitempty"`    // line of the route declaration
}

Route binds a finding to the HTTP route that reaches its sink (Proven Path v1). Populated by the Python route extractor for whitebox findings whose enclosing function is a registered Django/Flask/FastAPI handler; the correlator uses it to bind a blackbox endpoint to the exact handler + taint chain instead of fuzzy path matching. Empty when no route could be bound (e.g. a finding in a helper not directly wired to a URL).

type ScanConfig

type ScanConfig struct {
	URL      string
	SpecPath string
	CodePath string
	// ImportPaths lists SARIF 2.1.0 files from OTHER scanners to normalize
	// and merge into the evidence stream (`fendix scan --import`, repeatable)
	// or to ingest standalone (`fendix import`, via Orchestrator.RunImport).
	// "-" means stdin. A malformed file is a hard error (exit 2) — importing
	// half a document would misrepresent coverage.
	ImportPaths  []string
	Auth         *AuthContext
	AuthUser2    *AuthContext
	EnableActive bool
	// MaxProbesPerEndpoint caps the number of active probes sent to a single
	// endpoint. Zero means "use the scanner's default" (currently 20).
	MaxProbesPerEndpoint int
	Workers              int
	Timeout              int
	DelayMs              int
	Checks               []string
	Verbose              bool
	IgnorePath           string
	BaselinePath         string
	SaveBaselinePath     string
	OutputPath           string
	Format               string
	FailOn               string
	// WordlistPath overrides the built-in CommonPaths brute-force list.
	// Plain text, one path per line; lines starting with `#` and blank lines
	// are ignored; a leading `/` is added if missing.
	WordlistPath string
	// CrawlDepth controls recursive HTML link following from --url.
	// 0 disables HTML crawl; 1 (default) follows links from the home page.
	// Values >1 follow links from those pages too. Same-host only; visited
	// set prevents loops; --max-endpoints caps total discovery.
	CrawlDepth int
	// MaxEndpoints caps the total endpoint count after dedupe. 0 means
	// "no cap"; default is 500. Prevents runaway scans on large sites.
	MaxEndpoints int
	// MaxRequests caps the total HTTP request count across all checks for
	// the entire scan. 0 (default) means "no cap". When the cap is hit, the
	// scan soft-stops: in-flight requests finish, no new jobs are scheduled,
	// and the orchestrator emits a `budget summary` line with sent/rejected
	// counts. Enforced by an http.RoundTripper wrapper plus a worker-pool
	// ctx cancel; see internal/budget.
	MaxRequests int64
	// MaxDuration is the hard upper bound on scan wall-clock time. 0
	// (default) means "no cap". When set, the orchestrator wraps the run
	// context with `context.WithTimeout(parent, MaxDuration)`; deadline
	// expiry triggers the same soft-stop path as MaxRequests.
	MaxDuration time.Duration
	// RespectRobots controls how robots.txt Disallow directives are
	// interpreted. Default false: disallowed paths are queued as endpoint
	// hints (the security-tool default — those paths are exactly the URLs
	// operators don't want exposed). When true: disallowed paths are
	// filtered out of the discovered endpoint list, matching the
	// polite-crawler convention required for scanning third-party
	// production targets.
	RespectRobots bool
	// DebugBundlePath, when set, writes a redacted .tar.gz at scan end
	// containing the scan config (auth values masked), environment
	// versions, probe audit log, buffered DEBUG slog stream, and findings.
	// Empty disables the bundle. See internal/diagnostic.
	DebugBundlePath string
	// NoPlugins disables out-of-tree plugin discovery and execution
	// (TASK-113). When false (default), the orchestrator walks
	// ~/.fendix/plugins/ (and, only when AllowRepoLocalPlugins is set,
	// the repo-local .fendix/plugins/) after the embedded
	// blackbox/whitebox checks and feeds plugin findings through the
	// same correlation/dedup pipeline.
	NoPlugins bool
	// AllowRepoLocalPlugins opts in to discovering repo-local plugins
	// under <scan-cwd>/.fendix/plugins/ (F-H2). Default false: the
	// scanned repository is attacker-controlled in the poisoned-pipeline
	// threat model, so a `.fendix/plugins/` directory committed by a
	// malicious PR must NOT auto-execute in CI. The user-global
	// ~/.fendix/plugins/ root the operator populated by hand is always
	// trusted and searched regardless of this flag. Enable only when the
	// scanned tree is trusted (e.g. a first-party repo on a protected
	// branch), never on untrusted PRs.
	AllowRepoLocalPlugins bool
	// NoNativeDeps disables the in-process Go dep-CVE scanner
	// (TASK-119 / internal/scanner/deps/govulncheck). When false
	// (default), the orchestrator runs the native scanner against any
	// go.mod found under CodePath before spawning the Python whitebox
	// engine; native findings flow through the same dedup pipeline so
	// the transitional Python deps.py output collapses into one entry
	// per OSV. Set true to skip the native path (debugging, or when
	// the vuln DB is unreachable and the Python fallback is preferred).
	NoNativeDeps bool
	// UsePipAudit, when true, makes the Python dep-CVE pass shell out
	// to the pip-audit binary instead of using the native OSV.dev
	// /v1/query client. Falls back to OSV.dev with a stderr warning
	// if pip-audit is not on PATH (never fails-closed silently).
	// Surfaced by Sprint 01 of the enterprise-readiness plan to close
	// the audit's §15.5 trust gap (pip-audit naming vs. implementation).
	UsePipAudit bool
	// PythonEngine controls the Python whitebox engine (TASK-118). Its Cobra
	// default is false, but the scan command sets it true whenever --code is
	// present unless the user explicitly passes --python-engine=false. The
	// binary no longer bundles the Python distribution. Running the auth /
	// injection / deps Python checks therefore requires either a local
	// `python/` source tree or an explicit FENDIX_ENGINE env var
	// pointing at one; the official container supplies the tree separately.
	PythonEngine bool

	// PythonEngineExplicit is true only when the user passed --python-engine
	// directly (not when --code auto-enabled PythonEngine). It controls how a
	// missing engine is handled: an EXPLICIT request that can't be resolved is
	// a hard exit-2 error (the user asked for the AST taint engine and we have
	// nowhere to run it); an IMPLICIT one (auto-enabled by --code) degrades to
	// a WARN + native-Go-only scan, because the user didn't explicitly require
	// the Python phase and shouldn't have a plugin/native-only --code scan
	// aborted just because the external Python tree isn't present. Default false.
	PythonEngineExplicit bool

	// Lang controls the HTML reporter's language (Sprint 10). Today's
	// values: "en" (default) and "ar". Other formats (JSON, SARIF) stay
	// English because they're machine-consumed. Unknown values fall
	// back to English at render time; the CLI wrapper warns when a
	// passed --lang isn't a supported translation.
	Lang string

	// AllowPrivate disables the SSRF egress guard (internal/netguard) so the
	// scanner may connect to private/loopback/link-local addresses and the
	// cloud metadata IP. Default false: those addresses are refused at dial
	// time (anti-SSRF / anti-DNS-rebinding) and redirects into them are
	// re-blocked per hop. The scan command sets this from
	// --allow-private-targets and auto-enables it when the operator's own
	// --url target already resolves to a private/loopback IP (scanning your
	// own internal/staging/localhost target must keep working).
	AllowPrivate bool

	// Offline puts the native dep-CVE scanners (govulncheck / pip / npm) into
	// air-gapped mode (F-M4/F-H4). The native dependency paths MUST NOT make
	// an outbound advisory/tool call: pip/npm consult the local snapshot at
	// OfflineDBPath, and govulncheck is recorded as SKIPPED. This flag does
	// not suppress target traffic, arbitrary plugins, or the current Python
	// dependency phase (a documented product defect). See internal/offline.
	Offline bool
	// OfflineDBPath is the path to the offline-db snapshot consulted in
	// --offline mode. Empty falls back to offline.DefaultDBPath()
	// (~/.fendix/offline-db.json). Only effective with Offline=true.
	OfflineDBPath string

	// FailOnScannerError makes any recorded per-scanner failure
	// (F-L7/F-L13/F-L14) force a non-zero exit, regardless of the
	// --fail-on severity threshold. Opt-in for CI pipelines that want a
	// scanner crash (govulncheck/pip/npm/secrets/semgrep/textscan) to
	// fail the build instead of silently degrading coverage. Skipped
	// scanners (e.g. govulncheck in offline mode) do not count as
	// failures — only scanners that ran and errored.
	FailOnScannerError bool
	// FailOnCoverageGap exits 2 when metadata.coverage.configured_complete
	// is false: an analyzer this run was configured to execute was
	// unavailable or failed. Disabled, not-applicable and unsupported never
	// trip it. Off by default (coverage contract v1).
	FailOnCoverageGap bool
	// ManagedEvidencePath, when set, writes the managed-CI submission
	// document (contract managed-ci/v2) for the runner to POST. It needs
	// ManagedContextPath, and any failure to produce it fails the scan:
	// a managed run that cannot produce evidence must never look like one
	// that produced clean evidence.
	ManagedEvidencePath string
	// ManagedContextPath is the runner-supplied CI identity for that
	// document (managed-scan-context/v1 plus the submission id).
	ManagedContextPath string

	// RequiredAnalyzers names analyzers that must be delivered — recorded ok
	// or not_applicable — for the run to exit 0. Stricter than
	// FailOnCoverageGap: a disabled or unsupported required analyzer exits 2,
	// because the operator asked for it by name. Names are validated
	// against engine.Registry before the scan starts.
	RequiredAnalyzers []string

	// Diff enables diff-aware scanning: the whitebox scanners
	// (secrets/textscan/semgrep) are scoped to only the files git reports
	// as changed, and the dep-CVE scanners run only when their manifest
	// changed. This is the engine half of `fendix scan --diff[=ref]
	// --staged` — the "runs on every commit" developer-workflow feature.
	// When false (default) every scanner sees the full CodePath tree,
	// exactly as before. Diff mode can only narrow the file set, never
	// alter detection logic, so it does not move the heavy-eval F1 score.
	Diff bool
	// DiffRef is the git ref the diff is computed against (a branch, tag,
	// or commit-ish like "origin/main" or "HEAD~1"). Empty diffs against
	// HEAD. Only meaningful when Diff is true.
	DiffRef string
	// DiffStaged restricts the diff to staged changes (`git diff
	// --cached`) — the set a pre-commit hook scans. Only meaningful when
	// Diff is true.
	DiffStaged bool

	// DeescalateTests drops findings whose sink lives in test / fixture code
	// from WARN to INFO in the decision layer (v1.1 B3, fp_class
	// "test-fixture"). Evidence is preserved, never suppressed (Rule 3), and a
	// finding at or above --fail-on is held at WARN unless its evidence support
	// survives the decision policy's test-code rule.
	//
	// Default TRUE (the CLI flag defaults to true; a zero-valued ScanConfig
	// built directly in a test opts out). Real-world corpora showed 98-100% of
	// clean-library SAST noise lives in tests/, so demoting it is the
	// right default; teams that DO want to gate on test-code findings pass
	// --deescalate-tests=false or set scan.deescalate_tests in .fendix.yaml.
	DeescalateTests bool

	// EnforceConfidence gates the --fail-on threshold on the deterministic
	// confidence band: at or above the threshold a finding BLOCKs only when its
	// band and evidence support the claim (HIGH needs an independent or
	// self-evident signal; MEDIUM needs an independent signal; LOW never), and a
	// finding the correlator marked unconfirmed-by-live-scan never blocks on
	// its own. Evidence is preserved, never suppressed (Rule 3) — only
	// enforcement moves. (v1.2.2 FIX-08.)
	//
	// Default TRUE (the CLI flag defaults to true; a zero-valued ScanConfig
	// built directly in a test opts out — the same trap that left
	// DeescalateTests dead code, so a test that means to exercise the shipped
	// gate must set this explicitly). --enforce-confidence=false restores the
	// legacy severity-only mapping byte-for-byte; it does NOT also disable the
	// test-fixture rule, which is gated on DeescalateTests.
	EnforceConfidence bool

	// BlockOnInapplicable makes a dependency finding gate the build even when
	// Fendix has credible evidence its vulnerable component is unused. Default
	// false: such a finding is preserved in full and held at WARN. Set by
	// --block-on-inapplicable for teams whose policy is "no vulnerable version
	// ships, applicable or not".
	BlockOnInapplicable bool

	// Fast skips semgrep and the native dep-CVE scanners. It does not currently
	// suppress PythonEngine when --code auto-enabled it; callers that require
	// the native-only pre-commit path must also set --python-engine=false.
	Fast bool
}

ScanConfig holds all configuration for a scan run. It is populated from CLI flags and passed to the orchestrator.

type SecretRef

type SecretRef struct {
	Identifier string `json:"identifier,omitempty"`
	File       string `json:"file,omitempty"`
}

SecretRef is the SAFE identity of a committed credential: which non-sensitive identifier it was bound to and which file it lives in.

Identifier is the assignment key or config name the credential sits behind — AWS_SECRET_ACCESS_KEY, stripe_api_key, the JSON/YAML path. It is deliberately NOT the credential, and deliberately NOT a digest of the credential.

A digest was the obvious alternative and is rejected on purpose. The redaction marker already published in evidence is an unsalted, 4-byte truncated SHA-256 — the redact.go doc says outright that a low-entropy value is "trivially recoverable from it by dictionary". Evidence is one report; a fingerprint is forever: it is committed into .fendix-ignore files, saved into baselines, and uploaded to GitHub Code Scanning, where it would stand as a permanent, greppable oracle for the credential's value. Long-lived identity is exactly the wrong place to persist a reversible function of a secret. The identifier distinguishes two credentials in one file just as well and carries no credential material.

The residual trade-off, documented rather than hidden: when a pattern matches material with no binding identifier (a bare `-----BEGIN … KEY-----` block), Identifier is empty and two such blocks in one file share an identity — reported as one "private key material in this file" record. Merging two key blocks is a reporting imprecision; persisting a credential oracle would be a security defect.

type Severity

type Severity string

Severity represents the severity level of a security finding.

const (
	SeverityCritical Severity = "CRITICAL"
	SeverityHigh     Severity = "HIGH"
	SeverityMedium   Severity = "MEDIUM"
	SeverityLow      Severity = "LOW"
	SeverityInfo     Severity = "INFO"
)

func CalculateSeverity

func CalculateSeverity(category string, confidence Confidence, source Source) Severity

CalculateSeverity computes the severity level for a finding based on its category, confidence, and source using the scoring model.

REFERENCE MODEL — see the file header. Not called by any scanner; the live severity path is scanner-assigned → correlator escalation → EnforceSeverityConsistency.

func CalculateSeverityReachable

func CalculateSeverityReachable(category string, confidence Confidence, source Source, reachable bool) Severity

CalculateSeverityReachable extends CalculateSeverity with the Finding.Reachable=true bump (TASK-125 / docs/example_plan.md §3.5). When reachable is true, the score is multiplied by ReachableMult before banding, which lifts most findings by one severity level (subject to the confidence cap enforced by EnforceSeverityConsistency).

func MaxSeverityForConfidence

func MaxSeverityForConfidence(c Confidence) Severity

MaxSeverityForConfidence returns the highest severity level that a finding of the given confidence may carry. The cap is derived from the scoring formula's implicit maximum:

confidence=LOW    → score ≤ base × 0.5 × 1.1 = 5.5  → MEDIUM cap
confidence=MEDIUM → score ≤ base × 0.75 × 1.1 = 8.25 → HIGH cap (CRITICAL needs ≥ 9.0)
confidence=HIGH   → no cap (any severity allowed)

Findings that violate this contract are downgraded by the orchestrator's EnforceSeverityConsistency step before reports are written, so consumers of the JSON report can assume the cap holds.

type Source

type Source string

Source indicates which engine produced the finding.

const (
	SourceBlackbox   Source = "blackbox"
	SourceWhitebox   Source = "whitebox"
	SourceCorrelated Source = "correlated"
	// SourceImported marks a finding ingested from another scanner's SARIF
	// report (`fendix import` / `scan --import`). Imported findings carry an
	// empty SourceTier on purpose — the correlator scores unknown tiers most
	// conservatively, so external evidence can never masquerade as a native
	// high-trust analyzer. They are fenced out of the blackbox↔whitebox
	// correlator entirely; the only way an import strengthens another finding
	// is the strong-corroboration path in engine.CorrelateCrossTool.
	SourceImported Source = "imported"
)

type SourceTier

type SourceTier string

SourceTier records WHICH analysis engine tier produced a whitebox finding (Proven Path v1 / roadmap "Tier provenance enforcement"). The correlator weights tiers differently when escalating confidence: a CRITICAL driven by a Tier-3 semgrep regex that never cleared the F1≥0.95 gate must not escalate to CRITICAL via correlation. Preserved end-to-end through NDJSON IPC → correlator → ScanFinding → UI so the F1 gate can't be silently bypassed by the correlation moat.

Empty for blackbox findings (no code tier produced them) and for pre-existing findings emitted before the field existed — treat empty as "unknown tier", which the correlator scores most conservatively.

const (
	// TierNativeGo: in-binary Go analysis (textscan today; gosast later).
	TierNativeGo SourceTier = "native_go"
	// TierTreeSitter: the Python/tree-sitter sidecar (the AST taint
	// analyzer that emits taint chains — the highest-trust SAST tier).
	TierTreeSitter SourceTier = "tree_sitter_sidecar"
	// TierSemgrepShim: shelled-out semgrep (breadth, lowest trust until a
	// rule pack clears the F1 gate).
	TierSemgrepShim SourceTier = "semgrep_shim"
)

func (SourceTier) TrustRank

func (t SourceTier) TrustRank() int

TrustRank orders the analysis tiers by how much the engine trusts them. Higher wins. Used to pick the representative when two engines report the SAME sink at the same location, so the surviving finding is the one from the most trustworthy analyzer rather than whichever happened to run first.

The ordering mirrors the correlator's escalation gate (TASK-125): the tree-sitter taint analyzer proves a dataflow path, native Go rules are in-binary and line-exact, and the semgrep shim buys breadth at the cost of precision until its rule pack clears the F1 gate. An empty tier ("unknown", e.g. the SCA scanners) sorts above only semgrep — it is not a low-precision regex pass, it simply predates the field.

type TaintLink struct {
	File string `json:"file"`
	Line int    `json:"line"`
	Expr string `json:"expr"`
}

TaintLink is one step in a dataflow chain from a source (e.g. request.args.get) to a sink (e.g. cursor.execute). The Python AST analyzer records these chains for SQLi, SSRF, and open-redirect findings (TASK-114) so the correlator and reporters can prove "this is reachable" rather than "this looks dangerous."

Jump to

Keyboard shortcuts

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