Documentation
¶
Overview ¶
Package scanner is abcd's native secret + PII detector. It ports the Python PII scanner (scripts/abcd/src/pii.py) and the bundled secret patterns (scripts/abcd/defaults/pii.json) into a transport-agnostic Go engine: it reads files under a caller-supplied root, inspects their CONTENT, and returns structured findings — no printing, no os.Exit, no external tool (no gitleaks/trufflehog shell-out) — so it is fully testable and reusable across surfaces. The always-on native scanner is the default; deeper opt-in scanners fail closed when absent.
RE2 constraint: Go's regexp has no lookaround or backreferences, so every ported lookaround becomes a Go post-match predicate (see patterns.go and identity.go). regexp2 is deliberately NOT used (it would be a new dependency).
Index ¶
- Constants
- Variables
- func CallerHome() string
- func DecodedViews(line string) []string
- func DefaultIdentitySeverities() map[string]Severity
- func GoSourceSkip(kind, line string, start, end int) bool
- func IsHarnessLeakKind(kind string) bool
- func IsIdentityKind(kind string) bool
- func IsNonUserHomeSegment(seg string) bool
- func IsNonUserPosixHomeSegment(seg string) bool
- func IsPersonaName(seg string) bool
- func IsTokenKind(kind string) bool
- func MaxBinaryScanBytesForTest() int
- func Redact(text string, findings []Finding) (string, int)
- func RedactRefusal(repoRoot, text string) string
- func SetDefaultAugmenter(f func(repoRoot string) Augmenter) (restore func())
- func SweepCallerHome(text, home string) string
- type Augmenter
- type BundleFile
- type Config
- type Exclusion
- type Finding
- func BlockingResidual(findings []Finding) []Finding
- func CheckOutbound(repoRoot, text, label string) ([]Finding, error)
- func ScanText(text string, id Identity, patterns []Pattern, id2sev map[string]Severity, ...) []Finding
- func ScrubOutbound(repoRoot, text, label string) (string, []Finding, error)
- func SurvivingCallerHome(text, home string) (string, []Finding)
- func UnsealedAugmented(redacted string, findings []Finding) []Finding
- type Identity
- type Option
- type Pattern
- type ScanResult
- type Scanner
- func (s *Scanner) Augmented() bool
- func (s *Scanner) AugmenterGap() string
- func (s *Scanner) Fingerprint() string
- func (s *Scanner) NetworkPatterns() []Pattern
- func (s *Scanner) ScanAugmented(text, file string) []Finding
- func (s *Scanner) ScanBundle(files []BundleFile) (ScanResult, error)
- func (s *Scanner) ScanText(text, logicalName string) []Finding
- func (s *Scanner) ScanTextNative(text, logicalName string) []Finding
- func (s *Scanner) Unavailable() (bool, string)
- type Severity
Constants ¶
const AugmenterGapPath = "(configured scanner augmenter)"
AugmenterGapPath is the Unscanned entry ScanBundle adds for an augmenter the repository configured whose tool is not installed; UnscannedWhy carries the reason. It is not a path, and a reader words it as the gap it is.
const KindHomePathOther = kindHomeOther
KindHomePathOther is the identity kind for another account's home path: a generic /Users or /home path that is not the caller's own. The scanner grades it warn, so the gates that judge committed files let it pass; the release cut reads it by name to refuse it in newly composed public release text.
const OutboundPolicy = "Never put a live session URL or a tool's own attribution footer " +
"(\"generated with/by <tool>\") into public text — a pull-request body, an issue, a comment, " +
"a commit message or a release note. Disclosure goes in the repository's own trailer " +
"(Assisted-by: <Vendor>:<model-version>) and nowhere else. " +
"After creating ANY pull request, issue or comment, re-read what was actually created and strip " +
"any session URL or attribution footer from it: the harness appends them outside your own output, " +
"so text that left you clean can arrive dirty, and the forge keeps the pre-edit revision of what " +
"was posted — which is why the strip has to happen immediately, not at review time."
OutboundPolicy is the policy block an autonomous routine's prompt carries. It is a value rather than prose in a document because the prompt assembly, the audit rule's fix hint and this package's own contract must say the same thing: a policy that exists in three wordings is a policy with three meanings.
Variables ¶
var ErrAugmenterNotFound = errors.New("scanner augmenter configured but not found")
ErrAugmenterNotFound is the sentinel an augmenter's Available error matches when the repository configured it but its tool is not installed. It is one state with one consequence per consumer: launch fails closed on it (an Unscanned entry and a hard fail), while capture, history and memory write and record the gap in their receipt.
Functions ¶
func CallerHome ¶ added in v0.6.9
func CallerHome() string
CallerHome resolves the home of the person the text is being judged for, trimmed of any trailing slash; empty when none resolves. It reads $HOME, so tests and redirected runs agree, except inside a walled stage: a stage's home is its own folder, named home, and that name is no account, so the person's home stands in through the one resolver that tells the two apart. A fixture that moved HOME away from the stage's home keeps the home it moved to.
func DecodedViews ¶ added in v0.11.1
DecodedViews returns the decoded spellings of one line that the scan reads beside the line as written (lineViews), without their position maps: nil for a line with nothing to decode. It is the seam for a surface that judges committed lines with its own matchers — the repolint privacy rule and the harness_leak lint rule — so a JSON fixture, export or transcript that writes a home path, an address or a session URL behind an escape is read in the spelling the store-before-commit redactors read it in (iss-2609261658553101). A decoded view can carry line breaks the escapes stood for; a line-scoped check reads each one as the start of a line.
func DefaultIdentitySeverities ¶
DefaultIdentitySeverities is the built-in severity floor per identity kind (ported from pii.py DEFAULT_IDENTITY_SEVERITIES). A config override may raise but never lower these.
func GoSourceSkip ¶ added in v0.13.0
GoSourceSkip reports whether a finding of the given kind, matched at line[start:end], is Go code rather than the identifier the kind names. It is for a caller that KNOWS the line comes from a Go source file — the privacy lint rule, which reads tracked files by path — and for no other: a redactor with no file type (the history transcript store, memory, capture and the other write paths that call ScanText with a logical name) must never consult it, because the shapes it spares are written by logs, diagrams and prose too ("dial(…): connection refused", a mermaid node "nas(…) --> router").
It spares one shape, a Go selector closing or separating a call's argument list (callArgumentSelector), and only for net_lan_hostname (iss-2610020840196926, narrowed to Go files after sec-scannerSel).
func IsHarnessLeakKind ¶ added in v0.6.8
IsHarnessLeakKind reports whether a finding kind belongs to the harness-leak class. It is the selector the outbound scrub and the lint surfaces key on, so membership is declared once here rather than by each of them matching strings.
func IsIdentityKind ¶
IsIdentityKind reports whether a finding kind is a PII identity span (masked to a readable placeholder) rather than a secret token (masked to a fingerprint). The network kinds belong here too: an address, a MAC and a hostname are IDENTIFIERS, not high-entropy secrets. The secret fingerprint deliberately keeps the first three and last two runes so a leaked credential can be triaged, and on an identifier that is precisely the wrong trade — it preserves a MAC's vendor bytes and final octet, and a hostname's head and suffix, which is enough to re-identify the machine the redaction was meant to hide.
func IsNonUserHomeSegment ¶
IsNonUserHomeSegment reports whether seg, the segment immediately after a /Users home root, names a system directory rather than a user. The comparison is case-insensitive because a case-folding filesystem resolves /users/shared to the same directory.
func IsNonUserPosixHomeSegment ¶ added in v0.12.0
IsNonUserPosixHomeSegment reports whether seg, the segment immediately after a /home root, names a system account rather than a person.
func IsPersonaName ¶ added in v0.9.0
IsPersonaName reports whether seg is a given name from the persona registry, compared the way a path segment spells it: case-folded, because a home directory for the persona the conventions mandate is written `/Users/alice` whatever case the registry entry uses.
This is the SAME list personaDerivedHost consults for device names (iss-2609100505145554): the record asks for a persona home path to be treated "the same way a persona-derived device name is", and one list is what makes the two answers agree. A caller applying it to a home path must scope it to the username POSITION and must yield to the caller's own home — the case folding that is harmless for a fixture hostname is not, on its own, enough for a home path, because a real account for a person called Alice is spelled exactly like the fixture.
func IsTokenKind ¶ added in v0.13.0
IsTokenKind reports whether a finding kind is a credential: a key, a token or private-key material, the class every bundled secret rule names under the "token:" prefix. It is the one place that class is declared, because a token is a secret WHATEVER its severity: a rule that only warns (sk_key_generic, which a hash-like committed string must not fail a gate on) still names a credential that no store, refusal or outbound artefact may carry raw. So the sweeps and backstops that guard what is written select on it beside the severity (secretPatterns, BlockingResidual, RedactRefusal, ScrubOutbound's last stage), while the gates that judge files already committed — abcd lint and the launch scan's hard-fail count — still read the severity alone.
func MaxBinaryScanBytesForTest ¶ added in v0.6.9
func MaxBinaryScanBytesForTest() int
MaxBinaryScanBytesForTest exposes the byte-scan cap so the sibling privacy lint's tests can hold the two caps equal (repolint imports this package, so the constant cannot be shared the other way).
func Redact ¶
Redact rewrites every finding's matched span out of text, returning the sanitised text and the count of spans actually changed. It is the shared write-time sanitiser: both the history transcript store and any other pre-disk redactor route through it so the masking discipline lives in ONE place (it reuses the same maskSecret fingerprint Finding.MarshalJSON applies to the serialized surface).
EVERY kind is masked by AUTHORITATIVE BYTE SPAN — secret tokens to a non-reversible fingerprint (sealLine), identity kinds to a neutral placeholder (a self home path collapses to "~"). Byte-span masking is what makes two PARTIALLY overlapping secret spans safe: substring replacement, longest-first, used to let the wider match consume the narrower one's leading bytes so the narrower ReplaceAll found nothing and its raw tail survived — sealLine instead forces every overlap byte to '*'. Identity spans run AFTER the secrets are sealed, when no raw secret bytes remain and the seal has changed no byte COUNT, so the detector's offsets still describe the same bytes. Redact is only stage one; the caller MUST re-scan the result and fail closed if any hard_fail span survived.
Identity masking WAS a per-line strings.ReplaceAll, recorded as deliberate because an identity placeholder is length-changing and a whole-string rewrite needs no offsets. iss-2609120446083912 retired that choice: a whole-string replace cannot say "this occurrence masked, that one left", so it overrode every refusal the detector had learned to make — a reverse-DNS bundle component, a mid-word collision, an occurrence inside a URL — whenever a genuine mention shared the line, corrupting the technical content the record exists to hold. maskIdentitySpans below states the mechanism and names the fail-open cost the reversal accepts.
func RedactRefusal ¶ added in v0.12.0
RedactRefusal renders payload-chosen text for a refusal that is RETURNED to the caller rather than written: most often a strict decoder's message, which names an undeclared field, or a repeated key, by the payload's own key. That name is what the reader needs to find the fault, so it is kept and redacted rather than described, and a token or a home path inside it never reaches the terminal or the transcript (iss-2609290218032954).
The text goes through the canonical pattern set for repoRoot, then the literal sweep of the caller's home (independent of the pattern heuristic, the defence-in-depth every store-before-commit redactor applies), then termsafe.Sanitize, so the result is inert on a terminal. The pattern pass includes ScanText's glued sweep (glued.go): a token right behind an underscore or a letter, which the patterns' leading \b cannot see, is sealed byte for byte like any other (iss-2609290541525428).
It FAILS CLOSED. A returned refusal has no record to note a degradation in, so a scanner that cannot be built, runs degraded, cannot build its whole glued sweep, or leaves a secret span in the redacted text leaves the text DESCRIBED by termsafe.DescribeRefused and never echoed. The scanner is built per call: this runs on the refusal path alone, so a payload that decodes pays nothing for it.
func SetDefaultAugmenter ¶ added in v0.12.0
SetDefaultAugmenter registers the factory every New consults when no WithAugmenter option was given, and returns a function restoring the one it replaced. The composition root calls it once; a test calls it to install a fake and defers the restore.
func SweepCallerHome ¶ added in v0.6.9
SweepCallerHome is the deterministic literal $HOME backstop, independent of the pattern heuristic: every occurrence of home that stands as a path is collapsed to "~". An occurrence stands as a path when nothing path-like precedes it (the start of the text, or a byte that cannot continue a path segment) and nothing name-like follows it (the end, a separator, or any byte outside the username-continuation set). An unanchored replace turned "/rootfs/etc/hosts" into "~fs/etc/hosts" under HOME=/root and "/home/abc/x" abcd-lint:allow into "~bc/x" under HOME=/home/a, silently corrupting the committed text; the abcd-lint:allow anchor is what lets a short home coexist with the paths that merely share its prefix. An empty home sweeps nothing.
The home is read in every spelling the detector reads (backstopSpans): as written, and through the decoded views of each line that carries an escape, so "\/Users\/me", its \u002f form, a second JSON layer and "%2FUsers%2Fme" abcd-lint:allow are swept with the escape's own bytes, exactly as the literal home is (iss-2609261659041553).
Types ¶
type Augmenter ¶ added in v0.12.0
Augmenter is an opt-in external detector whose findings the scanner appends to its own. The scanner declares the interface and never imports an implementation: the gitleaks adapter (internal/adapter/gitleaks) imports this package for Finding, so the edge runs that way, and the implementation is wired at the composition root (SetDefaultAugmenter) or passed in with WithAugmenter (the 2026-09-25 technical ruling on iss-2608291814575788).
Available reports whether the augmenter can be trusted right now. It is asked once when the scanner is built and again after every Scan: an error matching ErrAugmenterNotFound is a configured-but-absent tool, which the scanner carries as a coverage gap (AugmenterGap); any other error degrades the scanner (Unavailable), and it stays degraded. So a Scan that fails reports it through the next Available call rather than returning a short list quietly.
Scan returns findings for text, located in text. Its output is untrusted input: the scanner bounds the count, keeps only findings whose Matched bytes sit at the declared line and column, and rebuilds every other field itself (the file label, the kind's shape, the severity, the snippet), so nothing the augmenter wrote reaches a report or a record except the located span. An augmenter must report EVERY occurrence of a value it flags: a write path verifies an augmented finding by its bytes anywhere in the redacted text (UnsealedAugmented).
type BundleFile ¶
BundleFile is the minimal descriptor ScanBundle needs. It is defined here (rather than importing the launch package) so the scanner has NO dependency on launch — that would create an import cycle, since launch's dry-run orchestrator imports the scanner. The launch package adapts its IncludedFile slice to this.
type Config ¶
type Config struct {
SkipDirs []string `json:"skip_dirs"`
SkipPathFragments []string `json:"skip_path_fragments"`
// ExcludePathFragments are the exclusions the technical facilitator
// declares: a bundle file whose path holds a fragment's whole segments
// (exclusionMatches) is left out of the scan by choice and reported so,
// with the reason, never as scanned.
ExcludePathFragments []Exclusion `json:"exclude_path_fragments"`
SkipExtensions []string `json:"skip_extensions"`
SkipFilenames []string `json:"skip_filenames"`
Patterns map[string]patternDef `json:"patterns"`
IdentitySeverities map[string]Severity `json:"identity_severities"`
}
Config is the on-disk scanner configuration (the per-repo pii.json override shape). Only the consumed fields are modelled.
type Exclusion ¶ added in v0.13.4
Exclusion is one declared exclusion: a path fragment and the reason it is left out of the scan, which is required and travels with every file it matches.
type Finding ¶
type Finding struct {
File string `json:"file"`
Line int `json:"line"`
Column int `json:"column"`
Kind string `json:"kind"`
Severity Severity `json:"severity"`
Snippet string `json:"snippet"`
Matched string `json:"matched"`
Suggested string `json:"suggested_fix,omitempty"`
// contains filtered or unexported fields
}
Finding is one secret or PII detection. File is the bundle logical path; Line and Column are 1-based.
func BlockingResidual ¶ added in v0.6.9
BlockingResidual filters a stage-two rescan to the findings that must refuse a write. Severity alone is the wrong gate: the hostname patterns are shape heuristics and therefore warn by design, so a LAN host or device name that survived stage-one redaction would otherwise be committed in silence — the very class of leak the stores exist to stop. Any surviving IDENTITY or NETWORK span refuses the write whatever its severity, and so does any surviving TOKEN (IsTokenKind): a credential rule that only warns, so a hash-like committed string cannot fail a gate, still names a key no store may commit raw. Everything else still gates on hard_fail. After the stage-one detector fixes this path is rarely reachable, which is what a backstop is for.
func CheckOutbound ¶ added in v0.9.0
CheckOutbound is the CHECK-direction twin of ScrubOutbound: it reports the outbound-policy findings in one artefact and refuses, and it has no way to hand back rewritten text at all.
WHY A SECOND DIRECTION, when ScrubOutbound already exists. A scrub is right for text a ROUTINE is about to post: the routine owns that text, nobody has read it yet, and rewriting it is the remedy. A gate judges text a PERSON already wrote — a commit message in a pull request's range, a pull-request body — and rewriting that is not a remedy, it is an edit made on the author's behalf to something already in the history. So this direction returns no text. The absence of a string return is the guarantee: a caller cannot silently rewrite an author's commit message through this door, because the door has no such outlet.
WHY IT REPORTS ONLY THE HARNESS-LEAK CLASS, where the scrub masks everything it finds. Masking more than the policy names is free — the artefact still reads and the extra mask costs the routine nothing. REFUSING more than the policy names is not free: this runs as a required check over every commit message of every pull request, so each extra class is a new way for the gate to go red on text that breaks no stated rule (a commit message quoting a private address is the live example), and a gate that reds on the innocent is a gate somebody switches off. Committed text is judged for the other classes by `abcd lint`'s privacy rule and by the record/docs `harness_leak` rule; this door judges the two shapes a harness stamps onto public text, which is the class OutboundPolicy actually states.
The error is non-nil whenever the artefact is refused, findings or not, so a caller that reads only the error still fails closed.
func ScanText ¶
func ScanText(text string, id Identity, patterns []Pattern, id2sev map[string]Severity, file string) []Finding
ScanText scans text for every secret pattern and identity-derived match, returning findings sorted deterministically. It is pure: identity, patterns and severities are all passed in.
func ScrubOutbound ¶ added in v0.6.8
ScrubOutbound sanitises one outbound artefact and returns the text to post, the findings that were removed, and a fail-closed error if anything blocking survived.
It is the ScanText → Redact → residual-rescan shape the store-before-commit paths already use (history, memory), with one difference: an attribution FOOTER takes its whole line rather than being masked in place. Masking is right for a secret, where the surrounding text is the artefact's own content; a footer IS the whole line the harness added, and leaving a masked stub behind would post the shape of the thing the policy bans. A session URL is masked like any other span, because it can sit inside a sentence the artefact meant to say.
repoRoot supplies the per-repo scanner config, so a repository that raised a severity in .abcd/config/pii.json is honoured here exactly as in Stage-1 redaction.
func SurvivingCallerHome ¶ added in v0.6.9
SurvivingCallerHome is the deterministic backstop after SweepCallerHome, with no dependency on the pattern heuristic. It REWRITES what it can and reports what it cannot: a "/Users/<user>" / "/home/<user>" segment for the caller's local username (basename of $HOME) is rewritten to the local_username placeholder wherever the name does not go on — whatever punctuation follows it, and whatever precedes it, since "/Users/me" behind a abcd-audit:allow URL host or under a longer root is still the caller's name — and the $HOME literal standing as a path is reported (defensive: the sweep removes exactly those, so this fires only if the two ever disagree). A backstop that refused the write on a segment it could rewrite stopped every page that quoted the caller's own path; one that rewrites keeps the write and drops the name. Returned findings carry only the kind (masked Matched), enough for a refusal to report without exposing raw material.
func UnsealedAugmented ¶ added in v0.12.0
UnsealedAugmented returns, for every augmented finding among findings whose reported bytes still occur anywhere in redacted, a finding naming its kind and declared position with the bytes withheld. It is a write path's verification of what the augmenter found: the native re-scan (ScanTextNative) cannot see an augmented span, since a different detector found it, and re-running the augmenter over redacted text is neither cheap nor deterministic, so the bytes it reported are what is checked (GHSA-j7v5-q7x6-v3rp). Presence anywhere is the test because an augmenter reports every occurrence of a value it flags.
func (Finding) MarshalJSON ¶
MarshalJSON redacts the raw secret material before a Finding reaches any serialized surface — the dry-run/ship report that `abcd launch --json` writes to stdout and that CI may archive as a log or artefact. The finding's existence and location (file, line, column, kind, severity, suggested fix) are preserved intact; only the matched token and the line snippet that carries it are masked. Hard-fail counting keys off Severity and is unaffected, so a redacted finding still blocks a ship.
type Identity ¶
type Identity struct {
GitUserName string
GitUserEmail string
// OtherGitUserNames and OtherGitUserEmails are the caller's OTHER git
// identities: every user.name / user.email value git resolves for this
// repository in a scope the effective value displaced — the unconditional
// global identity under a repo-local persona, or the reverse, or an
// includeIf persona keyed on where the repository sits — the
// GIT_AUTHOR_*/GIT_COMMITTER_* persona the environment sets, which no
// config listing reports at all, and every author.*/committer.* value and
// `git -c` persona git commits with (iss-2609261614450166). A persona ADDS
// an identity to redact; it never replaces one (GHSA-v826-5jf4-p8xg,
// GHSA-gxhr-pmwv-r99p, GHSA-rvhr-3455-c5jw).
OtherGitUserNames []string
OtherGitUserEmails []string
// GitRemoteUsername is the owner of the GitHub remote. It arms the
// github_username rule, which spares it where it stands as the owner half of
// an owner/repo slug on the forge (isOwnerSlug).
GitRemoteUsername string
HomePath string
HomeUser string
}
Identity is the caller's runtime identity, probed from git config and the environment. Its matchers are built at scan time; empty fields disable the corresponding kind.
func ProbeIdentity ¶
ProbeIdentity gathers the caller's identity from git config and $HOME, best-effort: any probe that fails leaves its field empty. repoRoot scopes the git config reads so a per-repo user.name/email is honoured — and honoured in ADDITION to the caller's other identities, not instead of them: the name and email fields hold the value git resolves in this repository, and the Other* fields hold every value another scope configured that it displaced.
Every key is read in ONE git process (iss-2609281546130900): a scanner is built by every verb and hook that scans, and four processes per build were four reads of the same configuration. A second process runs only when the parent carries `git -c` configuration, for the reason given below.
type Option ¶ added in v0.12.0
type Option func(*Scanner)
Option configures New.
func WithAugmenter ¶ added in v0.12.0
WithAugmenter wires a to the scanner being built, in place of the default the composition root registered. A nil a means no augmenter at all.
type Pattern ¶
type Pattern struct {
Name string
Kind string
Label string
Re *regexp.Regexp
Severity Severity
Skip func(match string) bool // nil == no skip
// SkipAt is the context-aware form of Skip: it receives the whole line and
// the match's half-open byte span, so a pattern can reject a match by what
// SURROUNDS it — the thing RE2 cannot express and Skip cannot see. The
// network patterns need it to tell a host from a filename (".work.local/")
// and a quad from a longer dotted run ("1.2.3.4.5.6"). nil == no skip.
SkipAt func(line string, start, end int) bool
Suggestion string
}
Pattern is one compiled secret regex plus its metadata. Skip is the RE2 lookaround replacement: when non-nil it is called with the full match and, when it returns true, the match is discarded (mirrors the negative lookaheads the Python patterns used, which RE2 cannot express).
func DefaultPatterns ¶
func DefaultPatterns() []Pattern
DefaultPatterns returns the bundled secret pattern set (spec §2.2), ported verbatim from scripts/abcd/defaults/pii.json, plus the network-identifier set from network.go. Every secret pattern is non-sanitisable and hard_fail but one: the plain sk- rule warns, its shape being too generic to fail a gate on (it is still redacted wherever a finding is). This set is the built-in baseline the merged config layers on top of (the Go analogue of the bundled defaults/pii.json).
func HarnessLeakPatterns ¶ added in v0.6.8
func HarnessLeakPatterns() []Pattern
HarnessLeakPatterns returns the canonical harness-leak pattern set. It is exported so the surfaces that judge COMMITTED text — the audit privacy rule and the record/docs lint — can run exactly these two without a second copy, and it is folded into DefaultPatterns so every scanner consumer inherits them.
Both are hard_fail. A session URL is a live handle on a run, and a footer is a policy breach on the one surface (a public forge artefact) whose edit history keeps the pre-scrub revision — there is no reading under which either belongs in public text, so neither is advisory.
func NetworkPatterns ¶
func NetworkPatterns() []Pattern
NetworkPatterns returns the canonical network-identifier pattern set. It is exported so the audit privacy-hygiene rule can run exactly these patterns over committed files without duplicating them, and it is included in DefaultPatterns so every scanner consumer gets the same detection.
Severity: addresses (IPv4/IPv6/MAC) are hard_fail — the reserved ranges make a non-reserved address an authoring error with near-zero ambiguity. The two hostname patterns are shape heuristics rather than range checks, so they are warn: Stage-1 redaction rewrites them either way (Redact acts on every finding), and a repo that wants them blocking can raise the severity through .abcd/config/pii.json, which may raise but never lower a floor.
type ScanResult ¶
type ScanResult struct {
Findings []Finding `json:"findings"`
FilesScanned int `json:"files_scanned"`
HardFails int `json:"hard_fails"`
// Unscanned lists bundle files that were present but could NOT be covered:
// unreadable, over the byte-scan cap, a non-regular or symlinked leaf,
// classified binary by the content sniff (e.g. a leading-NUL file) WITHOUT
// a reviewed skip explaining it, or matched by an unreviewed skip alone (a
// skip fragment, or an extension or filename the repository's config adds),
// which would have read it with the byte rules only
// (iss-2610090821506490). They are the fail-closed coverage gap —
// the launch gate refuses on them, so a crafted binary cannot smuggle
// unscanned content into a source bundle (GHSA-5mmm-3whv-3rqp).
Unscanned []string `json:"unscanned,omitempty"`
// UnscannedWhy carries, per Unscanned path, the reason it could not be
// covered, so an asset over the cap is distinguishable from an I/O error.
UnscannedWhy map[string]string `json:"unscanned_why,omitempty"`
// ScannedBinary lists bundle files that matched the reviewed skip sets
// (abcd's bundled binary extensions and filenames) AND whose
// name is on the plaintext allow-list (plaintextNames): a skip-listed file
// known to carry no compressed region, so the byte scan covers all of it.
// The raw bytes run through the byte rules — every secret rule, the
// harness-leak rules, and the long-literal identity rules — with no
// format decoded. A skip exempts a file from the short/generic identity
// rules that are noise on bytes; it is never an unverified allow, because
// a file that enters the payload enters it with its bytes, whatever its
// name says (GHSA-9wv7-88w3-f77m).
ScannedBinary []string `json:"scanned_binary,omitempty"`
// ContentUnverified lists every other skip-listed bundle file — the
// DEFAULT for the byte branch, because a closed list of compressed
// formats would label whatever it missed as verified. An archive, but
// equally a PNG (deflate IDAT and zTXt), a JPEG entropy stream, a PDF
// FlateDecode stream, an mp4 box, a database blob, or a packed
// executable. They get the same byte scan as ScannedBinary (cheap, and it still catches
// plaintext such as an uncompressed tar's entries or PNG tEXt metadata),
// but a compressed region is invisible to it, so they are NOT counted as
// content-verified and the report says so rather than claiming coverage
// it does not have. It is what remains AFTER the decoder (container.go)
// has had its turn: the formats abcd cannot decode, the streams that
// would not inflate, and the ones a decode bound refused. Every entry
// carries its reason in ContentUnverifiedWhy and the format detected from
// its magic bytes in ContentFormat. They do not refuse on their own.
ContentUnverified []string `json:"content_unverified,omitempty"`
// ContentDecoded lists skip-listed bundle files whose container format the
// scanner DECODES (container.go): the archive was opened or the compressed
// regions inflated, under the decode bounds, and every decoded region was
// scanned with the same byte rules. A file reaches this list only when the
// walk could ACCOUNT for the whole of its content — a zip whose entries do
// not tile it, a tar with bytes after its end marker, a stream with a
// trailer, an entry the walk could not read, a region only part of which
// reads as text, a structural field carrying a container signature: each of
// those stays in ContentUnverified with the reason, because the claim this
// list makes is that the bytes were read, not that the parts that were read
// looked fine. The residuals the claim does NOT cover are written down at
// container.go's coverStructuralField. So "decoded and clean" and "could
// not be read" are two tiers and never one green (iss-2608291832160371).
// The rules applied are the byte rules, as everywhere on this branch: a
// text file inside an archive is scanned as bytes, not with the full
// prose-and-identity set it would get loose in the payload.
ContentDecoded []string `json:"content_decoded,omitempty"`
// ContentUnverifiedWhy carries, per ContentUnverified path, why the content
// could not be read: no decoder for the detected format, an unrecognised
// format, a stream that would not inflate, an entry that is itself opaque,
// or one of the decode bounds (output budget, nesting depth, entry count)
// refusing a bomb.
ContentUnverifiedWhy map[string]string `json:"content_unverified_why,omitempty"`
// ContentFormat carries, per byte-branch path, the format detected from the
// file's MAGIC BYTES — never its extension, so a zip renamed .png reports
// "zip" and is decoded as one, which the record names as the defect in the
// old name-keyed label.
ContentFormat map[string]string `json:"content_format,omitempty"`
// Excluded lists bundle files an exclusion in the scanner config matched
// (Config.ExcludePathFragments): excluded by choice, with the reason the
// config gives in ExcludedWhy. They are not read, never counted as
// scanned and never a coverage gap, so they do not refuse on their own;
// a bundle they leave with no file scanned in full still trips the
// zero-coverage sentinel.
Excluded []string `json:"excluded,omitempty"`
ExcludedWhy map[string]string `json:"excluded_why,omitempty"`
// UnmatchedExclusions names, in config order, every declared exclusion
// fragment that matched no bundle file. Such a fragment leaves nothing
// out, so a typo'd one would read as working while the files it was meant
// for are scanned; launch warns on each (iss-2610120929469571).
UnmatchedExclusions []string `json:"unmatched_exclusions,omitempty"`
// FindingsOmitted counts the findings dropped past maxBundleFindings. They
// are counted in HardFails all the same, so a truncated list never reads
// as a smaller verdict.
FindingsOmitted int `json:"findings_omitted,omitempty"`
}
ScanResult is the outcome of scanning a bundle.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner holds the merged config, compiled patterns and probed identity for a repo. Construct it with New.
func New ¶
New builds a Scanner for repoRoot: it starts from the built-in secret set and identity floors, merges the per-repo .abcd/config/pii.json override when present (enforcing the severity floor), and probes identity. If the per-repo config exists but cannot be read or parsed, the scanner is marked unavailable (fail-closed): New still returns a usable value with no error, and ScanBundle surfaces Unavailable=true.
An augmenter (augment.go) is wired last: the one a WithAugmenter option names, or else the default the composition root registered, which reads the repository's own opt-in. Its findings are appended to ScanText's and ScanBundle's.
func NewContext ¶ added in v0.17.0
NewContext is New with the identity probe's git calls bound to ctx, for a hook that builds a scanner on its deadline. A ctx that ends before the probe has read the caller's identity leaves the identity floors without it, so the scanner is marked unavailable (fail-closed) rather than scanning as though the caller had no identity to redact.
func (*Scanner) Augmented ¶ added in v0.17.0
Augmented reports whether an augmenter runs inside ScanText. An augmenter reads the whole text it is handed and may match across lines, so a caller that would scan a text in parts asks this first: with an augmenter, a part boundary could hide a match that the whole text shows.
func (*Scanner) AugmenterGap ¶ added in v0.12.0
AugmenterGap is the reason the repository's configured augmenter could not run because its tool is not installed, or "" when there is no such gap (no augmenter configured, or one that runs). A write path records it in its receipt; launch fails closed on it through ScanBundle.
func (*Scanner) Fingerprint ¶ added in v0.17.0
Fingerprint is a digest of everything this scanner was built from that decides what ScanText finds: the pattern set (bundled and per-repository), the identity it redacts and the identity severities, the skip and exclusion sets, the degraded state, and whether an augmenter runs and the gap one left. Two scanners with the same fingerprint, in one binary, find the same spans in the same text.
It exists for a caller that keeps work done with one scanner and reuses it under another (the history store's redaction parts): a kept result is trusted only while the fingerprint is unchanged. A pattern's Skip and SkipAt functions are code, so only their presence is in the digest; the code itself changes with the binary, which a caller that keeps results across binaries fingerprints itself. The digest is a one-way hash, so the identity values in it are not recoverable from it.
func (*Scanner) NetworkPatterns ¶
NetworkPatterns returns the network-identifier subset of THIS scanner's merged patterns — the built-in set with the repo's .abcd/config/pii.json override applied. A consumer that wants only the network half (the audit privacy-hygiene rule) must come through here rather than through the package-level set, or a repo that raises a pattern's severity, exactly as the set documents it may, sees no effect at the surface that reports it.
func (*Scanner) ScanAugmented ¶ added in v0.12.0
ScanAugmented runs the augmenter alone over text and returns its findings, sanitised and located, or nil when no augmenter runs. It is for a reader whose own detection is not ScanText's (the privacy lint) and that reports what the repository's augmenter found beside it; a failed run degrades the scanner exactly as it does inside ScanText.
func (*Scanner) ScanBundle ¶
func (s *Scanner) ScanBundle(files []BundleFile) (ScanResult, error)
ScanBundle scans the resolved content of every bundle file, reading ResolvedPath and reporting under LogicalPath. A file a declared exclusion matches is not read and is reported under Excluded with its reason. A file on the reviewed skip sets (abcd's bundled extensions and filenames) is read through the guarded, capped primitive and its bytes scanned with the byte rules (scanBytes), reported under ScannedBinary (a plaintext allow-listed name), ContentDecoded or ContentUnverified. A file an unreviewed skip alone matches (a skip fragment, or an extension or filename the repository's config adds) is Unscanned, with the entry named as its reason; any other file is scanned with the full rule set when it is text throughout (no NUL, valid UTF-8 — every byte, not a sniff), or surfaced in Unscanned (with UnscannedWhy) when it is not. If the scanner is unavailable (config unreadable), it returns Unavailable=true and scans nothing (fail-closed).
func (*Scanner) ScanText ¶
ScanText scans an in-memory string with THIS scanner's merged patterns, probed identity, and per-repo severity floors — the same detection ScanBundle runs on a file's content, but with no filesystem read. It is the entry point a write-time redactor (the history store) uses to find every secret/PII span in a transcript before it lands on disk. logicalName is the label stamped into each finding's File field.
It intentionally exposes the merged config that the package-level ScanText cannot: a caller using the package-level function would bypass the .abcd/config/pii.json override that New folded in.
When an augmenter is wired (augment.go), its findings are appended, deduplicated on file, line and span; a caller that wired one consults Unavailable after the call, since a failed augmenter run degrades the scanner.
func (*Scanner) ScanTextNative ¶ added in v0.12.0
ScanTextNative is ScanText without the augmenter: the verification re-scan a write path runs over its own redacted text, beside UnsealedAugmented, which checks what the augmenter found by its bytes.
func (*Scanner) Unavailable ¶
Unavailable reports whether the scanner is in the fail-closed degraded state (the per-repo config exists but is unreadable, invalid JSON, carries a bad override regex, or carries a secret pattern the glued-token sweep cannot build) and, if so, a human reason. A write-time redactor MUST consult this before trusting ScanText/Redact: unlike ScanBundle, those entry points cannot signal degradation in-band, so a caller that skips this check would sanitise with a silently weakened pattern set. Mirrors ScanBundle's guard.
An augmenter that fails a run, or hands back a report the scanner cannot place, degrades the scanner from that call on, so a caller that wired one consults this after ScanText as well as before.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package augmenttest is the test double for the scanner's Augmenter seam (iss-2608291814575788): a fake augmenter that flags one fixed value the native pattern set does not see, a not-found augmenter, and Install, which registers either as the default every scanner.New picks up.
|
Package augmenttest is the test double for the scanner's Augmenter seam (iss-2608291814575788): a fake augmenter that flags one fixed value the native pattern set does not see, a not-found augmenter, and Install, which registers either as the default every scanner.New picks up. |