Skip to main content

redact_secret/
error.rs

1//! Sanitized public errors.
2//!
3//! Every failure that crosses the crate boundary is a [`SecretScanError`]
4//! carrying only a fixed [`SecretScanErrorCode`]. The code selects a fixed
5//! message; nothing about the input, a candidate, or a matched value is ever
6//! attached. Bindings surface the code string and message verbatim so every
7//! host reports identical, input-free diagnostics.
8
9use std::fmt;
10
11/// Fixed public error codes.
12///
13/// The string form ([`as_str`](Self::as_str)) and the message
14/// ([`message`](Self::message)) are part of the cross-language contract and
15/// must not change without a corpus review.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
17#[non_exhaustive]
18pub enum SecretScanErrorCode {
19    /// The host passed something other than a text input. The core itself
20    /// only accepts `&str`, so this code is produced by bindings.
21    InvalidInput,
22    /// Scan options could not be interpreted. Produced by bindings that accept
23    /// dynamically typed option objects.
24    InvalidOptions,
25    /// A detector registration was rejected: malformed or duplicate id.
26    InvalidDetector,
27    /// A detector reported a failure while scanning.
28    DetectorFailure,
29    /// A detector returned a candidate that violates the candidate contract.
30    InvalidCandidate,
31    /// The policy reported a failure while evaluating a finding.
32    PolicyFailure,
33    /// A policy returned something that is not one of the four actions.
34    /// The Rust [`Action`](crate::Action) enum cannot express this, so this
35    /// code is produced by bindings that accept dynamically typed actions.
36    InvalidPolicyAction,
37    /// A redaction finding is out of range, misordered, or overlaps another
38    /// finding.
39    InvalidFindings,
40    /// The placeholder formatter reported a failure while redacting.
41    PlaceholderFailure,
42    /// The placeholder formatter returned an empty, oversized, or
43    /// matched-value-reproducing placeholder.
44    InvalidPlaceholder,
45    /// An incremental session's or whole-input operation's limits were
46    /// missing, non-positive, or did not satisfy the documented relationship
47    /// between them.
48    InvalidLimits,
49    /// An accepted input would exceed the configured input-byte limit: an
50    /// incremental session's total accepted input across every append, or a
51    /// whole-input `scan`/`redact`/`scan_and_redact` call's input.
52    InputLimitExceeded,
53    /// An incremental session's retained, unresolved plaintext would exceed
54    /// `max_buffered_bytes`.
55    BufferLimitExceeded,
56    /// An incremental session's open single-line construct would exceed
57    /// `max_token_bytes` without closing.
58    TokenLimitExceeded,
59    /// An incremental session's open PEM-style private-key block would
60    /// exceed `max_multiline_bytes` without closing.
61    MultilineLimitExceeded,
62    /// The accepted finding count from a whole-input scan would exceed the
63    /// configured finding-count limit. Only whole-input `scan` and
64    /// `scan_and_redact` (and `redact` given an externally-constructed
65    /// finding list) produce this code; there is no incremental equivalent.
66    FindingLimitExceeded,
67    /// An incremental session received `append`, `finalize`, or `abort`
68    /// after it left the accepting state.
69    InvalidState,
70    /// A caller-supplied declarative ruleset was rejected while loading
71    /// (`decision-define-declarative-detector-ruleset-contract`). The fixed
72    /// rejection class is carried separately by
73    /// [`RulesetError::class`](crate::RulesetError::class), never by this
74    /// code alone.
75    InvalidRuleset,
76    /// A PII selector does not match the accepted lowercase grammar.
77    PiiSelectorInvalid,
78    /// A valid PII selector names no supported jurisdiction or family.
79    PiiSelectorUnsupported,
80    /// A known PII jurisdiction or family is absent from this artifact.
81    PiiSelectorUnavailable,
82    /// PII initialization conflicts with the already active selection.
83    PiiActivationConflict,
84    /// A caller-supplied declarative action policy was rejected while loading
85    /// (`decision-define-the-versioned-declarative-action-policy-and-default-overlay`).
86    /// The fixed rejection class and the rule index are carried separately by
87    /// [`ActionPolicyError`](crate::ActionPolicyError), never by this code
88    /// alone.
89    InvalidActionPolicy,
90    /// A detector-id selection was rejected while a registry or an owner was
91    /// configured (`decision-define-detector-id-selection-and-configuration-replacement-precedence`).
92    /// The fixed rejection class is carried separately by
93    /// [`DetectionConfigError::class_name`](crate::DetectionConfigError::class_name),
94    /// never by this code alone.
95    InvalidDetectionConfig,
96    /// A detector-selection initialization differs from the configuration the
97    /// owner is already fixed to. A conflict changes nothing.
98    DetectionConfigConflict,
99    /// The configuration leaves nothing enabled: no built-in detector, no
100    /// ruleset and no PII family. Binding it to a scan owner is refused; a
101    /// preview still describes it.
102    EmptyDetectionSet,
103}
104
105impl SecretScanErrorCode {
106    /// Every code, in declaration order.
107    pub const ALL: [Self; 26] = [
108        Self::InvalidInput,
109        Self::InvalidOptions,
110        Self::InvalidDetector,
111        Self::DetectorFailure,
112        Self::InvalidCandidate,
113        Self::PolicyFailure,
114        Self::InvalidPolicyAction,
115        Self::InvalidFindings,
116        Self::PlaceholderFailure,
117        Self::InvalidPlaceholder,
118        Self::InvalidLimits,
119        Self::InputLimitExceeded,
120        Self::BufferLimitExceeded,
121        Self::TokenLimitExceeded,
122        Self::MultilineLimitExceeded,
123        Self::FindingLimitExceeded,
124        Self::InvalidState,
125        Self::InvalidRuleset,
126        Self::PiiSelectorInvalid,
127        Self::PiiSelectorUnsupported,
128        Self::PiiSelectorUnavailable,
129        Self::PiiActivationConflict,
130        Self::InvalidActionPolicy,
131        Self::InvalidDetectionConfig,
132        Self::DetectionConfigConflict,
133        Self::EmptyDetectionSet,
134    ];
135
136    /// The stable `SCREAMING_SNAKE_CASE` code string.
137    #[must_use]
138    pub const fn as_str(self) -> &'static str {
139        match self {
140            Self::InvalidInput => "INVALID_INPUT",
141            Self::InvalidOptions => "INVALID_OPTIONS",
142            Self::InvalidDetector => "INVALID_DETECTOR",
143            Self::DetectorFailure => "DETECTOR_FAILURE",
144            Self::InvalidCandidate => "INVALID_CANDIDATE",
145            Self::PolicyFailure => "POLICY_FAILURE",
146            Self::InvalidPolicyAction => "INVALID_POLICY_ACTION",
147            Self::InvalidFindings => "INVALID_FINDINGS",
148            Self::PlaceholderFailure => "PLACEHOLDER_FAILURE",
149            Self::InvalidPlaceholder => "INVALID_PLACEHOLDER",
150            Self::InvalidLimits => "INVALID_LIMITS",
151            Self::InputLimitExceeded => "INPUT_LIMIT_EXCEEDED",
152            Self::BufferLimitExceeded => "BUFFER_LIMIT_EXCEEDED",
153            Self::TokenLimitExceeded => "TOKEN_LIMIT_EXCEEDED",
154            Self::MultilineLimitExceeded => "MULTILINE_LIMIT_EXCEEDED",
155            Self::FindingLimitExceeded => "FINDING_LIMIT_EXCEEDED",
156            Self::InvalidState => "INVALID_STATE",
157            Self::InvalidRuleset => "INVALID_RULESET",
158            Self::PiiSelectorInvalid => "PII_SELECTOR_INVALID",
159            Self::PiiSelectorUnsupported => "PII_SELECTOR_UNSUPPORTED",
160            Self::PiiSelectorUnavailable => "PII_SELECTOR_UNAVAILABLE",
161            Self::PiiActivationConflict => "PII_ACTIVATION_CONFLICT",
162            Self::InvalidActionPolicy => "INVALID_ACTION_POLICY",
163            Self::InvalidDetectionConfig => "INVALID_DETECTION_CONFIG",
164            Self::DetectionConfigConflict => "DETECTION_CONFIG_CONFLICT",
165            Self::EmptyDetectionSet => "EMPTY_DETECTION_SET",
166        }
167    }
168
169    /// The fixed, input-free message for this code.
170    #[must_use]
171    pub const fn message(self) -> &'static str {
172        match self {
173            Self::InvalidInput => "Secret scan input must be a string.",
174            Self::InvalidOptions => "Secret scan options are invalid.",
175            Self::InvalidDetector => "Invalid detector registration.",
176            Self::DetectorFailure => "A secret detector failed.",
177            Self::InvalidCandidate => "A secret detector returned an invalid candidate.",
178            Self::PolicyFailure => "The secret policy failed.",
179            Self::InvalidPolicyAction => "The secret policy returned an invalid action.",
180            Self::InvalidFindings => "Redaction findings are invalid.",
181            Self::PlaceholderFailure => "The placeholder formatter failed.",
182            Self::InvalidPlaceholder => "The placeholder formatter returned an invalid value.",
183            Self::InvalidLimits => "Secret scan limits are invalid.",
184            Self::InputLimitExceeded => "Secret scan input limit exceeded.",
185            Self::BufferLimitExceeded => "Incremental sanitizer buffer limit exceeded.",
186            Self::TokenLimitExceeded => "Incremental sanitizer token limit exceeded.",
187            Self::MultilineLimitExceeded => "Incremental sanitizer multiline limit exceeded.",
188            Self::FindingLimitExceeded => "Secret scan finding limit exceeded.",
189            Self::InvalidState => "The incremental sanitizer is no longer accepting input.",
190            Self::InvalidRuleset => "The supplied ruleset is invalid.",
191            Self::PiiSelectorInvalid => "PII selector is invalid.",
192            Self::PiiSelectorUnsupported => "PII jurisdiction or family is unsupported.",
193            Self::PiiSelectorUnavailable => "PII selection is unavailable in this artifact.",
194            Self::PiiActivationConflict => "PII activation is already initialized differently.",
195            Self::InvalidActionPolicy => "The supplied action policy is invalid.",
196            Self::InvalidDetectionConfig => "The detector selection is invalid.",
197            Self::DetectionConfigConflict => {
198                "The detector selection is already initialized differently."
199            }
200            Self::EmptyDetectionSet => "The configuration enables no detector.",
201        }
202    }
203}
204
205impl fmt::Display for SecretScanErrorCode {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        f.write_str(self.as_str())
208    }
209}
210
211/// A sanitized scan error. It holds nothing but its code.
212///
213/// Every failure this crate reports is one of these: a fixed
214/// [`SecretScanErrorCode`] and its fixed message, with no payload. No error
215/// carries the scanned input, a matched value, a candidate field, or a
216/// placeholder, so an error can be logged or returned to a caller without
217/// leaking what was being scanned.
218///
219/// # Examples
220///
221/// ```
222/// use redact_secret::{DetectorRegistry, SecretScanErrorCode, redact, scan, DefaultPolicy};
223///
224/// let registry = DetectorRegistry::with_built_in([])?;
225/// let input = "API_KEY=ghp_SYNTHETICREVOKED00000000000000000000";
226/// let findings = scan(input, &registry, &DefaultPolicy)?;
227///
228/// // The same findings do not describe a shorter input.
229/// let error = redact("short", &findings, &redact_secret::default_placeholder_formatter).unwrap_err();
230/// assert_eq!(error.code(), SecretScanErrorCode::InvalidFindings);
231/// assert_eq!(error.to_string(), "Redaction findings are invalid.");
232/// assert!(!error.to_string().contains("ghp_"));
233/// # Ok::<(), redact_secret::SecretScanError>(())
234/// ```
235#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
236pub struct SecretScanError {
237    code: SecretScanErrorCode,
238}
239
240impl SecretScanError {
241    /// Creates an error for `code`.
242    #[must_use]
243    pub const fn new(code: SecretScanErrorCode) -> Self {
244        Self { code }
245    }
246
247    /// The error code.
248    #[must_use]
249    pub const fn code(self) -> SecretScanErrorCode {
250        self.code
251    }
252
253    /// The fixed message; identical to the `Display` output.
254    #[must_use]
255    pub const fn message(self) -> &'static str {
256        self.code.message()
257    }
258}
259
260impl From<SecretScanErrorCode> for SecretScanError {
261    fn from(code: SecretScanErrorCode) -> Self {
262        Self::new(code)
263    }
264}
265
266impl fmt::Display for SecretScanError {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        f.write_str(self.message())
269    }
270}
271
272impl std::error::Error for SecretScanError {}
273
274/// Opaque failure reported by a [`Detector`](crate::Detector).
275///
276/// It carries no payload by design: a detector that fails cannot leak the
277/// substring it was inspecting. The pipeline maps it to
278/// [`SecretScanErrorCode::DetectorFailure`].
279#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
280pub struct DetectorFailure;
281
282/// Opaque failure reported by a [`Policy`](crate::Policy).
283///
284/// The pipeline maps it to [`SecretScanErrorCode::PolicyFailure`].
285#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
286pub struct PolicyFailure;
287
288/// Opaque failure reported by a [`PlaceholderFormatter`](crate::PlaceholderFormatter).
289///
290/// Redaction maps it to its own fixed placeholder-failure code.
291#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
292pub struct FormatterFailure;
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn codes_and_messages_are_fixed() {
300        let expected = [
301            ("INVALID_INPUT", "Secret scan input must be a string."),
302            ("INVALID_OPTIONS", "Secret scan options are invalid."),
303            ("INVALID_DETECTOR", "Invalid detector registration."),
304            ("DETECTOR_FAILURE", "A secret detector failed."),
305            (
306                "INVALID_CANDIDATE",
307                "A secret detector returned an invalid candidate.",
308            ),
309            ("POLICY_FAILURE", "The secret policy failed."),
310            (
311                "INVALID_POLICY_ACTION",
312                "The secret policy returned an invalid action.",
313            ),
314            ("INVALID_FINDINGS", "Redaction findings are invalid."),
315            ("PLACEHOLDER_FAILURE", "The placeholder formatter failed."),
316            (
317                "INVALID_PLACEHOLDER",
318                "The placeholder formatter returned an invalid value.",
319            ),
320            ("INVALID_LIMITS", "Secret scan limits are invalid."),
321            ("INPUT_LIMIT_EXCEEDED", "Secret scan input limit exceeded."),
322            (
323                "BUFFER_LIMIT_EXCEEDED",
324                "Incremental sanitizer buffer limit exceeded.",
325            ),
326            (
327                "TOKEN_LIMIT_EXCEEDED",
328                "Incremental sanitizer token limit exceeded.",
329            ),
330            (
331                "MULTILINE_LIMIT_EXCEEDED",
332                "Incremental sanitizer multiline limit exceeded.",
333            ),
334            (
335                "FINDING_LIMIT_EXCEEDED",
336                "Secret scan finding limit exceeded.",
337            ),
338            (
339                "INVALID_STATE",
340                "The incremental sanitizer is no longer accepting input.",
341            ),
342            ("INVALID_RULESET", "The supplied ruleset is invalid."),
343            ("PII_SELECTOR_INVALID", "PII selector is invalid."),
344            (
345                "PII_SELECTOR_UNSUPPORTED",
346                "PII jurisdiction or family is unsupported.",
347            ),
348            (
349                "PII_SELECTOR_UNAVAILABLE",
350                "PII selection is unavailable in this artifact.",
351            ),
352            (
353                "PII_ACTIVATION_CONFLICT",
354                "PII activation is already initialized differently.",
355            ),
356            (
357                "INVALID_ACTION_POLICY",
358                "The supplied action policy is invalid.",
359            ),
360            (
361                "INVALID_DETECTION_CONFIG",
362                "The detector selection is invalid.",
363            ),
364            (
365                "DETECTION_CONFIG_CONFLICT",
366                "The detector selection is already initialized differently.",
367            ),
368            (
369                "EMPTY_DETECTION_SET",
370                "The configuration enables no detector.",
371            ),
372        ];
373        assert_eq!(SecretScanErrorCode::ALL.len(), expected.len());
374        for (code, (name, message)) in SecretScanErrorCode::ALL.into_iter().zip(expected) {
375            assert_eq!(code.as_str(), name);
376            assert_eq!(code.message(), message);
377            assert_eq!(code.to_string(), name);
378            let error = SecretScanError::new(code);
379            assert_eq!(error.code(), code);
380            assert_eq!(error.to_string(), message);
381            assert_eq!(
382                format!("{error:?}"),
383                format!("SecretScanError {{ code: {code:?} }}")
384            );
385        }
386    }
387
388    #[test]
389    fn opaque_failures_carry_nothing() {
390        assert_eq!(std::mem::size_of::<DetectorFailure>(), 0);
391        assert_eq!(std::mem::size_of::<PolicyFailure>(), 0);
392        assert_eq!(std::mem::size_of::<FormatterFailure>(), 0);
393        assert_eq!(std::mem::size_of::<SecretScanError>(), 1);
394    }
395}