Documentation
¶
Overview ¶
Package redact implements PII detection and bidirectional substitution (real value <-> token) over arbitrary text, backed by a tokenstore.Store.
Detection is deliberately regex-only (RE2 via Go's stdlib regexp, which cannot backtrack: safe to run against untrusted scan output or page content with no ReDoS risk). This trades recall for predictability and zero false-positive risk on report prose: names, codenames, and other unpatterned PII are out of scope for v1. The Detector interface exists so a future LLM-backed or additional rule-based detector can be added later without touching the substitution engine.
The detection strategy here (a loose regex to find candidates, then a precise check (TLD allowlist, a real IP parser, a reserved-range check) to accept or reject each one) separates "does this look like the shape" from "is this actually valid", which matters because RE2 has no lookaround: anywhere a lookahead/lookbehind assertion would normally narrow the candidate regex itself, the equivalent here is a post-match Go check instead.
A curated TLD list (gTLDs + ccTLDs).
Used as a validation gate on top of golang.org/x/net/publicsuffix, not as the primary domain splitter: the public suffix spec deliberately treats any UNRECOGNIZED final label as an implicit valid suffix -- EffectiveTLDPlusOne("console.log") succeeds with suffix "log", icann=false, no error -- indistinguishable by return value alone from a real listed private suffix like "github.io". PSL still does the actual splitting (needed for correct multi-label suffixes like "co.uk" and "github.io"); this list only vetoes candidates whose suffix's last label isn't a real, deployed TLD, closing the "console.log", "scan_results_1.5.txt" class of false positive that PSL alone lets through.
Index ¶
- Constants
- func BuiltinAllowPatterns(disabled map[string]bool) []*regexp.Regexp
- func DomainRegistrablePart(value string) (registrable string, isBare bool, ok bool)
- func LooksLikeHostname(value string) bool
- type CategorizedDetector
- type CategoryInfo
- type Detection
- type Detector
- type Engine
- func (e *Engine) Detokenize(text string) string
- func (e *Engine) SafeFlushPoint(buf []byte) int
- func (e *Engine) SetAllowPatterns(patterns []*regexp.Regexp)
- func (e *Engine) SetDebugLogger(l *debuglog.Logger)
- func (e *Engine) SetDetectors(detectors []Detector)
- func (e *Engine) Tokenize(text string) (string, error)
Constants ¶
const ( SubcategoryWellKnownPlatforms = "wellknown_platforms" SubcategorySecurityTestingServices = "security_testing_services" SubcategoryWebInfrastructure = "web_infrastructure" SubcategoryThirdPartySaaS = "third_party_saas" )
const CategoryAllowlist = "allowlist"
CategoryAllowlist is the pseudo-detector category for this file's two built-in, curated domain allowlists. "Pseudo" because, unlike every entry in DefaultCategorizedDetectors, these aren't detectors that FIND PII; they're exceptions that stop the domain/email detectors from flagging known-safe public infrastructure. They still need a Category/Subcategory identity for the exact same reason every real detector has one: so an operator can disable them via `redactproxy rules disable` (persisted, see rules.Config.Categories) or the ephemeral -disable flag, for the rare engagement where overriding the default judgment call is correct (see BuiltinAllowPatterns' doc comment). Kept as its own top-level category (not folded into "network.domain") specifically so `rules show`'s category listing doesn't present a curated judgment call as if it carries the same certainty as an RFC-backed detector.
Variables ¶
This section is empty.
Functions ¶
func BuiltinAllowPatterns ¶
BuiltinAllowPatterns returns the compiled allow-patterns for every CategoryAllowlist subcategory NOT present in disabled; merge this into an Engine's allow-patterns (alongside rules.json's own Allow entries, via SetAllowPatterns) so the exclusion applies by default but remains fully within the SAME override mechanism every other detection category already has.
To force tokenization of one specific value that's in this allowlist (e.g. a single engagement where "pastebin.com" itself needs to be treated as sensitive), `rules block pastebin.com` does NOT work: Engine.filterAllowed drops a Detection based on its matched value alone, regardless of which Detector produced it, so an allow-pattern match vetoes a block-list match for the same value just as completely as it vetoes a built-in detector's. Allow always wins over block, with no exception for "this allow entry is built-in" vs. "this allow entry came from rules.json", the same precedence rule behind the plain block+allow-of-the-same-value confusion this was found alongside. The correct override here is `redactproxy rules disable allowlist.wellknown_platforms` (or `allowlist.security_testing_services`, or the bare `allowlist` category for both, persisted; the ephemeral `-disable` flag on `redactproxy` itself works the same way for a one-off run). That's a real category/subcategory toggle, not a per-value one; there is currently no way to force tokenization of a single built-in-allowlisted domain while leaving the rest of its category exempt.
func DomainRegistrablePart ¶
DomainRegistrablePart reports the registrable (base) domain this tool's own domain detector would recognize within value, and whether value IS exactly that bare registrable domain (no subdomain, no "www." prefix). ok is false when value isn't a syntactically clean, standalone hostname at all -- a URL, an email address, an arbitrary string like a company name, or an RFC-reserved example domain (see isReservedDomain) all report ok == false, never a wrong answer.
Exported for internal/rules and the CLI: a rules.json block entry an operator has explicitly marked as a domain (see rules.Entry.IsDomain) needs this to find its actual registrable part for forced domain-token treatment (DefaultCategorizedDetectorsWithForcedDomains), and to warn when what they marked isn't the bare form.
func LooksLikeHostname ¶
LooksLikeHostname reports whether value is syntactically a standalone hostname: dot-separated labels, nothing else (no scheme, no "@", no path), using the exact same grammar domainLabelUnicodeRe itself requires to ever match this text in real prose in the first place. Deliberately does NOT require the final label to be a recognized public suffix: an internal-only name (an Active Directory forest like "corp.internal", a purely-internal naming scheme) is never going to be on a public suffix list, but an operator who explicitly marks it IsDomain in rules.json is the actual authority on their own engagement's naming. See rules.Compiled.ForcedDomains and forcedDomainSuffix, the fallback path in domainDetector.Detect that this authorizes.
Types ¶
type CategorizedDetector ¶
CategorizedDetector pairs a Detector with the stable identifiers used to select it for selective enable/disable (see FilterDetectors) and in any reporting/config surface built on top of this package: "category.subcategory" (e.g. "cloud.aws") is the on-the-wire name. Description is a one-line, human-readable summary of what this detector catches, the single source of truth rules.Config's self-documenting "categories" section (see rules.EnsureAllCategories) pulls from, so a saved rules.json never has to duplicate or drift from this text.
Once assigned, treat a Category/Subcategory rename as a breaking change: anything outside this package (a saved config file, a CLI flag someone scripted) may already refer to it by name.
func DefaultCategorizedDetectors ¶
func DefaultCategorizedDetectors() []CategorizedDetector
DefaultCategorizedDetectors returns the standard regex-based detector set with category metadata attached. This is the source of truth; DefaultDetectors and FilterDetectors are both built from it.
func DefaultCategorizedDetectorsWithForcedDomains ¶
func DefaultCategorizedDetectorsWithForcedDomains(forceAsDomain map[string]bool) []CategorizedDetector
DefaultCategorizedDetectorsWithForcedDomains is DefaultCategorizedDetectors, except the domain detector treats every registrable domain in forceAsDomain as a real domain even where it would otherwise be skipped as a likely filename mention (see filenameCollisionTLDs/ looksLikeBareFilename in detector.go). forceAsDomain is meant to be populated from an engagement's own rules.json block entries that are exactly a bare registrable domain (see rules.Compiled.ForcedDomains, DomainRegistrablePart), so an operator's own client domain gets the same structure-preserving domain token everywhere it appears (bare, with a subdomain, in an email, in a URL), not just an opaque block-list token for the one literal form they typed in. A nil or empty map behaves identically to DefaultCategorizedDetectors.
func (CategorizedDetector) Name ¶
func (c CategorizedDetector) Name() string
Name returns the "category.subcategory" identifier for this detector.
type CategoryInfo ¶
type CategoryInfo struct {
Category string
Subcategory string
Description string
// Warning is non-empty only for categories where disabling has a
// counter-intuitive direction or effect worth calling out explicitly,
// currently just the allowlist.* exceptions, where "disable"
// means MORE gets redacted, not less.
Warning string
}
CategoryInfo describes one category/subcategory for a config-editing surface (rules.Config's self-documenting "categories" section), deliberately not CategorizedDetector itself, since not every category this package exposes is backed by a Detector (the allowlist.* pseudo-categories in wellknown.go are exceptions, not detectors; see CategoryAllowlist's doc comment). Name returns the same "category.subcategory" (or bare "category" if Subcategory is empty) identifier CategorizedDetector.Name does.
func AllCategoryInfo ¶
func AllCategoryInfo() []CategoryInfo
AllCategoryInfo returns every category/subcategory this package exposes for a config-editing surface to enumerate: every built-in detector (from DefaultCategorizedDetectors) plus the two allowlist.* exceptions (from wellknown.go), which aren't detectors but need the same enable/disable identity for the same reason (see CategoryAllowlist's doc comment). This is the single source rules.Config.EnsureAllCategories reconciles a saved rules.json against. New entries here show up in existing files automatically the next time they're loaded, and anything removed here is pruned the same way.
func (CategoryInfo) Name ¶
func (c CategoryInfo) Name() string
type Detection ¶
type Detection struct {
Start, End int
Lookups []lookup
// Format combines the resolved tokens (same order as Lookups) into
// the final replacement text. nil means "exactly one lookup, use its
// token directly", the common case for IPs, phone numbers, and a
// domain with no subdomain structure to reconstruct.
Format func(tokens []string) string
// PreserveIfUnknown marks a detection whose match is more likely a
// coincidentally domain-shaped word than a real second domain
// reference: e.g. "login.com" as a bare URL PATH segment
// ("/xyz/login.com"), as opposed to a host ("https://login.com") or a
// query-parameter value ("?to=login.com/phish", a plausible redirect
// target). Tokenizing it unconditionally would destroy a semantic cue
// Claude may need (this is a login page) for no privacy benefit in
// the common case where it isn't really a second domain at all. When
// true, the engine only tokenizes this match if its registrable
// domain is ALREADY a known real value in the store (established via
// some other, non-path-segment mention, in this call or a prior one);
// otherwise it's left as literal text. See domainDetector.Detect
// for how the position is classified.
PreserveIfUnknown bool
}
Detection is a single real-value match found in text, in byte offsets into that exact text, plus the token lookup(s) needed to redact it and (optionally) how to combine their results into the final replacement.
type Detector ¶
Detector finds real-value PII in text for the tokenize (real -> token) direction. Implementations must never match text that already looks like one of this tool's own tokens (see the per-detector exclusion checks below); otherwise tokenizing already-tokenized text would mint garbage entries and break idempotency.
Detect returns an error for detectors that can genuinely fail (e.g. a future LLM-backed detector hitting a timeout or rate limit); the regex detectors below never do. A detector error propagates out of Engine.Tokenize and fails the whole call closed: a detector that couldn't check its share of the text must never be treated as "found nothing," since that would silently let real PII through undetected.
func DefaultDetectors ¶
func DefaultDetectors() []Detector
DefaultDetectors returns the standard regex-based detector set, order preserved from DefaultCategorizedDetectors (the source of truth; see categories.go). Order does not encode priority; the engine resolves overlaps by match position and length, not by detector order.
func FilterDetectors ¶
func FilterDetectors(all []CategorizedDetector, disabled map[string]bool) []Detector
FilterDetectors returns the Detector for every entry in all whose Category or "Category.Subcategory" is NOT in disabled: disabling a bare category (e.g. "cloud") drops every subcategory under it; disabling "cloud.aws" drops only that one. Order is preserved from all.
func NewBlockDetector ¶
NewBlockDetector builds a Detector from user-supplied patterns: the exact-string or regex "always redact this" entries a config file or the setup wizard produces (see the internal/rules package). Every pattern here is a *regexp.Regexp compiled through Go's standard regexp package: same RE2 engine as every built-in detector, so a user-authored pattern is exactly as immune to ReDoS as any pattern in this codebase, and that guarantee doesn't get weaker just because the pattern text came from a config file instead of source code.
Each match is fully opaque (EntityCustomBlock); there's no structure worth preserving since the value could be anything a real engagement needs redacted that no built-in detector covers (a customer name variant, an internal project codename, ...).
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine performs bidirectional substitution over text using a set of pluggable Detectors (for the tokenize/real->token direction) and a fixed set of token-namespace patterns (for the detokenize/token->real direction, which needs no pluggability, since the token formats are this tool's own implementation detail, not user-configurable PII shapes).
The active detector set and allow-list are held behind atomic.Pointer, not a plain field, so SetDetectors/SetAllowPatterns can be called concurrently with in-flight Tokenize calls: a live rule reload (no process restart) swaps them for calls that start afterward, without touching a call already in progress or requiring a lock on the hot path.
func New ¶
func New(store *tokenstore.Store, detectors ...Detector) *Engine
New builds an Engine over store using the given detectors. Pass DefaultDetectors() for the standard regex set.
Allow-patterns default to BuiltinAllowPatterns(nil), the curated well-known-platform/security-testing-service exclusions active with nothing disabled, rather than empty, so a bare New(store, DefaultDetectors()...) keeps the same default protective behavior DefaultDetectors() implies without a caller also having to know to wire in BuiltinAllowPatterns separately. cmd/redactproxy's effectiveAllowPatterns still calls SetAllowPatterns explicitly once rules.json is loaded, since only then is the real Disabled set known, so this default is what's active in between (and for anything constructing an Engine directly, e.g. tests, without going through that wiring at all).
func (*Engine) Detokenize ¶
Detokenize replaces every recognized token in text with its real value. It fails open by design: a token that isn't found in the store (should never happen in practice, since every token was minted by this same store) is left as literal text rather than erroring. That's the safe direction to fail: worst case is a broken command Claude Code runs against a fake hostname, which is visibly wrong to the operator, not a silent PII leak.
func (*Engine) SafeFlushPoint ¶
SafeFlushPoint returns the largest N <= len(buf) such that buf[:N] can be safely detokenized and emitted right now during streaming, without risking cutting a credential that hasn't finished arriving yet. See tokenstore.spanTrie's doc comment for the underlying mechanism and why it's exact rather than an approximation: every span this could ever need to hold back was registered by this same Engine's Tokenize call before the request that could produce this response was ever sent, so there's nothing here Claude could echo that isn't already a known, exact, complete string.
func (*Engine) SetAllowPatterns ¶
SetAllowPatterns atomically replaces the allow-list: any Detection with at least one Lookup whose Real value matches one of these patterns is dropped entirely before substitution (see Tokenize's filterAllowed step), left as literal text even though a detector matched it. Whole-detection, not per-lookup: allow-listing a domain also leaves an email at that domain untouched, local part included, rather than trying to partially redact a Detection whose Format function expects every one of its Lookups to have resolved to a real token.
Also bumps the cache generation and clears the tokenize cache, for the identical reason SetDetectors does; see its doc comment.
func (*Engine) SetDebugLogger ¶
SetDebugLogger sets (or replaces) the optional debug sink; see package debuglog. A nil logger (the default) disables debug logging entirely, at effectively zero cost per call (Enabled short-circuits on a nil *Logger).
func (*Engine) SetDetectors ¶
SetDetectors atomically replaces the active detector set. Safe to call while Tokenize calls are in flight: each call reads the detector set once at the start, so this only affects calls that start afterward.
Also bumps the cache generation and clears the tokenize cache (see tokenize_cache.go): a cached (text -> output) entry was computed under the PREVIOUS detector set, and text that hasn't changed a single byte can still need a different result once a category is enabled/disabled. Serving a stale cached answer here would silently ignore a live rule-reload for any text already seen before the change, exactly the kind of under-redaction risk this tool exists to prevent. The generation bump is what actually guarantees this (see tokenizeCache.get's doc comment for why clear() alone has a race); clear() is kept alongside it purely to free the now-permanently-stale entries' memory promptly rather than waiting for LRU eviction to get around to them.
func (*Engine) Tokenize ¶
Tokenize replaces every detected real value in text with its token, minting new tokens for values seen for the first time. It fails closed: if any detector errors, or if the token store fails to mint/persist a token for any detected value, Tokenize returns an error and the (possibly partially built) string is discarded, and callers must never forward text after a Tokenize error, since that could mean real PII reaching the model un-redacted.
Checks the tokenize cache first (see tokenize_cache.go): Claude Code resends the full conversation history on every API call, so the same message/tool-result text (the system prompt and CLAUDE.md note above all, which repeat on literally every single request) gets rescanned by every detector on every turn without this. A cache hit skips collectDetections/filterAllowed/resolveOverlaps and the mint loop below entirely, including their debug-log calls: re-logging the exact same NewValue/Replacement events every time identical text is resent would be noise, not signal, so a cache hit is deliberately silent; the first call already logged the real detail.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Command redacttest is a read-only manual-testing harness: it does not modify any redaction logic.
|
Command redacttest is a read-only manual-testing harness: it does not modify any redaction logic. |