foxguard 0.3.2

Security scanner as fast as a linter. 118 built-in rules, 10 languages, sub-second scans.
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;

fn foxguard_cmd() -> Command {
    Command::new(env!("CARGO_BIN_EXE_foxguard"))
}

fn fixture_path(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join(name)
}

fn write_secrets_fixture(dir: &Path) -> PathBuf {
    let aws = ["AKIA", "1234567890ABCDEF"].concat();
    let aws_secret = ["ABCD1234+/", "wxyz5678+/", "MNOP9012+/", "qrst3456+/"].concat();
    let github = ["ghp_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let gitlab = ["gl", "pat-abcdefghijklmnopqrstuvwx123456"].concat();
    let npm = ["npm_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let slack = ["xoxb", "123456789012", "123456789012", "abcdefghijklmnop"].join("-");
    let stripe = ["sk", "live", "1234567890abcdefghijklmnop"].join("_");
    let private_key = ["-----BEGIN ", "PRIVATE KEY-----"].concat();

    let content = format!(
        "AWS_ACCESS_KEY_ID={aws}\nAWS_SECRET_ACCESS_KEY={aws_secret}\nGITHUB_TOKEN={github}\nGITLAB_TOKEN={gitlab}\nNPM_TOKEN={npm}\nSLACK_TOKEN={slack}\nSTRIPE_SECRET_KEY={stripe}\nPRIVATE_KEY_HEADER={private_key}\n"
    );

    let path = dir.join("secrets.txt");
    fs::write(&path, content).expect("failed to write secrets fixture");
    path
}

fn write_binary_secrets_fixture(dir: &Path) -> PathBuf {
    let secret = ["ghp_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let path = dir.join("binary-secrets.bin");
    let mut bytes = b"\0BINARY\0".to_vec();
    bytes.extend_from_slice(secret.as_bytes());
    fs::write(&path, bytes).expect("failed to write binary secrets fixture");
    path
}

fn write_secret_file(dir: &Path, relative_path: &str) -> PathBuf {
    let github = ["ghp_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let path = dir.join(relative_path);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("failed to create secret fixture directory");
    }
    fs::write(&path, format!("GITHUB_TOKEN={github}\n")).expect("failed to write secret file");
    path
}

fn setup_git_repo(files: &[&str]) -> TempDir {
    let repo = TempDir::new().expect("failed to create temp repo");

    Command::new("git")
        .args(["init"])
        .current_dir(repo.path())
        .output()
        .expect("failed to initialize git repo");

    for file in files {
        let src = fixture_path(file);
        let dest = repo.path().join(file);
        fs::copy(src, dest).expect("failed to copy fixture");
    }

    repo
}

fn write_config_file(dir: &Path, relative_path: &str, content: &str) -> PathBuf {
    let path = dir.join(relative_path);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("failed to create config directory");
    }
    fs::write(&path, content).expect("failed to write config file");
    path
}

fn copy_fixture_to(dir: &Path, fixture_name: &str, relative_path: &str) -> PathBuf {
    let src = fixture_path(fixture_name);
    let dest = dir.join(relative_path);
    if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent).expect("failed to create fixture directory");
    }
    fs::copy(src, &dest).expect("failed to copy fixture to target path");
    dest
}

// ─── Vulnerable file detection ──────────────────────────────────────────────

#[test]
fn test_vulnerable_js_finds_all_rules() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/vulnerable.js", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        !output.status.success(),
        "should exit non-zero when findings exist"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(
        findings.len(),
        30,
        "vulnerable.js should have 30 findings, got {}",
        findings.len()
    );

    // Verify all unique rule IDs are present
    let rule_ids: std::collections::HashSet<&str> = findings
        .iter()
        .filter_map(|f| f["rule_id"].as_str())
        .collect();

    let expected_rules = [
        "js/no-eval",
        "js/no-hardcoded-secret",
        "js/no-sql-injection",
        "js/no-xss-innerhtml",
        "js/no-command-injection",
        "js/no-document-write",
        "js/no-open-redirect",
        "js/no-weak-crypto",
        "js/no-path-traversal",
        "js/no-ssrf",
        "js/no-prototype-pollution",
        "js/no-unsafe-regex",
        "js/no-cors-star",
        "js/express-no-hardcoded-session-secret",
        "js/express-cookie-no-secure",
        "js/express-cookie-no-httponly",
        "js/express-cookie-no-samesite",
        "js/express-session-saveuninitialized-true",
        "js/express-direct-response-write",
        "js/jwt-hardcoded-secret",
        "js/jwt-none-algorithm",
        "js/jwt-ignore-expiration",
        "js/jwt-decode-without-verify",
        "js/jwt-verify-missing-algorithms",
    ];

    for rule in &expected_rules {
        assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
    }
}

#[test]
fn test_vulnerable_py_finds_all_rules() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/vulnerable.py", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(!output.status.success());

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(
        findings.len(),
        30,
        "vulnerable.py should have 30 findings, got {}",
        findings.len()
    );

    let rule_ids: std::collections::HashSet<&str> = findings
        .iter()
        .filter_map(|f| f["rule_id"].as_str())
        .collect();

    let expected_rules = [
        "py/no-eval",
        "py/no-hardcoded-secret",
        "py/no-sql-injection",
        "py/no-command-injection",
        "py/no-path-traversal",
        "py/no-ssrf",
        "py/no-weak-crypto",
        "py/no-pickle",
        "py/no-yaml-load",
        "py/no-debug-true",
        "py/no-open-redirect",
        "py/no-cors-star",
        "py/flask-debug-mode",
        "py/django-secret-key-hardcoded",
        "py/flask-secret-key-hardcoded",
        "py/session-cookie-secure-disabled",
        "py/session-cookie-httponly-disabled",
        "py/session-cookie-samesite-disabled",
        "py/csrf-cookie-secure-disabled",
        "py/csrf-cookie-httponly-disabled",
        "py/csrf-cookie-samesite-disabled",
        "py/csrf-exempt",
        "py/wtf-csrf-disabled",
        "py/wtf-csrf-check-default-disabled",
        "py/django-allowed-hosts-wildcard",
        "py/secure-ssl-redirect-disabled",
    ];

    for rule in &expected_rules {
        assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
    }
}

#[test]
fn test_vulnerable_go_finds_all_rules() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/vulnerable.go", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(!output.status.success());

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(
        findings.len(),
        10,
        "vulnerable.go should have 10 findings, got {}",
        findings.len()
    );

    let rule_ids: std::collections::HashSet<&str> = findings
        .iter()
        .filter_map(|f| f["rule_id"].as_str())
        .collect();

    let expected_rules = [
        "go/no-sql-injection",
        "go/no-command-injection",
        "go/no-hardcoded-secret",
        "go/no-weak-crypto",
        "go/no-ssrf",
        "go/insecure-tls-skip-verify",
        "go/net-http-no-timeout",
    ];

    for rule in &expected_rules {
        assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
    }
}

// ─── Safe file detection ────────────────────────────────────────────────────

#[test]
fn test_safe_js_no_findings() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/safe.js", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(output.status.success(), "safe.js should exit zero");

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(findings.len(), 0, "safe.js should have 0 findings");
}

#[test]
fn test_safe_py_no_findings() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/safe.py", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(output.status.success(), "safe.py should exit zero");

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(findings.len(), 0, "safe.py should have 0 findings");
}

#[test]
fn test_safe_go_no_findings() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/safe.go", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(output.status.success(), "safe.go should exit zero");

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(findings.len(), 0, "safe.go should have 0 findings");
}

#[test]
fn test_invalid_path_exits_nonzero() {
    let output = foxguard_cmd()
        .args(["not_a_real_path_foxguard_test", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        !output.status.success(),
        "invalid paths should exit non-zero"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("does not exist"),
        "expected missing path error, got: {}",
        stderr
    );
}

#[test]
fn test_no_builtins_without_external_rules_finds_nothing() {
    let output = foxguard_cmd()
        .args([
            "tests/fixtures/vulnerable.js",
            "-f",
            "json",
            "--no-builtins",
        ])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        output.status.success(),
        "no built-ins and no external rules should exit zero"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(findings.len(), 0, "expected no findings without any rules");
}

#[test]
fn test_no_builtins_with_external_rules_still_finds_matches() {
    let output = foxguard_cmd()
        .args([
            "tests/fixtures/vulnerable.py",
            "-f",
            "json",
            "--no-builtins",
            "--rules",
            "tests/semgrep_rules",
        ])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        !output.status.success(),
        "external rules should still report findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert!(
        !findings.is_empty(),
        "expected findings from external rules when built-ins are disabled"
    );
}

#[test]
fn test_external_rules_respect_semgrep_paths_filters() {
    let repo = TempDir::new().expect("failed to create temp repo");
    copy_fixture_to(repo.path(), "vulnerable.py", "src/vulnerable.py");
    copy_fixture_to(repo.path(), "vulnerable.py", "tests/vulnerable.py");

    let rules_dir = repo.path().join("rules");
    fs::create_dir_all(&rules_dir).expect("failed to create rules directory");
    fs::write(
        rules_dir.join("path-filter.yaml"),
        r#"
rules:
  - id: path-filtered-eval
    pattern: eval(...)
    message: eval usage
    severity: ERROR
    languages: [python]
    paths:
      include:
        - src/**/*.py
"#,
    )
    .expect("failed to write rules file");

    let output = foxguard_cmd()
        .current_dir(repo.path())
        .args([".", "-f", "json", "--no-builtins", "--rules", "rules"])
        .output()
        .expect("failed to execute foxguard with path-filtered rules");

    assert!(
        !output.status.success(),
        "path-filtered external rule should still report findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert!(
        findings.iter().all(|finding| finding["file"]
            .as_str()
            .unwrap_or_default()
            .contains("/src/")),
        "expected path filters to restrict findings to src/"
    );
}

#[test]
fn test_write_and_apply_baseline() {
    let repo = TempDir::new().expect("failed to create temp dir");
    let source = fixture_path("vulnerable.js");
    let target = repo.path().join("vulnerable.js");
    fs::copy(source, &target).expect("failed to copy fixture");
    let baseline = repo.path().join("baseline.json");

    let initial = foxguard_cmd()
        .args([
            target.to_str().expect("non-utf8 path"),
            "-f",
            "json",
            "--write-baseline",
            baseline.to_str().expect("non-utf8 path"),
        ])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        !initial.status.success(),
        "writing a baseline should still report current findings"
    );
    assert!(baseline.exists(), "baseline file should be created");

    let suppressed = foxguard_cmd()
        .args([
            target.to_str().expect("non-utf8 path"),
            "-f",
            "json",
            "--baseline",
            baseline.to_str().expect("non-utf8 path"),
        ])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        suppressed.status.success(),
        "baseline should suppress the existing findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&suppressed.stdout).expect("invalid JSON output");
    assert_eq!(findings.len(), 0, "expected no findings after baseline");
}

#[test]
fn test_scan_uses_discovered_config_baseline() {
    let repo = TempDir::new().expect("failed to create temp dir");
    fs::copy(
        fixture_path("vulnerable.js"),
        repo.path().join("vulnerable.js"),
    )
    .expect("failed to copy vulnerable fixture");

    let baseline = repo.path().join(".foxguard").join("baseline.json");
    fs::create_dir_all(baseline.parent().expect("missing baseline parent"))
        .expect("failed to create baseline directory");

    let initial = foxguard_cmd()
        .current_dir(repo.path())
        .args([
            "vulnerable.js",
            "-f",
            "json",
            "--write-baseline",
            baseline.to_str().expect("non-utf8 path"),
        ])
        .output()
        .expect("failed to execute foxguard");

    assert!(
        !initial.status.success(),
        "writing the baseline should still report findings"
    );

    write_config_file(
        repo.path(),
        ".foxguard.yml",
        "scan:\n  baseline: .foxguard/baseline.json\n",
    );

    let suppressed = foxguard_cmd()
        .current_dir(repo.path())
        .args(["vulnerable.js", "-f", "json"])
        .output()
        .expect("failed to execute foxguard with config");

    assert!(
        suppressed.status.success(),
        "configured baseline should suppress the existing findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&suppressed.stdout).expect("invalid JSON output");
    assert_eq!(
        findings.len(),
        0,
        "expected no findings after config baseline"
    );
}

#[test]
fn test_changed_mode_scans_only_staged_files() {
    let repo = setup_git_repo(&["vulnerable.js", "safe.py"]);

    Command::new("git")
        .args(["add", "vulnerable.js"])
        .current_dir(repo.path())
        .output()
        .expect("failed to stage vulnerable.js");

    let output = foxguard_cmd()
        .args(["--changed", "-f", "json", "."])
        .current_dir(repo.path())
        .output()
        .expect("failed to execute foxguard");

    assert!(
        !output.status.success(),
        "changed-mode scan should report findings from staged vulnerable.js"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");
    assert!(
        findings.iter().all(|finding| finding["file"]
            .as_str()
            .unwrap_or_default()
            .ends_with("vulnerable.js")),
        "changed mode should only scan the staged file"
    );
}

#[test]
fn test_init_installs_hook_and_baseline() {
    let repo = setup_git_repo(&["vulnerable.js"]);

    let output = foxguard_cmd()
        .args(["init", "--path", ".", "--force"])
        .current_dir(repo.path())
        .output()
        .expect("failed to execute foxguard init");

    assert!(output.status.success(), "init should succeed");
    assert!(
        repo.path().join(".git/hooks/pre-commit").exists(),
        "pre-commit hook should be installed"
    );
    assert!(
        repo.path().join(".foxguard/baseline.json").exists(),
        "baseline should be created by default"
    );
    assert!(
        repo.path().join(".foxguard/secrets-baseline.json").exists(),
        "secrets baseline should be created by default"
    );
    assert!(
        repo.path().join(".foxguard.yml").exists(),
        "starter config should be created by default"
    );

    let hook = fs::read_to_string(repo.path().join(".git/hooks/pre-commit"))
        .expect("failed to read pre-commit hook");
    assert!(
        hook.contains("foxguard --config \".foxguard.yml\" --changed"),
        "hook should use the generated config"
    );
    assert!(
        hook.contains("foxguard secrets --config \".foxguard.yml\" --changed"),
        "hook should run the secrets scanner"
    );

    let config = fs::read_to_string(repo.path().join(".foxguard.yml"))
        .expect("failed to read generated config");
    assert!(
        config.contains("scan:\n  baseline: .foxguard/baseline.json"),
        "generated config should include the code baseline"
    );
    assert!(
        config.contains("secrets:\n  baseline: .foxguard/secrets-baseline.json"),
        "generated config should include the secrets baseline"
    );
}

#[test]
fn test_init_preserves_existing_config_and_keeps_baseline_flags_when_needed() {
    let repo = setup_git_repo(&["vulnerable.js"]);
    write_config_file(
        repo.path(),
        ".foxguard.yml",
        "secrets:\n  exclude_paths:\n    - fixtures\n",
    );

    let output = foxguard_cmd()
        .args(["init", "--path", ".", "--force"])
        .current_dir(repo.path())
        .output()
        .expect("failed to execute foxguard init");

    assert!(output.status.success(), "init should succeed");

    let hook = fs::read_to_string(repo.path().join(".git/hooks/pre-commit"))
        .expect("failed to read pre-commit hook");
    assert!(
        hook.contains("--config \".foxguard.yml\""),
        "hook should still use the existing config"
    );
    assert!(
        hook.contains("--baseline \".foxguard/baseline.json\""),
        "hook should keep explicit code baseline flags when existing config lacks them"
    );
    assert!(
        hook.contains("--baseline \".foxguard/secrets-baseline.json\""),
        "hook should keep explicit secrets baseline flags when existing config lacks them"
    );

    let config = fs::read_to_string(repo.path().join(".foxguard.yml"))
        .expect("failed to read preserved config");
    assert!(
        config.contains("exclude_paths:\n    - fixtures"),
        "existing config should be preserved"
    );
}

// ─── Severity filtering ─────────────────────────────────────────────────────

#[test]
fn test_severity_filter_high() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/vulnerable.js", "-f", "json", "-s", "high"])
        .output()
        .expect("failed to execute foxguard");

    assert!(!output.status.success());

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    // High and Critical only
    assert_eq!(
        findings.len(),
        19,
        "high severity filter on vulnerable.js should yield 19 findings, got {}",
        findings.len()
    );

    // All findings should be High or Critical
    for finding in &findings {
        let severity = finding["severity"].as_str().unwrap();
        assert!(
            severity == "high" || severity == "critical",
            "expected high or critical, got: {}",
            severity
        );
    }
}

#[test]
fn test_secrets_mode_finds_common_credentials() {
    let repo = TempDir::new().expect("failed to create temp dir");
    let path = write_secrets_fixture(repo.path());

    let output = foxguard_cmd()
        .args([
            "secrets",
            path.to_str().expect("non-utf8 path"),
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    assert!(
        !output.status.success(),
        "secrets mode should exit non-zero when findings exist"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(
        findings.len(),
        8,
        "secrets fixture should yield 8 findings, got {}",
        findings.len()
    );

    let rule_ids: std::collections::HashSet<&str> = findings
        .iter()
        .filter_map(|f| f["rule_id"].as_str())
        .collect();

    let expected_rules = [
        "secret/aws-access-key-id",
        "secret/aws-secret-access-key",
        "secret/github-token",
        "secret/gitlab-token",
        "secret/npm-token",
        "secret/slack-token",
        "secret/stripe-live-key",
        "secret/private-key",
    ];

    for rule in &expected_rules {
        assert!(
            rule_ids.contains(rule),
            "missing expected secret rule: {}",
            rule
        );
    }
}

#[test]
fn test_secrets_mode_changed_scans_only_staged_files() {
    let repo = setup_git_repo(&["safe.py"]);
    write_secrets_fixture(repo.path());

    Command::new("git")
        .args(["add", "secrets.txt"])
        .current_dir(repo.path())
        .output()
        .expect("failed to stage secrets fixture");

    let output = foxguard_cmd()
        .args(["secrets", "--changed", "-f", "json", "."])
        .current_dir(repo.path())
        .output()
        .expect("failed to execute foxguard secrets --changed");

    assert!(
        !output.status.success(),
        "changed secrets scan should report staged secrets"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");
    assert!(
        findings.iter().all(|finding| finding["file"]
            .as_str()
            .unwrap_or_default()
            .ends_with("secrets.txt")),
        "changed secrets scan should only scan the staged secret fixture"
    );
}

#[test]
fn test_secrets_mode_skips_binary_files() {
    let repo = TempDir::new().expect("failed to create temp dir");
    let path = write_binary_secrets_fixture(repo.path());

    let output = foxguard_cmd()
        .args([
            "secrets",
            path.to_str().expect("non-utf8 path"),
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    assert!(output.status.success(), "binary file should be skipped");

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");
    assert_eq!(
        findings.len(),
        0,
        "binary secrets fixture should be skipped"
    );
}

#[test]
fn test_write_and_apply_secrets_baseline() {
    let repo = TempDir::new().expect("failed to create temp dir");
    let target = write_secrets_fixture(repo.path());
    let baseline = repo.path().join("secrets-baseline.json");

    let initial = foxguard_cmd()
        .args([
            "secrets",
            target.to_str().expect("non-utf8 path"),
            "-f",
            "json",
            "--write-baseline",
            baseline.to_str().expect("non-utf8 path"),
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    assert!(
        !initial.status.success(),
        "writing a secrets baseline should still report current findings"
    );
    assert!(baseline.exists(), "secrets baseline file should be created");

    let suppressed = foxguard_cmd()
        .args([
            "secrets",
            target.to_str().expect("non-utf8 path"),
            "-f",
            "json",
            "--baseline",
            baseline.to_str().expect("non-utf8 path"),
        ])
        .output()
        .expect("failed to execute foxguard secrets with baseline");

    assert!(
        suppressed.status.success(),
        "secrets baseline should suppress the existing findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&suppressed.stdout).expect("invalid JSON output");
    assert_eq!(
        findings.len(),
        0,
        "expected no findings after applying the secrets baseline"
    );

    let baseline_content = fs::read_to_string(&baseline).expect("failed to read secrets baseline");
    assert!(
        !baseline_content.contains("\"snippet\""),
        "secrets baseline should not persist snippets"
    );
    assert!(
        !baseline_content.contains("[REDACTED]"),
        "secrets baseline should only store suppression metadata"
    );
}

#[test]
fn test_secrets_mode_redacts_snippets() {
    let repo = TempDir::new().expect("failed to create temp dir");
    let path = write_secrets_fixture(repo.path());

    let output = foxguard_cmd()
        .args([
            "secrets",
            path.to_str().expect("non-utf8 path"),
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    for finding in findings {
        let snippet = finding["snippet"].as_str().expect("missing snippet");
        assert!(
            snippet.contains("[REDACTED]"),
            "secrets snippet should be redacted"
        );
        assert!(
            !snippet.contains("1234567890ABCDEF")
                && !snippet.contains("abcdefghijklmnopqrstuvwxyz1234567890"),
            "secrets snippet should not contain raw secrets"
        );
    }
}

#[test]
fn test_secrets_mode_exclude_path_skips_matching_files() {
    let repo = TempDir::new().expect("failed to create temp dir");
    write_secret_file(repo.path(), "included.txt");
    write_secret_file(repo.path(), "fixtures/ignored.txt");

    let output = foxguard_cmd()
        .args([
            "secrets",
            "--exclude-path",
            "fixtures",
            repo.path().to_str().expect("non-utf8 path"),
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    assert!(
        !output.status.success(),
        "non-excluded secrets should still produce findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(findings.len(), 1, "expected only one non-excluded finding");
    assert!(
        findings[0]["file"]
            .as_str()
            .is_some_and(|file| file.ends_with("included.txt")),
        "expected only the included file to be scanned"
    );
}

#[test]
fn test_secrets_mode_exclude_path_file_skips_matching_files() {
    let repo = TempDir::new().expect("failed to create temp dir");
    write_secret_file(repo.path(), "fixtures/ignored.txt");
    let ignore_file = repo.path().join(".foxguard").join("secrets.ignore");
    fs::create_dir_all(ignore_file.parent().expect("missing ignore directory"))
        .expect("failed to create ignore directory");
    fs::write(&ignore_file, "# comment\nfixtures\n").expect("failed to write ignore file");

    let output = foxguard_cmd()
        .args([
            "secrets",
            "--exclude-path-file",
            ignore_file.to_str().expect("non-utf8 path"),
            repo.path().to_str().expect("non-utf8 path"),
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    assert!(
        output.status.success(),
        "excluded secrets should not produce findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");
    assert!(findings.is_empty(), "expected excluded file to be skipped");
}

#[test]
fn test_secrets_mode_ignore_rule_skips_specific_patterns() {
    let repo = TempDir::new().expect("failed to create temp dir");
    write_secrets_fixture(repo.path());

    let output = foxguard_cmd()
        .args([
            "secrets",
            "--ignore-rule",
            "secret/github-token",
            repo.path().to_str().expect("non-utf8 path"),
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets");

    assert!(
        !output.status.success(),
        "remaining secrets should still produce findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert_eq!(
        findings.len(),
        7,
        "expected github token finding to be ignored"
    );
    assert!(
        findings
            .iter()
            .all(|finding| finding["rule_id"].as_str() != Some("secret/github-token")),
        "ignored rule should be absent from findings"
    );
}

#[test]
fn test_secrets_mode_uses_explicit_config_file() {
    let repo = TempDir::new().expect("failed to create temp dir");
    write_secret_file(repo.path(), "fixtures/ignored.txt");

    let config = write_config_file(
        repo.path(),
        "config/foxguard.yml",
        "secrets:\n  exclude_paths:\n    - ../fixtures\n",
    );

    let output = foxguard_cmd()
        .current_dir(repo.path())
        .args([
            "secrets",
            "--config",
            config.to_str().expect("non-utf8 path"),
            ".",
            "-f",
            "json",
        ])
        .output()
        .expect("failed to execute foxguard secrets with config");

    assert!(
        output.status.success(),
        "configured excludes should suppress matching secret findings"
    );

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");
    assert!(
        findings.is_empty(),
        "expected no findings after config excludes"
    );
}

#[test]
fn test_severity_filter_critical() {
    let output = foxguard_cmd()
        .args([
            "tests/fixtures/vulnerable.js",
            "-f",
            "json",
            "-s",
            "critical",
        ])
        .output()
        .expect("failed to execute foxguard");

    assert!(!output.status.success());

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    // All findings should be Critical
    for finding in &findings {
        let severity = finding["severity"].as_str().unwrap();
        assert_eq!(severity, "critical", "expected critical, got: {}", severity);
    }
}

// ─── JSON output structure ──────────────────────────────────────────────────

#[test]
fn test_json_output_structure() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/vulnerable.js", "-f", "json"])
        .output()
        .expect("failed to execute foxguard");

    let findings: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("invalid JSON output");

    assert!(!findings.is_empty());

    let first = &findings[0];

    // Verify all expected fields exist
    assert!(first["rule_id"].is_string(), "missing rule_id");
    assert!(first["severity"].is_string(), "missing severity");
    assert!(first["description"].is_string(), "missing description");
    assert!(first["file"].is_string(), "missing file");
    assert!(first["line"].is_number(), "missing line");
    assert!(first["column"].is_number(), "missing column");
    assert!(first["end_line"].is_number(), "missing end_line");
    assert!(first["end_column"].is_number(), "missing end_column");
    assert!(first["snippet"].is_string(), "missing snippet");
}

// ─── SARIF output ───────────────────────────────────────────────────────────

#[test]
fn test_sarif_output_valid() {
    let output = foxguard_cmd()
        .args(["tests/fixtures/vulnerable.js", "-f", "sarif"])
        .output()
        .expect("failed to execute foxguard");

    let sarif: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("invalid SARIF JSON");

    assert_eq!(sarif["version"].as_str(), Some("2.1.0"));
    assert!(sarif["runs"].is_array());
    assert!(sarif["$schema"].is_string());

    let results = sarif["runs"][0]["results"]
        .as_array()
        .expect("missing results array");
    assert!(!results.is_empty(), "SARIF results should not be empty");
}