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
//! Confluent Cloud API secret detection.
//!
//! The reviewed grammar (issue #309, applying the existing provider-grammar
//! freeze policy recorded in `docs/specs/detector-families.md`) covers two
//! generations of one credential, both documented by Confluent itself
//! (`docs.confluent.io/cloud/current/security/authenticate/workload-identities/service-accounts/api-keys/overview.html`,
//! observed 2026-09-22):
//!
//! - **Current (created after 2025-07-30).** The literal `cflt` prefix
//!   followed by exactly 60 bytes of the standard base64 body alphabet
//!   ([`pattern::is_base64_body`], `[A-Za-z0-9+/]`), 64 bytes total.
//!   Confluent's page states that "the final 6 characters contain a
//!   Base64-encoded CRC32 checksum of the prior 54 characters", and its own
//!   secret-detection example fixes the algorithm precisely enough to
//!   recompute independently (issue #738): the IEEE CRC-32 of the 54 body
//!   bytes after `cflt` (the prefix is not covered), serialized as 4
//!   little-endian bytes, standard-base64 encoded, first 6 characters. That
//!   recipe reproduces the page's own example exactly, and a big-endian or
//!   prefix-included variant fails it. This detector therefore validates
//!   the checksum ([`checksum_matches`]): a `cflt`-prefixed value of the
//!   right length and alphabet whose final 6 bytes are not that checksum is
//!   rejected. This supersedes the earlier shape-only reading, which
//!   treated the checksum as unpublished and accepted every checksum-invalid
//!   value as an intentional false positive.
//! - **Legacy (created on or before 2025-07-30).** The same documentation
//!   states older secrets "may lack the `cflt` prefix but remain valid" -- a bare
//!   64-byte run of the same alphabet, with no marker of its own and no
//!   documented checksum, so this path is not checksum-validated. A run
//!   that starts with `cflt` is the current generation's shape and is left
//!   to the prefixed detector alone, so a checksum-invalid `cflt` value is
//!   not re-reported here as a legacy secret. This
//!   shape is indistinguishable by structure alone from any other opaque
//!   base64 blob, so it is never reported without same-line corroboration,
//!   the same reasoning [`super::twilio`] already documents for its own
//!   unmarked Auth Token and API Key Secret bodies. Two independently
//!   maintained tools, consulted only as external behavioral references per
//!   `AGENTS.md`, converge on requiring a case-insensitive `confluent`
//!   substring alongside this exact bare shape and never emit it
//!   unconditionally:
//!
//!   ```text
//!   gitleaks 8.30.1's confluent-secret-key rule (keyword-gated, `[a-z0-9]{64}` body):
//!     (?i)[\w.-]{0,50}?(?:confluent)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{64})(?:[\x60'"\s;]|\\[nr]|$)
//!   trufflehog 3.97.4's confluent detector (keyword-gated, `[a-zA-Z0-9+/]{64}` body):
//!     confluent\b...\b[a-zA-Z0-9+/]{64}\b
//!   ```
//!
//!   This detector follows the same corroborated policy: a bare 64-byte
//!   [`pattern::is_base64_body`] run is reported only when its line also
//!   carries a case-insensitive `confluent` substring, at
//!   [`Confidence::Medium`] -- the same weaker-heuristic tier
//!   [`super::twilio`]'s own keyword-only path uses, and, like that path,
//!   deliberately left out of [`policy::ALWAYS_REDACT_TYPES`] rather than
//!   promoted to an unconditional redact. gitleaks additionally requires
//!   the same keyword gate on the Access Token (Key ID) half of the pair;
//!   this detector does not emit any Key ID finding at all (see "Out of
//!   scope" below), so that half of its rule has no analog here.
//!
//!   A legacy candidate introduced by a hash-algorithm label
//!   ([`text::is_labelled_digest`]: `@sha256:`, `sha512=`, ...) is never
//!   reported (issue #744): `image: confluentinc/cp-server@sha256:<64 hex>`
//!   names Confluent but carries a container image digest, and Confluent
//!   documents no form in which an API secret follows such a label.
//!
//!   A Schema Registry client config names Confluent only on the
//!   `schema.registry.url` line, above the credential line (issue #933).
//!   A legacy secret that is the secret half of a
//!   `basic.auth.user.info=<key id>:<secret>` property is therefore also
//!   reported when one of the at most [`PROPERTIES_LOOKBACK_LINES`]
//!   property lines directly above it names `confluent`, at
//!   [`Confidence::High`] since issue #936 (the property names the
//!   credential and the block binds it to Confluent, as a Confluent-named
//!   key does; #933 reported it at medium, which only warned). A blank or non-property line ends the block, and no
//!   other property name is read this way. The incremental session holds
//!   such a block open ([`has_open_confluent_properties`]).
//!
//! No code from either tool is reproduced here; this module's matching and
//! context-gating logic is authored independently.
//!
//! ## Out of scope
//!
//! The API Key ID (the public, non-secret half of the pair -- Confluent's
//! own overview page states "It is not considered secret information",
//! example `ABCD1234567890AB`) is never itself a finding, matching the
//! issue's explicit scope: "Distinguish key identifiers from secret
//! values; do not classify cluster IDs, bootstrap hosts, or arbitrary
//! base64 as credentials." Confluent's documentation gives no published
//! character-class grammar for the Key ID beyond that one example; unlike
//! [`super::twilio`]'s Account SID and API Key SID, it is not used here even
//! as an internal context signal, since two tools' community-observed
//! shapes (`[A-Za-z0-9]{16}`) are a materially weaker evidence bar than
//! Twilio's own well-documented SID format. Cluster IDs (`lkc-...`),
//! Schema Registry and ksqlDB resource IDs (`lsrc-...`, `lksqlc-...`), and
//! bootstrap host strings all carry a `-` outside this module's alphabets
//! and are excluded automatically, with no special-casing needed.

use crate::detectors::additional_providers::KnownFormatProviderDetector;
use crate::detectors::pattern::{self, Alphabet, PrefixShape};
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};

const SECRET_PREFIX: &str = "cflt";
/// The documented exact body length following the `cflt` prefix.
const PREFIXED_BODY_LEN: usize = 60;
/// The documented exact length of a legacy, unprefixed secret.
const LEGACY_SECRET_LEN: usize = 64;
const CONTEXT_KEYWORD: &str = "confluent";

/// [`pattern::is_base64_body`] widened to also admit `_` and `-`, so a
/// directly-glued wider identifier or a token-adjacent separator still
/// rejects a truncated candidate the way every other exact-length base64
/// shape in this crate's boundary checks does; see
/// [`pattern::RunLength::Exact`]'s own doc on the trailing check this
/// depends on.
fn is_confluent_secret_boundary(byte: u8) -> bool {
    pattern::is_base64_body(byte) || byte == b'_' || byte == b'-'
}

/// The documented checksum length: the final 6 of the 60 body bytes.
const CHECKSUM_LEN: usize = 6;

const PREFIXED_SIGNALS: [&str; 3] = [
    "confluent-documented-prefix",
    "base64-exact-length",
    "crc32-checksum",
];

/// The IEEE CRC-32 lookup table (reflected polynomial `0xEDB88320`), built
/// at compile time so the core keeps its empty dependency list.
const CRC32_TABLE: [u32; 256] = {
    let mut table = [0u32; 256];
    let mut index = 0;
    while index < 256 {
        #[allow(clippy::cast_possible_truncation)]
        let mut crc = index as u32;
        let mut bit = 0;
        while bit < 8 {
            crc = if crc & 1 == 1 {
                (crc >> 1) ^ 0xEDB8_8320
            } else {
                crc >> 1
            };
            bit += 1;
        }
        table[index] = crc;
        index += 1;
    }
    table
};

/// The IEEE CRC-32 (the one zlib, PNG and Ethernet use) of `bytes`.
fn crc32(bytes: &[u8]) -> u32 {
    !bytes.iter().fold(!0u32, |crc, &byte| {
        CRC32_TABLE[usize::from(crc.to_le_bytes()[0] ^ byte)] ^ (crc >> 8)
    })
}

const STANDARD_BASE64: &[u8; 64] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// The documented checksum of `body`: its CRC-32 as 4 little-endian bytes,
/// standard-base64 encoded, first [`CHECKSUM_LEN`] characters (the 8-byte
/// padded encoding minus its trailing `==`).
fn documented_checksum(body: &[u8]) -> [u8; CHECKSUM_LEN] {
    let [b0, b1, b2, b3] = crc32(body).to_le_bytes();
    let sextets = [
        b0 >> 2,
        ((b0 & 0x03) << 4) | (b1 >> 4),
        ((b1 & 0x0f) << 2) | (b2 >> 6),
        b2 & 0x3f,
        b3 >> 2,
        (b3 & 0x03) << 4,
    ];
    sextets.map(|sextet| STANDARD_BASE64[usize::from(sextet)])
}

/// `true` when the matched `cflt` value's final [`CHECKSUM_LEN`] bytes equal
/// the documented checksum of the 54 body bytes between the prefix and the
/// checksum -- the [`pattern::PostCheck`] the exact-length shape alone
/// cannot express. `start..end` is the whole match, prefix included.
fn checksum_matches(bytes: &[u8], start: usize, end: usize) -> bool {
    let body_start = start + SECRET_PREFIX.len();
    let checksum_start = end - CHECKSUM_LEN;
    documented_checksum(&bytes[body_start..checksum_start]) == bytes[checksum_start..end]
}

/// The `cflt`-prefixed current-format secret: an exact `cflt` + 60-byte
/// base64-body shape whose final 6 bytes are the documented CRC-32 checksum
/// ([`checksum_matches`]), unconditionally [`Confidence::High`] and
/// [`Specificity::Provider`] -- no context needed, matching
/// [`super::additional_providers::NPM`] and
/// [`super::additional_providers::DIGITALOCEAN`]'s own "documented literal
/// prefix is evidence enough by itself" precedent.
pub(super) const CONFLUENT_CLOUD_API_SECRET: KnownFormatProviderDetector =
    KnownFormatProviderDetector::new(
        "confluent-cloud-api-secret",
        "confluent_cloud_api_secret",
        &[PrefixShape::exact(
            SECRET_PREFIX,
            PREFIXED_BODY_LEN,
            pattern::is_base64_body,
            &PREFIXED_SIGNALS,
        )
        .with_post_check(checksum_matches)],
        is_confluent_secret_boundary,
    );

/// `true` when `needle` (ASCII, case-insensitive) occurs anywhere in `line`.
fn line_contains_ci(line: &str, needle: &str) -> bool {
    text::contains_ci(line, needle)
}

/// Every non-overlapping, boundary-checked bare run of exactly
/// [`LEGACY_SECRET_LEN`] `alphabet` bytes, left to right.
fn scan_bare_legacy_runs(
    input: &str,
    alphabet: Alphabet,
    boundary: Alphabet,
) -> Vec<(usize, usize)> {
    let bytes = input.as_bytes();
    let mut matches = Vec::new();
    let mut start = 0;
    while start < bytes.len() {
        if !alphabet(bytes[start]) {
            start += 1;
            continue;
        }
        let run_end = pattern::run_end(bytes, start, alphabet);
        if run_end - start == LEGACY_SECRET_LEN
            && pattern::boundary_ok(bytes, start, run_end, boundary)
        {
            matches.push((start, run_end));
        }
        start = run_end;
    }
    matches
}

/// How many lines above a `basic.auth.user.info` property the Confluent
/// context may sit (issue #933): the `schema.registry.url` line, the
/// `basic.auth.credentials.source` line, and one more property.
pub(super) const PROPERTIES_LOOKBACK_LINES: usize = 3;

/// `true` for a Java `.properties` (or `.conf`) line: a comment (`#`, `!`)
/// or a `name=value` / `name: value` property whose name is `[A-Za-z0-9._-]+`.
fn is_properties_line(line: &str) -> bool {
    let trimmed = line.trim_start_matches([' ', '\t']);
    if trimmed.starts_with(['#', '!']) {
        return true;
    }
    let name_len = trimmed
        .bytes()
        .take_while(|&byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
        .count();
    name_len > 0 && matches!(trimmed.as_bytes().get(name_len), Some(b'=' | b':'))
}

/// `true` when `previous` (the lines before the value's line, oldest first)
/// ends with at most [`PROPERTIES_LOOKBACK_LINES`] property lines, one of
/// which names `confluent` (`schema.registry.url=https://psrc-...confluent.cloud`).
fn ends_inside_confluent_properties(previous: &[&str]) -> bool {
    for line in previous.iter().rev().take(PROPERTIES_LOOKBACK_LINES) {
        if !is_properties_line(line) {
            return false;
        }
        if line_contains_ci(line, CONTEXT_KEYWORD) {
            return true;
        }
    }
    false
}

/// `true` when the value at `value_start` is the secret half of a Schema
/// Registry `basic.auth.user.info=<key id>:<secret>` property (or its
/// `schema.registry.`-prefixed client form): the line is that property, and
/// only an alphanumeric key id and `:` sit between its operator and the
/// value.
fn is_basic_auth_user_info_secret(line: &str, value_start: usize) -> bool {
    let trimmed_start = line.len() - line.trim_start_matches([' ', '\t']).len();
    let Some(operator) = line[trimmed_start..]
        .find(['=', ':'])
        .map(|at| trimmed_start + at)
    else {
        return false;
    };
    let name = line[trimmed_start..operator].trim_end_matches([' ', '\t']);
    let key_id = line[operator + 1..value_start]
        .trim_start_matches([' ', '\t'])
        .strip_suffix(':');
    name.to_ascii_lowercase().ends_with("basic.auth.user.info")
        && key_id
            .is_some_and(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_alphanumeric()))
}

/// Internal retention hint for the built-in incremental scanner: `true` when
/// the retained lines end inside a Confluent properties block
/// ([`ends_inside_confluent_properties`]), so the session keeps the unit
/// open while a `basic.auth.user.info` line can still follow (issue #933).
/// The window it holds is exactly the one
/// [`ConfluentLegacyApiSecretDetector`] reads back.
#[cfg(test)]
pub(crate) fn has_open_confluent_properties(input: &str) -> bool {
    has_open_confluent_properties_in(&super::lookback_tail(input))
}

/// [`has_open_confluent_properties`] over a [`super::lookback_tail`].
pub(crate) fn has_open_confluent_properties_in(tail: &[&str]) -> bool {
    ends_inside_confluent_properties(text::tail_lines(tail, PROPERTIES_LOOKBACK_LINES))
}

/// Detects a legacy (pre-`cflt`) Confluent Cloud API secret: a bare 64-byte
/// base64-body run on the same line as a case-insensitive `confluent`
/// substring. Never emitted without that context; see the module doc.
pub(super) struct ConfluentLegacyApiSecretDetector;

impl Detector for ConfluentLegacyApiSecretDetector {
    fn id(&self) -> &'static str {
        "confluent-cloud-api-secret-legacy"
    }

    fn detect(
        &self,
        input: &str,
        _context: &DetectorContext,
    ) -> Result<Vec<Candidate>, DetectorFailure> {
        let mut candidates = Vec::new();
        text::for_each_long_run_line(input, |line_start, line_end| {
            let line = &input[line_start..line_end];
            let raw_matches =
                scan_bare_legacy_runs(line, pattern::is_base64_body, is_confluent_secret_boundary);
            if raw_matches.is_empty() {
                return;
            }
            let same_line = line_contains_ci(line, CONTEXT_KEYWORD);
            let in_properties_block = !same_line && {
                let previous = text::preceding_lines(input, line_start, PROPERTIES_LOOKBACK_LINES);
                ends_inside_confluent_properties(&previous)
            };
            if !same_line && !in_properties_block {
                return;
            }
            for (relative_start, relative_end) in raw_matches {
                if !same_line && !is_basic_auth_user_info_secret(line, relative_start) {
                    continue;
                }
                let value = &line[relative_start..relative_end];
                // A `cflt`-led run is the current generation's shape, which
                // `CONFLUENT_CLOUD_API_SECRET` alone judges: legacy secrets
                // are the ones that "lack the `cflt` prefix", so a `cflt`
                // value whose checksum fails is no secret at all rather than
                // a legacy one (#738).
                if value.starts_with(SECRET_PREFIX)
                    || text::is_repeated_character_filler(value)
                    || text::is_labelled_digest(line, relative_start)
                {
                    continue;
                }
                let Some(range) =
                    ByteRange::new(line_start + relative_start, line_start + relative_end)
                else {
                    continue;
                };
                let (confidence, signal) = if !same_line {
                    // Issue #936: `basic.auth.user.info` names the
                    // credential and the Confluent-named property above binds
                    // it, as a Confluent-named key does.
                    (Confidence::High, "confluent-properties-block")
                } else if text::is_provider_named_assignment(
                    line,
                    relative_start,
                    &[CONTEXT_KEYWORD],
                ) {
                    (Confidence::High, "confluent-named-assignment")
                } else {
                    (Confidence::Medium, "confluent-keyword-cooccurrence")
                };
                candidates.push(
                    Candidate::built_in("confluent_cloud_api_secret_legacy", confidence, range)
                        .with_specificity(Specificity::Provider)
                        .with_signals([signal]),
                );
            }
        });
        Ok(candidates)
    }
}

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

    /// Exactly [`PREFIXED_BODY_LEN`] base64-body bytes whose final
    /// [`CHECKSUM_LEN`] bytes are the documented checksum of the first 54.
    /// Locally constructed synthetic value; never provider-issued.
    const PREFIXED_BODY: &str = "SYNTHETIC0REVOKED0PrefixedSecretValue0ABCDEFGHIJKLMNOPn2NMow";
    const _: () = assert!(PREFIXED_BODY.len() == PREFIXED_BODY_LEN);

    /// Exactly [`LEGACY_SECRET_LEN`] base64-body bytes, carrying no
    /// `confluent` substring of its own so keyword-gating tests are clean.
    /// Locally constructed synthetic value; never provider-issued.
    const LEGACY_BODY: &str = "SYNTHETIC0REVOKED0LegacyBareSecretValue0NoPrefix0ABCDEFGHIJKLMNO";
    const _: () = assert!(LEGACY_BODY.len() == LEGACY_SECRET_LEN);

    /// A synthetic Confluent Cloud API Key ID (the non-secret half of the
    /// pair): 16 bytes, matching the documented example's shape. Never
    /// itself a finding; see the module doc.
    const KEY_ID: &str = "SYNTHETICKEYID01";
    const _: () = assert!(KEY_ID.len() == 16);

    fn prefixed_secret() -> String {
        format!("{SECRET_PREFIX}{PREFIXED_BODY}")
    }

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

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

    // -- Structural (`cflt`-prefixed) detector -----------------------------

    #[test]
    fn detects_a_prefixed_secret_with_no_context_needed() {
        let value = prefixed_secret();
        let candidates = detect_prefixed(&value);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].type_name(), "confluent_cloud_api_secret");
        assert_eq!(candidates[0].confidence(), Confidence::High);
        assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
        assert_eq!(
            candidates[0].range(),
            ByteRange::new(0, value.len()).unwrap()
        );
    }

    /// The issue #738 canonical body: 54 synthetic bytes and the
    /// checksum each documented or undocumented recipe gives for them.
    const CANONICAL_BODY: &str = "SYNTHETIC0REVOKED0ConfluentChecksumFixture0ABCDEFGHIJK";
    const _: () = assert!(CANONICAL_BODY.len() == PREFIXED_BODY_LEN - CHECKSUM_LEN);

    #[test]
    fn computes_the_ieee_crc32_check_value() {
        assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
        assert_eq!(crc32(b""), 0);
    }

    #[test]
    fn computes_the_documented_little_endian_standard_base64_checksum() {
        assert_eq!(&documented_checksum(CANONICAL_BODY.as_bytes()), b"E3aswA");
        let body = &PREFIXED_BODY.as_bytes()[..PREFIXED_BODY_LEN - CHECKSUM_LEN];
        assert_eq!(
            &documented_checksum(body),
            &PREFIXED_BODY.as_bytes()[PREFIXED_BODY_LEN - CHECKSUM_LEN..]
        );
    }

    #[test]
    fn accepts_only_the_documented_checksum() {
        let valid = format!("{SECRET_PREFIX}{CANONICAL_BODY}E3aswA");
        assert_eq!(detect_prefixed(&valid).len(), 1);
        // A changed first checksum byte, the big-endian serialization, and a
        // CRC over `cflt` + body each keep prefix, length and alphabet.
        for checksum in ["A3aswA", "wKx2Ew", "pw1DTQ"] {
            let input = format!("{SECRET_PREFIX}{CANONICAL_BODY}{checksum}");
            assert!(detect_prefixed(&input).is_empty(), "{checksum}");
        }
    }

    #[test]
    fn rejects_a_valid_checksum_after_a_changed_body_byte() {
        let mut body = PREFIXED_BODY.to_owned();
        body.replace_range(0..1, "T");
        assert!(detect_prefixed(&format!("{SECRET_PREFIX}{body}")).is_empty());
    }

    #[test]
    fn rejects_a_prefixed_body_one_byte_short_of_the_documented_length() {
        let short_body = &PREFIXED_BODY[..PREFIXED_BODY_LEN - 1];
        assert!(detect_prefixed(&format!("{SECRET_PREFIX}{short_body}")).is_empty());
    }

    #[test]
    fn rejects_a_prefixed_body_one_byte_longer_than_the_documented_length() {
        assert!(detect_prefixed(&format!("{SECRET_PREFIX}{PREFIXED_BODY}a")).is_empty());
    }

    #[test]
    fn rejects_undocumented_near_miss_prefixes() {
        for input in [
            format!("clft{PREFIXED_BODY}"),
            format!("Cflt{PREFIXED_BODY}"),
            format!("cfltx{PREFIXED_BODY}"),
            format!("cfl{PREFIXED_BODY}"),
        ] {
            assert!(detect_prefixed(&input).is_empty(), "{input}");
        }
    }

    #[test]
    fn rejects_the_prefix_embedded_in_a_wider_identifier() {
        assert!(detect_prefixed(&format!("legacy_{}", prefixed_secret())).is_empty());
        assert!(detect_prefixed(&format!("{}_backup", prefixed_secret())).is_empty());
    }

    #[test]
    fn rejects_a_doc_style_placeholder_value() {
        assert!(detect_prefixed(&format!("{SECRET_PREFIX}${{CONFLUENT_API_SECRET}}")).is_empty());
    }

    #[test]
    fn never_flags_a_bare_key_id_by_itself() {
        assert!(detect_prefixed(KEY_ID).is_empty());
        assert!(detect_legacy(&format!("confluent {KEY_ID}")).is_empty());
    }

    #[test]
    fn rejects_benign_confluent_context_with_no_secret_present() {
        for input in [
            "bootstrap.servers=pkc-abc123.us-east-1.aws.confluent.cloud:9092",
            "cluster_id: lkc-abc123",
            "schema.registry.url=https://lsrc-abc123.us-east-1.aws.confluent.cloud",
        ] {
            assert!(detect_prefixed(input).is_empty(), "{input}");
            assert!(detect_legacy(input).is_empty(), "{input}");
        }
    }

    #[test]
    fn rejects_a_hash_algorithm_labelled_legacy_shaped_digest() {
        // Issue #744: a container image digest on a line naming Confluent.
        for input in [
            format!("image: confluentinc/cp-server@sha256:{LEGACY_BODY}"),
            format!("image: confluentinc/cp-server@SHA256:{LEGACY_BODY}"),
            format!("confluent-7.6.0.tar.gz sha256={LEGACY_BODY}"),
            format!("confluent checksum sha-256: {LEGACY_BODY}"),
        ] {
            assert!(detect_legacy(&input).is_empty(), "{input}");
        }
    }

    #[test]
    fn a_digest_label_does_not_hide_a_legacy_secret_after_an_ordinary_name() {
        let input = format!("CONFLUENT_API_SECRET={LEGACY_BODY}");
        let candidates = detect_legacy(&input);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].range().start(), 21);
        assert_eq!(candidates[0].range().end(), 85);
        let input = format!("confluent image@sha256:abc api_secret={LEGACY_BODY}");
        assert_eq!(detect_legacy(&input).len(), 1);
    }

    #[test]
    fn accepts_env_json_yaml_and_quoted_contexts() {
        let value = prefixed_secret();
        for input in [
            format!("CONFLUENT_CLOUD_API_SECRET={value}"),
            format!("{{\"apiSecret\": \"{value}\"}}"),
            format!("sasl.password: {value}"),
            format!("sasl.password=\"{value}\""),
        ] {
            let candidates = detect_prefixed(&input);
            assert_eq!(candidates.len(), 1, "{input}");
            let start = input.rfind(&value).unwrap();
            assert_eq!(
                candidates[0].range(),
                ByteRange::new(start, start + value.len()).unwrap(),
                "{input}"
            );
        }
    }

    #[test]
    fn finds_a_match_across_crlf_and_a_unicode_prefix() {
        let value = prefixed_secret();
        let input = format!("# \u{1F511} caf\u{e9}\r\n{value}\r\n");
        let candidates = detect_prefixed(&input);
        assert_eq!(candidates.len(), 1);
        let start = input.find(&value).unwrap();
        assert_eq!(
            candidates[0].range(),
            ByteRange::new(start, start + value.len()).unwrap()
        );
    }

    #[test]
    fn finds_deterministic_findings_across_repeated_calls() {
        let value = prefixed_secret();
        assert_eq!(detect_prefixed(&value), detect_prefixed(&value));
    }

    #[test]
    fn reports_a_repeated_identical_value_once_per_occurrence() {
        let value = prefixed_secret();
        let input = format!("{value} {value}");
        assert_eq!(detect_prefixed(&input).len(), 2);
    }

    #[test]
    fn stays_bounded_over_a_long_run_of_near_miss_prefixes() {
        let short_body = &PREFIXED_BODY[..PREFIXED_BODY_LEN - 1];
        let input = format!("{SECRET_PREFIX}{short_body} ").repeat(10_000);
        assert_eq!(detect_prefixed(&input).len(), 0);
    }

    // -- Legacy (bare, keyword-gated) detector ------------------------------

    #[test]
    fn detects_a_legacy_secret_under_a_confluent_named_key_at_high_confidence() {
        let input = format!("CONFLUENT_API_SECRET={LEGACY_BODY}");
        let candidates = detect_legacy(&input);
        assert_eq!(candidates.len(), 1);
        assert_eq!(
            candidates[0].type_name(),
            "confluent_cloud_api_secret_legacy"
        );
        assert_eq!(candidates[0].confidence(), Confidence::High);
        assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
        let start = input.rfind(LEGACY_BODY).unwrap();
        assert_eq!(
            candidates[0].range(),
            ByteRange::new(start, start + LEGACY_BODY.len()).unwrap()
        );
    }

    #[test]
    fn never_reports_a_cflt_led_run_as_a_legacy_secret() {
        for checksum in ["E3aswA", "A3aswA"] {
            let input = format!("CONFLUENT_CLOUD_API_SECRET=cflt{CANONICAL_BODY}{checksum}");
            assert!(detect_legacy(&input).is_empty(), "{checksum}");
        }
    }

    #[test]
    fn rejects_a_bare_legacy_secret_with_no_context() {
        assert!(detect_legacy(LEGACY_BODY).is_empty());
    }

    #[test]
    fn rejects_a_legacy_secret_whose_context_is_on_a_different_line() {
        let input = format!("# confluent cluster credentials\n{LEGACY_BODY}\n");
        assert!(detect_legacy(&input).is_empty());
    }

    #[test]
    fn rejects_a_legacy_body_one_byte_short_or_long() {
        assert!(
            detect_legacy(&format!(
                "confluent {}",
                &LEGACY_BODY[..LEGACY_SECRET_LEN - 1]
            ))
            .is_empty()
        );
        assert!(detect_legacy(&format!("confluent {LEGACY_BODY}a")).is_empty());
    }

    #[test]
    fn rejects_a_repeated_character_filler_value() {
        assert!(detect_legacy(&format!("confluent {}", "a".repeat(LEGACY_SECRET_LEN))).is_empty());
    }

    #[test]
    fn rejects_an_environment_variable_reference() {
        assert!(detect_legacy("confluent CONFLUENT_API_SECRET=${CONFLUENT_API_SECRET}").is_empty());
    }

    #[test]
    fn matches_confluent_keyword_case_insensitively() {
        for keyword in ["Confluent", "CONFLUENT", "confluent"] {
            let input = format!("{keyword}_SECRET={LEGACY_BODY}");
            assert_eq!(detect_legacy(&input).len(), 1, "{keyword}");
        }
    }

    #[test]
    fn finds_a_qualified_legacy_match_across_crlf_and_a_unicode_prefix() {
        let input = format!("# \u{1F511} caf\u{e9}\r\nconfluent {LEGACY_BODY}\r\n");
        let candidates = detect_legacy(&input);
        assert_eq!(candidates.len(), 1);
        let start = input.rfind(LEGACY_BODY).unwrap();
        assert_eq!(
            candidates[0].range(),
            ByteRange::new(start, start + LEGACY_BODY.len()).unwrap()
        );
    }

    #[test]
    fn finds_deterministic_legacy_findings_across_repeated_calls() {
        let input = format!("confluent {LEGACY_BODY}");
        assert_eq!(detect_legacy(&input), detect_legacy(&input));
    }

    #[test]
    fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
        let input = format!("{LEGACY_BODY} ").repeat(10_000);
        assert_eq!(detect_legacy(&input).len(), 0);
    }

    fn schema_registry_config(url: &str, separator: &str, secret: &str) -> String {
        format!(
            "schema.registry.url={url}\n{separator}basic.auth.credentials.source=USER_INFO\n\
             basic.auth.user.info={KEY_ID}:{secret}\n"
        )
    }

    #[test]
    fn detects_a_basic_auth_user_info_secret_below_a_confluent_registry_url() {
        // Issue #933.
        let url = "https://psrc-3n9vd.us-east-2.aws.confluent.cloud";
        for input in [
            schema_registry_config(url, "", LEGACY_BODY),
            schema_registry_config(url, "# client\n", LEGACY_BODY),
            format!(
                "schema.registry.url: {url}\nschema.registry.basic.auth.user.info: {KEY_ID}:{LEGACY_BODY}"
            ),
            schema_registry_config(url, "", LEGACY_BODY).replace('\n', "\r\n"),
        ] {
            let found = detect_legacy(&input);
            assert_eq!(found.len(), 1, "{input:?}");
            let range = found[0].range();
            assert_eq!(&input[range.start()..range.end()], LEGACY_BODY);
            // Issue #936: high, so the default policy redacts it.
            assert_eq!(found[0].confidence(), Confidence::High);
        }
    }

    #[test]
    fn rejects_a_properties_block_without_confluent_context_nearby() {
        let url = "https://psrc-3n9vd.us-east-2.aws.confluent.cloud";
        for input in [
            // Another registry host, a blank line, a free-text line, and a
            // confluent line too far above.
            schema_registry_config("https://registry.example.test", "", LEGACY_BODY),
            schema_registry_config(url, "\n", LEGACY_BODY),
            schema_registry_config(url, "see the wiki for rotation\n", LEGACY_BODY),
            schema_registry_config(url, "a=1\nb=2\n", LEGACY_BODY),
            // Another property name, and no key id in front.
            format!("schema.registry.url={url}\nssl.truststore.password={LEGACY_BODY}\n"),
            format!("schema.registry.url={url}\nbasic.auth.user.info={LEGACY_BODY}\n"),
        ] {
            assert!(detect_legacy(&input).is_empty(), "{input:?}");
        }
    }

    #[test]
    fn the_retention_hint_holds_exactly_the_properties_window_open() {
        for open in [
            "bootstrap.servers=pkc-1.confluent.cloud:9092\n",
            "schema.registry.url=https://psrc-1.confluent.cloud\na=1\nb=2\n",
            "# confluent cloud\n",
        ] {
            assert!(has_open_confluent_properties(open), "{open:?}");
        }
        for closed in [
            "",
            "schema.registry.url=https://registry.example.test\n",
            "schema.registry.url=https://psrc-1.confluent.cloud\na=1\nb=2\nc=3\n",
            "schema.registry.url=https://psrc-1.confluent.cloud\n\n",
            "we use confluent cloud\n",
        ] {
            assert!(!has_open_confluent_properties(closed), "{closed:?}");
        }
    }
}