keyhog 0.5.38

keyhog: detects leaked credentials in source trees, git history, and cloud storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
//! Format-surface integration tests: every `--format` value
//! (text / json / jsonl / sarif / csv / html / junit) on an EMPTY corpus
//! and a NON-EMPTY corpus, asserting structural validity + the documented
//! exit code (0 = clean, 1 = unverified findings present).
//!
//! Every expectation below is derived directly from the real reporters in
//! `crates/core/src/report/{json,sarif,csv,html,junit,text}.rs`, the
//! format dispatch in `crates/cli/src/reporting.rs::report_with`, and the
//! exit-code ladder in `crates/cli/src/orchestrator/run.rs` (lines 332-340)
//! / the daemon path in `crates/cli/src/subcommands/scan.rs` (line 224-228):
//!
//!   * live credentials -> 10, scanner panic -> 11, any reported finding
//!     -> 1, otherwise -> 0. With no `--verify`, every finding is
//!     `VerificationResult::Skipped`, so a non-empty report exits 1.
//!
//! The product is the binary (`CARGO_BIN_EXE_keyhog`); these drive it the
//! way CI gates and SARIF/CSV consumers do.
//!
//! `--no-daemon` is passed on every scan so behavior never depends on
//! whether a `keyhog daemon` socket happens to exist on the test host
//! (see `scan.rs::daemon_route`): the in-process orchestrator is the
//! single source of truth for the exit-code ladder we assert.

use std::path::PathBuf;
use std::process::Command;

use tempfile::TempDir;

fn binary() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_keyhog"))
}

/// A planted credential that the embedded corpus catches with HIGH
/// confidence and that is NOT on the bundled test-fixture suppression
/// list (it is a freshly-randomized AKIA body, not AWS's published
/// `AKIAIOSFODNN7EXAMPLE`). `concat!` keeps the literal from tripping
/// keyhog's own self-scan / pre-commit hook on this very test file.
const AWS_KEY_FIXTURE: &str = concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n");

/// A file with no credential whatsoever -> the empty-corpus case.
const CLEAN_FIXTURE: &str = "fn main() { println!(\"hello, world\"); }\n";

/// Run `keyhog scan --no-daemon --format <fmt> <file>` over a temp file
/// containing `content`. Returns (stdout, stderr, exit-code).
fn scan_with_format(content: &str, fmt: &str) -> (String, String, Option<i32>) {
    let dir = TempDir::new().expect("tempdir");
    // Neutral filename + extension: no `test`/`fixture`/`example` token in
    // the path, so the test-path confidence down-weighting does not fire
    // and a genuine AKIA key reports at full strength.
    let path = dir.path().join("planted.env");
    std::fs::write(&path, content).expect("write fixture");

    let output = Command::new(binary())
        .arg("scan")
        .arg("--no-daemon")
        .arg("--format")
        .arg(fmt)
        .arg(&path)
        .output()
        .unwrap_or_else(|e| panic!("spawn keyhog scan --format {fmt}: {e}"));

    (
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
        output.status.code(),
    )
}

/// Same as `scan_with_format` but writes to `--output <file>` and returns
/// the file's bytes alongside the exit code. The reporting code in
/// `reporting.rs` atomic-writes the report to a NamedTempFile then renames,
/// so the on-disk bytes are the canonical structured artifact (no banner /
/// progress noise can leak in, unlike stdout).
fn scan_to_output_file(content: &str, fmt: &str) -> (String, Option<i32>) {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.env");
    std::fs::write(&path, content).expect("write fixture");
    let out = dir.path().join("report.out");

    let output = Command::new(binary())
        .arg("scan")
        .arg("--no-daemon")
        .arg("--format")
        .arg(fmt)
        .arg("--output")
        .arg(&out)
        .arg(&path)
        .output()
        .unwrap_or_else(|e| panic!("spawn keyhog scan --format {fmt} --output: {e}"));

    let bytes = std::fs::read_to_string(&out)
        .unwrap_or_else(|e| panic!("read --output file for {fmt}: {e}"));
    (bytes, output.status.code())
}

// ---------------------------------------------------------------------------
// EXIT-CODE CONTRACT across every format
// ---------------------------------------------------------------------------

/// Clean corpus -> exit 0 for EVERY format. The exit code is computed in
/// `orchestrator/run.rs` purely from finding count; it is format-agnostic.
#[test]
fn every_format_exits_0_on_clean_corpus() {
    for fmt in ["text", "json", "jsonl", "sarif", "csv", "html", "junit"] {
        let (_stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, fmt);
        assert_eq!(
            code,
            Some(0),
            "format `{fmt}` on a clean corpus must exit 0; stderr={stderr}"
        );
    }
}

/// Non-empty corpus (planted AKIA key, unverified) -> exit 1 for EVERY
/// format. No `--verify`, so the finding is `Skipped`, not `Live`; the
/// ladder lands on `has_new_entries` => `ExitCode::from(1)`.
#[test]
fn every_format_exits_1_on_planted_finding() {
    for fmt in ["text", "json", "jsonl", "sarif", "csv", "html", "junit"] {
        let (_stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, fmt);
        assert_eq!(
            code,
            Some(1),
            "format `{fmt}` with a planted unverified finding must exit 1 \
             (not 10/live, not 0/clean); stderr={stderr}"
        );
    }
}

/// The exit code must NOT be the live-credential code (10) or panic code
/// (11) for any format on the planted-but-unverified fixture. Pins the
/// ladder ordering: `has_live_credentials` is false without `--verify`.
#[test]
fn planted_finding_is_never_live_or_panic_exit() {
    for fmt in ["text", "json", "jsonl", "sarif", "csv", "html", "junit"] {
        let (_stdout, _stderr, code) = scan_with_format(AWS_KEY_FIXTURE, fmt);
        assert_ne!(
            code,
            Some(10),
            "format `{fmt}` must not report live (10) without --verify"
        );
        assert_ne!(code, Some(11), "format `{fmt}` must not report panic (11)");
        assert_ne!(
            code,
            Some(2),
            "format `{fmt}` must not report user/config error (2)"
        );
        assert_ne!(
            code,
            Some(3),
            "format `{fmt}` must not report system error (3)"
        );
    }
}

// ---------------------------------------------------------------------------
// JSON (JsonArrayReporter)
// ---------------------------------------------------------------------------

/// Empty corpus -> stdout is exactly `[]`. The reporter writes `[` in
/// `new()` and `]` in `finish()` with nothing between when no finding is
/// reported. No trailing newline is emitted by the JSON array path.
#[test]
fn json_empty_corpus_is_exact_empty_array() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "json");
    assert_eq!(
        code,
        Some(0),
        "clean json scan must exit 0; stderr={stderr}"
    );
    assert_eq!(
        stdout, "[]",
        "empty JSON report must be exactly `[]` with no whitespace/newline; got {stdout:?}"
    );
}

/// Empty corpus JSON parses to an empty array (structural validity).
#[test]
fn json_empty_corpus_parses_to_empty_array() {
    let (stdout, _stderr, _code) = scan_with_format(CLEAN_FIXTURE, "json");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("empty JSON parses");
    assert_eq!(
        v.as_array().map(Vec::len),
        Some(0),
        "empty JSON must parse to a zero-length array; got {v}"
    );
}

/// Non-empty corpus -> stdout is a valid JSON array with >=1 object, each
/// carrying the contract fields the JsonReporter serializes from
/// VerifiedFinding.
#[test]
fn json_planted_finding_is_valid_array_with_contract_fields() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "json");
    assert_eq!(
        code,
        Some(1),
        "json planted scan must exit 1; stderr={stderr}"
    );
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("planted JSON parses");
    let arr = v.as_array().expect("JSON report is an array");
    assert!(
        !arr.is_empty(),
        "planted finding must produce >=1 JSON object"
    );
    for f in arr {
        for field in [
            "detector_id",
            "detector_name",
            "service",
            "severity",
            "credential_redacted",
            "credential_hash",
            "location",
            "verification",
        ] {
            assert!(
                f.get(field).is_some(),
                "JSON finding missing `{field}`: {f}"
            );
        }
    }
}

/// The AKIA fixture surfaces as an AWS detection in JSON. AWS keys are
/// caught by the named `aws-access-key` detector or the simdsieve fast
/// path `hot-aws_key`; either is a correct AWS detection.
#[test]
fn json_planted_finding_is_aws_detection() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("JSON parses");
    let arr = v.as_array().expect("array");
    let aws = arr.iter().any(|f| {
        matches!(
            f.get("detector_id").and_then(|x| x.as_str()),
            Some("aws-access-key" | "hot-aws_key")
        )
    });
    assert!(aws, "expected an AWS detection in JSON output; got {arr:?}");
}

/// Verification is `Skipped` (no `--verify`): the serialized discriminant
/// must reflect that, never `live`. VerifiedFinding serializes unit
/// variants as lowercase bare strings (see html.rs flatten comment).
#[test]
fn json_unverified_finding_serializes_skipped() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("JSON parses");
    let arr = v.as_array().expect("array");
    for f in arr {
        let verification = f.get("verification").expect("verification field");
        // Skipped serializes as the bare string "skipped".
        assert_eq!(
            verification.as_str(),
            Some("skipped"),
            "unverified finding must serialize verification as \"skipped\"; got {verification}"
        );
    }
}

/// Redaction contract: with no `--show-secrets`, credential_redacted is
/// `redact(cred)` = first4 + "..." + last4 for a >8-char ASCII credential.
/// The AKIA key is `AKIAQYLPMN5HFIQR7XYA` (20 chars) -> `AKIA...7XYA`.
#[test]
fn json_credential_is_redacted_not_plaintext() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("JSON parses");
    let arr = v.as_array().expect("array");
    let aws = arr
        .iter()
        .find(|f| {
            matches!(
                f.get("detector_id").and_then(|x| x.as_str()),
                Some("aws-access-key" | "hot-aws_key")
            )
        })
        .expect("aws finding present");
    let red = aws
        .get("credential_redacted")
        .and_then(|v| v.as_str())
        .expect("credential_redacted string");
    assert_eq!(
        red, "AKIA...7XYA",
        "redact() of the 20-char AKIA key must be first4...last4; got {red:?}"
    );
    // The full plaintext key body must never appear.
    assert!(
        !stdout.contains("AKIAQYLPMN5HFIQR7XYA"),
        "plaintext credential must not leak into JSON without --show-secrets"
    );
}

/// `--output <file>` JSON: the on-disk artifact equals the structured
/// report exactly (atomic-write path in reporting.rs), `[]` when clean.
#[test]
fn json_output_file_clean_is_exact_empty_array() {
    let (bytes, code) = scan_to_output_file(CLEAN_FIXTURE, "json");
    assert_eq!(code, Some(0));
    assert_eq!(
        bytes, "[]",
        "JSON --output file for a clean scan must be exactly `[]`; got {bytes:?}"
    );
}

// ---------------------------------------------------------------------------
// JSONL (JsonlReporter)
// ---------------------------------------------------------------------------

/// Empty corpus -> JSONL emits nothing (zero objects, zero lines). The
/// JsonlReporter only writes in `report()`; `finish()` just flushes.
#[test]
fn jsonl_empty_corpus_is_empty_output() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "jsonl");
    assert_eq!(
        code,
        Some(0),
        "clean jsonl scan must exit 0; stderr={stderr}"
    );
    assert_eq!(
        stdout, "",
        "empty JSONL report must be completely empty (no `[]`, no newline); got {stdout:?}"
    );
}

/// Non-empty corpus -> one JSON object per line, each line a complete
/// object terminated by `\n` (writeln! after each object).
#[test]
fn jsonl_planted_finding_is_one_object_per_line() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "jsonl");
    assert_eq!(
        code,
        Some(1),
        "jsonl planted scan must exit 1; stderr={stderr}"
    );
    assert!(
        stdout.ends_with('\n'),
        "JSONL output must end with a newline after the final object; got {stdout:?}"
    );
    let lines: Vec<&str> = stdout.lines().filter(|l| !l.trim().is_empty()).collect();
    assert!(
        !lines.is_empty(),
        "planted finding must produce >=1 JSONL line"
    );
    for line in &lines {
        let obj: serde_json::Value = serde_json::from_str(line)
            .unwrap_or_else(|e| panic!("each JSONL line is an object: {e}; line={line:?}"));
        assert!(
            obj.is_object(),
            "each JSONL line must be a JSON object, not an array; got {obj}"
        );
        assert!(
            obj.get("detector_id").is_some(),
            "JSONL object missing detector_id: {obj}"
        );
    }
}

/// JSONL is NOT a bracketed array: a line must never start with `[`.
#[test]
fn jsonl_is_not_a_bracketed_array() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "jsonl");
    assert!(
        !stdout.trim_start().starts_with('['),
        "JSONL must emit bare objects, never a `[...]` array; got {stdout:?}"
    );
}

// ---------------------------------------------------------------------------
// SARIF (SarifReporter, streaming v2.1.0)
// ---------------------------------------------------------------------------

/// Empty corpus -> SARIF still emits a complete, valid v2.1.0 document
/// with an empty results array and empty rules array. `finish()` calls
/// `ensure_prefix()` even when no result was reported.
#[test]
fn sarif_empty_corpus_is_valid_empty_document() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "sarif");
    assert_eq!(
        code,
        Some(0),
        "clean sarif scan must exit 0; stderr={stderr}"
    );
    let v: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("empty SARIF must still be valid JSON");
    assert_eq!(
        v["version"], "2.1.0",
        "SARIF version must be 2.1.0 even when empty"
    );
    assert!(
        v["$schema"]
            .as_str()
            .is_some_and(|s| s.contains("sarif-2.1.0")),
        "empty SARIF must carry the 2.1.0 $schema; got {}",
        v["$schema"]
    );
    let run = &v["runs"][0];
    assert_eq!(
        run["results"].as_array().map(Vec::len),
        Some(0),
        "empty SARIF results array must be length 0; got {}",
        run["results"]
    );
    assert_eq!(
        run["tool"]["driver"]["rules"].as_array().map(Vec::len),
        Some(0),
        "empty SARIF rules array must be length 0; got {}",
        run["tool"]["driver"]["rules"]
    );
    assert_eq!(
        run["tool"]["driver"]["name"], "keyhog",
        "SARIF tool.driver.name must be keyhog"
    );
}

/// SARIF document ends with a trailing newline (sarif.rs `finish()` does
/// `writeln!` after the closing braces) and carries the taxonomies block.
#[test]
fn sarif_empty_corpus_carries_taxonomies_and_trailing_newline() {
    let (stdout, _stderr, _code) = scan_with_format(CLEAN_FIXTURE, "sarif");
    assert!(
        stdout.ends_with('\n'),
        "SARIF doc must end with a trailing newline; got tail {:?}",
        &stdout[stdout.len().saturating_sub(8)..]
    );
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("valid JSON");
    assert!(
        v["runs"][0]["taxonomies"].is_array(),
        "SARIF run must carry a `taxonomies` array (CWE/OWASP); got {}",
        v["runs"][0]["taxonomies"]
    );
}

/// Non-empty corpus -> SARIF has >=1 result; each result's ruleId resolves
/// into tool.driver.rules[]; each result has a valid SARIF level.
#[test]
fn sarif_planted_finding_result_resolves_into_rules() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "sarif");
    assert_eq!(
        code,
        Some(1),
        "sarif planted scan must exit 1; stderr={stderr}"
    );
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("SARIF parses");
    assert_eq!(v["version"], "2.1.0");
    let run = &v["runs"][0];
    let results = run["results"].as_array().expect("results array");
    assert!(
        !results.is_empty(),
        "planted AKIA key must produce a SARIF result"
    );

    let rule_ids: std::collections::HashSet<String> = run["tool"]["driver"]["rules"]
        .as_array()
        .expect("rules array")
        .iter()
        .filter_map(|r| r["id"].as_str().map(str::to_string))
        .collect();
    assert!(
        !rule_ids.is_empty(),
        "non-empty SARIF must populate driver.rules"
    );

    for r in results {
        let rid = r["ruleId"].as_str().expect("each result has a ruleId");
        assert!(
            rule_ids.contains(rid),
            "ruleId {rid:?} not found in tool.driver.rules[]; GitHub would drop it"
        );
        assert!(
            matches!(
                r["level"].as_str(),
                Some("error" | "warning" | "note" | "none")
            ),
            "result.level must be a valid SARIF level; got {}",
            r["level"]
        );
        // CWE/OWASP taxonomy properties applied to every secret finding.
        assert_eq!(
            r["properties"]["cwe"], "CWE-798",
            "every SARIF result must carry CWE-798 (hard-coded credentials)"
        );
        assert_eq!(
            r["properties"]["owasp"], "A07:2021",
            "every SARIF result must carry OWASP A07:2021"
        );
        // Unverified -> verification property is "skipped".
        assert_eq!(
            r["properties"]["verification"], "skipped",
            "unverified SARIF result must carry verification=skipped; got {}",
            r["properties"]["verification"]
        );
    }
}

/// SARIF rules carry GitHub code-scanning severity metadata: a numeric
/// `security-severity` and a `security` tag (apply_code_scanning_props).
#[test]
fn sarif_rules_carry_code_scanning_severity_props() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "sarif");
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("SARIF parses");
    let rules = v["runs"][0]["tool"]["driver"]["rules"]
        .as_array()
        .expect("rules array");
    assert!(!rules.is_empty());
    for rule in rules {
        let props = &rule["properties"];
        let sev = props["security-severity"]
            .as_str()
            .unwrap_or_else(|| panic!("rule {} missing security-severity", rule["id"]));
        sev.parse::<f64>()
            .unwrap_or_else(|_| panic!("security-severity must be numeric; got {sev:?}"));
        let tags: Vec<&str> = props["tags"]
            .as_array()
            .map(|a| a.iter().filter_map(|t| t.as_str()).collect())
            .unwrap_or_default();
        assert!(
            tags.contains(&"security"),
            "rule {} must be tagged `security`; tags={tags:?}",
            rule["id"]
        );
    }
}

// ---------------------------------------------------------------------------
// CSV (CsvReporter)
// ---------------------------------------------------------------------------

/// The CSV header is written in `CsvReporter::new()` unconditionally, so
/// it appears even on an EMPTY corpus. Assert the exact 15-column header.
const CSV_HEADER: &str = "detector_id,detector_name,service,severity,credential_redacted,credential_hash,source,file_path,line,offset,commit,author,date,verification,confidence";

#[test]
fn csv_empty_corpus_is_header_only() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "csv");
    assert_eq!(code, Some(0), "clean csv scan must exit 0; stderr={stderr}");
    let lines: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(
        lines.len(),
        1,
        "empty CSV report must be header-only (1 line); got {lines:?}"
    );
    assert_eq!(
        lines[0], CSV_HEADER,
        "CSV header must match the reporter exactly"
    );
}

/// Non-empty corpus -> header + >=1 data row. Each data row has exactly
/// 15 logical fields (matching the header column count). We count rows
/// rather than naive comma-splitting because redacted/path fields are
/// RFC-4180 safe (no embedded commas for an AKIA detection).
#[test]
fn csv_planted_finding_has_header_plus_data_rows() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "csv");
    assert_eq!(
        code,
        Some(1),
        "csv planted scan must exit 1; stderr={stderr}"
    );
    let lines: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
    assert!(
        lines.len() >= 2,
        "CSV must have header + >=1 data row; got {lines:?}"
    );
    assert_eq!(lines[0], CSV_HEADER, "first CSV line must be the header");
    // The AKIA detection has no comma/quote/newline in any field, so the
    // header's 15 columns map to exactly 15 comma-separated fields per row.
    let header_cols = CSV_HEADER.split(',').count();
    assert_eq!(header_cols, 15, "CSV header must declare 15 columns");
    for row in &lines[1..] {
        assert_eq!(
            row.split(',').count(),
            15,
            "CSV data row must have 15 columns matching the header; row={row:?}"
        );
    }
}

/// CSV data row carries the expected detector + redacted credential for
/// the AKIA fixture (column 0 = detector_id, column 4 = credential_redacted).
#[test]
fn csv_data_row_carries_aws_detector_and_redacted_credential() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "csv");
    let lines: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
    let row = lines
        .iter()
        .skip(1)
        .find(|r| {
            let cols: Vec<&str> = r.split(',').collect();
            matches!(
                cols.first().copied(),
                Some("aws-access-key" | "hot-aws_key")
            )
        })
        .expect("a CSV data row for the AWS detection");
    let cols: Vec<&str> = row.split(',').collect();
    assert_eq!(
        cols[4], "AKIA...7XYA",
        "credential_redacted column must be the redacted key; row={row:?}"
    );
    // verification column (index 13) must be the unverified discriminant.
    assert_eq!(
        cols[13], "skipped",
        "verification column must be `skipped` without --verify; row={row:?}"
    );
    // Full plaintext must never appear.
    assert!(
        !stdout.contains("AKIAQYLPMN5HFIQR7XYA"),
        "CSV must not leak plaintext credential"
    );
}

// ---------------------------------------------------------------------------
// HTML (HtmlReporter)
// ---------------------------------------------------------------------------

/// Empty corpus -> a full, well-formed HTML document is still emitted
/// (skeleton is written in `finish()` regardless of finding count), with
/// `const rawFindings = [];` inlined.
#[test]
fn html_empty_corpus_is_full_document_with_empty_findings() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "html");
    assert_eq!(
        code,
        Some(0),
        "clean html scan must exit 0; stderr={stderr}"
    );
    assert!(
        stdout.starts_with("<!DOCTYPE html>"),
        "HTML report must start with <!DOCTYPE html>; got {:?}",
        &stdout[..stdout.len().min(40)]
    );
    assert!(
        stdout.contains("<title>KeyHog Secret Scan Report</title>"),
        "HTML must carry the KeyHog report title"
    );
    assert!(
        stdout.contains("const rawFindings = [];"),
        "empty HTML must inline `const rawFindings = [];`"
    );
    assert!(
        stdout.trim_end().ends_with("</html>"),
        "HTML report must close with </html>"
    );
}

/// Non-empty corpus -> the document carries a non-empty `rawFindings`
/// array literal. The inlined array is the data the report JS renders.
#[test]
fn html_planted_finding_inlines_nonempty_findings_array() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "html");
    assert_eq!(
        code,
        Some(1),
        "html planted scan must exit 1; stderr={stderr}"
    );
    assert!(
        stdout.starts_with("<!DOCTYPE html>"),
        "HTML must start with the doctype"
    );
    // Locate the inlined array literal between `const rawFindings = ` and `;`.
    let marker = "const rawFindings = ";
    let start = stdout
        .find(marker)
        .expect("HTML must contain the rawFindings assignment");
    let after = &stdout[start + marker.len()..];
    let end = after
        .find(";\n")
        .or_else(|| after.find(';'))
        .expect("rawFindings terminator");
    let literal = &after[..end];
    assert!(
        literal.starts_with('[') && literal.ends_with(']'),
        "rawFindings must be a JSON array literal; got {literal:?}"
    );
    assert_ne!(
        literal, "[]",
        "planted finding must produce a non-empty rawFindings array"
    );
    assert!(
        literal.contains("aws-access-key") || literal.contains("hot-aws_key"),
        "rawFindings must reference the AWS detector id; got {literal}"
    );
}

/// HTML script-injection hardening: the inlined findings JSON escapes
/// `<`, `>`, `/` to `\uXXXX` so a `</script>` byte sequence in any
/// finding field can never break out of the `<script>` element. Even on
/// the planted AKIA key (whose redacted form has no slash), the escaping
/// of `/` means the literal byte sequence `</script` must not appear
/// inside the inlined array.
#[test]
fn html_inlined_findings_never_contain_raw_script_close() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "html");
    let marker = "const rawFindings = ";
    let start = stdout.find(marker).expect("rawFindings present");
    let after = &stdout[start + marker.len()..];
    let end = after.find(';').expect("terminator");
    let literal = &after[..end];
    assert!(
        !literal.contains("</script"),
        "inlined findings must not contain a raw </script close; got {literal}"
    );
    // escape_for_script replaces every `/` with /, so a forward slash
    // must not appear raw inside the literal at all.
    assert!(
        !literal.contains('/'),
        "escape_for_script must escape `/` to \\u002f inside rawFindings; got {literal}"
    );
}

// ---------------------------------------------------------------------------
// JUnit (JunitReporter)
// ---------------------------------------------------------------------------

/// Empty corpus -> a valid JUnit XML doc with a single empty testsuite:
/// tests="0" failures="0" errors="0". Skeleton is written in `finish()`.
#[test]
fn junit_empty_corpus_is_empty_testsuite() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "junit");
    assert_eq!(
        code,
        Some(0),
        "clean junit scan must exit 0; stderr={stderr}"
    );
    assert!(
        stdout.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"),
        "JUnit must start with the XML declaration; got {:?}",
        &stdout[..stdout.len().min(50)]
    );
    assert!(
        stdout.contains("<testsuites>"),
        "JUnit must contain <testsuites>"
    );
    assert!(
        stdout.contains(
            "<testsuite name=\"keyhog\" tests=\"0\" failures=\"0\" errors=\"0\" time=\"0.0\">"
        ),
        "empty JUnit testsuite must declare tests=0 failures=0; got {stdout}"
    );
    assert!(
        !stdout.contains("<testcase"),
        "empty JUnit must contain no <testcase> elements"
    );
    assert!(
        stdout.trim_end().ends_with("</testsuites>"),
        "JUnit must close with </testsuites>"
    );
}

/// Non-empty corpus -> testsuite counts equal the finding count (the
/// reporter sets tests==failures==findings.len()), one <testcase> per
/// finding, each with a <failure> child.
#[test]
fn junit_planted_finding_counts_match_testcases() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "junit");
    assert_eq!(
        code,
        Some(1),
        "junit planted scan must exit 1; stderr={stderr}"
    );
    let testcase_count = stdout.matches("<testcase ").count();
    let failure_count = stdout.matches("<failure ").count();
    assert!(
        testcase_count >= 1,
        "planted finding must produce >=1 <testcase>"
    );
    assert_eq!(
        testcase_count, failure_count,
        "each JUnit <testcase> must carry exactly one <failure>; \
         testcases={testcase_count} failures={failure_count}"
    );
    // The testsuite header must report tests==failures==testcase_count.
    let expected_header = format!(
        "<testsuite name=\"keyhog\" tests=\"{n}\" failures=\"{n}\" errors=\"0\" time=\"0.0\">",
        n = testcase_count
    );
    assert!(
        stdout.contains(&expected_header),
        "JUnit testsuite header must report tests=failures={testcase_count}; \
         expected line: {expected_header}\n--- got ---\n{stdout}"
    );
}

/// JUnit failure body carries the secret-detection metadata inside a
/// CDATA block, including the detector id and the unverified
/// "Verification:  skipped" line.
#[test]
fn junit_failure_body_carries_detection_metadata() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "junit");
    assert!(
        stdout.contains("Secret detected:"),
        "JUnit <failure> message must announce a detected secret"
    );
    assert!(
        stdout.contains("<![CDATA["),
        "JUnit failure detail must be wrapped in CDATA"
    );
    assert!(
        stdout.contains("Detector ID:"),
        "JUnit CDATA body must include the Detector ID label"
    );
    assert!(
        stdout.contains("Verification:  skipped"),
        "unverified JUnit finding must report Verification: skipped; got {stdout}"
    );
    // Redacted credential, not plaintext.
    assert!(
        stdout.contains("Redacted:      AKIA...7XYA"),
        "JUnit body must show the redacted credential; got {stdout}"
    );
    assert!(
        !stdout.contains("AKIAQYLPMN5HFIQR7XYA"),
        "JUnit must not leak plaintext credential"
    );
}

// ---------------------------------------------------------------------------
// TEXT (TextReporter) — the human default
// ---------------------------------------------------------------------------

/// Empty corpus -> text reporter prints the clean-repo summary. There is
/// no example-suppression for a genuinely clean fixture, so the
/// "No secrets found. Your code is clean." branch fires.
#[test]
fn text_empty_corpus_prints_clean_summary() {
    let (stdout, stderr, code) = scan_with_format(CLEAN_FIXTURE, "text");
    assert_eq!(
        code,
        Some(0),
        "clean text scan must exit 0; stderr={stderr}"
    );
    let combined = format!("{stdout}{stderr}");
    assert!(
        combined.contains("No secrets found. Your code is clean."),
        "clean text scan must print the clean-repo summary; \
         stdout={stdout:?} stderr={stderr:?}"
    );
    // Text must never look like JSON.
    assert!(
        !stdout.trim_start().starts_with('['),
        "text format must not emit a JSON `[`; got {stdout:?}"
    );
}

/// Non-empty corpus -> text reporter prints the "N secret(s) found"
/// results summary and references the AWS finding. The text reporter
/// writes findings to stdout (the report writer), so assert on the
/// combined stream to be robust to where the summary lands.
#[test]
fn text_planted_finding_prints_results_summary() {
    let (stdout, stderr, code) = scan_with_format(AWS_KEY_FIXTURE, "text");
    assert_eq!(
        code,
        Some(1),
        "text planted scan must exit 1; stderr={stderr}"
    );
    let combined = format!("{stdout}{stderr}");
    assert!(
        combined.contains("secret found") || combined.contains("secrets found"),
        "text scan with a finding must print a `secret(s) found` summary; \
         stdout={stdout:?} stderr={stderr:?}"
    );
    assert!(
        combined.contains("No secrets found. Your code is clean.") == false,
        "text scan with a finding must NOT print the clean-repo summary"
    );
    assert!(
        !stdout.trim_start().starts_with('['),
        "text format must not emit a JSON `[`; got {stdout:?}"
    );
}

/// Text mode redacts by default: the bordered finding box shows
/// `Secret:    AKIA...7XYA`, never the plaintext key.
#[test]
fn text_planted_finding_is_redacted() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "text");
    assert!(
        stdout.contains("AKIA...7XYA"),
        "text finding box must show the redacted credential; got {stdout}"
    );
    assert!(
        !stdout.contains("AKIAQYLPMN5HFIQR7XYA"),
        "text mode must not leak the plaintext credential without --show-secrets"
    );
}

// ---------------------------------------------------------------------------
// CROSS-FORMAT INVARIANTS
// ---------------------------------------------------------------------------

/// The structured formats (json/jsonl/sarif/csv) must produce
/// deterministic, machine-parseable stdout that does NOT carry ANSI color
/// escapes, since stdout is piped (not a TTY) under `Command::output()`.
#[test]
fn structured_formats_emit_no_ansi_escapes_when_piped() {
    for fmt in ["json", "jsonl", "sarif", "csv"] {
        let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, fmt);
        assert!(
            !stdout.contains('\u{1b}'),
            "structured format `{fmt}` must not emit ANSI escape (\\x1b) on piped stdout; got {stdout:?}"
        );
    }
}

/// JSON and JSONL agree on finding COUNT for the same corpus: the JSON
/// array length equals the number of non-empty JSONL lines. Both reporters
/// consume the identical `findings` slice in `finish_reporter`.
#[test]
fn json_and_jsonl_agree_on_finding_count() {
    let (json_out, _e1, _c1) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let (jsonl_out, _e2, _c2) = scan_with_format(AWS_KEY_FIXTURE, "jsonl");
    let json_v: serde_json::Value = serde_json::from_str(json_out.trim()).expect("json parses");
    let json_count = json_v.as_array().expect("array").len();
    let jsonl_count = jsonl_out.lines().filter(|l| !l.trim().is_empty()).count();
    assert_eq!(
        json_count, jsonl_count,
        "JSON array length ({json_count}) must equal JSONL line count ({jsonl_count}) \
         for the same corpus"
    );
    assert!(
        json_count >= 1,
        "both must report at least the planted finding"
    );
}

/// SARIF result count equals the JSON array length for the same corpus.
/// (SARIF builds one result per reported finding in `report()`.)
#[test]
fn sarif_result_count_matches_json_finding_count() {
    let (json_out, _e1, _c1) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let (sarif_out, _e2, _c2) = scan_with_format(AWS_KEY_FIXTURE, "sarif");
    let json_count = serde_json::from_str::<serde_json::Value>(json_out.trim())
        .expect("json")
        .as_array()
        .expect("array")
        .len();
    let sarif_v: serde_json::Value = serde_json::from_str(sarif_out.trim()).expect("sarif");
    let sarif_count = sarif_v["runs"][0]["results"]
        .as_array()
        .expect("results array")
        .len();
    assert_eq!(
        json_count, sarif_count,
        "SARIF result count ({sarif_count}) must equal JSON finding count ({json_count})"
    );
}

/// CSV data-row count equals the JSON array length for the same corpus
/// (one CSV row per finding, minus the header line).
#[test]
fn csv_row_count_matches_json_finding_count() {
    let (json_out, _e1, _c1) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let (csv_out, _e2, _c2) = scan_with_format(AWS_KEY_FIXTURE, "csv");
    let json_count = serde_json::from_str::<serde_json::Value>(json_out.trim())
        .expect("json")
        .as_array()
        .expect("array")
        .len();
    let csv_rows = csv_out
        .lines()
        .filter(|l| !l.is_empty())
        .count()
        .saturating_sub(1); // drop the header
    assert_eq!(
        csv_rows, json_count,
        "CSV data-row count ({csv_rows}) must equal JSON finding count ({json_count})"
    );
}

/// JUnit testcase count equals the JSON finding count for the same corpus.
#[test]
fn junit_testcase_count_matches_json_finding_count() {
    let (json_out, _e1, _c1) = scan_with_format(AWS_KEY_FIXTURE, "json");
    let (junit_out, _e2, _c2) = scan_with_format(AWS_KEY_FIXTURE, "junit");
    let json_count = serde_json::from_str::<serde_json::Value>(json_out.trim())
        .expect("json")
        .as_array()
        .expect("array")
        .len();
    let junit_count = junit_out.matches("<testcase ").count();
    assert_eq!(
        junit_count, json_count,
        "JUnit testcase count ({junit_count}) must equal JSON finding count ({json_count})"
    );
}

// ---------------------------------------------------------------------------
// ADVERSARIAL / EVASION & BOUNDARY
// ---------------------------------------------------------------------------

/// CSV formula-injection neutralization: a credential-bearing line whose
/// REDACTED value would start with a formula-trigger char is prefixed with
/// a single quote by `escape_csv`. We cannot easily force a redaction to
/// start with `=`/`+`/`-`/`@`, but we can prove the neutralizer is wired by
/// confirming no UNquoted data cell in the report begins with a bare
/// formula trigger. (On a clean AKIA detection none should; this guards
/// against a regression that drops the neutralizer.)
#[test]
fn csv_no_unquoted_formula_trigger_cells() {
    let (stdout, _stderr, _code) = scan_with_format(AWS_KEY_FIXTURE, "csv");
    for (i, line) in stdout.lines().enumerate() {
        if i == 0 || line.is_empty() {
            continue; // skip header / blanks
        }
        for cell in line.split(',') {
            if let Some(first) = cell.as_bytes().first() {
                // A neutralized cell is either quoted (`"..."`) or starts
                // with the guard quote `'`; a raw formula trigger means the
                // neutralizer regressed.
                let is_trigger = matches!(first, b'=' | b'+' | b'@');
                assert!(
                    !is_trigger,
                    "CSV cell {cell:?} starts with an un-neutralized formula trigger; \
                     escape_csv must prefix it with a single quote"
                );
            }
        }
    }
}

/// Boundary: an empty input FILE (zero bytes) is a clean corpus for every
/// format and exits 0. Exercises the no-finding path with a degenerate
/// input rather than clean source code.
#[test]
fn empty_file_is_clean_for_every_format() {
    for fmt in ["text", "json", "jsonl", "sarif", "csv", "html", "junit"] {
        let (_stdout, stderr, code) = scan_with_format("", fmt);
        assert_eq!(
            code,
            Some(0),
            "format `{fmt}` on a zero-byte file must exit 0 (clean); stderr={stderr}"
        );
    }
    // And the empty-corpus structural invariants still hold.
    let (json_out, _e, _c) = scan_with_format("", "json");
    assert_eq!(json_out, "[]", "zero-byte file JSON must be `[]`");
    let (jsonl_out, _e, _c) = scan_with_format("", "jsonl");
    assert_eq!(jsonl_out, "", "zero-byte file JSONL must be empty");
}

/// Boundary: an UNKNOWN `--format` value is rejected by clap as a usage
/// error (exit 2), not silently defaulted. The OutputFormat ValueEnum only
/// accepts text/json/jsonl/sarif/csv/html/junit.
#[test]
fn unknown_format_value_is_clap_usage_error() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.env");
    std::fs::write(&path, CLEAN_FIXTURE).expect("write fixture");
    let output = Command::new(binary())
        .arg("scan")
        .arg("--no-daemon")
        .arg("--format")
        .arg("yaml") // not a valid OutputFormat variant
        .arg(&path)
        .output()
        .expect("spawn keyhog scan --format yaml");
    assert_eq!(
        output.status.code(),
        Some(2),
        "an unknown --format value must be a clap usage error (exit 2); \
         stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Default format is `text`: omitting `--format` entirely must behave
/// exactly like `--format text` (ScanArgs default_value = "text").
#[test]
fn default_format_is_text() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.env");
    std::fs::write(&path, CLEAN_FIXTURE).expect("write fixture");
    let output = Command::new(binary())
        .arg("scan")
        .arg("--no-daemon")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan (no --format)");
    assert_eq!(output.status.code(), Some(0), "clean default scan exits 0");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}{stderr}");
    assert!(
        !stdout.trim_start().starts_with('['),
        "default (text) format must not emit JSON; got {stdout:?}"
    );
    assert!(
        combined.contains("No secrets found. Your code is clean."),
        "default-format clean scan must print the text clean summary; \
         stdout={stdout:?} stderr={stderr:?}"
    );
}

/// Format value matching is case-SENSITIVE: clap `value_enum` defaults to
/// `ignore_case = false`, and `ScanArgs::format` does not override it. So
/// uppercase `JSON` is NOT a valid OutputFormat variant and must be
/// rejected as a clap usage error (exit 2), exactly like a typo. This pins
/// that the accepted spellings are the lowercase variant names only
/// (text/json/jsonl/sarif/csv/html/junit).
#[test]
fn format_value_is_case_sensitive() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.env");
    std::fs::write(&path, CLEAN_FIXTURE).expect("write fixture");
    let output = Command::new(binary())
        .arg("scan")
        .arg("--no-daemon")
        .arg("--format")
        .arg("JSON") // uppercase: not a valid variant when ignore_case=false
        .arg(&path)
        .output()
        .expect("spawn keyhog scan --format JSON");
    assert_eq!(
        output.status.code(),
        Some(2),
        "uppercase `JSON` must be a clap usage error (exit 2) because value_enum \
         matching is case-sensitive by default; stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// `--output` for SARIF writes a valid, complete SARIF doc to disk for the
/// non-empty case, with results resolving into rules — the atomic-write
/// path must not truncate or corrupt the streamed document.
#[test]
fn sarif_output_file_is_complete_for_planted_finding() {
    let (bytes, code) = scan_to_output_file(AWS_KEY_FIXTURE, "sarif");
    assert_eq!(code, Some(1), "sarif --output planted scan must exit 1");
    let v: serde_json::Value =
        serde_json::from_str(bytes.trim()).expect("on-disk SARIF must be valid JSON");
    assert_eq!(v["version"], "2.1.0");
    let results = v["runs"][0]["results"].as_array().expect("results array");
    assert!(
        !results.is_empty(),
        "SARIF --output file must contain the planted result"
    );
    let rule_ids: std::collections::HashSet<String> = v["runs"][0]["tool"]["driver"]["rules"]
        .as_array()
        .expect("rules array")
        .iter()
        .filter_map(|r| r["id"].as_str().map(str::to_string))
        .collect();
    for r in results {
        let rid = r["ruleId"].as_str().expect("ruleId");
        assert!(
            rule_ids.contains(rid),
            "on-disk SARIF ruleId {rid:?} must resolve into rules"
        );
    }
}

/// `--output` for CSV writes header + data rows to disk for the non-empty
/// case (atomic-write path), header-only for the clean case.
#[test]
fn csv_output_file_roundtrips_header_and_rows() {
    let (clean_bytes, clean_code) = scan_to_output_file(CLEAN_FIXTURE, "csv");
    assert_eq!(clean_code, Some(0));
    let clean_lines: Vec<&str> = clean_bytes.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(
        clean_lines,
        vec![CSV_HEADER],
        "clean CSV --output must be header-only"
    );

    let (planted_bytes, planted_code) = scan_to_output_file(AWS_KEY_FIXTURE, "csv");
    assert_eq!(planted_code, Some(1));
    let planted_lines: Vec<&str> = planted_bytes.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(
        planted_lines[0], CSV_HEADER,
        "CSV --output first line is the header"
    );
    assert!(
        planted_lines.len() >= 2,
        "CSV --output must carry >=1 data row for the planted finding"
    );
}