keyhog-scanner 0.5.50

keyhog-scanner: high-performance SIMD-accelerated secret detection engine
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
use keyhog_scanner::context::{infer_context, CodeContext};
use keyhog_scanner::testing::context::{
    is_false_positive_context, is_false_positive_match_context,
};

#[test]
fn assignment_context() {
    let lines = vec!["API_KEY = sk-proj-abc123"];
    assert_eq!(infer_context(&lines, 0, None), CodeContext::Assignment);
}

#[test]
fn comment_context() {
    // A prose comment with NO assignment/mapping shape is Comment. (A commented
    // `key: value` / `KEY=value` is deliberately classified Assignment instead -
    // see `commented_assignment_context` - so a secret hidden in a commented
    // config line is not downgraded. The earlier fixture `# old key: sk-proj-...`
    // carried a `key: value` mapping and therefore correctly resolved to
    // Assignment under that policy; use genuine prose here.)
    let lines = vec!["# old key was sk-proj-abc123, now rotated"];
    assert_eq!(infer_context(&lines, 0, None), CodeContext::Comment);
}

#[test]
fn commented_assignment_context() {
    for line in [
        "# API_KEY=sk-proj-abc123",
        "// token = sk-proj-abc123",
        "/* SECRET: sk-proj-abc123 */",
        "<!-- OPENAI_API_KEY=sk-proj-abc123 -->",
    ] {
        assert_eq!(
            infer_context(&[line], 0, None),
            CodeContext::Assignment,
            "{line:?} should be treated as a commented-out config assignment"
        );
    }
}

#[test]
fn test_file_context() {
    let lines = vec!["key = sk-proj-abc123"];
    assert_eq!(
        infer_context(&lines, 0, Some("tests/test_auth.py")),
        CodeContext::TestCode
    );
}

#[test]
fn encrypted_block_context() {
    let lines = vec!["$ANSIBLE_VAULT;1.1;AES256", "6162636465666768"];
    assert_eq!(infer_context(&lines, 1, None), CodeContext::Encrypted);
}

#[test]
fn documentation_context() {
    let lines = vec![
        "```bash",
        "curl -H 'Authorization: Bearer sk-proj-abc'",
        "```",
    ];
    assert_eq!(infer_context(&lines, 1, None), CodeContext::Documentation);
}

#[test]
fn test_function_context() {
    let lines = vec![
        "def test_api_call():",
        "    key = 'sk-proj-abc123'",
        "    assert call(key)",
    ];
    assert_eq!(infer_context(&lines, 1, None), CodeContext::TestCode);
}

#[test]
fn confidence_multipliers() {
    assert!(
        CodeContext::Assignment.confidence_multiplier()
            > CodeContext::Comment.confidence_multiplier()
    );
    assert!(
        CodeContext::Comment.confidence_multiplier()
            > CodeContext::Encrypted.confidence_multiplier()
    );
    assert!(
        CodeContext::TestCode.confidence_multiplier()
            < CodeContext::Assignment.confidence_multiplier()
    );
}

#[test]
fn false_positive_context_detects_go_sum() {
    let lines = vec!["github.com/example/module v1.0.0 h1:AKIAIOSFODNN7EXAMPLEabc"];
    assert!(is_false_positive_context(&lines, 0, Some("deps/go.sum")));
}

#[test]
fn false_positive_context_does_not_suppress_bare_h1_outside_go_sum() {
    let lines = vec!["api_secret = \"h1:AKIAIOSFODNN7EXAMPLEabc\""];
    assert!(
        !is_false_positive_context(&lines, 0, Some("src/config.env")),
        "a bare h1: substring outside go.sum must not suppress a real secret"
    );
}

#[test]
fn false_positive_context_detects_strict_go_sum_checksum_without_path() {
    let lines =
        vec!["github.com/example/module v1.0.0 h1:Fr1vK8xdpbQ5OCaCB3ABAfRtq5B4JZc0jRUXPv7Q3k0="];
    assert!(
        is_false_positive_context(&lines, 0, None),
        "pathless go.sum-shaped h1 checksums should still suppress when the checksum token shape is strict"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_adjacent_go_sum_checksum() {
    let text = concat!(
        "github.com/example/module v1.0.0 h1:Fr1vK8xdpbQ5OCaCB3ABAfRtq5B4JZc0jRUXPv7Q3k0=\n",
        "api_key = sk-proj-abcdefghijklmnopqrstuvwxyz123456\n",
    );
    let offset = text.find("sk-proj").expect("fixture contains secret");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "a Go module checksum on a neighboring line must not suppress the credential line"
    );
}

#[test]
fn false_positive_context_detects_configmap_binary_data_block() {
    let lines = vec![
        "kind: ConfigMap",
        "binaryData:",
        "  cert-fingerprint-sha256: Z2hwX2FiYw==",
    ];
    assert!(is_false_positive_context(&lines, 2, None));
}

#[test]
fn false_positive_match_context_does_not_suppress_configmap_without_line_scope() {
    let text = "kind: ConfigMap\nbinaryData:\n  cert-fingerprint-sha256: Z2hwX2FiYw==\n";
    let offset = text.find("Z2hw").expect("fixture contains base64 value");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "ConfigMap binaryData suppression requires line-indexed YAML block ownership"
    );
}

#[test]
fn false_positive_context_detects_later_configmap_binary_data_value() {
    let text = concat!(
        "kind: ConfigMap\n",
        "binaryData:\n",
        "  first.bin: QUJDREVGRw==\n",
        "  second.bin: SElKS0xNTg==\n",
        "  third.bin: T1BRUlNUVQ==\n",
    );
    let lines: Vec<_> = text.lines().collect();
    assert!(is_false_positive_context(&lines, 4, None));
}

#[test]
fn false_positive_context_does_not_suppress_secret_like_configmap_binary_data_value() {
    let lines = vec![
        "kind: ConfigMap",
        "binaryData:",
        "  api-token: sk-proj-abcdefghijklmnopqrstuvwxyz123456",
    ];
    assert!(
        !is_false_positive_context(&lines, 2, None),
        "binaryData suppression is for base64 scalar data, not secret-shaped cleartext values"
    );
}

#[test]
fn false_positive_context_does_not_suppress_data_block_after_configmap_binary_data() {
    let lines = vec![
        "kind: ConfigMap",
        "binaryData:",
        "  cert.bin: QUJDREVGRw==",
        "data:",
        "  api-token: Z2hwX2FiYw==",
    ];
    assert!(
        !is_false_positive_context(&lines, 4, None),
        "binaryData suppression must stop when indentation returns to a sibling data block"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_data_block_after_configmap_binary_data() {
    let text = concat!(
        "kind: ConfigMap\n",
        "binaryData:\n",
        "  cert.bin: QUJDREVGRw==\n",
        "data:\n",
        "  api-token: Z2hwX2FiYw==\n",
    );
    let offset = text.rfind("Z2hw").expect("fixture contains data value");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "match-window binaryData suppression must honor YAML sibling block boundaries"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_secret_like_configmap_binary_data_value() {
    let text =
        "kind: ConfigMap\nbinaryData:\n  api-token: sk-proj-abcdefghijklmnopqrstuvwxyz123456\n";
    let offset = text.find("sk-proj").expect("fixture contains secret");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "match-window binaryData suppression must not hide cleartext secret-shaped values"
    );
}

// ── ConfigMap binaryData block-header lookback (the >8-entry FP regression) ───
//
// `is_inside_configmap_binary_data_block` walks back to the `binaryData:` header
// by indentation. A fixed 8-line lookback truncated that walk, so every 9th and
// later base64 blob in a block failed to find its header and leaked as a false
// positive. The header search now clears any realistic block. Entry `e` (0-based)
// of `configmap_binary_block(n)` lives at line index `2 + e`; the header is at
// line index 1.

/// A ConfigMap `binaryData:` block with `entries` base64 value lines.
fn configmap_binary_block(entries: usize) -> Vec<String> {
    const B64: [&str; 4] = [
        "QUJDREVGRw==",
        "SElKS0xNTg==",
        "T1BRUlNUVQ==",
        "Z2hwX2FiYw==",
    ];
    let mut lines = vec!["kind: ConfigMap".to_string(), "binaryData:".to_string()];
    for i in 0..entries {
        lines.push(format!("  entry-{i}.bin: {}", B64[i % B64.len()]));
    }
    lines
}

fn borrow(lines: &[String]) -> Vec<&str> {
    lines.iter().map(String::as_str).collect()
}

#[test]
fn configmap_binary_data_ninth_entry_beyond_old_cap_suppressed() {
    // The regression: the 9th entry (line index 10) sits past the old 8-line cap.
    let owned = configmap_binary_block(9);
    let lines = borrow(&owned);
    assert!(
        is_false_positive_context(&lines, 10, None),
        "9th binaryData entry must still resolve its header and be suppressed"
    );
}

#[test]
fn configmap_binary_data_eighth_entry_within_old_cap_still_suppressed() {
    // Boundary control: the 8th entry (index 9) was reachable under the old cap.
    let owned = configmap_binary_block(8);
    let lines = borrow(&owned);
    assert!(is_false_positive_context(&lines, 9, None));
}

#[test]
fn configmap_binary_data_first_entry_still_suppressed() {
    let owned = configmap_binary_block(9);
    let lines = borrow(&owned);
    assert!(is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_fiftieth_entry_suppressed() {
    let owned = configmap_binary_block(50);
    let lines = borrow(&owned);
    assert!(is_false_positive_context(&lines, 51, None));
}

#[test]
fn configmap_binary_data_hundredth_entry_suppressed() {
    let owned = configmap_binary_block(100);
    let lines = borrow(&owned);
    assert!(is_false_positive_context(&lines, 101, None));
}

#[test]
fn configmap_binary_data_two_hundredth_entry_suppressed() {
    let owned = configmap_binary_block(200);
    let lines = borrow(&owned);
    assert!(is_false_positive_context(&lines, 201, None));
}

#[test]
fn configmap_binary_data_thousandth_entry_suppressed() {
    // Well within the generous lookback bound; proves the cap is not merely a
    // slightly-larger magic number.
    let owned = configmap_binary_block(1000);
    let lines = borrow(&owned);
    assert!(is_false_positive_context(&lines, 1001, None));
}

#[test]
fn configmap_binary_data_all_hundred_entries_suppressed() {
    let owned = configmap_binary_block(100);
    let lines = borrow(&owned);
    for entry in 0..100 {
        assert!(
            is_false_positive_context(&lines, 2 + entry, None),
            "entry {entry} (line {}) must be suppressed",
            2 + entry
        );
    }
}

#[test]
fn configmap_binary_data_deep_secret_like_value_not_suppressed() {
    // A cleartext secret-shaped value deep in a large block must NOT be hidden.
    let mut owned = configmap_binary_block(15);
    owned.push("  api-token: sk-proj-abcdefghijklmnopqrstuvwxyz123456".to_string());
    let lines = borrow(&owned);
    assert!(
        !is_false_positive_context(&lines, 17, None),
        "a secret-shaped value must not be suppressed even deep in a binaryData block"
    );
}

#[test]
fn configmap_data_block_after_deep_binary_data_not_suppressed() {
    // A sibling `data:` block after a large binaryData block: its values are
    // secrets, not binary (the nearest dedent parent is `data:`, not the header).
    let mut owned = configmap_binary_block(15);
    owned.push("data:".to_string());
    owned.push("  api-token: Z2hwX2FiYw==".to_string());
    let lines = borrow(&owned);
    assert!(
        !is_false_positive_context(&lines, 18, None),
        "a data: block value after a deep binaryData block must not be suppressed"
    );
}

#[test]
fn configmap_binary_data_lookback_stops_at_first_dedent_even_if_header_below() {
    // The walk must return at the FIRST less-indented parent. A `binaryData:`
    // header that sits ABOVE an intervening non-header parent must not be reached.
    let lines = vec!["binaryData:", "otherblock:", "  entry.bin: QUJDREVGRw=="];
    assert!(
        !is_false_positive_context(&lines, 2, None),
        "the nearest dedent parent (otherblock:) wins; a binaryData header above it is not the owner"
    );
}

#[test]
fn configmap_binary_data_blank_lines_between_entries_still_suppressed() {
    let lines = vec![
        "kind: ConfigMap",
        "binaryData:",
        "  a.bin: QUJDREVGRw==",
        "",
        "  b.bin: SElKS0xNTg==",
        "",
        "  c.bin: T1BRUlNUVQ==",
    ];
    assert!(
        is_false_positive_context(&lines, 6, None),
        "blank lines between entries must be skipped, not stop the header search"
    );
}

#[test]
fn configmap_binary_data_header_case_insensitive() {
    let lines = vec!["kind: ConfigMap", "BinaryData:", "  a.bin: QUJDREVGRw=="];
    assert!(is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_header_trailing_whitespace_recognized() {
    let lines = vec!["kind: ConfigMap", "binaryData:   ", "  a.bin: QUJDREVGRw=="];
    assert!(is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_zero_indent_value_not_suppressed() {
    // A value at column 0 has no parent to own it.
    let lines = vec!["binaryData:", "x.bin: QUJDREVGRw=="];
    assert!(!is_false_positive_context(&lines, 1, None));
}

#[test]
fn configmap_binary_data_deeper_nested_values_suppressed() {
    // binaryData: at indent 2, values at indent 4.
    let lines = vec!["spec:", "  binaryData:", "    a.bin: QUJDREVGRw=="];
    assert!(is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_non_header_word_not_matched() {
    // `binaryDataFoo:` is a different key, not the block header.
    let lines = vec!["kind: ConfigMap", "binaryDataFoo:", "  a.bin: QUJDREVGRw=="];
    assert!(!is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_no_header_above_not_suppressed() {
    let lines = vec!["kind: ConfigMap", "data:", "  a.bin: QUJDREVGRw=="];
    assert!(!is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_quoted_value_suppressed() {
    let lines = vec![
        "kind: ConfigMap",
        "binaryData:",
        "  a.bin: \"QUJDREVGRw==\"",
    ];
    assert!(is_false_positive_context(&lines, 2, None));
}

#[test]
fn configmap_binary_data_dedent_to_metadata_parent_not_suppressed() {
    // The value's nearest dedent parent is `metadata:`, so the binaryData header
    // two blocks up does not own it.
    let lines = vec![
        "binaryData:",
        "  cert.bin: QUJDREVGRw==",
        "metadata:",
        "  name.bin: SElKS0xNTg==",
    ];
    assert!(!is_false_positive_context(&lines, 3, None));
}

// ── Rust `#[test]` attribute-block lookback (the >3-attr TestCode regression) ─
//
// A Rust test fn has an arbitrary name and is marked by a `#[test]`-family
// attribute. The attribute can sit several attribute / doc-comment lines above
// the `fn` signature; a fixed 3-line lookback missed it, leaving the test body
// at full confidence (a fixture-credential false positive). The block-walk now
// clears the whole contiguous attribute block, bounded, and still stops at the
// item boundary so a `#[test]` from an unrelated item above is never adopted.

/// The inferred context of the fixture line carrying the `sk-proj-` marker.
fn context_of_secret(src: &[&str]) -> CodeContext {
    let idx = src
        .iter()
        .position(|line| line.contains("sk-proj-"))
        .expect("fixture must contain a secret line");
    infer_context(src, idx, None)
}

const RUST_SECRET: &str = "    let key = \"sk-proj-abcdefghijklmnopqrstuvwxyz123456\";";

#[test]
fn test_attr_four_attrs_above_fn_is_test_code() {
    // The regression: `#[test]` is 4 lines above the signature (past the old cap).
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "#[ignore]",
            "#[should_panic]",
            "#[allow(clippy::unwrap_used)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_eight_attrs_above_fn_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "#[ignore]",
            "#[should_panic]",
            "#[allow(a)]",
            "#[allow(b)]",
            "#[allow(c)]",
            "#[allow(d)]",
            "#[allow(e)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_directly_above_fn_is_test_code() {
    assert_eq!(
        context_of_secret(&["#[test]", "fn arbitrary_name() {", RUST_SECRET, "}"]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_tokio_test_with_attrs_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[tokio::test]",
            "#[ignore]",
            "#[allow(x)]",
            "#[allow(y)]",
            "async fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_cfg_test_with_attrs_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            concat!("#[cfg(", "test)]"),
            "#[allow(a)]",
            "#[allow(b)]",
            "#[allow(c)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_pub_fn_with_attrs_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "#[ignore]",
            "#[allow(a)]",
            "#[allow(b)]",
            "pub fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_should_panic_with_message_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "#[should_panic(expected = \"boom\")]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_doc_comment_inside_block_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "#[allow(a)]",
            "/// a stray doc line inside the attribute block",
            "#[allow(b)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_doc_comment_above_test_attr_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "/// Tests the arbitrary thing.",
            "#[test]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_single_blank_between_attr_and_fn_is_test_code() {
    // rustfmt removes this, but unformatted input must still classify.
    assert_eq!(
        context_of_secret(&["#[test]", "", "fn arbitrary_name() {", RUST_SECRET, "}"]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_multiple_blanks_between_attr_and_fn_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "",
            "",
            "",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_test_case_parameterized_attr_is_test_code() {
    // `#[test_case(...)]` (the test-case crate) matches the `#[test` prefix.
    assert_eq!(
        context_of_secret(&[
            "#[test_case(1)]",
            "#[test_case(2)]",
            "#[allow(a)]",
            "#[allow(b)]",
            "fn arbitrary_name(n: u32) {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn test_attr_cfg_attr_miri_ignore_is_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "#[cfg_attr(miri, ignore)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::TestCode
    );
}

#[test]
fn non_test_fn_with_many_attrs_is_not_test_code() {
    assert_eq!(
        context_of_secret(&[
            "#[inline]",
            "#[allow(a)]",
            "#[allow(b)]",
            "#[allow(c)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::Assignment
    );
}

#[test]
fn non_test_fn_no_attrs_is_not_test_code() {
    assert_eq!(
        context_of_secret(&["fn arbitrary_name() {", RUST_SECRET, "}"]),
        CodeContext::Assignment
    );
}

#[test]
fn non_test_fn_after_previous_test_fn_is_not_test_code() {
    // The block-walk must stop at the previous item's boundary and NOT adopt its
    // `#[test]`.
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "fn previous_test() {",
            "    assert!(true);",
            "}",
            "",
            "#[allow(dead_code)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::Assignment
    );
}

#[test]
fn non_test_fn_with_code_between_attr_and_fn_is_not_test_code() {
    // A non-attribute line between `#[test]` and the fn ends the block.
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "const X: u32 = 1;",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::Assignment
    );
}

#[test]
fn test_attr_beyond_block_cap_is_not_test_code() {
    // `#[test]` separated from the fn by more blank lines than ATTR_BLOCK_LOOKBACK
    // is beyond the bounded walk, an absurd shape rustfmt never emits; the cap
    // trades this for a guaranteed-bounded walk.
    let mut src = vec!["#[test]".to_string()];
    for _ in 0..40 {
        src.push(String::new());
    }
    src.push("fn arbitrary_name() {".to_string());
    src.push(RUST_SECRET.to_string());
    src.push("}".to_string());
    let borrowed = borrow(&src);
    assert_eq!(context_of_secret(&borrowed), CodeContext::Assignment);
}

#[test]
fn non_test_fn_test_attr_beyond_closing_brace_is_not_test_code() {
    // `#[test]` above a previous item's closing brace must not leak downward.
    assert_eq!(
        context_of_secret(&[
            "#[test]",
            "}",
            "#[allow(dead_code)]",
            "fn arbitrary_name() {",
            RUST_SECRET,
            "}",
        ]),
        CodeContext::Assignment
    );
}

#[test]
fn test_attr_go_test_func_still_detected() {
    // The Go `func TestX` path is unaffected by the Rust attribute-block change.
    assert_eq!(
        context_of_secret(&["func TestArbitrary(t *testing.T) {", RUST_SECRET, "}",]),
        CodeContext::TestCode
    );
}

#[test]
fn false_positive_context_detects_git_lfs_pointer() {
    let lines = vec![
        "version https://git-lfs.github.com/spec/v1",
        "oid sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
        "size 12345",
    ];
    assert!(is_false_positive_context(&lines, 1, None));
}

#[test]
fn false_positive_match_context_detects_git_lfs_pointer() {
    let text = concat!(
        "version https://git-lfs.github.com/spec/v1\n",
        "oid sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n",
        "size 12345\n"
    );
    let offset = text.find("012345").expect("fixture contains oid");
    assert!(is_false_positive_match_context(text, offset, None));
}

#[test]
fn false_positive_match_context_does_not_suppress_adjacent_git_lfs_pointer() {
    let text = concat!(
        "version https://git-lfs.github.com/spec/v1\n",
        "oid sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n",
        "size 12345\n",
        "api_key = sk-proj-abcdefghijklmnopqrstuvwxyz123456\n",
    );
    let offset = text.find("sk-proj").expect("fixture contains secret");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "a Git LFS pointer in the surrounding window must not suppress a different credential line"
    );
}

#[test]
fn false_positive_context_does_not_suppress_nearby_git_lfs_prose() {
    let lines = vec![
        "# git-lfs stores large binaries out of band",
        "OPENAI_API_KEY = sk-proj-abcdefghijklmnopqrstuvwxyz123456",
    ];
    assert!(
        !is_false_positive_context(&lines, 1, None),
        "a nearby git-lfs mention is not a Git LFS pointer and must not hide a real credential"
    );
}

#[test]
fn false_positive_context_does_not_suppress_out_of_order_git_lfs_pointer() {
    let lines = vec![
        "size 12345",
        "version https://git-lfs.github.com/spec/v1",
        "oid sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
    ];
    assert!(
        !is_false_positive_context(&lines, 2, None),
        "Git LFS suppression requires the size line after the object id"
    );
}

#[test]
fn false_positive_context_does_not_suppress_malformed_git_lfs_oid() {
    let lines = vec![
        "version https://git-lfs.github.com/spec/v1",
        "oid sha256:sk-proj-abcdefghijklmnopqrstuvwxyz123456",
        "size 12345",
    ];
    assert!(
        !is_false_positive_context(&lines, 1, None),
        "Git LFS suppression requires a 64-hex object id, not any oid sha256 line"
    );
}

#[test]
fn false_positive_context_detects_integrity_hash() {
    let lines = vec!["integrity sha512-Z2hwX2FiYw=="];
    assert!(is_false_positive_context(&lines, 0, None));
}

#[test]
fn false_positive_match_context_detects_integrity_hash() {
    let text = r#"<script integrity="sha256-Z2hwX2FiYw=="></script>"#;
    let offset = text.find("Z2hw").expect("fixture contains sri hash");
    assert!(is_false_positive_match_context(text, offset, None));
}

#[test]
fn false_positive_context_does_not_suppress_adjacent_integrity_prose() {
    let lines = vec![
        "# integrity check uses sha256-digest metadata",
        "api_key = sk-proj-abcdefghijklmnopqrstuvwxyz123456",
    ];
    assert!(
        !is_false_positive_context(&lines, 1, None),
        "integrity prose on an adjacent line is not an SRI hash for the secret line"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_adjacent_integrity_prose() {
    let text = "# integrity check uses sha256-digest metadata\napi_key = sk-proj-abcdefghijklmnopqrstuvwxyz123456\n";
    let offset = text.find("sk-proj").expect("fixture contains secret");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "match-window integrity checks must not let adjacent prose hide the current secret line"
    );
}

#[test]
fn false_positive_context_does_not_suppress_integrity_key_secret_value() {
    let lines = vec!["integrity: sk-proj-abcdefghijklmnopqrstuvwxyz123456"];
    assert!(
        !is_false_positive_context(&lines, 0, None),
        "an integrity-named config key holding a secret-shaped value must surface"
    );
}

#[test]
fn false_positive_context_detects_sum_file_path() {
    let lines = vec!["github.com/example/module v1.0.0 checksum"];
    assert!(
        !is_false_positive_context(&lines, 0, Some("deps/go.sum")),
        "go.sum path alone is not enough; the line must carry an h1 checksum token"
    );
}

#[test]
fn false_positive_context_does_not_suppress_renovate_digest_without_match_offset() {
    let lines = vec![r#""branchName": "renovate/node-8f3a9b2c1d4e5f60""#];
    assert!(
        !is_false_positive_context(&lines, 0, None),
        "Renovate suppression requires the match offset so same-line credentials are not hidden"
    );
}

#[test]
fn false_positive_match_context_detects_renovate_digest() {
    let text = r#""branchName": "renovate/node-8f3a9b2c1d4e5f60""#;
    let offset = text.find("8f3a").expect("fixture contains digest");
    assert!(is_false_positive_match_context(text, offset, None));
}

#[test]
fn false_positive_match_context_detects_second_renovate_digest_on_line() {
    let text = r#""branches": ["renovate/no-digest", "renovate/node-8f3a9b2c1d4e5f60"]"#;
    let offset = text.find("8f3a").expect("fixture contains second digest");
    assert!(
        is_false_positive_match_context(text, offset, None),
        "Renovate suppression must inspect every renovate/ token on the line"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_renovate_branch_prefix() {
    let text = r#""branchName": "renovate/node-8f3a9b2c1d4e5f60""#;
    let offset = text.find("node").expect("fixture contains branch prefix");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "Renovate suppression must overlap the digest run, not any byte inside the branch name"
    );
}

#[test]
fn false_positive_context_does_not_suppress_adjacent_renovate_branch() {
    let lines = vec![
        r#""branchName": "renovate/node-8f3a9b2c1d4e5f60","#,
        r#""renovate_token": "ghp_abcdefghijklmnopqrstuvwxyz123456""#,
    ];
    assert!(
        !is_false_positive_context(&lines, 1, None),
        "a Renovate branch on an adjacent line is not context for suppressing a real token"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_adjacent_renovate_branch() {
    let text = concat!(
        r#""branchName": "renovate/node-8f3a9b2c1d4e5f60","#,
        "\n",
        r#""renovate_token": "ghp_abcdefghijklmnopqrstuvwxyz123456""#,
        "\n",
    );
    let offset = text.find("ghp_").expect("fixture contains token");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "match-window Renovate suppression must not leak to adjacent token lines"
    );
}

#[test]
fn false_positive_context_does_not_suppress_renovate_token_value() {
    let lines = vec![r#""renovate_token": "renovate/ghp_abcdefghijklmnopqrstuvwxyz123456""#];
    assert!(
        !is_false_positive_context(&lines, 0, None),
        "a secret value containing renovate/ is not a Renovate branch digest"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_renovate_token_value() {
    let text = r#""renovate_token": "renovate/ghp_abcdefghijklmnopqrstuvwxyz123456""#;
    let offset = text.find("ghp_").expect("fixture contains token");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "offset-aware Renovate suppression must not hide secret values containing renovate/"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_same_line_renovate_branch_neighbor() {
    let text = concat!(
        r#""branchName": "renovate/node-8f3a9b2c1d4e5f60", "#,
        r#""renovate_token": "ghp_abcdefghijklmnopqrstuvwxyz123456""#,
    );
    let offset = text.find("ghp_").expect("fixture contains token");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "Renovate suppression must apply to the matched branch token, not any other token on the same line"
    );
}

#[test]
fn false_positive_context_detects_cors_header() {
    let lines = vec!["Access-Control-Allow-Headers: Authorization, X-API-Key"];
    assert!(is_false_positive_context(&lines, 0, None));
}

#[test]
fn false_positive_context_does_not_suppress_custom_access_control_secret() {
    let lines = vec!["access-control-api-token: sk-proj-abcdefghijklmnopqrstuvwxyz123456"];
    assert!(
        !is_false_positive_context(&lines, 0, None),
        "only real CORS header names are context suppressors; custom secret-bearing names must surface"
    );
}

#[test]
fn false_positive_context_detects_http_cache_header() {
    let lines = vec![r#"ETag: W/concat!("xox", "b-8f3a9b2c1d4e5f60718293a4b5c6d7e8f9a0b")"#];
    assert!(is_false_positive_context(&lines, 0, None));
}

#[test]
fn false_positive_match_context_detects_http_cache_header() {
    let text = r#"ETag: W/concat!("xox", "b-8f3a9b2c1d4e5f60718293a4b5c6d7e8f9a0b")"#;
    let offset = text.find("xox").expect("fixture contains header token");
    assert!(is_false_positive_match_context(text, offset, None));
}

#[test]
fn false_positive_context_does_not_suppress_adjacent_etag_metadata() {
    let lines = vec![
        r#""etag": "v1","#,
        r#""api_key": "sk-proj-abcdefghijklmnopqrstuvwxyz123456""#,
    ];
    assert!(
        !is_false_positive_context(&lines, 1, None),
        "an adjacent JSON etag field is not an HTTP ETag header and must not hide a secret"
    );
}

#[test]
fn false_positive_context_does_not_suppress_adjacent_unquoted_etag_metadata() {
    let lines = vec![
        "etag: v1",
        "api_key = sk-proj-abcdefghijklmnopqrstuvwxyz123456",
    ];
    assert!(
        !is_false_positive_context(&lines, 1, None),
        "an adjacent unquoted etag metadata key is not an HTTP ETag header for the secret line"
    );
}

#[test]
fn false_positive_match_context_does_not_suppress_adjacent_etag_metadata() {
    let text = "etag: v1\napi_key = sk-proj-abcdefghijklmnopqrstuvwxyz123456\n";
    let offset = text.find("sk-proj").expect("fixture contains secret");
    assert!(
        !is_false_positive_match_context(text, offset, None),
        "match-window checks must not let adjacent etag metadata hide the current secret line"
    );
}