redact-secret 0.1.0-beta.15

Deterministic secret detection and redaction for runtime data and AI context: scans text locally before it reaches logs, storage, telemetry, tools, or model context. Side-effect free: no runtime network, filesystem, environment, telemetry, secret storage, or UI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Bounded validators for structured PII type evidence.
//!
//! This registry is deliberately crate-private and fixed at compile time. A
//! detector submits one already-bounded candidate and a built-in validator
//! identity; callers cannot register code or widen declarative ruleset v1.
//! Successful validation proves only that the candidate has the requested
//! structure. It does not decide whether the occurrence is sensitive.

/// Stable identity recorded when validator evidence is exported for evaluation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ValidatorProvenance {
    /// Stable algorithm name. A semantic change requires a new version.
    pub(crate) identity: &'static str,
    /// Positive semantic version of this validator contract.
    pub(crate) version: u16,
}

/// Safe, input-free reasons that validation did not produce type evidence.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ValidationFailure {
    /// The registry does not contain the requested built-in identity/version.
    UnknownValidator,
    /// The candidate exceeds the selected validator's byte bound.
    CandidateTooLong,
    /// The candidate does not satisfy the validator's lexical shape.
    Malformed,
    /// The shape is valid but its check value is not.
    ChecksumMismatch,
}

/// Type evidence returned only after a complete successful validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ValidationEvidence {
    /// Exact validator contract that produced this evidence.
    pub(crate) provenance: ValidatorProvenance,
}

#[derive(Clone, Copy)]
struct Registration {
    provenance: ValidatorProvenance,
    max_candidate_bytes: usize,
    validate: fn(&str) -> Result<(), ValidationFailure>,
}

const LUHN_V1: ValidatorProvenance = ValidatorProvenance {
    identity: "luhn",
    version: 1,
};
const IBAN_MOD97_V1: ValidatorProvenance = ValidatorProvenance {
    identity: "iban-mod97",
    version: 1,
};
const US_SSN_ALLOCATION_V1: ValidatorProvenance = ValidatorProvenance {
    identity: "us-ssn-allocation",
    version: 1,
};

const REGISTRATIONS: [Registration; 3] = [
    Registration {
        provenance: LUHN_V1,
        max_candidate_bytes: 19,
        validate: validate_luhn_v1,
    },
    Registration {
        provenance: IBAN_MOD97_V1,
        max_candidate_bytes: 34,
        validate: validate_iban_mod97_v1,
    },
    Registration {
        provenance: US_SSN_ALLOCATION_V1,
        max_candidate_bytes: 9,
        validate: validate_us_ssn_allocation_v1,
    },
];

/// Fixed built-in registry shared by all PII detectors in the Rust core.
pub(crate) struct StructuredValidatorRegistry;

impl StructuredValidatorRegistry {
    /// Validates one candidate under an exact validator identity and version.
    ///
    /// Lookup happens before candidate inspection. Oversized candidates fail
    /// before an algorithm runs, every algorithm makes one bounded pass, and
    /// failures contain neither the candidate nor a derived value.
    pub(crate) fn validate(
        identity: &str,
        version: u16,
        candidate: &str,
    ) -> Result<ValidationEvidence, ValidationFailure> {
        let Some(registration) = REGISTRATIONS.iter().find(|entry| {
            entry.provenance.identity == identity && entry.provenance.version == version
        }) else {
            return Err(ValidationFailure::UnknownValidator);
        };
        if candidate.len() > registration.max_candidate_bytes {
            return Err(ValidationFailure::CandidateTooLong);
        }
        (registration.validate)(candidate)?;
        Ok(ValidationEvidence {
            provenance: registration.provenance,
        })
    }
}

fn validate_luhn_v1(candidate: &str) -> Result<(), ValidationFailure> {
    if candidate.len() < 2 || !candidate.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(ValidationFailure::Malformed);
    }

    let mut sum = 0_u16;
    let parity = candidate.len() % 2;
    for (index, byte) in candidate.bytes().enumerate() {
        let mut digit = u16::from(byte - b'0');
        if index % 2 == parity {
            digit *= 2;
            if digit > 9 {
                digit -= 9;
            }
        }
        sum += digit;
    }
    if sum.is_multiple_of(10) {
        Ok(())
    } else {
        Err(ValidationFailure::ChecksumMismatch)
    }
}

fn validate_iban_mod97_v1(candidate: &str) -> Result<(), ValidationFailure> {
    let bytes = candidate.as_bytes();
    if !(15..=34).contains(&bytes.len())
        || !bytes[0..2].iter().all(u8::is_ascii_uppercase)
        || !bytes[2..4].iter().all(u8::is_ascii_digit)
        || !bytes[4..]
            .iter()
            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
    {
        return Err(ValidationFailure::Malformed);
    }

    let mut remainder = 0_u16;
    for byte in bytes[4..].iter().chain(&bytes[..4]) {
        if byte.is_ascii_digit() {
            remainder = push_decimal_digit(remainder, byte - b'0');
        } else {
            remainder = push_letter_value(remainder, byte - b'A' + 10);
        }
    }
    if remainder == 1 {
        Ok(())
    } else {
        Err(ValidationFailure::ChecksumMismatch)
    }
}

fn validate_us_ssn_allocation_v1(candidate: &str) -> Result<(), ValidationFailure> {
    let bytes = candidate.as_bytes();
    if bytes.len() != 9 || !bytes.iter().all(u8::is_ascii_digit) {
        return Err(ValidationFailure::Malformed);
    }

    let area = u16::from(bytes[0] - b'0') * 100
        + u16::from(bytes[1] - b'0') * 10
        + u16::from(bytes[2] - b'0');
    let group = u16::from(bytes[3] - b'0') * 10 + u16::from(bytes[4] - b'0');
    let serial = u16::from(bytes[5] - b'0') * 1_000
        + u16::from(bytes[6] - b'0') * 100
        + u16::from(bytes[7] - b'0') * 10
        + u16::from(bytes[8] - b'0');

    if area == 0 || area == 666 || area >= 900 || group == 0 || serial == 0 {
        Err(ValidationFailure::Malformed)
    } else {
        Ok(())
    }
}

const fn push_decimal_digit(remainder: u16, digit: u8) -> u16 {
    (remainder * 10 + digit as u16) % 97
}

/// Appends one letter's two-digit expansion (`value` in 10..=35) in a single
/// modulo step. `(r * 10 + tens) % 97` followed by `(. * 10 + ones) % 97` is
/// `(r * 100 + value) % 97`; with `r <= 96` the operand is at most 9,635.
const fn push_letter_value(remainder: u16, value: u8) -> u16 {
    (remainder * 100 + value as u16) % 97
}

#[cfg(test)]
mod tests {
    use super::{
        IBAN_MOD97_V1, LUHN_V1, StructuredValidatorRegistry, US_SSN_ALLOCATION_V1,
        ValidationFailure, ValidatorProvenance, push_decimal_digit, push_letter_value,
        validate_iban_mod97_v1,
    };

    fn validate(
        provenance: ValidatorProvenance,
        candidate: &str,
    ) -> Result<ValidatorProvenance, ValidationFailure> {
        StructuredValidatorRegistry::validate(provenance.identity, provenance.version, candidate)
            .map(|evidence| evidence.provenance)
    }

    fn synthetic_us_ssn() -> String {
        let mut hash = 0x811c_9dc5_u32;
        for byte in b"redact-secret-us-ssn-v1-fixture-879" {
            hash ^= u32::from(*byte);
            hash = hash.wrapping_mul(0x0100_0193);
        }
        let mut area = 1 + hash % 898;
        if area >= 666 {
            area += 1;
        }
        let group = 1 + (hash / 898) % 99;
        let serial = 1 + (hash / (898 * 99)) % 9_999;
        format!("{area:03}{group:02}{serial:04}")
    }

    #[test]
    fn luhn_and_non_luhn_validators_share_the_registry_contract() {
        // All-zero digits and the ZZ/SYNTHETIC IBAN body are algorithm-only,
        // unmistakably synthetic values rather than personal data.
        assert_eq!(validate(LUHN_V1, "0000000000000000"), Ok(LUHN_V1));
        assert_eq!(
            validate(IBAN_MOD97_V1, "ZZ50SYNTHETIC000000"),
            Ok(IBAN_MOD97_V1)
        );
        assert_eq!(
            validate(US_SSN_ALLOCATION_V1, &synthetic_us_ssn()),
            Ok(US_SSN_ALLOCATION_V1)
        );
    }

    #[test]
    fn us_ssn_v1_enforces_only_current_ssa_structural_exclusions() {
        assert_eq!(
            validate(US_SSN_ALLOCATION_V1, &synthetic_us_ssn()),
            Ok(US_SSN_ALLOCATION_V1)
        );
        for excluded in [
            "000010001",
            "666010001",
            "900010001",
            "999010001",
            "001000001",
            "001010000",
        ] {
            assert_eq!(
                validate(US_SSN_ALLOCATION_V1, excluded),
                Err(ValidationFailure::Malformed)
            );
        }
    }

    #[test]
    fn luhn_v1_pins_even_and_odd_length_doubling_parity() {
        // These deliberately short, nondegenerate algorithm vectors are not
        // plausible personal identifiers. For the even vector, indexes 0 and
        // 2 double; for the odd vector, indexes 1 and 3 double. Applying the
        // opposite parity makes both checksums fail.
        assert_eq!(validate(LUHN_V1, "1230"), Ok(LUHN_V1));
        assert_eq!(validate(LUHN_V1, "12344"), Ok(LUHN_V1));
        assert_eq!(
            validate(LUHN_V1, "1231"),
            Err(ValidationFailure::ChecksumMismatch)
        );
        assert_eq!(
            validate(LUHN_V1, "12345"),
            Err(ValidationFailure::ChecksumMismatch)
        );
    }

    #[test]
    fn malformed_candidates_fail_without_checksum_evidence() {
        for candidate in ["", "0", "0000-0000", "000000000000000x", "0000"] {
            assert_eq!(
                validate(LUHN_V1, candidate),
                Err(ValidationFailure::Malformed),
                "candidate length {}",
                candidate.len()
            );
        }
        for candidate in [
            "ZZ50SYNTHETIC",       // shorter than the IBAN lower bound
            "zz50SYNTHETIC000000", // lower-case country code
            "ZZ5XSYNTHETIC000000", // non-digit check field
            "ZZ50SYNTHETIC-00000", // punctuation
            "ZZ50SYNTHETIC000", // non-ASCII digits
        ] {
            assert_eq!(
                validate(IBAN_MOD97_V1, candidate),
                Err(ValidationFailure::Malformed),
                "candidate length {}",
                candidate.len()
            );
        }
        for candidate in ["", "00000000", "00000000x"] {
            assert_eq!(
                validate(US_SSN_ALLOCATION_V1, candidate),
                Err(ValidationFailure::Malformed),
                "candidate length {}",
                candidate.len()
            );
        }
    }

    #[test]
    fn checksum_mismatches_are_distinct_from_malformed_input() {
        assert_eq!(
            validate(LUHN_V1, "0000000000000001"),
            Err(ValidationFailure::ChecksumMismatch)
        );
        assert_eq!(
            validate(IBAN_MOD97_V1, "ZZ51SYNTHETIC000000"),
            Err(ValidationFailure::ChecksumMismatch)
        );
    }

    #[test]
    fn exact_bounds_are_processed_and_oversized_inputs_fail_before_validation() {
        assert_eq!(validate(LUHN_V1, "0000000000000000000"), Ok(LUHN_V1));
        assert_eq!(
            validate(LUHN_V1, "0".repeat(20).as_str()),
            Err(ValidationFailure::CandidateTooLong)
        );

        let max_iban = format!("ZZ25SYNTHETIC{}", "0".repeat(21));
        assert_eq!(max_iban.len(), 34);
        assert_eq!(validate(IBAN_MOD97_V1, &max_iban), Ok(IBAN_MOD97_V1));
        assert_eq!(
            validate(IBAN_MOD97_V1, format!("{max_iban}0").as_str()),
            Err(ValidationFailure::CandidateTooLong)
        );
        assert_eq!(
            validate(US_SSN_ALLOCATION_V1, "0000000000"),
            Err(ValidationFailure::CandidateTooLong)
        );
        for display_or_unicode in ["000-00-0000", "000000000"] {
            assert_eq!(
                validate(US_SSN_ALLOCATION_V1, display_or_unicode),
                Err(ValidationFailure::CandidateTooLong)
            );
        }
    }

    #[test]
    fn adversarial_and_unknown_inputs_have_fixed_failures() {
        let adversarial = "9".repeat(1_000_000);
        assert_eq!(
            validate(LUHN_V1, &adversarial),
            Err(ValidationFailure::CandidateTooLong)
        );
        assert_eq!(
            StructuredValidatorRegistry::validate("user-code", 1, &adversarial),
            Err(ValidationFailure::UnknownValidator)
        );
        assert_eq!(
            StructuredValidatorRegistry::validate("luhn", 2, "0000000000000000"),
            Err(ValidationFailure::UnknownValidator)
        );
        assert_eq!(
            StructuredValidatorRegistry::validate("us-ssn-allocation", 2, &synthetic_us_ssn(),),
            Err(ValidationFailure::UnknownValidator)
        );
    }

    #[test]
    fn repeated_runs_are_byte_for_byte_deterministic() {
        let synthetic_ssn = synthetic_us_ssn();
        let cases = [
            (LUHN_V1, "0000000000000000"),
            (LUHN_V1, "0000000000000001"),
            (IBAN_MOD97_V1, "ZZ50SYNTHETIC000000"),
            (IBAN_MOD97_V1, "ZZ51SYNTHETIC000000"),
            (US_SSN_ALLOCATION_V1, synthetic_ssn.as_str()),
            (US_SSN_ALLOCATION_V1, "900626879"),
        ];
        for (provenance, candidate) in cases {
            let first = validate(provenance, candidate);
            for _ in 0..1_000 {
                assert_eq!(validate(provenance, candidate), first);
            }
        }
    }

    /// The IBAN validator exactly as shipped before #1149 (two modulo steps per
    /// letter). Kept only as the differential oracle.
    fn iban_two_step_oracle(candidate: &str) -> Result<(), ValidationFailure> {
        let bytes = candidate.as_bytes();
        if !(15..=34).contains(&bytes.len())
            || !bytes[0..2].iter().all(u8::is_ascii_uppercase)
            || !bytes[2..4].iter().all(u8::is_ascii_digit)
            || !bytes[4..]
                .iter()
                .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
        {
            return Err(ValidationFailure::Malformed);
        }
        let mut remainder = 0_u16;
        for byte in bytes[4..].iter().chain(&bytes[..4]) {
            if byte.is_ascii_digit() {
                remainder = push_decimal_digit(remainder, byte - b'0');
            } else {
                let expanded = byte - b'A' + 10;
                remainder = push_decimal_digit(remainder, expanded / 10);
                remainder = push_decimal_digit(remainder, expanded % 10);
            }
        }
        if remainder == 1 {
            Ok(())
        } else {
            Err(ValidationFailure::ChecksumMismatch)
        }
    }

    fn assert_iban_equivalent(candidate: &str) {
        assert_eq!(
            validate_iban_mod97_v1(candidate),
            iban_two_step_oracle(candidate),
            "candidate length {}",
            candidate.len()
        );
        // Through the registry the bound and identity gates precede the
        // algorithm, and they are untouched.
        let registry = StructuredValidatorRegistry::validate("iban-mod97", 1, candidate);
        if candidate.len() > 34 {
            assert_eq!(registry, Err(ValidationFailure::CandidateTooLong));
        } else {
            assert_eq!(registry.map(|_| ()), iban_two_step_oracle(candidate));
        }
    }

    #[test]
    fn iban_letter_fusion_is_exact_for_every_remainder_and_letter() {
        // The only arithmetic that changed: every reachable remainder (0..=96)
        // times every letter value (10..=35), including the u16 bound.
        for remainder in 0_u16..97 {
            for value in 10_u8..=35 {
                let two_step =
                    push_decimal_digit(push_decimal_digit(remainder, value / 10), value % 10);
                assert_eq!(push_letter_value(remainder, value), two_step);
            }
        }
        assert!(u16::try_from(96_u32 * 100 + 35).is_ok());
    }

    #[test]
    fn iban_fusion_matches_the_two_step_oracle_over_every_check_value() {
        // For each body and country prefix, all 100 check-digit pairs: one or two
        // validate (mod 97), and old and new agree on every pair.
        let alphabet: Vec<u8> = (b'0'..=b'9').chain(b'A'..=b'Z').collect();
        let mut state = 0x9e37_79b9_7f4a_7c15_u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        let mut valid_seen = 0;
        for length in 15..=34_usize {
            for round in 0..60 {
                let body: String = (0..length - 4)
                    .map(|index| {
                        let pick = usize::try_from(next() >> 33).unwrap();
                        match round % 4 {
                            // letter-heavy, digit-heavy, mixed, boundary letters
                            0 => char::from(b'A' + u8::try_from(pick % 26).unwrap()),
                            1 => char::from(b'0' + u8::try_from(pick % 10).unwrap()),
                            2 => char::from(alphabet[pick % alphabet.len()]),
                            _ => char::from(if (index + pick).is_multiple_of(2) {
                                b'A'
                            } else {
                                b'Z'
                            }),
                        }
                    })
                    .collect();
                let mut valid_for_body = 0;
                for check in 0..100_u8 {
                    let candidate = format!("ZZ{}{}{}", check / 10, check % 10, body);
                    assert_eq!(candidate.len(), length);
                    assert_iban_equivalent(&candidate);
                    if validate_iban_mod97_v1(&candidate).is_ok() {
                        valid_for_body += 1;
                    }
                }
                // Check pairs 00..=99 hold each residue once, plus 97..=99 again as
                // 00..=02, so a body admits one or two valid pairs.
                assert!((1..=2).contains(&valid_for_body));
                valid_seen += valid_for_body;
            }
        }
        assert!(valid_seen >= 20 * 60);
    }

    #[test]
    fn iban_fusion_matches_the_oracle_on_malformed_and_out_of_range_inputs() {
        // Every length 0..=40 over a spread of byte classes at every position.
        let probes: [&str; 11] = [
            "A", "Z", "0", "9", "a", "z", "-", " ", "\u{ff10}", "\u{e9}", "\0",
        ];
        for length in 0..=40_usize {
            let base: String = (0..length)
                .map(|index| match index {
                    0 | 1 => 'Z',
                    2 | 3 => '5',
                    _ if index % 3 == 0 => 'A',
                    _ if index % 3 == 1 => 'Z',
                    _ => '7',
                })
                .collect();
            assert_iban_equivalent(&base);
            for position in 0..length {
                for probe in probes {
                    let mut chars: Vec<char> = base.chars().collect();
                    chars.splice(position..=position, probe.chars());
                    let candidate: String = chars.into_iter().collect();
                    assert_iban_equivalent(&candidate);
                }
            }
        }
        for candidate in [
            "",
            "ZZ",
            "ZZ50SYNTHETIC",
            "ZZ50SYNTHETIC00000000000000000000000000000",
        ] {
            assert_iban_equivalent(candidate);
        }
    }

    #[test]
    fn iban_fusion_keeps_published_example_outcomes() {
        // Widely published documentation examples (synthetic, not accounts).
        for valid in [
            "GB82WEST12345698765432",
            "DE89370400440532013000",
            "FR1420041010050500013M02606",
            "MT84MALT011000012345MTLCAST001S",
        ] {
            assert_eq!(validate(IBAN_MOD97_V1, valid), Ok(IBAN_MOD97_V1));
            assert_iban_equivalent(valid);
        }
        assert_eq!(
            validate(IBAN_MOD97_V1, "GB83WEST12345698765432"),
            Err(ValidationFailure::ChecksumMismatch)
        );
        assert_eq!(
            validate(IBAN_MOD97_V1, "GB82WEST1234569876543x"),
            Err(ValidationFailure::Malformed)
        );
    }
}