eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! Finding secrets in a string and replacing them with a marker that says what was there.
//!
//! This is the matching half of the `redact-secrets` hook ([`crate::hooks`]); it is a pure
//! function over text, so it can be tested without a loop, a config or a store.
//!
//! # Hand-written, high precision first
//!
//! There is no regex engine here, on purpose: every dependency is a thing to audit, and the
//! shapes below are all "a literal prefix, then a run of characters from a small set". Each
//! one is cheap to scan for and cheap to reason about. The trade is made explicit:
//!
//! - A pattern with a *distinctive prefix* (`sk-`, `ghp_`, `AKIA`, a PEM header) fires on the
//!   prefix and a minimum length. A near-miss — one character short, a word that merely
//!   contains the prefix — is left alone, because a false positive mangles a file the user
//!   asked to read.
//! - The *assignment* pattern (`password = …`) has no distinctive prefix, so it is the one
//!   that can over-match: `token = refresh_access_token_now` looks like a secret to a scanner
//!   that has no idea what a variable is. It is kept because `API_TOKEN=…` in an `.env` is the
//!   commonest way a real secret reaches a prompt; `allow` is the escape hatch.
//!
//! # Properties that are tested
//!
//! - **Idempotent.** Redacting redacted text changes nothing. A marker never contains a run
//!   the scanner would take for a secret, and the text before and after a marker is judged the
//!   same way both times.
//! - **A marker is not a secret.** Text that is already `[redacted:…]` is skipped whole.
//! - **Ordinary text is byte-identical**: prose, logs, code that merely mentions a password.
//! - **Matches never overlap**, and the earliest pattern in the text wins: in
//!   `API_KEY=sk-…` the label is `api_key`, not a second marker nested in the first.
//!
//! Only the secret is replaced where a pattern has context worth keeping: `Bearer` stays,
//! the user in `https://user:pass@host` stays, the name in `password=…` stays. The reader
//! — the model — can still see what kind of thing was there.
use std::collections::BTreeMap;

/// What a redaction pass did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Redacted {
    pub text: String,
    /// How many secrets were replaced. 0 means `text` is the input, byte for byte.
    pub count: usize,
}

/// Replace every secret in `input`. A match that lies entirely inside one of the `allow`
/// strings (compared literally) is left as it is.
///
/// The text is scanned again after a replacement until a scan finds nothing, because a
/// replacement can change what a *neighbouring* pattern sees: a private key block that sat
/// inside the password of a URL, say, took the spaces that kept that URL from being one.
/// That is what makes the result idempotent by construction rather than by luck; it is
/// bounded, and every extra scan is a cheap read over text that is already a marker or plain.
pub fn redact(input: &str, allow: &[String]) -> Redacted {
    let mut current = scan(input, allow);
    for _ in 0..MAX_RESCANS {
        if current.count == 0 {
            break;
        }
        let again = scan(&current.text, allow);
        if again.count == 0 {
            break;
        }
        current = Redacted {
            text: again.text,
            count: current.count + again.count,
        };
    }
    current
}

const MAX_RESCANS: usize = 8;

/// One left-to-right pass.
fn scan(input: &str, allow: &[String]) -> Redacted {
    let b = input.as_bytes();
    let allowed = allowed_spans(input, allow);
    // Keyed by start. Matches found first win an overlap, so the map never holds two that
    // touch, and iterating it yields them left to right.
    let mut hits: BTreeMap<usize, Hit> = BTreeMap::new();

    let mut i = 0;
    while i < b.len() {
        if let Some(end) = marker_end(b, i) {
            i = end;
            continue;
        }
        // Inside a span that is already taken, any match would overlap it and be refused;
        // skipping it also keeps a long `token=token=token=…` from being measured from every
        // `token`.
        if let Some(taken) = hits.range(..=i).next_back().map(|(_, h)| h.end) {
            if taken > i {
                i = taken;
                continue;
            }
        }
        // Text that follows a replaced span will follow a `]`, which is not a word byte, so it
        // starts on an edge even when the secret before it ended on one.
        let after_hit = hits
            .range(..=i)
            .next_back()
            .is_some_and(|(_, h)| h.end == i && h.replacement.is_some());
        let Some(mut hit) = try_at(b, i, after_hit) else {
            i += 1;
            continue;
        };
        let ahead = hit.start > i;
        if allowed.iter().any(|&(a, z)| a <= hit.start && hit.end <= z) {
            // Reserved rather than dropped, so a smaller pattern cannot redact a piece of a
            // string the user said to leave alone.
            hit.replacement = None;
        }
        if !overlaps(&hits, hit.start, hit.end) {
            let end = hit.end;
            hits.insert(hit.start, hit);
            if !ahead {
                i = end;
                continue;
            }
        }
        // A match that starts further on (the value of `name = value`, the password of a
        // URL) leaves the text before it still to be scanned: the user of that URL could be
        // a key of its own.
        i += 1;
    }

    let mut text = String::with_capacity(input.len());
    let mut done = 0;
    let mut count = 0;
    for hit in hits.values() {
        let Some(replacement) = &hit.replacement else {
            continue;
        };
        text.push_str(slice(input, done, hit.start));
        text.push_str(replacement);
        done = hit.end;
        count += 1;
    }
    text.push_str(slice(input, done, input.len()));
    Redacted { text, count }
}

struct Hit {
    start: usize,
    end: usize,
    /// `None` for a match the allow-list protects: it still reserves its span.
    replacement: Option<String>,
}

fn hit(start: usize, end: usize, label: &str) -> Hit {
    Hit {
        start,
        end,
        replacement: Some(format!("[redacted:{label}]")),
    }
}

fn overlaps(hits: &BTreeMap<usize, Hit>, start: usize, end: usize) -> bool {
    hits.range(..end)
        .next_back()
        .is_some_and(|(_, h)| h.end > start)
}

/// Slicing that cannot panic. Every offset passed here sits next to an ASCII byte, so the
/// fallback is not expected to run; an empty string is the safe answer if it ever does.
fn slice(s: &str, from: usize, to: usize) -> &str {
    s.get(from..to).unwrap_or_default()
}

fn allowed_spans(input: &str, allow: &[String]) -> Vec<(usize, usize)> {
    allow
        .iter()
        .filter(|a| !a.is_empty())
        .flat_map(|a| {
            input
                .match_indices(a.as_str())
                .map(|(at, m)| (at, at + m.len()))
        })
        .collect()
}

const MARKER: &[u8] = b"[redacted:";

/// If a marker starts at `i`, where it ends. A marker is ours (or looks it), never a secret.
fn marker_end(b: &[u8], i: usize) -> Option<usize> {
    if !b[i..].starts_with(MARKER) {
        return None;
    }
    let tail = &b[i + MARKER.len()..];
    let close = tail.iter().take(48).position(|&c| c == b']')?;
    Some(i + MARKER.len() + close + 1)
}

fn try_at(b: &[u8], i: usize, after_hit: bool) -> Option<Hit> {
    if b[i] == b'-' {
        return private_key(b, i);
    }
    // Most patterns start on a word edge, so `task-…` and `desk_…` do not begin `sk-`.
    let word_edge = after_hit || i == 0 || !is_word(b[i - 1]);
    let found = if word_edge {
        prefixed_token(b, i)
            .or_else(|| url_password(b, i))
            .or_else(|| bearer(b, i))
            .or_else(|| jwt(b, i))
    } else {
        None
    };
    // A name may follow a hyphen (`--token=…`, `x-api-key:`), which a word edge would refuse.
    found.or_else(|| {
        let name_edge = after_hit || i == 0 || !is_ident(b[i - 1]);
        name_edge.then(|| assignment(b, i)).flatten()
    })
}

fn is_word(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_' || c == b'-'
}

fn is_ident(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_'
}

fn is_b64url(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_' || c == b'-'
}

/// End of the run of bytes at `from` that satisfy `pred`.
fn run(b: &[u8], from: usize, pred: impl Fn(u8) -> bool) -> usize {
    b[from.min(b.len())..]
        .iter()
        .position(|&c| !pred(c))
        .map_or(b.len(), |n| from + n)
}

/// Whether `b[i..]` starts with `prefix`, byte for byte.
fn at(b: &[u8], i: usize, prefix: &[u8]) -> bool {
    b.get(i..).is_some_and(|t| t.starts_with(prefix))
}

fn prefixed_token(b: &[u8], i: usize) -> Option<Hit> {
    // `sk-…`: OpenAI, Anthropic (`sk-ant-`), project keys (`sk-proj-`).
    if at(b, i, b"sk-") {
        let end = run(b, i + 3, is_b64url);
        return (end - (i + 3) >= 20).then(|| hit(i, end, "api-key"));
    }
    // `ghp_ gho_ ghu_ ghs_ ghr_`: GitHub's own token kinds.
    if at(b, i, b"gh") && b.get(i + 2).is_some_and(|c| b"pousr".contains(c)) && at(b, i + 3, b"_") {
        let end = run(b, i + 4, |c| c.is_ascii_alphanumeric());
        return (end - (i + 4) >= 30).then(|| hit(i, end, "github-token"));
    }
    if at(b, i, b"github_pat_") {
        let end = run(b, i + 11, |c| c.is_ascii_alphanumeric() || c == b'_');
        return (end - (i + 11) >= 20).then(|| hit(i, end, "github-token"));
    }
    // An AWS access key id is exactly four letters and sixteen of [A-Z0-9]. A seventeenth
    // character means this is some other identifier that happens to begin `AKIA`.
    if at(b, i, b"AKIA") || at(b, i, b"ASIA") {
        let end = run(b, i + 4, |c| c.is_ascii_uppercase() || c.is_ascii_digit());
        let tail_clean = !b.get(end).is_some_and(|c| c.is_ascii_alphanumeric());
        return (end - (i + 4) == 16 && tail_clean).then(|| hit(i, end, "aws-key-id"));
    }
    if at(b, i, b"xox") && b.get(i + 3).is_some_and(|c| b"bparsa".contains(c)) && at(b, i + 4, b"-")
    {
        let end = run(b, i + 5, |c| c.is_ascii_alphanumeric() || c == b'-');
        return (end - (i + 5) >= 10).then(|| hit(i, end, "slack-token"));
    }
    // A Google API key is `AIza` and 35 more.
    if at(b, i, b"AIza") {
        let end = run(b, i + 4, is_b64url);
        return (end - (i + 4) >= 35).then(|| hit(i, end, "google-key"));
    }
    None
}

fn jwt(b: &[u8], i: usize) -> Option<Hit> {
    if !at(b, i, b"eyJ") {
        return None;
    }
    let first = run(b, i, is_b64url);
    if first - i < 6 || b.get(first) != Some(&b'.') {
        return None;
    }
    let second = run(b, first + 1, is_b64url);
    if second - (first + 1) < 4 || b.get(second) != Some(&b'.') {
        return None;
    }
    let third = run(b, second + 1, is_b64url);
    (third - (second + 1) >= 4).then(|| hit(i, third, "jwt"))
}

fn bearer(b: &[u8], i: usize) -> Option<Hit> {
    let word = b.get(i..i + 6)?;
    if !word.eq_ignore_ascii_case(b"bearer") {
        return None;
    }
    let gap = run(b, i + 6, |c| c == b' ' || c == b'\t');
    if gap == i + 6 {
        return None;
    }
    let mut end = run(b, gap, |c| {
        is_b64url(c) || matches!(c, b'.' | b'~' | b'+' | b'/' | b'=')
    });
    // A full stop closes a sentence far more often than it ends a token.
    while end > gap && b[end - 1] == b'.' {
        end -= 1;
    }
    let token = &b[gap..end];
    let varied = token.iter().any(u8::is_ascii_digit)
        || (token.iter().any(u8::is_ascii_uppercase) && token.iter().any(u8::is_ascii_lowercase));
    // Sixteen and a digit or mixed case: "Bearer authentication" is a phrase, not a token.
    (token.len() >= 16 && varied).then(|| hit(gap, end, "bearer-token"))
}

/// `scheme://user:password@host`: the password goes, the user stays.
fn url_password(b: &[u8], i: usize) -> Option<Hit> {
    if !b[i].is_ascii_alphabetic() {
        return None;
    }
    let scheme_end = i + b[i..]
        .iter()
        .take(32)
        .position(|&c| !(c.is_ascii_alphanumeric() || matches!(c, b'+' | b'.' | b'-')))?;
    if !at(b, scheme_end, b"://") {
        return None;
    }
    let user_start = scheme_end + 3;
    let stop = |c: u8| {
        c.is_ascii_whitespace() || matches!(c, b'"' | b'\'' | b'<' | b'>' | b'/' | b'?' | b'#')
    };
    // `[` ends the user so that a marker already standing there is never read as one.
    let user_end = run(b, user_start, |c| {
        !stop(c) && !matches!(c, b':' | b'@' | b'[' | b']')
    });
    if user_end == user_start || b.get(user_end) != Some(&b':') {
        return None;
    }
    let pass_start = user_end + 1;
    let region_end = run(b, pass_start, |c| !stop(c));
    // A password may hold an unescaped `@`; the host starts after the last one.
    let at_sign = b[pass_start..region_end].iter().rposition(|&c| c == b'@')? + pass_start;
    let pass = &b[pass_start..at_sign];
    let placeholder = pass.first().is_some_and(|c| matches!(c, b'$' | b'{'))
        || pass.iter().all(|&c| c == b'*')
        || pass.starts_with(MARKER);
    (!pass.is_empty() && !placeholder).then(|| hit(pass_start, at_sign, "password"))
}

/// Names whose value is a secret, longest first so `client_secret` is not reported as
/// `secret`. A name matches when it *ends* with one: `API_TOKEN`, `DB_PASSWORD` and
/// `AWS_SECRET_ACCESS_KEY` are how these appear in an `.env`, and the bare words almost never do.
const NAMES: &[&str] = &[
    "client_secret",
    "access_key",
    "api_key",
    "apikey",
    "password",
    "passwd",
    "secret",
    "token",
    "pwd",
];

fn secret_name(ident: &[u8]) -> Option<&'static str> {
    let lowered: Vec<u8> = ident
        .iter()
        .map(|&c| {
            if c == b'-' {
                b'_'
            } else {
                c.to_ascii_lowercase()
            }
        })
        .collect();
    NAMES
        .iter()
        .find(|n| lowered.ends_with(n.as_bytes()))
        .copied()
}

/// A value shaped like a name out of code — an uppercase letter inside it and no digit,
/// `AccessTokenRequest`, `ApiKeyConfig`, `MY_SECRET_VALUE` — is a type, a field or a reference to
/// another variable far more often than it is a secret, and this rule reads a great deal of code.
/// Such a value is taken only under a password name, where an all-letter secret is ordinary.
/// A lowercase run (`abcdefghijkl`) is what an unremarkable `.env` token looks like, so it stays;
/// a real key of any prefix is caught by the prefix rules regardless.
fn is_bare_identifier(value: &[u8]) -> bool {
    let Some((first, rest)) = value.split_first() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || *first == b'_') {
        return false;
    }
    let shaped = rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
        && !value.iter().any(u8::is_ascii_digit);
    shaped && rest.iter().any(u8::is_ascii_uppercase)
}

fn assignment(b: &[u8], i: usize) -> Option<Hit> {
    if !is_ident(b[i]) {
        return None;
    }
    // A name is short; capping the run keeps a long hyphenated token from being rescanned
    // from every segment.
    let name_end = run(&b[..b.len().min(i + 65)], i, is_b64url);
    if name_end - i > 64 {
        return None;
    }
    let label = secret_name(&b[i..name_end])?;
    let blank = |c: u8| c == b' ' || c == b'\t';
    // `#415`: inside an escaped JSON string the bytes are `\"password\": \"…\"` — the backslash
    // before each quote is part of the text, so a check that only looks for the quote sees `\` and
    // gives up. Skip one escape before each quote; in plain text this is a no-op.
    let quoteless = |b: &[u8], mut k: usize| -> usize {
        if b.get(k) == Some(&b'\\') {
            k += 1;
        }
        if matches!(b.get(k), Some(b'"' | b'\'')) {
            k += 1;
        }
        k
    };
    let mut j = quoteless(b, name_end);
    j = run(b, j, blank);
    if !matches!(b.get(j), Some(b'=' | b':')) {
        return None;
    }
    j += 1;
    // `==` is a comparison and `::` a path, not an assignment.
    if matches!(b.get(j), Some(b'=' | b':')) {
        return None;
    }
    j = quoteless(b, run(b, j, blank));
    // A password is a password whatever it looks like: `hunter2` and `Sup3r$ecret!` are the shapes
    // a `cat .env` actually produces, and both were missed because the value was scanned as a
    // base64url run (the `$` and `!` ended it after five characters) and then held to a twelve
    // character floor (`#415`). So for those three names the value is any run without a separator.
    let password = matches!(label, "password" | "passwd" | "pwd");
    let end = if password {
        run(b, j, |c| {
            !matches!(
                c,
                b' ' | b'\t'
                    | b'\n'
                    | b'\r'
                    | b'"'
                    | b'\''
                    | b'`'
                    | b','
                    | b';'
                    | b')'
                    | b']'
                    | b'}'
                    | b'>'
                    | b'<'
                    | b'&'
                    | b'\\'
            )
        })
    } else {
        run(b, j, |c| is_b64url(c) || matches!(c, b'/' | b'+' | b'='))
    };
    // `${…}`, `$(…)`, `~/…` and `[redacted:…]` never start a value; an absolute path does not
    // either. The marker matters for idempotence: without `[` here, the second pass reads
    // `[redacted:password]` as a value that starts with `[` and ends at `]`, redacts it again, and
    // the pass is no longer a fixed point.
    if matches!(b.get(j), Some(b'/' | b'$' | b'[' | b'{' | b'(')) {
        return None;
    }
    let len = end - j;
    // Six characters is allowed only when something in them is not a letter — `hunter2`, `Sup3r$e!`
    // — because `password: required` and `password: elevenchars` are a config schema, not a secret,
    // and a redacted field name degrades every read of a codebase.
    let acceptable = if password {
        len >= 12 || (len >= 6 && b[j..end].iter().any(|c| !c.is_ascii_alphabetic()))
    } else {
        len >= 12
    };
    if !acceptable {
        return None;
    }
    // A type or a variable name where a secret was expected: `token: AccessTokenRequest` is code.
    if !matches!(label, "password" | "passwd" | "pwd") && is_bare_identifier(&b[j..end]) {
        return None;
    }
    let closed = match b.get(end) {
        None => true,
        Some(c) if c.is_ascii_whitespace() => true,
        Some(
            b'"' | b'\'' | b'`' | b',' | b';' | b')' | b']' | b'}' | b'>' | b'&' | b'<' | b'\\',
        ) => true,
        // A full stop that ends a sentence, not one inside a dotted name.
        Some(b'.') => !b.get(end + 1).is_some_and(|c| !c.is_ascii_whitespace()),
        Some(_) => false,
    };
    closed.then(|| hit(j, end, label))
}

/// A PEM private key: the whole block, header to footer, becomes one marker.
fn private_key(b: &[u8], i: usize) -> Option<Hit> {
    const BEGIN: &[u8] = b"-----BEGIN ";
    if !at(b, i, BEGIN) {
        return None;
    }
    let label_start = i + BEGIN.len();
    let label_end = label_start + find(&b[label_start..], b"-----", 40)?;
    if !is_private_label(&b[label_start..label_end]) {
        return None;
    }
    let body = label_end + 5;
    if let Some(footer) = footer_end(b, body) {
        return Some(hit(i, footer, "private-key"));
    }
    // No footer: the output was cut short, or the key was never closed. What was printed of
    // the body is still a key, so take the header and the base64 lines that follow it, and
    // stop at the first line that is something else.
    let mut end = body;
    let mut cursor = body;
    let mut lines = 0;
    while cursor < b.len() {
        let line_end = b[cursor..]
            .iter()
            .position(|&c| c == b'\n')
            .map_or(b.len(), |n| cursor + n);
        let line = &b[cursor..line_end];
        let lead = line
            .iter()
            .take_while(|&&c| c == b' ' || c == b'\t')
            .count();
        let text = trim_end(&line[lead..]);
        let base64 = !text.is_empty()
            && text
                .iter()
                .all(|&c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'='));
        let pem_header = text.starts_with(b"Proc-Type:") || text.starts_with(b"DEK-Info:");
        if base64 && (text.len() >= 16 || lines > 0) {
            lines += 1;
            end = cursor + lead + text.len();
        } else if !(pem_header || text.is_empty() && lines == 0) {
            break;
        }
        cursor = line_end + 1;
    }
    (lines > 0).then(|| hit(i, end, "private-key"))
}

fn trim_end(mut text: &[u8]) -> &[u8] {
    while let [rest @ .., b' ' | b'\t' | b'\r'] = text {
        text = rest;
    }
    text
}

fn is_private_label(label: &[u8]) -> bool {
    label.ends_with(b"PRIVATE KEY")
}

/// The longest key body searched for its footer. A 4096-bit RSA key is about 3 KiB; past this
/// the block is read as unclosed, and its base64 lines are taken instead.
const MAX_KEY_BODY: usize = 16 * 1024;

/// Where the `-----END … PRIVATE KEY-----` line that closes a block starting at `from` ends.
fn footer_end(b: &[u8], from: usize) -> Option<usize> {
    const END: &[u8] = b"-----END ";
    let at_footer = from + find(&b[from..], END, MAX_KEY_BODY)?;
    let label_start = at_footer + END.len();
    let label_end = label_start + find(&b[label_start..], b"-----", 40)?;
    is_private_label(&b[label_start..label_end]).then_some(label_end + 5)
}

/// Offset of `needle` in the first `limit` bytes of `hay`.
fn find(hay: &[u8], needle: &[u8], limit: usize) -> Option<usize> {
    let hay = &hay[..hay.len().min(limit)];
    hay.windows(needle.len()).position(|w| w == needle)
}

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

    fn r(text: &str) -> String {
        redact(text, &[]).text
    }

    /// Run the scanner and check the two things every case owes: the replacement, and that
    /// a second pass finds nothing more to do.
    fn fires(input: &str, expected: &str) {
        let first = redact(input, &[]);
        assert_eq!(first.text, expected, "input: {input}");
        assert!(first.count >= 1, "nothing was counted for: {input}");
        let second = redact(&first.text, &[]);
        assert_eq!(second.text, first.text, "not idempotent for: {input}");
        assert_eq!(second.count, 0, "a marker was matched again: {input}");
    }

    fn passes(input: &str) {
        let out = redact(input, &[]);
        assert_eq!(out.text, input, "a near-miss was changed");
        assert_eq!(out.count, 0);
    }

    // sk- ------------------------------------------------------------------------------------

    #[test]
    fn an_sk_key_of_twenty_or_more_characters_is_redacted() {
        fires(
            "key is sk-abcdefghij0123456789 ok",
            "key is [redacted:api-key] ok",
        );
        fires(
            "ANTHROPIC=sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv_wx-yz",
            "ANTHROPIC=[redacted:api-key]",
        );
        fires("\"sk-proj-abcdefghij0123456789\"", "\"[redacted:api-key]\"");
    }

    #[test]
    fn an_sk_prefix_that_is_short_or_inside_a_word_is_left_alone() {
        passes("sk-abcdefghij012345678"); // 19 after the prefix
        passes("sk-learn");
        passes("the task-abcdefghij0123456789 queue");
        passes("risk-assessment-for-the-whole-quarter");
    }

    // GitHub ----------------------------------------------------------------------------------

    #[test]
    fn github_tokens_of_every_kind_are_redacted() {
        for kind in ["ghp", "gho", "ghu", "ghs", "ghr"] {
            let token = format!("{kind}_0123456789abcdefghijABCDEFGHIJ");
            fires(&format!("token {token}!"), "token [redacted:github-token]!");
        }
        fires(
            "github_pat_11ABCDEFG0abcdefghij_klmnopqrstuvwxyz",
            "[redacted:github-token]",
        );
    }

    #[test]
    fn a_github_token_that_is_too_short_or_of_an_unknown_kind_is_left_alone() {
        passes("ghp_0123456789abcdefghijABCDEFGHI"); // 29
        passes("ghx_0123456789abcdefghijABCDEFGHIJ");
        passes("github_pat_short");
        passes("ghp_ is the prefix GitHub uses");
    }

    // AWS -------------------------------------------------------------------------------------

    #[test]
    fn an_aws_access_key_id_is_redacted() {
        fires(
            "id AKIAIOSFODNN7EXAMPLE here",
            "id [redacted:aws-key-id] here",
        );
        fires("ASIAIOSFODNN7EXAMPLE", "[redacted:aws-key-id]");
    }

    #[test]
    fn something_that_only_starts_like_an_aws_key_id_is_left_alone() {
        passes("AKIAIOSFODNN7EXAMPL"); // 15
        passes("AKIAIOSFODNN7EXAMPLES"); // 17
        passes("AKIAiosfodnn7example1234");
        passes("AKIAIOSFODNN7EXAMPLEx");
    }

    // Slack -----------------------------------------------------------------------------------

    #[test]
    fn slack_tokens_are_redacted() {
        for kind in ["xoxb", "xoxp", "xoxa", "xoxr", "xoxs"] {
            fires(
                &format!("{kind}-123456789012-AbCdEfGhIj"),
                "[redacted:slack-token]",
            );
        }
    }

    #[test]
    fn a_short_or_unknown_slack_shape_is_left_alone() {
        passes("xoxb-123456789"); // 9
        passes("xoxz-123456789012-AbCdEfGhIj");
        passes("xoxb is how a bot token starts");
    }

    // Google ----------------------------------------------------------------------------------

    #[test]
    fn a_google_api_key_is_redacted() {
        let key = format!("AIza{}", "Sy0123456789_abcdefghijKLMNOPQRST-x");
        assert_eq!(key.len(), 4 + 35);
        fires(&format!("key={key}&x=1"), "key=[redacted:google-key]&x=1");
    }

    #[test]
    fn a_google_key_that_is_too_short_is_left_alone() {
        passes("AIzaSy0123456789_abcdefghijKLMNOPQRST-"); // 34 after the prefix
        passes("AIza is how a Google key starts");
    }

    // Private keys ----------------------------------------------------------------------------

    #[test]
    fn a_whole_private_key_block_becomes_one_marker() {
        let block = "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA1234567890abcdef\nZm9vYmFy\n-----END RSA PRIVATE KEY-----";
        fires(
            &format!("before\n{block}\nafter"),
            "before\n[redacted:private-key]\nafter",
        );
        fires(
            "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----",
            "[redacted:private-key]",
        );
        fires(
            "-----BEGIN OPENSSH PRIVATE KEY-----\\nb3BlbnNzaC1rZXk\\n-----END OPENSSH PRIVATE KEY-----\\n",
            "[redacted:private-key]\\n",
        );
    }

    #[test]
    fn a_private_key_cut_off_before_its_footer_is_still_redacted() {
        fires(
            "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\nKcwggSjAgEAAoIBAQC7VJTUt9Us8cKj\n[output truncated]",
            "[redacted:private-key]\n[output truncated]",
        );
    }

    #[test]
    fn public_keys_certificates_and_a_bare_header_are_left_alone() {
        passes("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n-----END PUBLIC KEY-----");
        passes("-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0B\n-----END CERTIFICATE-----");
        passes("Keys start with -----BEGIN PRIVATE KEY----- and end with a footer.");
    }

    // Bearer ----------------------------------------------------------------------------------

    #[test]
    fn a_bearer_token_is_replaced_and_the_word_stays() {
        fires(
            "Authorization: Bearer abc123DEF456ghi789jkl",
            "Authorization: Bearer [redacted:bearer-token]",
        );
        fires(
            "curl -H 'authorization: bearer Zm9vYmFyYmF6cXV4MTIz'",
            "curl -H 'authorization: bearer [redacted:bearer-token]'",
        );
        fires(
            "Send Bearer abc123DEF456ghi789jkl.",
            "Send Bearer [redacted:bearer-token].",
        );
    }

    #[test]
    fn the_word_bearer_in_prose_is_left_alone() {
        passes("Bearer authentication is described in RFC 6750");
        passes("the bearer of this letter");
        passes("Bearer tokens are sent in a header");
        passes("Bearer abcdefghijklmnopqrstuvwxyz"); // no digit, no mixed case
    }

    // JWT -------------------------------------------------------------------------------------

    #[test]
    fn a_jwt_is_redacted() {
        fires(
            "id_token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk;",
            "id_token=[redacted:jwt];",
        );
    }

    #[test]
    fn something_that_only_looks_like_the_start_of_a_jwt_is_left_alone() {
        passes("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9"); // two parts
        passes("eyJ.a.b");
        passes("see eyJ for the base64 of an opening brace and quote");
        passes("xeyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.dBjftJeZ4CVP");
    }

    // URL userinfo ----------------------------------------------------------------------------

    #[test]
    fn the_password_in_a_url_is_replaced_and_the_user_stays() {
        fires(
            "clone https://alice:hunter2@example.com/repo.git",
            "clone https://alice:[redacted:password]@example.com/repo.git",
        );
        fires(
            "postgres://app:p%40ss@db.internal:5432/app",
            "postgres://app:[redacted:password]@db.internal:5432/app",
        );
        fires(
            "mongodb+srv://u:p@ss@cluster0.example.net/db",
            "mongodb+srv://u:[redacted:password]@cluster0.example.net/db",
        );
    }

    #[test]
    fn urls_without_a_password_or_with_a_placeholder_are_left_alone() {
        passes("https://example.com:8080/path");
        passes("ssh://git@github.com/org/repo");
        passes("https://alice@example.com/");
        passes("http://[::1]:8080/");
        passes("https://alice:${DB_PASSWORD}@example.com/");
        passes("https://alice:****@example.com/");
        passes("see user:pass@host for the format"); // no scheme
        passes("https://example.com/a:b@c");
    }

    #[test]
    fn a_secret_that_is_the_user_of_a_url_is_found_as_well() {
        fires(
            "https://sk-abcdefghij0123456789:hunter2@example.com",
            "https://[redacted:api-key]:[redacted:password]@example.com",
        );
    }

    // Assignments -----------------------------------------------------------------------------

    #[test]
    fn a_secret_named_assignment_is_redacted_and_the_name_stays() {
        fires("API_TOKEN=abcdef0123456789", "API_TOKEN=[redacted:token]");
        fires(
            "export DB_PASSWORD=correct-horse-battery",
            "export DB_PASSWORD=[redacted:password]",
        );
        fires(
            "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
            "aws_secret_access_key = [redacted:access_key]",
        );
        fires(
            r#"{"client_secret": "0123456789abcdefAB"}"#,
            r#"{"client_secret": "[redacted:client_secret]"}"#,
        );
        fires(
            "password: 'abcdefghijkl'",
            "password: '[redacted:password]'",
        );
        fires(
            "GET /x?access_token=abc123abc123abc&b=1",
            "GET /x?access_token=[redacted:token]&b=1",
        );
        fires(
            "GET /x?token=abc123abc123abc&b=1",
            "GET /x?token=[redacted:token]&b=1",
        );
        fires("--token=abcdef0123456789", "--token=[redacted:token]");
        fires("API_KEY=abcdef0123456789", "API_KEY=[redacted:api_key]");
        fires("apikey=abcdef0123456789", "apikey=[redacted:apikey]");
        fires("passwd = abcdef0123456789", "passwd = [redacted:passwd]");
        fires("pwd=abcdef0123456789", "pwd=[redacted:pwd]");
        fires("secret=abcdef0123456789", "secret=[redacted:secret]");
        fires(
            "access_key=abcdef0123456789",
            "access_key=[redacted:access_key]",
        );
        // The exception above is for names that carry keys; a password may be all letters.
        fires(
            "DB_PASSWORD=correcthorsebatterystaple",
            "DB_PASSWORD=[redacted:password]",
        );
        // `#415`: the two shapes a `cat .env` actually produces — a short value, and a value with
        // punctuation in it — both used to pass through untouched.
        fires("password=hunter2", "password=[redacted:password]");
        // A name whose value carries punctuation: the `!` used to end the value run.
        fires("DB_PASSWORD=hunter2!", "DB_PASSWORD=[redacted:password]");
        // …and the same shape inside an escaped JSON string, where every quote has a backslash
        // in front of it and the old scan gave up on the first one it met.
        fires(
            r#"{"json": "{\"password\": \"hunter2\"}"}"#,
            r#"{"json": "{\"password\": \"[redacted:password]\"}"}"#,
        );
    }

    #[test]
    fn an_assignment_whose_value_is_not_a_plain_secret_is_left_alone() {
        passes("password=short");
        passes("password=elevenchars"); // 11
        passes("token=${API_TOKEN_VALUE_FROM_ENV}");
        passes("password=$(cat /run/secrets/db_password)");
        passes("secret_path=/etc/ssl/private/server.key");
        passes("token=/var/run/secrets/kubernetes.io/serviceaccount/token");
        passes("OLDPWD=/home/user/projects/eclipse");
        passes("token == abcdefghijklmnop");
        passes("password: required");
        passes("token = generate_secret_key_value()");
        passes("tokenizer=abcdefghijklmnop");
        passes("max_tokens=1234567890123");
        // `#415`: this used to pass, deliberately (`!` ended the run after twelve characters of
        // scanning). It is a password with a punctuation mark in it — the commonest shape there is.
        fires("password=abcdefghijkl!zzz", "password=[redacted:password]");
        // A type or a variable where a secret was expected. Seen in the agent's own source, so it
        // is the case that matters most: a redacted field name degrades every read of a codebase.
        passes("token: AccessTokenRequest");
        passes("api_key: ApiKeyConfig");
        passes("access_key: AuthenticationProvider");
        passes("secret: SomeLongIdentifierName");
    }

    #[test]
    fn a_value_that_is_a_known_key_is_reported_under_the_assignments_name() {
        fires(
            "API_KEY=sk-abcdefghij0123456789",
            "API_KEY=[redacted:api_key]",
        );
    }

    // The properties --------------------------------------------------------------------------

    #[test]
    fn ordinary_prose_and_logs_pass_through_byte_identical() {
        passes("");
        passes("The quick brown fox jumps over the lazy dog.");
        passes("2026-11-28T19:00:00Z INFO server listening on 127.0.0.1:8787 (pid 4242)");
        passes("error[E0432]: unresolved import `crate::redact` at src/lib.rs:12:5");
        passes("commit d3fc7fe docs: the repository is private until the first public release");
        passes("sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08");
        passes("let token = lexer.next_token(); // tokens are not secrets");
        passes("Reset your password at https://example.com/reset?user=1 and log in again.");
        passes("héllo wörld — ünïcode ✓ and 日本語 pass through");
        passes("    \t\n\r\n");
    }

    #[test]
    fn an_already_redacted_region_is_not_touched() {
        passes("key [redacted:api-key] and [redacted:private-key] and [redacted:token]");
        passes("API_TOKEN=[redacted:token]");
        passes("Authorization: Bearer [redacted:bearer-token]");
        passes("https://alice:[redacted:password]@example.com/");
    }

    #[test]
    fn redacting_twice_changes_nothing_more() {
        let messy = [
            "a sk-abcdefghij0123456789 b ghp_0123456789abcdefghijABCDEFGHIJ c AKIAIOSFODNN7EXAMPLE",
            "Bearer abc123DEF456ghi789jkl then https://u:pw@h/ then password=abcdefghijkl1",
            "API_KEY=sk-abcdefghij0123456789 token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.dBjftJeZ4CVP",
            "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\nsk-abcdefghij0123456789",
            "xoxb-123456789012-AbCdEfGhIj\u{e9}sk-abcdefghij0123456789",
            "sk-abcdefghij0123456789sk-abcdefghij0123456789",
            "token=abcdefghijkl token=abcdefghijkl,token=abcdefghijkl",
        ];
        for text in messy {
            let once = redact(text, &[]);
            assert!(once.count > 0, "nothing found in: {text}");
            let twice = redact(&once.text, &[]);
            assert_eq!(twice.text, once.text, "not idempotent for: {text}");
            assert_eq!(twice.count, 0);
        }
    }

    /// Fragments that border on every pattern, shuffled by a fixed generator: whatever comes
    /// out must be a fixed point.
    #[test]
    fn a_pass_over_scrambled_fragments_is_always_a_fixed_point() {
        let parts = [
            "sk-",
            "ghp_",
            "AKIA",
            "xoxb-",
            "AIza",
            "eyJ",
            ".",
            "Bearer ",
            "://",
            "user:",
            "pw@",
            "token=",
            "password: ",
            "\"",
            "'",
            " ",
            "\n",
            "-----BEGIN PRIVATE KEY-----",
            "AAAA",
            "-----END PRIVATE KEY-----",
            "0123456789abcdefghijKLMNOP",
            "[redacted:",
            "]",
            "=",
            "é",
            "/",
            "_",
            "-",
            "api_key=",
        ];
        let mut seed: u64 = 0x2545F4914F6CDD1D;
        for _ in 0..10_000 {
            let mut text = String::new();
            for _ in 0..24 {
                seed ^= seed << 13;
                seed ^= seed >> 7;
                seed ^= seed << 17;
                text.push_str(parts[(seed % parts.len() as u64) as usize]);
            }
            let once = redact(&text, &[]);
            let twice = redact(&once.text, &[]);
            assert_eq!(twice.text, once.text, "not a fixed point for: {text:?}");
        }
    }

    #[test]
    fn an_allowed_literal_is_skipped_and_its_neighbours_are_not() {
        let fixture = "sk-fixture0000000000000000";
        let allow = vec![fixture.to_string()];
        let text = format!("fixture {fixture} real sk-abcdefghij0123456789 and API_KEY={fixture}");
        let out = redact(&text, &allow);
        assert_eq!(
            out.text,
            format!("fixture {fixture} real [redacted:api-key] and API_KEY={fixture}")
        );
        assert_eq!(out.count, 1);
    }

    #[test]
    fn an_allowed_string_does_not_exempt_a_longer_secret_that_merely_contains_it() {
        let allow = vec!["sk-fixture0000000000000000".to_string()];
        let out = redact("sk-fixture0000000000000000-and-more-real-secret", &allow);
        assert_eq!(out.text, "[redacted:api-key]");
    }

    #[test]
    fn an_allowed_value_keeps_the_assignment_around_it_whole() {
        let allow = vec!["abcdef0123456789".to_string()];
        let out = redact("API_TOKEN=abcdef0123456789", &allow);
        assert_eq!(out.text, "API_TOKEN=abcdef0123456789");
        assert_eq!(out.count, 0);
    }

    #[test]
    fn the_count_is_the_number_of_secrets_replaced() {
        let out = redact("sk-abcdefghij0123456789 and AKIAIOSFODNN7EXAMPLE", &[]);
        assert_eq!(out.count, 2);
        assert_eq!(r("nothing here"), "nothing here");
    }

    /// Long runs of the characters every pattern scans over must stay linear: a tool result
    /// can be 32 KB of anything, and this runs on every one.
    #[test]
    fn pathological_runs_are_scanned_in_linear_time() {
        let started = std::time::Instant::now();
        for text in [
            "a-".repeat(100_000),
            "sk-".repeat(60_000),
            "token=".repeat(30_000),
            "[redacted:".repeat(20_000),
            "https://a:".repeat(20_000),
            "-----BEGIN PRIVATE KEY-----".repeat(5_000),
            "Bearer ".repeat(30_000),
            "a".repeat(200_000),
            "eyJ.".repeat(50_000),
            "password: x".repeat(20_000),
            "xoxb-".repeat(40_000),
        ] {
            let _ = redact(&text, &[]);
        }
        assert!(
            started.elapsed() < std::time::Duration::from_secs(10),
            "scanning took {:?}",
            started.elapsed()
        );
    }

    #[test]
    fn multibyte_text_around_a_secret_survives() {
        fires(
            "clé: sk-abcdefghij0123456789 — fin",
            "clé: [redacted:api-key] — fin",
        );
    }
}