Skip to main content

Crate redact_secret

Crate redact_secret 

Source
Expand description

Deterministic secret detection and redaction core.

This crate is the canonical implementation that every language binding translates to (decision-adopt-rust-core-monorepo). It uses std but is side-effect free by policy:

  • no runtime network access,
  • no filesystem access,
  • no process-environment lookup,
  • no telemetry or logging sinks,
  • no secret storage,
  • no user interface.

The crate-level lints below make the policy visible at compile time, and scripts/check-rust-workspace.py rejects dependencies that would breach it. Ranges reported by this crate use UTF-8 byte offsets; each binding converts them to its documented native unit (decision-define-runtime-bindings).

§Pipeline contract

run_detector_pipeline runs every detector in a DetectorRegistry in registration order, validates each Candidate, resolves overlapping candidates with the documented precedence (resolved-action severity, specificity, confidence, narrower span, registration order, emission order), and numbers the disjoint survivors by input offset. scan then evaluates a Policy once per finding. Identical input and configuration always produce identical findings and ids.

Every failure is a SecretScanError with a fixed code and message and no payload; no public value carries an input fragment or a matched value.

redact then applies Finding actions to the input in one ordered pass, replacing redact/block ranges with placeholders from a PlaceholderFormatter and validating that formatter’s output. scan_and_redact runs both and returns a ScanResult.

scan, redact, and scan_and_redact apply a default WholeInputLimits before doing any work — DEFAULT_MAX_INPUT_BYTES and DEFAULT_MAX_FINDINGS — and fail with SecretScanErrorCode::InputLimitExceeded or SecretScanErrorCode::FindingLimitExceeded rather than truncating. scan_with_limits, redact_with_limits, and scan_and_redact_with_limits accept an explicit WholeInputLimits instead (decision-bound-whole-input-operations-by-default).

§Public surface

ConcernAPI
Scanscan, scan_with_limits, run_detector_pipeline
Redactredact, redact_with_limits, MAX_PLACEHOLDER_LENGTH
Scan and redactscan_and_redact, scan_and_redact_with_limits
Golden pathsanitize, sanitize_with_profile
Whole-input limitsWholeInputLimits, DEFAULT_MAX_INPUT_BYTES, DEFAULT_MAX_FINDINGS
IncrementalIncrementalSanitizer, IncrementalLimits, SessionState, IncrementalPolicy, IncrementalPolicyContext
PolicyPolicy, PolicyContext, DefaultPolicy, Action
FormatterPlaceholderFormatter, PlaceholderContext, default_placeholder_formatter, typed_placeholder_formatter
FindingFinding, DetectedFinding, ByteRange, Confidence, Specificity, Obfuscation
ResultScanResult, IncrementalResult
Sanitized errorSecretScanError, SecretScanErrorCode, DetectorFailure, PolicyFailure, FormatterFailure
Custom detectorsDetector, Candidate, DetectorContext, DetectorRegistry, RegisteredDetector
Thread-shareable built-in registryBuiltInRegistry
Declarative rulesetsload_ruleset, RulesetError, RulesetErrorClass
Declarative action policyload_action_policy, ActionPolicy, ActionPolicyError, ActionPolicyErrorClass, MAX_ACTION_POLICY_BYTES
Explain and compare action policiescompare_action_policies, compare_action_policies_with_limits, ComparedPolicy, ActionComparison, ComparedFinding, ActionDecision, DecisionBasis, ComparedSide, PolicyBinding, ActionCounts, DetectionIdentity, MAX_COMPARED_POLICIES
Compare detection configurationscompare_configurations, ConfigurationSide, ConfigurationComparison, ConfigurationResult, ConfigurationDifferences, ConfigurationDifference, DifferenceKind, Correspondence, SideStatus
Profiles and PII activationProfile, PiiSelection
Artifact manifestArtifactManifest, ArtifactKind, ArtifactManifestError
Static custom compositioncomposition
Detector selectionDetectionSelection, DetectionConfigError
Effective configurationresolve_config, describe_config, ConfigRequest, ConfigResolution, ConfigSnapshot, ConfigDiagnostic, ConfigSeverity, SampleRuleHits
Identifiers and unitsis_identifier, MAX_IDENTIFIER_LENGTH, RANGE_UNIT, VERSION
Detector building blocksshannon_entropy

That table is the whole surface — it lists every name this crate root exports, and [workspace.metadata.redact-secret] core-public-api in the workspace manifest repeats it so a name cannot join or leave without a reviewed manifest change. Everything else is private. In particular, the built-in detector set of each profile is reached only through DetectorRegistry::with_built_in (full) and DetectorRegistry::with_common_built_in (common), and the retention tuning the incremental session depends on is derived through IncrementalLimits::minimum_buffered_bytes rather than exposed as a constant, so both can change without breaking a caller. decision-define-detector-profile-and-pack-contract fixes which built-in detectors each Profile holds and its compatibility class.

§Examples

The minimal path redacts with the supported defaults (full profile, DefaultPolicy, default_placeholder_formatter, default WholeInputLimits) in one call:

let result = redact_secret::sanitize("API_KEY=ghp_SYNTHETICREVOKED00000000000000000000")?;
assert_eq!(result.text(), "API_KEY=<SECRET_1>");

Custom detectors, PII activation, a custom policy or formatter, explicit limits, and registry reuse use the advanced path, scan_and_redact:

use redact_secret::{
    DefaultPolicy, DetectorRegistry, default_placeholder_formatter, scan_and_redact,
};

let registry = DetectorRegistry::with_built_in([])?;
let input = "API_KEY=ghp_SYNTHETICREVOKED00000000000000000000\nplain text";

let result = scan_and_redact(input, &registry, &DefaultPolicy, &default_placeholder_formatter)?;

assert_eq!(result.text(), "API_KEY=<SECRET_1>\nplain text");
// Ranges index the original input, in UTF-8 bytes.
let range = result.findings()[0].range();
assert_eq!(&input[range.start()..range.end()], "ghp_SYNTHETICREVOKED00000000000000000000");

§Incremental sanitization contract

IncrementalSanitizer runs the same built-in detectors, default policy, and redaction over text supplied in chunks. It is a bounded, four-state session (accepting, finalized, aborted, failed) that emits only text whose detection window is closed, never rescans finalized input, and accepts input independently of how a caller partitions it into chunks. See the module documentation for the full contract.

The Rust core and the top-level conformance corpus are the canonical source of behavior. Bindings translate host values and range units without reimplementing detection (decision-govern-cross-language-conformance).

Modules§

composition
Static custom composition (issue #1253, decision-define-the-configuration-capability-ceiling-runtime-ownership-and-surface-support).

Structs§

ActionComparison
The result of compare_action_policies.
ActionCounts
How many findings a policy assigned to each action.
ActionDecision
One policy’s decision for one finding.
ActionPolicy
A parsed, validated, immutable action policy.
ActionPolicyError
A rejected action policy document, returned by load_action_policy.
ArtifactManifest
What one artifact contains and supports, generated from its real composition (artifact-manifest/v1).
BuiltInRegistry
A built-in-only detector registry that is Send + Sync, so one value can be shared by reference or through an Arc across threads (issue #1178).
ByteRange
A non-empty half-open range [start, end) of UTF-8 byte offsets.
Candidate
A detector’s private proposal: classification and range only.
ComparedFinding
One finalized finding and every compared policy’s decision for it.
ComparedSide
One compared policy: its revision binding and its action totals.
ConfigDiagnostic
One safe finding about a configuration input (config-diagnostics/v1).
ConfigRequest
What to resolve: explicit runtime input over the artifact’s defaults.
ConfigResolution
The result of resolve_config (config-resolution/v1): the snapshot when the input is valid, and every safe diagnostic either way.
ConfigSnapshot
The resolved, effective configuration (config-snapshot/v1): immutable data. It is not a handle and cannot scan.
ConfigurationComparison
The result of compare_configurations.
ConfigurationDifference
One difference between the base side and another.
ConfigurationDifferences
The differences of one side against the base side, on this input only.
ConfigurationResult
One side of a ConfigurationComparison.
ConfigurationSide
One configuration taking part in a comparison: a registry (or the reason it could not be built), the policy evaluated over its findings, its limits and the identity digests of the configuration it was built from.
DefaultPolicy
The default Policy: deterministic, infallible, and independent of PolicyContext.
DetectedFinding
A finding after overlap resolution and before policy evaluation.
DetectionConfigError
Why a detector selection was rejected: a fixed class and, for a problem in one id, that id’s zero-based position in its array.
DetectionIdentity
The detection configuration the single pass ran under, identified apart from every policy.
DetectionSelection
Which of an artifact’s included built-in detectors are enabled (detection of runtime-config/v1).
DetectorContext
Read-only information a detector receives alongside the input.
DetectorFailure
Opaque failure reported by a Detector.
DetectorRegistry
An ordered, duplicate-free set of detectors.
Finding
The public, immutable result of scanning: safe metadata plus the action.
FormatterFailure
Opaque failure reported by a PlaceholderFormatter.
IncrementalLimits
Explicit, positive byte limits every incremental session requires. There are no environment-derived or silent defaults.
IncrementalPolicyContext
Position information an incremental policy receives.
IncrementalSanitizer
A bounded, side-effect-free incremental sanitizer session over built-in detectors. Custom detectors are not accepted: each has no retention declaration, so the session cannot bound what it must hold open.
PiiSelection
A canonical, closed PII selector set for the loaded artifact.
PlaceholderContext
Position information a placeholder formatter receives.
PolicyContext
Position information a whole-input policy receives.
PolicyFailure
Opaque failure reported by a Policy.
RegisteredDetector
A detector together with the id captured at registration time.
RulesetError
A rejected ruleset, returned by load_ruleset.
SampleRuleHits
How often each rule of one policy was the deciding rule across a set of sample findings.
ScanResult
Sanitized text paired with the findings that produced it.
SecretScanError
A sanitized scan error. It holds nothing but its code.
WholeInputLimits
Explicit byte and finding-count bounds a whole-input operation checks before doing detection work.

Enums§

Action
The enforcement decision a policy attaches to a finding.
ActionPolicyErrorClass
The fixed rejection class of a rejected action policy document.
ArtifactKind
The kind of artifact a manifest describes: the build target class.
ArtifactManifestError
Why a manifest could not be generated or did not match its artifact.
ComparedPolicy
One policy taking part in a comparison.
Confidence
How strongly a detector believes a candidate is a credential.
ConfigSeverity
How serious a ConfigDiagnostic is.
Correspondence
How sure the pairing of an entry’s findings is.
DecisionBasis
Why a policy chose an action for one finding.
DifferenceKind
How one entry of a difference list relates the two sides.
Obfuscation
Whether a finding’s reported range shows evidence of invisible-character obfuscation.
PolicyBinding
What identifies a compared policy: the revision binding.
Profile
A named, reviewed built-in detector composition (decision-define-detector-profile-and-pack-contract).
RulesetErrorClass
The public, fixed rejection class of a rejected ruleset (issue #495, decision-define-declarative-detector-ruleset-contract’s “Closed validator enum” and “Fail-closed loading rule” sections).
SecretScanErrorCode
Fixed public error codes.
SessionState
The terminally distinct lifecycle states of an IncrementalSanitizer.
SideStatus
Whether a side produced findings.
Specificity
The evidence class a detector claims for a candidate. This is the first key of overlap resolution.

Constants§

DEFAULT_MAX_FINDINGS
The default max_findings: 50,000. Sized so every legitimate workload and every fixture in the conformance corpus stays well under it, while still being a real, reachable ceiling for a deliberately dense-packed adversarial input well before that input reaches DEFAULT_MAX_INPUT_BYTES — a second, independent bound, not a restatement of the byte bound (decision-bound-whole-input-operations-by-default).
DEFAULT_MAX_INPUT_BYTES
The default max_input_bytes: 64 MiB, the same bound crates/secret-scan-cli already declares for a whole file or a streamed total input, so the product has one whole-input bound rather than two.
MAX_ACTION_POLICY_BYTES
The largest action policy document, in bytes. A longer document is rejected with ActionPolicyErrorClass::ActionPolicyTooLarge before any byte of it is parsed. A host that reads a file bounds its read by this value plus one.
MAX_COMPARED_POLICIES
The most policies one comparison accepts (a baseline and three candidates).
MAX_IDENTIFIER_LENGTH
Maximum length in bytes of a public identifier (type, detector id, finding id).
MAX_PLACEHOLDER_LENGTH
Maximum length in bytes of a placeholder a PlaceholderFormatter may return.
RANGE_UNIT
The string-index unit used by every range this crate reports.
VERSION
The shared product version. Every crate, binding, and package in the workspace reports the same version (decision-release-bindings-in-lockstep).

Traits§

Detector
An independent detection unit.
IncrementalPolicy
Maps a finalized finding to an Action within an incremental session.
PlaceholderFormatter
Produces the replacement text for a replaced finding.
Policy
Maps finalized safe metadata to an Action.

Functions§

compare_action_policies
Runs detection once over input and evaluates every policy in policies on the same finalized findings, under the default WholeInputLimits.
compare_action_policies_with_limits
Same as compare_action_policies, against limits instead of the default WholeInputLimits.
compare_configurations
Runs one independent detection pass per side over input and relates every side to the first. See the module documentation (configuration_compare).
default_placeholder_formatter
The default formatter: <SECRET_N>, N one-based among replaced findings.
describe_config
Describes the configuration a registry is fixed to: its enabled built-in detectors, PII selection and the artifact’s defaults for everything a call supplies. Input-free: it reads no scan input, builds nothing and does not change the registry.
is_identifier
Returns true when value matches ^[a-z][a-z0-9]*([._-][a-z0-9]+)*$ and is at most MAX_IDENTIFIER_LENGTH bytes.
load_action_policy
Parses bytes as an action policy document (actionPolicyRevision: 1) and returns the whole validated ActionPolicy, or rejects the whole document.
load_ruleset
Parses bytes as a declarative ruleset and returns one registrable Detector per validated detector: block, in the ruleset’s own declaration order (decision-define-declarative-detector-ruleset-contract).
redact
Reconstructs input in one ordered pass: warn and allow findings pass their span through unchanged; redact and block findings have their span replaced by formatter’s output.
redact_with_limits
Same as redact, against limits instead of the default WholeInputLimits.
resolve_config
Resolves explicit runtime input over manifest’s build defaults into an immutable ConfigSnapshot, with no hidden concatenation and no silent fallback.
run_detector_pipeline
Runs every registered detector over input, validates each candidate, resolves overlaps with the documented precedence, and returns the surviving findings ordered by input offset with ids finding-1, finding-2, and so on.
sanitize
Redacts input with the supported defaults, in one call.
sanitize_with_profile
Same as sanitize, for the built-in detectors of profile.
scan
Runs the detector pipeline and evaluates policy once per finding.
scan_and_redact
Scans input and redacts it in one call, returning the sanitized text and the findings that produced it.
scan_and_redact_with_limits
Same as scan_and_redact, against limits instead of the default WholeInputLimits.
scan_with_limits
Same as scan, against limits instead of the default WholeInputLimits.
shannon_entropy
Returns Shannon entropy in bits per Unicode scalar value (char).
typed_placeholder_formatter
A formatter that names the finding type: <TYPE_NAME_N>, upper-cased with . and - mapped to _.

Type Aliases§

IncrementalResult
The sanitized text and final findings produced by one append or finalize call.