redact_secret/lib.rs
1//! Deterministic secret detection and redaction core.
2//!
3//! This crate is the canonical implementation that every language binding
4//! translates to (`decision-adopt-rust-core-monorepo`). It uses `std` but is
5//! side-effect free by policy:
6//!
7//! - no runtime network access,
8//! - no filesystem access,
9//! - no process-environment lookup,
10//! - no telemetry or logging sinks,
11//! - no secret storage,
12//! - no user interface.
13//!
14//! The crate-level lints below make the policy visible at compile time, and
15//! `scripts/check-rust-workspace.py` rejects dependencies that would breach it.
16//! Ranges reported by this crate use UTF-8 byte offsets; each binding converts
17//! them to its documented native unit (`decision-define-runtime-bindings`).
18//!
19//! # Pipeline contract
20//!
21//! [`run_detector_pipeline`] runs every detector in a [`DetectorRegistry`]
22//! in registration order, validates each [`Candidate`], resolves overlapping
23//! candidates with the documented precedence (resolved-action severity,
24//! specificity, confidence, narrower span, registration order, emission
25//! order), and numbers the
26//! disjoint survivors by input offset. [`scan`] then evaluates a [`Policy`]
27//! once per finding. Identical input and configuration always produce
28//! identical findings and ids.
29//!
30//! Every failure is a [`SecretScanError`] with a fixed code and message and
31//! no payload; no public value carries an input fragment or a matched value.
32//!
33//! [`redact`] then applies [`Finding`] actions to the input in one ordered
34//! pass, replacing `redact`/`block` ranges with placeholders from a
35//! [`PlaceholderFormatter`] and validating that formatter's output.
36//! [`scan_and_redact`] runs both and returns a [`ScanResult`].
37//!
38//! [`scan`], [`redact`], and [`scan_and_redact`] apply a default
39//! [`WholeInputLimits`] before doing any work — [`DEFAULT_MAX_INPUT_BYTES`]
40//! and [`DEFAULT_MAX_FINDINGS`] — and fail with
41//! [`SecretScanErrorCode::InputLimitExceeded`] or
42//! [`SecretScanErrorCode::FindingLimitExceeded`] rather than truncating.
43//! [`scan_with_limits`], [`redact_with_limits`], and
44//! [`scan_and_redact_with_limits`] accept an explicit [`WholeInputLimits`]
45//! instead (`decision-bound-whole-input-operations-by-default`).
46//!
47//! # Public surface
48//!
49//! | Concern | API |
50//! | --- | --- |
51//! | Scan | [`scan`], [`scan_with_limits`], [`run_detector_pipeline`] |
52//! | Redact | [`redact`], [`redact_with_limits`], [`MAX_PLACEHOLDER_LENGTH`] |
53//! | Scan and redact | [`scan_and_redact`], [`scan_and_redact_with_limits`] |
54//! | Golden path | [`sanitize`], [`sanitize_with_profile`] |
55//! | Whole-input limits | [`WholeInputLimits`], [`DEFAULT_MAX_INPUT_BYTES`], [`DEFAULT_MAX_FINDINGS`] |
56//! | Incremental | [`IncrementalSanitizer`], [`IncrementalLimits`], [`SessionState`], [`IncrementalPolicy`], [`IncrementalPolicyContext`] |
57//! | Policy | [`Policy`], [`PolicyContext`], [`DefaultPolicy`], [`Action`] |
58//! | Formatter | [`PlaceholderFormatter`], [`PlaceholderContext`], [`default_placeholder_formatter`], [`typed_placeholder_formatter`] |
59//! | Finding | [`Finding`], [`DetectedFinding`], [`ByteRange`], [`Confidence`], [`Specificity`], [`Obfuscation`] |
60//! | Result | [`ScanResult`], [`IncrementalResult`] |
61//! | Sanitized error | [`SecretScanError`], [`SecretScanErrorCode`], [`DetectorFailure`], [`PolicyFailure`], [`FormatterFailure`] |
62//! | Custom detectors | [`Detector`], [`Candidate`], [`DetectorContext`], [`DetectorRegistry`], [`RegisteredDetector`] |
63//! | Thread-shareable built-in registry | [`BuiltInRegistry`] |
64//! | Declarative rulesets | [`load_ruleset`], [`RulesetError`], [`RulesetErrorClass`] |
65//! | Declarative action policy | [`load_action_policy`], [`ActionPolicy`], [`ActionPolicyError`], [`ActionPolicyErrorClass`], [`MAX_ACTION_POLICY_BYTES`] |
66//! | Explain and compare action policies | [`compare_action_policies`], [`compare_action_policies_with_limits`], [`ComparedPolicy`], [`ActionComparison`], [`ComparedFinding`], [`ActionDecision`], [`DecisionBasis`], [`ComparedSide`], [`PolicyBinding`], [`ActionCounts`], [`DetectionIdentity`], [`MAX_COMPARED_POLICIES`] |
67//! | Compare detection configurations | [`compare_configurations`], [`ConfigurationSide`], [`ConfigurationComparison`], [`ConfigurationResult`], [`ConfigurationDifferences`], [`ConfigurationDifference`], [`DifferenceKind`], [`Correspondence`], [`SideStatus`] |
68//! | Profiles and PII activation | [`Profile`], [`PiiSelection`] |
69//! | Artifact manifest | [`ArtifactManifest`], [`ArtifactKind`], [`ArtifactManifestError`] |
70//! | Static custom composition | [`composition`] |
71//! | Detector selection | [`DetectionSelection`], [`DetectionConfigError`] |
72//! | Effective configuration | [`resolve_config`], [`describe_config`], [`ConfigRequest`], [`ConfigResolution`], [`ConfigSnapshot`], [`ConfigDiagnostic`], [`ConfigSeverity`], [`SampleRuleHits`] |
73//! | Identifiers and units | [`is_identifier`], [`MAX_IDENTIFIER_LENGTH`], [`RANGE_UNIT`], [`VERSION`] |
74//! | Detector building blocks | [`shannon_entropy`] |
75//!
76//! That table is the whole surface — it lists every name this crate root
77//! exports, and `[workspace.metadata.redact-secret] core-public-api` in the
78//! workspace manifest repeats it so a name cannot join or leave without a
79//! reviewed manifest change. Everything else is private. In particular, the
80//! built-in detector set of each profile is reached only through
81//! [`DetectorRegistry::with_built_in`] (`full`) and
82//! [`DetectorRegistry::with_common_built_in`] (`common`), and the retention
83//! tuning the incremental session depends on is derived through
84//! [`IncrementalLimits::minimum_buffered_bytes`] rather than exposed as a
85//! constant, so both can change without breaking a caller.
86//! `decision-define-detector-profile-and-pack-contract` fixes which built-in
87//! detectors each [`Profile`] holds and its compatibility class.
88//!
89//! # Examples
90//!
91//! The minimal path redacts with the supported defaults (`full` profile,
92//! [`DefaultPolicy`], [`default_placeholder_formatter`], default
93//! [`WholeInputLimits`]) in one call:
94//!
95//! ```
96//! let result = redact_secret::sanitize("API_KEY=ghp_SYNTHETICREVOKED00000000000000000000")?;
97//! assert_eq!(result.text(), "API_KEY=<SECRET_1>");
98//! # Ok::<(), redact_secret::SecretScanError>(())
99//! ```
100//!
101//! Custom detectors, PII activation, a custom policy or formatter, explicit
102//! limits, and registry reuse use the advanced path, [`scan_and_redact`]:
103//!
104//! ```
105//! use redact_secret::{
106//! DefaultPolicy, DetectorRegistry, default_placeholder_formatter, scan_and_redact,
107//! };
108//!
109//! let registry = DetectorRegistry::with_built_in([])?;
110//! let input = "API_KEY=ghp_SYNTHETICREVOKED00000000000000000000\nplain text";
111//!
112//! let result = scan_and_redact(input, ®istry, &DefaultPolicy, &default_placeholder_formatter)?;
113//!
114//! assert_eq!(result.text(), "API_KEY=<SECRET_1>\nplain text");
115//! // Ranges index the original input, in UTF-8 bytes.
116//! let range = result.findings()[0].range();
117//! assert_eq!(&input[range.start()..range.end()], "ghp_SYNTHETICREVOKED00000000000000000000");
118//! # Ok::<(), redact_secret::SecretScanError>(())
119//! ```
120//!
121//! # Incremental sanitization contract
122//!
123//! [`IncrementalSanitizer`] runs the same built-in detectors, default
124//! policy, and redaction over text supplied in chunks. It is a bounded,
125//! four-state session (`accepting`, `finalized`, `aborted`, `failed`) that
126//! emits only text whose detection window is closed, never rescans
127//! finalized input, and accepts input independently of how a caller
128//! partitions it into chunks. See the module documentation for the full
129//! contract.
130//!
131//! The Rust core and the top-level conformance corpus are the canonical source
132//! of behavior. Bindings translate host values and range units without
133//! reimplementing detection (`decision-govern-cross-language-conformance`).
134
135#![forbid(unsafe_code)]
136#![deny(clippy::print_stdout, clippy::print_stderr)]
137#![deny(missing_docs)]
138#![deny(rustdoc::broken_intra_doc_links, rustdoc::private_intra_doc_links)]
139
140mod action_policy;
141mod compare;
142mod config;
143mod configuration_compare;
144mod detectors;
145mod entropy;
146mod error;
147mod evidence;
148mod incremental;
149mod invisible_table;
150mod json;
151mod limits;
152mod manifest;
153mod normalize;
154#[cfg_attr(
155 not(test),
156 expect(
157 dead_code,
158 reason = "PII families consume this substrate in later issues"
159 )
160)]
161mod pii;
162mod pipeline;
163mod policy;
164mod policy_diagnostics;
165mod redact;
166mod registry;
167mod ruleset;
168mod selection;
169mod sha256;
170mod structured_validators;
171mod types;
172
173pub mod composition;
174
175pub use action_policy::{
176 ActionPolicy, ActionPolicyError, ActionPolicyErrorClass, MAX_ACTION_POLICY_BYTES,
177 load_action_policy,
178};
179pub use compare::{
180 ActionComparison, ActionCounts, ActionDecision, ComparedFinding, ComparedPolicy, ComparedSide,
181 DecisionBasis, DetectionIdentity, MAX_COMPARED_POLICIES, PolicyBinding,
182 compare_action_policies, compare_action_policies_with_limits,
183};
184pub use config::{
185 ConfigDiagnostic, ConfigRequest, ConfigResolution, ConfigSeverity, ConfigSnapshot,
186 describe_config, resolve_config,
187};
188pub use configuration_compare::{
189 ConfigurationComparison, ConfigurationDifference, ConfigurationDifferences,
190 ConfigurationResult, ConfigurationSide, Correspondence, DifferenceKind, SideStatus,
191 compare_configurations,
192};
193pub use entropy::shannon_entropy;
194pub use error::{
195 DetectorFailure, FormatterFailure, PolicyFailure, SecretScanError, SecretScanErrorCode,
196};
197pub use incremental::{
198 IncrementalLimits, IncrementalPolicy, IncrementalPolicyContext, IncrementalResult,
199 IncrementalSanitizer, SessionState,
200};
201pub use limits::{DEFAULT_MAX_FINDINGS, DEFAULT_MAX_INPUT_BYTES, WholeInputLimits};
202pub use manifest::{ArtifactKind, ArtifactManifest, ArtifactManifestError};
203pub use pii::PiiSelection;
204pub use pipeline::{
205 run_detector_pipeline, sanitize, sanitize_with_profile, scan, scan_and_redact,
206 scan_and_redact_with_limits, scan_with_limits,
207};
208pub use policy::DefaultPolicy;
209pub use policy_diagnostics::SampleRuleHits;
210pub use redact::{
211 MAX_PLACEHOLDER_LENGTH, default_placeholder_formatter, redact, redact_with_limits,
212 typed_placeholder_formatter,
213};
214pub use registry::{BuiltInRegistry, DetectorRegistry, Profile, RegisteredDetector};
215pub use ruleset::{RulesetError, RulesetErrorClass, load_ruleset};
216pub use selection::{DetectionConfigError, DetectionSelection};
217pub use types::{
218 Action, ByteRange, Candidate, Confidence, DetectedFinding, Detector, DetectorContext, Finding,
219 MAX_IDENTIFIER_LENGTH, Obfuscation, PlaceholderContext, PlaceholderFormatter, Policy,
220 PolicyContext, ScanResult, Specificity, is_identifier,
221};
222
223/// The shared product version. Every crate, binding, and package in the
224/// workspace reports the same version (`decision-release-bindings-in-lockstep`).
225pub const VERSION: &str = env!("CARGO_PKG_VERSION");
226
227/// The string-index unit used by every range this crate reports.
228///
229/// Bindings convert to their host unit without changing the selected span:
230/// JavaScript uses UTF-16 code units and Python uses Unicode code points.
231pub const RANGE_UNIT: &str = "utf8-bytes";
232
233#[cfg(test)]
234mod test_rng;
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[test]
241 fn version_matches_manifest() {
242 assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
243 assert!(!VERSION.is_empty());
244 }
245
246 #[test]
247 fn range_unit_is_utf8_bytes() {
248 assert_eq!(RANGE_UNIT, "utf8-bytes");
249 }
250}