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 ¶
- func DefaultIdentitySeverities() map[string]Severity
- func IsIdentityKind(kind string) bool
- func IsNonUserHomeSegment(seg string) bool
- func Redact(text string, findings []Finding) (string, int)
- type BundleFile
- type Config
- type Finding
- type Identity
- type Pattern
- type ScanResult
- type Scanner
- type Severity
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 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 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 and the same per-line strings.ReplaceAll approach as Finding.MarshalJSON).
Secret tokens are masked to a non-reversible fingerprint by AUTHORITATIVE BYTE SPAN (reusing sealLine), and 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 placeholders keep the substring rewrite (they are length-changing) and run AFTER the secrets are sealed, when no raw secret bytes remain to be shifted. Redact is only stage one; the caller MUST re-scan the result and fail closed if any hard_fail span survived.
Types ¶
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"`
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 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 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 (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
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.
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 hard_fail and non-sanitisable. This set is the built-in baseline the merged config layers on top of (the Go analogue of the bundled defaults/pii.json).
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, or classified binary/unscannable by the content sniff (e.g. a
// leading-NUL file) WITHOUT a reviewed skip explaining it. 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"`
// Skipped lists bundle files intentionally not scanned because they matched
// the reviewed skip sets (a binary media extension, a skip filename, or a
// skip fragment). Unlike Unscanned they are an accepted allow, not a refusal
// — but they are surfaced rather than silently dropped, so what the skip
// list actually excluded is visible.
Skipped []string `json:"skipped,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.
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) ScanBundle ¶
func (s *Scanner) ScanBundle(files []BundleFile) (ScanResult, error)
ScanBundle scans the resolved content of every bundle file, reading ResolvedPath and reporting under LogicalPath. Binary/oversized/skip-listed files are skipped via the extension/filename sets and a null-byte + UTF-8 sniff. 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.
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, or carries a bad override regex) 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.