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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
//! PEM private-key delimiter parser.
//!
//! Complete, well-paired blocks require encoded body evidence. Nested,
//! repeated, or mismatched supported delimiters produce one conservative
//! candidate from the outermost header through resolution, or through end of
//! input when the delimiter stack never resolves. This prevents an inner
//! block from winning overlap resolution while surrounding key material is
//! left behind. A lone incomplete header is ignored so prose fragments are
//! not classified as a key. This mirrors `src/detectors/private-key.ts`
//! (`decision-govern-cross-language-conformance`).

use crate::detectors::prefilter::Literals;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};

const LABELS: [&str; 6] = [
    "PRIVATE KEY",
    "RSA PRIVATE KEY",
    "DSA PRIVATE KEY",
    "EC PRIVATE KEY",
    "OPENSSH PRIVATE KEY",
    "ENCRYPTED PRIVATE KEY",
];

#[derive(Clone, Copy, PartialEq, Eq)]
enum DelimiterKind {
    Begin,
    End,
}

struct Delimiter {
    start: usize,
    end: usize,
    kind: DelimiterKind,
    label: usize,
}

/// The start of every `BEGIN` delimiter [`find_next_delimiter`] accepts.
const DELIMITER_BEGIN: &str = "-----BEGIN ";
/// The start of every `END` delimiter [`find_next_delimiter`] accepts.
const DELIMITER_END: &str = "-----END ";

/// Bytes the dash-jumping probe examines before discovery switches to the
/// strided exact search (issue #1163).
const DELIMITER_PROBE_BYTES: usize = 8;
/// The run of dashes every delimiter starts with.
const DASH_RUN: &[u8] = b"-----";

/// The first offset at or after `from` where a run of five dashes starts.
///
/// Adaptive (issue #1163): the first [`DELIMITER_PROBE_BYTES`] bytes are
/// walked one at a time, which has no setup cost and so keeps
/// delimiter-dense input fast (an exact substring search is slower when the
/// next delimiter is a few bytes away); a probe that finds no run in that
/// window signals a sparse stretch, and the remainder is searched by
/// [`next_dash_run_strided`]. Both return the first run the earlier
/// dash-by-dash walk returned.
fn next_dash_run(bytes: &[u8], from: usize) -> Option<usize> {
    let rest = bytes.get(from..)?;
    let probe = &rest[..rest.len().min(DELIMITER_PROBE_BYTES)];
    for (offset, &byte) in probe.iter().enumerate() {
        if byte == b'-' && rest[offset..].starts_with(DASH_RUN) {
            return Some(from + offset);
        }
    }
    next_dash_run_strided(bytes, from + probe.len())
}

/// Exact search for the first run of five dashes at or after `from`, reading
/// every fifth byte. Any five consecutive bytes contain exactly one sampled
/// offset, so a run of five dashes contains a sampled dash; the run is then
/// extended left (never before `from`) and right to its full length.
fn next_dash_run_strided(bytes: &[u8], from: usize) -> Option<usize> {
    let mut sample = from.checked_add(DASH_RUN.len() - 1)?;
    while sample < bytes.len() {
        if bytes[sample] == b'-' {
            let mut start = sample;
            while start > from && bytes[start - 1] == b'-' {
                start -= 1;
            }
            let mut end = sample + 1;
            while end < bytes.len() && bytes[end] == b'-' {
                end += 1;
            }
            if end - start >= DASH_RUN.len() {
                return Some(start);
            }
        }
        sample += DASH_RUN.len();
    }
    None
}

/// Finds the next `-----BEGIN <label>-----` / `-----END <label>-----`
/// delimiter at or after `from`. `label` is an index into [`LABELS`].
fn find_next_delimiter(input: &str, from: usize) -> Option<Delimiter> {
    let bytes = input.as_bytes();
    let mut position = from;
    // Every delimiter starts with `-----`: jump between those runs.
    while let Some(start) = next_dash_run(bytes, position) {
        position = start;
        for (kind, lead) in [
            (DelimiterKind::Begin, DELIMITER_BEGIN),
            (DelimiterKind::End, DELIMITER_END),
        ] {
            if bytes[position..].starts_with(lead.as_bytes()) {
                let label_start = position + lead.len();
                for (label, name) in LABELS.iter().enumerate() {
                    let label_end = label_start + name.len();
                    let suffix_end = label_end + 5;
                    if suffix_end <= bytes.len()
                        && bytes[label_start..label_end] == *name.as_bytes()
                        && bytes[label_end..suffix_end] == *b"-----"
                    {
                        return Some(Delimiter {
                            start: position,
                            end: suffix_end,
                            kind,
                            label,
                        });
                    }
                }
            }
        }
        position += 1;
    }
    None
}

/// Delimiter-stack state carried across a full scan of the input.
struct ParserState {
    stack: Vec<usize>,
    /// `true` once any `BEGIN` delimiter has been seen. Unused by
    /// [`PrivateKeyDetector::detect`], which discards its state after one
    /// scan; read by [`PrivateKeyRetentionTracker`] to decide whether
    /// retained plaintext is bound by the multiline limit instead of the
    /// token limit.
    has_begin: bool,
    malformed: bool,
    outer_start: Option<usize>,
    outer_body_start: Option<usize>,
}

impl ParserState {
    const fn new() -> Self {
        Self {
            stack: Vec::new(),
            has_begin: false,
            malformed: false,
            outer_start: None,
            outer_body_start: None,
        }
    }
}

struct CompletedSpan {
    start: usize,
    body_start: usize,
    footer_start: usize,
    end: usize,
    malformed: bool,
}

/// Advances `state` past one delimiter, returning the completed span once the
/// stack unwinds back to empty.
fn process_delimiter(state: &mut ParserState, delimiter: &Delimiter) -> Option<CompletedSpan> {
    if delimiter.kind == DelimiterKind::Begin {
        state.has_begin = true;
        if state.stack.is_empty() {
            state.outer_start = Some(delimiter.start);
            state.outer_body_start = Some(delimiter.end);
        } else {
            state.malformed = true;
        }
        state.stack.push(delimiter.label);
        return None;
    }

    let &top = state.stack.last()?;
    if top != delimiter.label {
        state.malformed = true;
        return None;
    }
    state.stack.pop();
    if !state.stack.is_empty() {
        return None;
    }

    let start = state.outer_start?;
    let body_start = state.outer_body_start?;
    let completed = CompletedSpan {
        start,
        body_start,
        footer_start: delimiter.start,
        end: delimiter.end,
        malformed: state.malformed,
    };
    state.malformed = false;
    state.outer_start = None;
    state.outer_body_start = None;
    Some(completed)
}

/// `true` when `input[start..end]` (with CR and LF ignored) contains a run of
/// at least 16 consecutive base64-alphabet bytes.
fn has_encoded_body(input: &str, start: usize, end: usize) -> bool {
    let mut run_length = 0u32;
    for &byte in &input.as_bytes()[start..end] {
        if byte == b'\n' || byte == b'\r' {
            continue;
        }
        if byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/' {
            run_length += 1;
            if run_length >= 16 {
                return true;
            }
        } else {
            run_length = 0;
        }
    }
    false
}

/// Builds the candidate for a span, or `None` when `start == end` (never the
/// case for a delimiter-bounded span, but the pipeline validates ranges
/// rather than this detector trusting its own arithmetic).
fn candidate(start: usize, end: usize, malformed: bool) -> Option<Candidate> {
    let range = ByteRange::new(start, end)?;
    let signals: [&str; 2] = if malformed {
        ["pem-boundaries", "malformed-delimiters"]
    } else {
        ["pem-boundaries", "encoded-body"]
    };
    Some(
        Candidate::built_in("private_key", Confidence::High, range)
            .with_specificity(Specificity::PrivateKey)
            .with_signals(signals),
    )
}

/// `"-----BEGIN ".len() + longest label + "-----".len()"`: the longest
/// possible supported delimiter.
const fn max_label_len() -> usize {
    let mut max = 0;
    let mut index = 0;
    while index < LABELS.len() {
        let len = LABELS[index].len();
        if len > max {
            max = len;
        }
        index += 1;
    }
    max
}

const MAX_DELIMITER_LEN: usize = "-----BEGIN ".len() + max_label_len() + "-----".len();

/// The longest suffix of `input` that is at most `max_bytes` long and starts
/// on a UTF-8 character boundary. The returned suffix may be shorter than
/// `max_bytes` when the exact cut point falls inside a multi-byte character;
/// every supported delimiter is pure ASCII, so trimming a little further
/// into an unrelated character never drops part of a delimiter.
fn byte_suffix(input: &str, max_bytes: usize) -> &str {
    if input.len() <= max_bytes {
        return input;
    }
    let mut start = input.len() - max_bytes;
    while !input.is_char_boundary(start) {
        start += 1;
    }
    &input[start..]
}

/// How many leading bytes of `piece` a delimiter that starts in the
/// lookbehind can reach into, rounded up to a character boundary.
fn junction_head_len(piece: &str) -> usize {
    let mut head = piece.len().min(MAX_DELIMITER_LEN - 1);
    while !piece.is_char_boundary(head) {
        head += 1;
    }
    head
}

/// Scans `input` from `from` for delimiters, advancing `state` and reporting
/// completed spans, while skipping any delimiter already accounted for by
/// `processed_bytes` (one already scanned in an earlier call whose text was
/// carried forward only as lookbehind). `input_offset` converts positions
/// local to `input` to positions absolute in the logical session input.
/// Returns where the search ended: the end of the last delimiter found
/// (skipped ones included), or `from` when it found none.
fn scan_delimiters(
    input: &str,
    from: usize,
    state: &mut ParserState,
    processed_bytes: usize,
    input_offset: usize,
    mut on_complete: impl FnMut(CompletedSpan),
) -> usize {
    let mut position = from;
    while let Some(delimiter) = find_next_delimiter(input, position) {
        position = delimiter.end;
        let absolute_end = input_offset + delimiter.end;
        if absolute_end <= processed_bytes {
            continue;
        }
        let absolute = Delimiter {
            start: input_offset + delimiter.start,
            end: absolute_end,
            kind: delimiter.kind,
            label: delimiter.label,
        };
        if let Some(span) = process_delimiter(state, &absolute) {
            on_complete(span);
        }
    }
    position
}

/// Tracks the supported PEM delimiter grammar incrementally for the
/// built-in incremental scanner. Each [`append`](Self::append) rescans only
/// a bounded lookbehind window plus the newly appended text, so chunk
/// boundaries and repeated headers never cause previously retained prefixes
/// to be rescanned. Mirrors `createPrivateKeyRetentionTracker` in
/// `src/detectors/private-key.ts` (`decision-govern-cross-language-conformance`).
pub(crate) struct PrivateKeyRetentionTracker {
    state: ParserState,
    processed_bytes: usize,
    lookbehind: String,
}

impl PrivateKeyRetentionTracker {
    /// Creates a tracker with no retained state.
    pub(crate) const fn new() -> Self {
        Self {
            state: ParserState::new(),
            processed_bytes: 0,
            lookbehind: String::new(),
        }
    }

    /// Advances past `piece`. Returns `(has_begin, has_open)`: whether any
    /// `BEGIN` delimiter has been seen since the last [`reset`](Self::reset),
    /// and whether a block is currently open (an unresolved `BEGIN` remains
    /// on the delimiter stack).
    ///
    /// The first piece after a [`reset`](Self::reset), which is every piece
    /// of a unit that arrives as one line, is scanned in place: with no
    /// lookbehind there is nothing to join it to. `lookbehind` only ever
    /// holds a bounded delimiter suffix, and its allocation is reused for the
    /// next one instead of reallocated (issue #1060).
    pub(crate) fn append(&mut self, piece: &str) -> (bool, bool) {
        self.append_reporting(piece, |_| {})
    }

    /// [`append`](Self::append), also reporting every span it completes.
    fn append_reporting(
        &mut self,
        piece: &str,
        mut on_complete: impl FnMut(CompletedSpan),
    ) -> (bool, bool) {
        let lookbehind_len = self.lookbehind.len();
        if lookbehind_len == 0 {
            // Nothing to join the piece to: scan it in place.
            scan_delimiters(
                piece,
                0,
                &mut self.state,
                self.processed_bytes,
                self.processed_bytes,
                on_complete,
            );
            self.processed_bytes += piece.len();
            self.set_lookbehind_from(piece);
            return (self.state.has_begin, !self.state.stack.is_empty());
        }

        // Only a delimiter that starts in the lookbehind can cross into the
        // piece, and it is at most `MAX_DELIMITER_LEN - 1` bytes into it. So
        // the junction, the lookbehind and that head of the piece, is
        // scanned joined, in the lookbehind's own allocation, and the rest
        // of the piece in place, from where the junction scan stopped.
        // A delimiter is matched by its own bytes alone, so this finds
        // exactly the delimiters, in the order, of scanning the whole join
        // (issue #1087).
        let head = junction_head_len(piece);
        self.lookbehind.push_str(&piece[..head]);
        let resume = scan_delimiters(
            &self.lookbehind,
            0,
            &mut self.state,
            self.processed_bytes,
            self.processed_bytes - lookbehind_len,
            &mut on_complete,
        );
        if head < piece.len() {
            scan_delimiters(
                piece,
                resume.saturating_sub(lookbehind_len),
                &mut self.state,
                self.processed_bytes,
                self.processed_bytes,
                on_complete,
            );
            self.lookbehind.clear();
            self.processed_bytes += piece.len();
            self.set_lookbehind_from(piece);
        } else {
            // The join is the whole input: its delimiter-bearing suffix is
            // the next lookbehind, trimmed in place.
            self.processed_bytes += piece.len();
            let keep = byte_suffix(&self.lookbehind, MAX_DELIMITER_LEN.saturating_sub(1));
            let from = self.lookbehind.len() - keep.len();
            let from = from + keep.find('-').unwrap_or(keep.len());
            self.lookbehind.drain(..from);
        }
        (self.state.has_begin, !self.state.stack.is_empty())
    }

    /// Replaces the lookbehind with the delimiter-bearing suffix of `input`,
    /// reusing its allocation. Every delimiter starts with `-`, so nothing
    /// before the suffix's first dash can be part of one; `input_offset`
    /// stays `processed_bytes - lookbehind.len()` (issue #1074).
    fn set_lookbehind_from(&mut self, input: &str) {
        let suffix = byte_suffix(input, MAX_DELIMITER_LEN.saturating_sub(1));
        let suffix = suffix.find('-').map_or("", |dash| &suffix[dash..]);
        self.lookbehind.clear();
        self.lookbehind.push_str(suffix);
    }

    /// Discards all retained parser state.
    pub(crate) fn reset(&mut self) {
        *self = Self::new();
    }
}

/// Recognizes complete and fail-safe malformed PEM private-key blocks.
pub struct PrivateKeyDetector;

impl Detector for PrivateKeyDetector {
    fn id(&self) -> &'static str {
        "private-key"
    }

    fn detect(
        &self,
        input: &str,
        _context: &DetectorContext,
    ) -> Result<Vec<Candidate>, DetectorFailure> {
        let mut candidates = Vec::new();
        let mut state = ParserState::new();
        let mut position = 0;

        while let Some(delimiter) = find_next_delimiter(input, position) {
            position = delimiter.end;
            if let Some(span) = process_delimiter(&mut state, &delimiter)
                && (span.malformed || has_encoded_body(input, span.body_start, span.footer_start))
                && let Some(found) = candidate(span.start, span.end, span.malformed)
            {
                candidates.push(found);
            }
        }

        if !state.stack.is_empty()
            && state.malformed
            && let Some(start) = state.outer_start
            && start < input.len()
            && let Some(found) = candidate(start, input.len(), true)
        {
            candidates.push(found);
        }

        Ok(candidates)
    }
}

/// The literals one of which every private-key candidate contains, for the
/// shared prefilter (`super::prefilter`, issue #983).
///
/// Every candidate span comes from a `-----BEGIN <label>-----` or
/// `-----END <label>-----` delimiter [`find_next_delimiter`] found.
pub(super) const REQUIRED_LITERALS: &[Literals] =
    &[Literals::Strs(&[DELIMITER_BEGIN, DELIMITER_END])];

#[cfg(test)]
mod tests {
    use super::*;

    fn detect(input: &str) -> Vec<Candidate> {
        PrivateKeyDetector
            .detect(input, &DetectorContext::new(input.len()))
            .unwrap()
    }

    fn spans(candidates: &[Candidate]) -> Vec<(usize, usize)> {
        candidates
            .iter()
            .map(|c| (c.range().start(), c.range().end()))
            .collect()
    }

    fn block(label: &str) -> String {
        format!(
            "-----BEGIN {label}-----\nU1lOVEhFVElDX1JFVk9LRURfRklYVFVSRQ==\n-----END {label}-----"
        )
    }

    #[test]
    fn detects_a_complete_block_with_encoded_body() {
        let input = block("PRIVATE KEY");
        let found = detect(&input);
        assert_eq!(spans(&found), [(0, input.len())]);
        assert_eq!(found[0].type_name(), "private_key");
        assert_eq!(found[0].confidence(), Confidence::High);
        assert_eq!(found[0].effective_specificity(), Specificity::PrivateKey);
    }

    #[test]
    fn every_supported_label_is_recognized() {
        for label in LABELS {
            let input = block(label);
            assert_eq!(spans(&detect(&input)), [(0, input.len())], "{label}");
        }
    }

    #[test]
    fn rejects_public_key_and_unsupported_labels() {
        for input in [
            "-----BEGIN PUBLIC KEY-----",
            "-----BEGIN CERTIFICATE-----\nU1lOVEhFVElDX1JFVk9LRURfQ0VSVA==\n-----END CERTIFICATE-----",
            "----BEGIN PRIVATE KEY-----\nU1lOVEhFVElDX1JFVk9LRURfTk8=\n-----END PRIVATE KEY-----",
            "-----BEGIN PRIVATE KEYS-----\nU1lOVEhFVElDX1JFVk9LRURfTk8=\n-----END PRIVATE KEYS-----",
        ] {
            assert_eq!(detect(input), Vec::new(), "{input}");
        }
    }

    #[test]
    fn ignores_a_lone_incomplete_header() {
        assert_eq!(
            detect("-----BEGIN PRIVATE KEY-----\nSYNTHETIC_TRUNCATED"),
            Vec::new()
        );
    }

    #[test]
    fn rejects_a_complete_pair_without_enough_encoded_body() {
        assert_eq!(
            detect("-----BEGIN PRIVATE KEY-----\nSHORT\n-----END PRIVATE KEY-----"),
            Vec::new()
        );
    }

    #[test]
    fn returns_separate_spans_for_adjacent_complete_blocks() {
        let first = block("PRIVATE KEY");
        let second = block("EC PRIVATE KEY");
        let input = format!("{first}\n{second}");
        assert_eq!(
            spans(&detect(&input)),
            [(0, first.len()), (first.len() + 1, input.len())]
        );
    }

    #[test]
    fn blocks_one_outer_span_for_properly_nested_delimiters() {
        let input = [
            "-----BEGIN RSA PRIVATE KEY-----",
            "U1lOVEhFVElDX1JFVk9LRURfT1VURVI=",
            "-----BEGIN EC PRIVATE KEY-----",
            "U1lOVEhFVElDX1JFVk9LRURfSU5ORVI=",
            "-----END EC PRIVATE KEY-----",
            "-----END RSA PRIVATE KEY-----",
        ]
        .join("\n");
        let found = detect(&input);
        assert_eq!(spans(&found), [(0, input.len())]);
        assert_eq!(
            found[0].signals(),
            ["pem-boundaries", "malformed-delimiters"]
        );
    }

    #[test]
    fn blocks_unresolved_repeated_or_mismatched_delimiters_to_end_of_input() {
        let fixtures = [
            [
                "-----BEGIN PRIVATE KEY-----",
                "SYNTHETIC_REVOKED_OUTER_BODY",
                "-----BEGIN PRIVATE KEY-----",
                "SYNTHETIC_REVOKED_INNER_BODY",
            ]
            .join("\n"),
            [
                "-----BEGIN RSA PRIVATE KEY-----",
                "SYNTHETIC_REVOKED_MISMATCHED_BODY",
                "-----END EC PRIVATE KEY-----",
                "ordinary trailing text",
            ]
            .join("\n"),
            [
                "-----BEGIN RSA PRIVATE KEY-----",
                "-----BEGIN EC PRIVATE KEY-----",
                "-----END RSA PRIVATE KEY-----",
                "SYNTHETIC_REVOKED_TRAILING_INNER_BODY",
                "-----END EC PRIVATE KEY-----",
            ]
            .join("\n"),
        ];

        for input in fixtures {
            assert_eq!(spans(&detect(&input)), [(0, input.len())], "{input}");
        }
    }

    #[test]
    fn handles_many_unmatched_headers_in_bounded_time() {
        let input = "-----BEGIN PRIVATE KEY-----\n".repeat(10_000);
        let found = detect(&input);
        assert_eq!(spans(&found), [(0, input.len())]);
    }

    #[test]
    fn finds_one_full_span_for_a_large_complete_block() {
        let input = format!(
            "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----",
            "U1lOVEhFVElDX1JFVk9LRURfQk9EWQ==".repeat(32_000)
        );
        assert_eq!(spans(&detect(&input)), [(0, input.len())]);
    }

    #[test]
    fn long_missing_footer_terminates_without_a_finding() {
        let input = format!("-----BEGIN PRIVATE KEY-----\n{}", "A".repeat(100_000));
        assert_eq!(detect(&input), Vec::new());
    }

    #[test]
    fn id_is_stable() {
        assert_eq!(PrivateKeyDetector.id(), "private-key");
    }

    #[test]
    fn retention_tracker_reports_open_only_between_begin_and_end() {
        let mut tracker = PrivateKeyRetentionTracker::new();
        assert_eq!(tracker.append("no header here\n"), (false, false));
        assert_eq!(
            tracker.append("-----BEGIN PRIVATE KEY-----\n"),
            (true, true)
        );
        assert_eq!(tracker.append("U1lOVEhFVElDX1JFVk9LRUQ=\n"), (true, true));
        assert_eq!(tracker.append("-----END PRIVATE KEY-----"), (true, false));
    }

    #[test]
    fn retention_tracker_detects_a_delimiter_split_across_appended_pieces() {
        let mut tracker = PrivateKeyRetentionTracker::new();
        let whole = "-----BEGIN PRIVATE KEY-----";
        let split = whole.len() / 2;
        assert_eq!(tracker.append(&whole[..split]), (false, false));
        assert_eq!(tracker.append(&whole[split..]), (true, true));
    }

    #[test]
    fn retention_tracker_reset_discards_state() {
        let mut tracker = PrivateKeyRetentionTracker::new();
        tracker.append("-----BEGIN PRIVATE KEY-----\n");
        tracker.reset();
        assert_eq!(tracker.append("ordinary text"), (false, false));
    }

    #[test]
    fn retention_tracker_does_not_reprocess_a_delimiter_carried_in_the_lookbehind() {
        // The lookbehind window is at most MAX_DELIMITER_LEN - 1 bytes, so a
        // short first piece is carried forward whole; appending more text
        // must not re-trigger `has_begin`/`has_open` bookkeeping for the same
        // delimiter twice in a way that would misreport state.
        let mut tracker = PrivateKeyRetentionTracker::new();
        assert_eq!(tracker.append("-----BEGIN PRIVATE KEY-----"), (true, true));
        assert_eq!(tracker.append("\nbody\n"), (true, true));
        assert_eq!(tracker.append("-----END PRIVATE KEY-----"), (true, false));
    }

    /// The scan-every-byte form of [`find_next_delimiter`] before #1074.
    fn oracle_find_next_delimiter(input: &str, from: usize) -> Option<Delimiter> {
        let bytes = input.as_bytes();
        let mut position = from;
        while position + 5 <= bytes.len() {
            if &bytes[position..position + 5] == b"-----" {
                for (kind, lead) in [
                    (DelimiterKind::Begin, DELIMITER_BEGIN),
                    (DelimiterKind::End, DELIMITER_END),
                ] {
                    if bytes[position..].starts_with(lead.as_bytes()) {
                        let label_start = position + lead.len();
                        for (label, name) in LABELS.iter().enumerate() {
                            let label_end = label_start + name.len();
                            let suffix_end = label_end + 5;
                            if suffix_end <= bytes.len()
                                && bytes[label_start..label_end] == *name.as_bytes()
                                && bytes[label_end..suffix_end] == *b"-----"
                            {
                                return Some(Delimiter {
                                    start: position,
                                    end: suffix_end,
                                    kind,
                                    label,
                                });
                            }
                        }
                    }
                }
            }
            position += 1;
        }
        None
    }

    /// The dash-jumping five-dash discovery before #1163.
    fn oracle_dash_jump_run(bytes: &[u8], from: usize) -> Option<usize> {
        let mut position = from;
        while let Some(offset) = bytes.get(position..)?.iter().position(|&byte| byte == b'-') {
            position += offset;
            if position + 5 > bytes.len() {
                return None;
            }
            if &bytes[position..position + 5] == b"-----" {
                return Some(position);
            }
            position += 1;
        }
        None
    }

    fn key_tuple(delimiter: Option<Delimiter>) -> Option<(usize, usize, usize, bool)> {
        delimiter.map(|d| (d.start, d.end, d.label, d.kind == DelimiterKind::Begin))
    }

    #[test]
    fn adaptive_discovery_matches_the_earlier_walks_across_the_probe_window() {
        const PIECES: &[&str] = &[
            "-----BEGIN PRIVATE KEY-----",
            "-----END RSA PRIVATE KEY-----",
            "-----BEGIN PUBLIC KEY-----",
            "------BEGIN PRIVATE KEY------",
            "-----",
            "----",
            "-",
            "--",
            "-a-b-",
            "\n",
            "\u{e9}",
            "\u{1f511}",
            "\u{ac00}-\u{ac01}",
        ];
        let mut state = 0xD1B5_4A32_D192_ED03u64;
        let mut next = move |bound: usize| {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            usize::try_from(state % u64::try_from(bound).unwrap()).unwrap()
        };
        let mut found = 0;
        for round in 0..3_000 {
            let mut text = String::new();
            for _ in 0..next(10) {
                // Gaps straddle the probe window in both directions.
                text.push_str(&"x".repeat(match round % 4 {
                    0 => next(3),
                    1 => DELIMITER_PROBE_BYTES - 3 + next(7),
                    2 => next(300),
                    _ => 2 * DELIMITER_PROBE_BYTES + next(5),
                }));
                text.push_str(PIECES[next(PIECES.len())]);
            }
            text.push_str(&"y".repeat(next(100)));
            let stride = 1 + text.len() / 60;
            for from in (0..=text.len() + 2).step_by(stride) {
                // `from` need not be a character boundary: discovery is on bytes.
                let new = find_next_delimiter(&text, from);
                let old = oracle_find_next_delimiter(&text, from);
                found += usize::from(new.is_some());
                assert_eq!(key_tuple(new), key_tuple(old), "{text:?} {from}");
                assert_eq!(
                    next_dash_run(text.as_bytes(), from),
                    oracle_dash_jump_run(text.as_bytes(), from),
                    "{text:?} {from}"
                );
            }
        }
        assert!(found > 2_000);
    }

    #[test]
    fn strided_search_matches_the_dash_jump_walk_for_every_run_length_offset_and_start() {
        // Runs of 1..=12 dashes at every offset of a short text, searched from
        // every start, so each phase of the every-fifth-byte sampling and
        // each way a run can straddle a sample is covered.
        for run in 1..=12 {
            for at in 0..=30 {
                let mut bytes = vec![b'x'; 40];
                for byte in bytes.iter_mut().skip(at).take(run) {
                    *byte = b'-';
                }
                // A second, shorter run to find after the first.
                bytes[36] = b'-';
                for from in 0..=bytes.len() + 1 {
                    let expected = oracle_dash_jump_run(&bytes, from);
                    assert_eq!(
                        next_dash_run_strided(&bytes, from),
                        expected,
                        "run {run} at {at} from {from}"
                    );
                    assert_eq!(
                        next_dash_run(&bytes, from),
                        expected,
                        "run {run} at {at} from {from}"
                    );
                }
            }
        }
    }

    #[test]
    fn adaptive_discovery_lists_the_same_delimiters_on_sparse_dense_and_noisy_inputs() {
        let sparse = format!(
            "{}-----BEGIN PRIVATE KEY-----\nU1lOVEhFVElDX1JFVk9LRUQ=\n-----END PRIVATE KEY-----\n{}",
            "lorem ipsum ".repeat(900),
            "dolor \u{ac00} sit ".repeat(500)
        );
        let dense =
            "-----BEGIN PRIVATE KEY-----\nU1lOVEhFVElDX1JFVk9LRUQ=\n-----END PRIVATE KEY-----\n"
                .repeat(300);
        let noise = "a-b -- --- ---- c".repeat(2_000);
        let near = "-----BEGIN PUBLIC KEY-----\nAAAA\n-----END PUBLIC KEY-----\n".repeat(200);
        let nested = format!("{dense}-----BEGIN RSA PRIVATE KEY-----\n{sparse}");
        let unterminated = format!("{sparse}-----BEGIN PRIVATE KEY-----\n{}", "A".repeat(500));
        for text in [sparse, dense, noise, near, nested, unterminated] {
            let (mut new, mut old) = (Vec::new(), Vec::new());
            let mut position = 0;
            while let Some(d) = find_next_delimiter(&text, position) {
                position = d.end;
                new.push(key_tuple(Some(d)));
            }
            position = 0;
            while let Some(d) = oracle_find_next_delimiter(&text, position) {
                position = d.end;
                old.push(key_tuple(Some(d)));
            }
            assert_eq!(new, old);
        }
    }

    /// The tracker before #1074: lookbehind is the untrimmed byte suffix.
    struct OracleTracker {
        state: ParserState,
        processed_bytes: usize,
        lookbehind: String,
    }

    impl OracleTracker {
        fn append(&mut self, piece: &str, spans: &mut Vec<(usize, usize)>) -> (bool, bool) {
            let input = [self.lookbehind.as_str(), piece].concat();
            let input_offset = self.processed_bytes - self.lookbehind.len();
            let mut found = |span: CompletedSpan| spans.push((span.start, span.end));
            let mut position = 0;
            while let Some(delimiter) = oracle_find_next_delimiter(&input, position) {
                position = delimiter.end;
                let absolute_end = input_offset + delimiter.end;
                if absolute_end <= self.processed_bytes {
                    continue;
                }
                let absolute = Delimiter {
                    start: input_offset + delimiter.start,
                    end: absolute_end,
                    kind: delimiter.kind,
                    label: delimiter.label,
                };
                if let Some(span) = process_delimiter(&mut self.state, &absolute) {
                    found(span);
                }
            }
            self.processed_bytes += piece.len();
            self.lookbehind = byte_suffix(&input, MAX_DELIMITER_LEN - 1).to_owned();
            (self.state.has_begin, !self.state.stack.is_empty())
        }
    }

    #[test]
    fn dash_jumping_delimiter_search_and_trimmed_lookbehind_match_the_oracles() {
        const PARTS: &[&str] = &[
            "-----BEGIN PRIVATE KEY-----",
            "-----END PRIVATE KEY-----",
            "-----BEGIN RSA PRIVATE KEY-----",
            "-----END RSA PRIVATE KEY-----",
            "-----BEGIN ",
            "-----END ",
            "-----",
            "----",
            "-",
            "--",
            "PRIVATE KEY",
            "ENCRYPTED PRIVATE KEY",
            "\n",
            "\r\n",
            "body",
            " ",
            "\u{e9}",
            "\u{1f511}",
        ];
        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut next = move |bound: usize| {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            usize::try_from(state % u64::try_from(bound).unwrap()).unwrap()
        };
        for _ in 0..4_000 {
            let mut text = String::new();
            for _ in 0..next(14) {
                text.push_str(PARTS[next(PARTS.len())]);
            }
            for from in 0..=text.len().min(40) {
                if text.is_char_boundary(from) {
                    let new = find_next_delimiter(&text, from);
                    let old = oracle_find_next_delimiter(&text, from);
                    assert_eq!(
                        new.map(|d| (d.start, d.end, d.label)),
                        old.map(|d| (d.start, d.end, d.label)),
                        "{text:?} {from}"
                    );
                }
            }
            // Random chunking, per char boundary.
            let mut tracker = PrivateKeyRetentionTracker::new();
            let mut oracle = OracleTracker {
                state: ParserState::new(),
                processed_bytes: 0,
                lookbehind: String::new(),
            };
            let (mut new_spans, mut old_spans) = (Vec::new(), Vec::new());
            let mut rest = text.as_str();
            while !rest.is_empty() {
                let mut cut = (1 + next(30)).min(rest.len());
                while !rest.is_char_boundary(cut) {
                    cut += 1;
                }
                let (piece, tail) = rest.split_at(cut);
                let got = tracker.append_reporting(piece, |span| {
                    new_spans.push((span.start, span.end));
                });
                assert_eq!(got, oracle.append(piece, &mut old_spans), "{text:?}");
                assert_eq!(new_spans, old_spans, "{text:?}");
                assert!(tracker.lookbehind.is_empty() || tracker.lookbehind.starts_with('-'));
                rest = tail;
            }
        }
    }

    /// The tracker before #1087: the whole piece is joined to the lookbehind
    /// and the join scanned, then trimmed the same way.
    struct JoinTracker {
        state: ParserState,
        processed_bytes: usize,
        lookbehind: String,
    }

    impl JoinTracker {
        fn new() -> Self {
            Self {
                state: ParserState::new(),
                processed_bytes: 0,
                lookbehind: String::new(),
            }
        }

        fn append(&mut self, piece: &str, spans: &mut Vec<(usize, usize)>) -> (bool, bool) {
            let joined = [self.lookbehind.as_str(), piece].concat();
            let input_offset = self.processed_bytes - self.lookbehind.len();
            scan_delimiters(
                &joined,
                0,
                &mut self.state,
                self.processed_bytes,
                input_offset,
                |span| spans.push((span.start, span.end)),
            );
            self.processed_bytes += piece.len();
            let suffix = byte_suffix(&joined, MAX_DELIMITER_LEN.saturating_sub(1));
            let suffix = suffix.find('-').map_or("", |dash| &suffix[dash..]);
            self.lookbehind = suffix.to_owned();
            (self.state.has_begin, !self.state.stack.is_empty())
        }
    }

    fn assert_chunks_match_the_join_oracle(pieces: &[&str]) {
        let mut tracker = PrivateKeyRetentionTracker::new();
        let mut oracle = JoinTracker::new();
        let (mut new_spans, mut old_spans) = (Vec::new(), Vec::new());
        for piece in pieces {
            let got = tracker.append_reporting(piece, |span| {
                new_spans.push((span.start, span.end));
            });
            assert_eq!(got, oracle.append(piece, &mut old_spans), "{pieces:?}");
            assert_eq!(new_spans, old_spans, "{pieces:?}");
            assert_eq!(tracker.lookbehind, oracle.lookbehind, "{pieces:?}");
            assert_eq!(tracker.processed_bytes, oracle.processed_bytes);
        }
    }

    #[test]
    fn junction_scan_matches_the_whole_join_at_every_split_of_delimiters() {
        let texts = [
            "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n",
            "x-----BEGIN ENCRYPTED PRIVATE KEY-----\r\nAAAA\r\n-----END ENCRYPTED PRIVATE KEY-----",
            "\u{e9}-----BEGIN RSA PRIVATE KEY-----\u{1f511}-----END RSA PRIVATE KEY-----\u{e9}",
            "-----BEGIN PRIVATE KEY-----BEGIN PRIVATE KEY-----END PRIVATE KEY-----END PRIVATE KEY-----",
            "------BEGIN PRIVATE KEY------END PRIVATE KEY-----\n-----BEGIN EC PRIVATE KEY-----",
        ];
        for text in texts {
            let cuts: Vec<usize> = (0..=text.len())
                .filter(|&at| text.is_char_boundary(at))
                .collect();
            for &first in &cuts {
                assert_chunks_match_the_join_oracle(&[&text[..first], &text[first..]]);
                for &second in cuts.iter().filter(|&&at| at >= first) {
                    // A long middle piece crosses the junction head bound.
                    assert_chunks_match_the_join_oracle(&[
                        &text[..first],
                        &text[first..second],
                        &text[second..],
                    ]);
                }
            }
            // Pieces of one byte up to beyond the junction head.
            for size in [1, 2, 7, 35, 36, 37, 38, 40, 90] {
                let mut pieces = Vec::new();
                let mut rest = text;
                while !rest.is_empty() {
                    let mut cut = size.min(rest.len());
                    while !rest.is_char_boundary(cut) {
                        cut += 1;
                    }
                    let (piece, tail) = rest.split_at(cut);
                    pieces.push(piece);
                    rest = tail;
                }
                assert_chunks_match_the_join_oracle(&pieces);
            }
        }
    }

    #[test]
    fn junction_scan_matches_the_whole_join_on_random_chunks() {
        const PARTS: &[&str] = &[
            "-----BEGIN PRIVATE KEY-----",
            "-----END PRIVATE KEY-----",
            "-----BEGIN ENCRYPTED PRIVATE KEY-----",
            "-----END ENCRYPTED PRIVATE KEY-----",
            "-----BEGIN ",
            "-----END ",
            "-----",
            "----",
            "-",
            "PRIVATE KEY",
            "\n",
            "\r\n",
            "body",
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
            " ",
            "\u{e9}",
            "\u{1f511}",
        ];
        let mut state = 0x2545_F491_4F6C_DD1Du64;
        let mut next = move |bound: usize| {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            usize::try_from(state % u64::try_from(bound).unwrap()).unwrap()
        };
        for _ in 0..4_000 {
            let mut text = String::new();
            for _ in 0..next(16) {
                text.push_str(PARTS[next(PARTS.len())]);
            }
            let mut pieces = Vec::new();
            let mut rest = text.as_str();
            while !rest.is_empty() {
                let mut cut = (1 + next(120)).min(rest.len());
                while !rest.is_char_boundary(cut) {
                    cut += 1;
                }
                let (piece, tail) = rest.split_at(cut);
                pieces.push(piece);
                rest = tail;
            }
            assert_chunks_match_the_join_oracle(&pieces);
        }
    }
}