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
//! Differential tests for batching closed units (issue #985): a session that
//! processes every line closed in one `append` together must release exactly
//! what the same session releases when it processes each unit as soon as it
//! closes — the same text, findings, error, and callback calls in the same
//! order. Every value is synthetic.
//!
//! These drive the crate-private parts: the unbatched reference mode, custom
//! registries, and the retention peak. The conformance corpora run through
//! the public API in `tests/incremental_batching.rs`, since core sources may
//! not include files.

use std::cell::RefCell;
use std::fmt::Write as _;
use std::rc::Rc;

use super::*;
use crate::error::{DetectorFailure, FormatterFailure};
use crate::types::{Candidate, Confidence, Detector, DetectorContext, PlaceholderContext};

type Outcome = Result<(String, Vec<Finding>), SecretScanErrorCode>;

fn drive(mut sanitizer: IncrementalSanitizer, chunks: &[&str]) -> Outcome {
    let mut text = String::new();
    let mut findings = Vec::new();
    for chunk in chunks {
        let result = sanitizer.append(chunk).map_err(SecretScanError::code)?;
        text.push_str(result.text());
        findings.extend_from_slice(result.findings());
    }
    let result = sanitizer.finalize().map_err(SecretScanError::code)?;
    text.push_str(result.text());
    findings.extend_from_slice(result.findings());
    Ok((text, findings))
}

fn unbatched(mut sanitizer: IncrementalSanitizer) -> IncrementalSanitizer {
    sanitizer.unbatched = true;
    sanitizer
}

/// Splits `input` into chunks of at least `bytes` bytes on char boundaries.
fn chunked(input: &str, bytes: usize) -> Vec<&str> {
    let mut chunks = Vec::new();
    let mut cursor = 0;
    while cursor < input.len() {
        let mut end = (cursor + bytes).min(input.len());
        while !input.is_char_boundary(end) {
            end += 1;
        }
        chunks.push(&input[cursor..end]);
        cursor = end;
    }
    chunks
}

fn limits() -> IncrementalLimits {
    IncrementalLimits::new(
        1 << 26,
        IncrementalLimits::minimum_buffered_bytes(1 << 16, 1 << 16),
        1 << 16,
        1 << 16,
    )
    .unwrap()
}

fn full() -> IncrementalSanitizer {
    IncrementalSanitizer::new(limits()).unwrap()
}

/// Runs `input` in chunks of each size through a batched and an unbatched
/// session and requires identical outcomes.
fn assert_batching_is_invisible(
    make: &dyn Fn() -> IncrementalSanitizer,
    label: &str,
    input: &str,
    chunk_sizes: &[usize],
) {
    for &size in chunk_sizes {
        let chunks = chunked(input, size);
        let expected = drive(unbatched(make()), &chunks);
        let actual = drive(make(), &chunks);
        assert_eq!(actual, expected, "{label}, {size}-byte chunks");
    }
}

/// Emits one fixed candidate per `tie-` line, at a span and confidence
/// chosen so that, within the line, the two disjoint pairs {`d0`, `d3`} and
/// {`d1`, `d2`} tie on every overlap-resolution key but emission order. A
/// `pre-<n>` line gives only detector `n` a candidate, which moves that
/// detector's emission order on every later line of the same scan.
struct TieDetector {
    id: &'static str,
    role: usize,
}

impl Detector for TieDetector {
    fn id(&self) -> &str {
        self.id
    }

    fn detect(
        &self,
        input: &str,
        _context: &DetectorContext,
    ) -> Result<Vec<Candidate>, DetectorFailure> {
        // (start, end, confidence) inside a `tie-` line: a1 = d0, b1 = d1,
        // b2 = d2, a2 = d3. Severity follows confidence (High redacts,
        // Medium warns), so each pair holds one of each.
        let spans = [
            (2, 8, Confidence::High),
            (0, 4, Confidence::Medium),
            (6, 12, Confidence::High),
            (10, 14, Confidence::Medium),
        ];
        let mut candidates = Vec::new();
        let mut line_start = 0;
        for line in input.split_inclusive('\n') {
            let (start, end, confidence) = if line.starts_with("tie-") {
                spans[self.role]
            } else if line.starts_with(&format!("pre-{}", self.role)) {
                (0, 4, Confidence::High)
            } else {
                line_start += line.len();
                continue;
            };
            candidates.push(Candidate::new(
                "synthetic_tie",
                confidence,
                ByteRange::new(line_start + start, line_start + end).ok_or(DetectorFailure)?,
            ));
            line_start += line.len();
        }
        Ok(candidates)
    }
}

fn tie_registry() -> DetectorRegistry {
    let mut registry = DetectorRegistry::default();
    for (role, id) in ["tie-d0", "tie-d1", "tie-d2", "tie-d3"]
        .into_iter()
        .enumerate()
    {
        registry
            .register(Box::new(TieDetector { id, role }))
            .unwrap();
    }
    registry
}

fn tie_session() -> IncrementalSanitizer {
    IncrementalSanitizer::from_registry(
        tie_registry(),
        limits(),
        Box::new(DefaultPolicy),
        Box::new(default_placeholder_formatter),
    )
}

#[test]
fn an_exact_overlap_tie_resolves_as_in_its_own_unit_when_batched() {
    let registry = tie_registry();
    let unit = "tie-line-0000\n";
    let alone = detect(unit, &registry, None).unwrap();
    assert_eq!(alone.len(), 2, "the tie line resolves to one of two pairs");

    let mut whole_input_flipped = false;
    for role in 0..4 {
        let earlier = format!("pre-{role}-line\n");
        let input = format!("{earlier}{unit}");
        let unit_ends = [earlier.len(), input.len()];

        // Batched: the tie line's findings are exactly its own.
        let batched = detect_units(&input, 0, &registry, &unit_ends, None)
            .unwrap()
            .expect("every candidate is inside one unit");
        let tie_findings: Vec<_> = batched
            .iter()
            .filter(|found| found.range().start() >= earlier.len())
            .map(|found| {
                (
                    found.detector().to_owned(),
                    found.range().start() - earlier.len(),
                )
            })
            .collect();
        let expected: Vec<_> = alone
            .iter()
            .map(|found| (found.detector().to_owned(), found.range().start()))
            .collect();
        assert_eq!(tie_findings, expected, "pre-{role}");

        // Scanned as one input, emission order counts across lines, so an
        // earlier line can flip the tie: the gap batching must not inherit.
        let whole: Vec<_> = detect(&input, &registry, None)
            .unwrap()
            .iter()
            .filter(|found| found.range().start() >= earlier.len())
            .map(|found| {
                (
                    found.detector().to_owned(),
                    found.range().start() - earlier.len(),
                )
            })
            .collect();
        whole_input_flipped |= whole != expected;

        assert_batching_is_invisible(&tie_session, "tie", &input, &[usize::MAX]);
    }
    assert!(
        whole_input_flipped,
        "the fixture must hold a tie that emission order across lines decides",
    );
}

/// Records every policy and formatter call, failing on the configured
/// finding ids.
fn recording_session(
    fail_policy_on: Option<&'static str>,
    fail_formatter_on: Option<&'static str>,
    limits: IncrementalLimits,
    log: &Rc<RefCell<Vec<String>>>,
) -> IncrementalSanitizer {
    let policy_log = Rc::clone(log);
    let policy = move |finding: &DetectedFinding, context: &IncrementalPolicyContext| {
        policy_log.borrow_mut().push(format!(
            "policy {} {} {:?}",
            finding.id(),
            context.finding_index(),
            finding.range()
        ));
        if fail_policy_on == Some(finding.id()) {
            return Err(PolicyFailure);
        }
        Policy::evaluate(&DefaultPolicy, finding, &PolicyContext::new(0, 0))
    };
    let formatter_log = Rc::clone(log);
    let formatter = move |finding: &Finding, context: &PlaceholderContext| {
        formatter_log.borrow_mut().push(format!(
            "format {} {} {:?}",
            finding.id(),
            context.placeholder_index(),
            finding.range()
        ));
        if fail_formatter_on == Some(finding.id()) {
            return Err(FormatterFailure);
        }
        default_placeholder_formatter(finding, context)
    };
    IncrementalSanitizer::with_policy_and_formatter(limits, Box::new(policy), Box::new(formatter))
        .unwrap()
}

/// Which finding the policy and the formatter fail on, the session limits,
/// and the chunks.
type FailureCase = (
    Option<&'static str>,
    Option<&'static str>,
    IncrementalLimits,
    Vec<String>,
);

#[test]
fn failures_and_callbacks_keep_the_unbatched_order() {
    let secret = |n: usize| format!("api_key=SYNTHETICq8vN3xR7tLm2Kp9W{n:02}\n");
    let many: String = (0..8).map(secret).collect();
    // Room for a few secret lines at a time, not for all of `many`.
    let tight = IncrementalLimits::new(1 << 20, 256, 64, 64).unwrap();
    assert!(many.len() > tight.max_buffered_bytes());
    let cases: Vec<FailureCase> = vec![
        // A formatter failure on the first finding comes before a policy
        // failure on the second, as when each line was processed alone.
        (
            Some("finding-2"),
            Some("finding-1"),
            limits(),
            vec![many.clone()],
        ),
        (Some("finding-4"), None, limits(), vec![many.clone()]),
        (None, Some("finding-5"), limits(), vec![many.clone()]),
        (None, None, limits(), vec![many.clone()]),
        // Closed lines are processed before a limit failure later in the
        // same chunk, so their callbacks run and their failure wins.
        (
            None,
            None,
            tight,
            vec![format!("{}{}", secret(0), "x".repeat(100))],
        ),
        (
            Some("finding-1"),
            None,
            tight,
            vec![format!("{}{}", secret(0), "x".repeat(100))],
        ),
        (
            None,
            Some("finding-2"),
            tight,
            vec![format!("{}{}{}", secret(0), secret(1), "y".repeat(100))],
        ),
        // A small buffer flushes the batch in the middle of a chunk.
        (None, None, tight, vec![many.clone()]),
        (Some("finding-3"), None, tight, vec![many]),
    ];
    for (policy, formatter, limits, chunks) in cases {
        let chunks: Vec<&str> = chunks.iter().map(String::as_str).collect();
        let expected_log = Rc::new(RefCell::new(Vec::new()));
        let expected = drive(
            unbatched(recording_session(policy, formatter, limits, &expected_log)),
            &chunks,
        );
        let actual_log = Rc::new(RefCell::new(Vec::new()));
        let actual = drive(
            recording_session(policy, formatter, limits, &actual_log),
            &chunks,
        );
        let label = format!("policy {policy:?}, formatter {formatter:?}, {limits:?}");
        assert_eq!(actual, expected, "{label}");
        assert_eq!(*actual_log.borrow(), *expected_log.borrow(), "{label}");
    }
}

/// Fails detection with an invalid candidate on `bad` lines only.
struct FailingOnLine;

impl Detector for FailingOnLine {
    fn id(&self) -> &'static str {
        "failing-on-line"
    }

    fn detect(
        &self,
        input: &str,
        _context: &DetectorContext,
    ) -> Result<Vec<Candidate>, DetectorFailure> {
        // A candidate whose text is its own type name is rejected as
        // malformed by the pipeline.
        Ok(input
            .match_indices("synthetic_bad")
            .filter_map(|(start, matched)| {
                ByteRange::new(start, start + matched.len())
                    .map(|range| Candidate::new("synthetic_bad", Confidence::High, range))
            })
            .collect())
    }
}

#[test]
fn a_detection_failure_in_a_batch_is_met_in_unit_order() {
    for fail_policy in [false, true] {
        let make = |log: &Rc<RefCell<Vec<String>>>| {
            let mut registry = DetectorRegistry::with_built_in([]).unwrap();
            registry.register(Box::new(FailingOnLine)).unwrap();
            let policy_log = Rc::clone(log);
            let policy = move |finding: &DetectedFinding, _: &IncrementalPolicyContext| {
                policy_log.borrow_mut().push(finding.id().to_owned());
                if fail_policy {
                    Err(PolicyFailure)
                } else {
                    Ok(Action::Redact)
                }
            };
            IncrementalSanitizer::from_registry(
                registry,
                limits(),
                Box::new(policy),
                Box::new(default_placeholder_formatter),
            )
        };
        let input = "api_key=SYNTHETICq8vN3xR7tLm2Kp9Wd\nplain\nsynthetic_bad\n";
        let expected_log = Rc::new(RefCell::new(Vec::new()));
        let expected = drive(unbatched(make(&expected_log)), &[input]);
        let actual_log = Rc::new(RefCell::new(Vec::new()));
        let actual = drive(make(&actual_log), &[input]);
        assert_eq!(actual, expected);
        assert_eq!(*actual_log.borrow(), *expected_log.borrow());
        let expected_code = if fail_policy {
            SecretScanErrorCode::PolicyFailure
        } else {
            SecretScanErrorCode::InvalidCandidate
        };
        assert_eq!(actual, Err(expected_code));
    }
}

#[test]
fn closed_lines_in_one_append_are_detected_together() {
    // Guards the tests above against a batch that silently falls back to
    // per-unit scanning: a plain multi-line chunk takes the batched path.
    let registry = DetectorRegistry::with_built_in([]).unwrap();
    let input = "first line\napi_key=SYNTHETICq8vN3xR7tLm2Kp9Wd\nlast line\n";
    let unit_ends = [11, 46, input.len()];
    let batched = detect_units(input, 0, &registry, &unit_ends, None).unwrap();
    assert_eq!(batched.map(|found| found.len()), Some(1));

    let mut sanitizer = full();
    sanitizer.append(input).unwrap();
    assert_eq!(sanitizer.batched_units, 3);
}

#[test]
fn the_lead_is_kept_in_front_of_the_batch_and_dropped_with_it() {
    // Issue #1060: the released line above the next unit is kept as the
    // first `lead_len` bytes of `retained`, so lead and batch scan as one
    // slice. It is dropped with the rest of the buffer on abort, and a CRLF
    // pair split across appends keeps the same line as the lead.
    let mut state: u64 = 0x1060;
    let mut filler = |alphabet: &[u8], length: usize| -> String {
        (0..length)
            .map(|_| {
                state = state
                    .wrapping_mul(6_364_136_223_846_793_005)
                    .wrapping_add(1_442_695_040_888_963_407);
                char::from(alphabet[usize::try_from(state >> 33).unwrap() % alphabet.len()])
            })
            .collect()
    };
    let id = format!("AKIA{}", filler(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", 16));
    let secret = filler(
        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        40,
    );
    let whole = crate::scan_and_redact(
        &format!("{id}\r\n{secret}\n"),
        &DetectorRegistry::with_built_in([]).unwrap(),
        &DefaultPolicy,
        &default_placeholder_formatter,
    )
    .unwrap();
    assert_eq!(whole.findings().len(), 2, "the ID and the secret below it");

    for chunks in [
        vec![format!("{id}\r"), "\n".to_string(), format!("{secret}\n")],
        vec![format!("{id}\r\n"), format!("{secret}\n")],
        vec![format!("{id}\r\n{secret}\n")],
    ] {
        let mut sanitizer = full();
        let mut text = String::new();
        let mut findings = Vec::new();
        for (index, chunk) in chunks.iter().enumerate() {
            let result = sanitizer.append(chunk).unwrap();
            text.push_str(result.text());
            findings.extend_from_slice(result.findings());
            if index + 1 < chunks.len() {
                assert!(sanitizer.lead_len > 0, "{chunks:?}");
                assert!(sanitizer.retained[..sanitizer.lead_len].starts_with(&id));
                assert_eq!(sanitizer.unit_start, sanitizer.lead_len);
            }
        }
        let result = sanitizer.finalize().unwrap();
        text.push_str(result.text());
        findings.extend_from_slice(result.findings());
        assert_eq!(
            (text.as_str(), findings.as_slice()),
            (whole.text(), whole.findings())
        );
    }

    let mut sanitizer = full();
    sanitizer.append(&format!("{id}\npartial")).unwrap();
    assert!(sanitizer.lead_len > 0);
    sanitizer.abort().unwrap();
    assert_eq!(sanitizer.retained.capacity(), 0);
    assert_eq!(sanitizer.lead_len, 0);
}

#[test]
fn closed_units_waiting_in_a_batch_never_outgrow_the_buffer_limit() {
    let limits = IncrementalLimits::new(1 << 20, 256, 64, 64).unwrap();
    let mut input = String::new();
    for n in 0..64 {
        writeln!(input, "line {n:02} api_key=SYNTHETICq8vN3xR7tLm2Kp{n:02}").unwrap();
    }
    let mut sanitizer = IncrementalSanitizer::new(limits).unwrap();
    sanitizer.append(&input).unwrap();
    assert!(sanitizer.batched_units > 1, "the chunk was batched");
    assert!(
        sanitizer.peak_retained <= limits.max_buffered_bytes(),
        "{} bytes retained",
        sanitizer.peak_retained,
    );
}