greengate 5.5.0

Opinionated git hooks that judge what you are committing, not what is on disk
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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
//! The dependency audits, end to end: warn on a branch push, refuse a
//! `v*` tag push carrying known vulnerabilities, never block when the
//! tool is missing. Fake audit tools on a prepended PATH give each test
//! total control of output and exit code — the checks' verdicts come from
//! parsing, and parsing is what these pin.
#![cfg(unix)]

use crate::common;
use common::Repo;

use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::process::Stdio;

/// A directory of fake tools, prepended to PATH for one invocation.
fn shim(r: &Repo, name: &str, body: &str) {
    let dir = r.path(".git/toolshims");
    std::fs::create_dir_all(&dir).expect("mkdir");
    let p = dir.join(name);
    std::fs::write(&p, format!("#!/bin/sh\n{body}")).expect("write");
    std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).expect("chmod");
}

/// Run ONE audit check with a single pushed ref, fake tools first on PATH.
fn push_check(r: &Repo, check: &str, remote_ref: &str) -> (i32, String) {
    push_check_in(r, check, remote_ref, None)
}

/// As [`push_check`], with the run's temp directory pointed at `scratch_dir`.
fn push_check_in(
    r: &Repo,
    check: &str,
    remote_ref: &str,
    scratch_dir: Option<&std::path::Path>,
) -> (i32, String) {
    let oid = "a".repeat(40);
    let line = format!("{remote_ref} {oid} {remote_ref} {}\n", "0".repeat(40));
    let path = format!(
        "{}:{}",
        r.path(".git/toolshims").display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let mut command = crate::common::amont_cmd();
    if let Some(scratch_dir) = scratch_dir {
        command.env("TMPDIR", scratch_dir);
    }
    let mut child = command
        .arg("--hooks-dir")
        .arg(r.path(".git/hooks"))
        .arg(check)
        .current_dir(&r.dir)
        .env("PATH", path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(line.as_bytes())
        .unwrap();
    let out = child.wait_with_output().expect("wait");
    (
        out.status.code().unwrap_or(-1),
        format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        ),
    )
}

/// A fake `cargo`: `audit` reports RUSTSEC-2025-0001 against `bad`, and
/// `tree -i bad` over the shipped edges (normal,build) prints `shipped` —
/// a local crate line like `app v0.1.0 (/repo/app)` reaches it, an empty
/// string means nothing that ships does. Any other `tree` sees the dev edge.
fn cargo_reaching(shipped: &str) -> String {
    // Real cargo, for a crate only a dev edge reaches: exit 0 and
    // "warning: nothing to print." The tree is asked about `bad@1.0.0`,
    // the version cargo audit reported.
    let answer = if shipped.is_empty() {
        "echo 'warning: nothing to print.' >&2; exit 0".to_string()
    } else {
        format!("printf 'bad v1.0.0\\n%s\\n' '{shipped}'; exit 0")
    };
    format!(
        "case \"$1\" in\n\
         audit) echo 'Crate: bad'; echo 'Version: 1.0.0'; echo 'ID: RUSTSEC-2025-0001'; echo 'error: 1 vulnerability found'; exit 1;;\n\
         tree) case \"$*\" in\n\
           *bad@1.0.0*normal,build*) {answer};;\n\
           *normal,build*) echo 'error: package ID specification is ambiguous' >&2; exit 101;;\n\
           *) printf 'bad v1.0.0\\n└── devtool v0.1.0 (/repo/devtool)\\n'; exit 0;;\n\
         esac;;\n\
         esac\nexit 0"
    )
}

/// A repository that has opted every audit in: each audit runs only where
/// its lockfile is tracked, so the fixture carries all four. Content is
/// irrelevant — the fake tools on PATH decide, and parsing is what these
/// tests pin.
fn repo() -> Repo {
    let r = bare_repo();
    for lockfile in [
        "Cargo.lock",
        "package-lock.json",
        "go.sum",
        "requirements.txt",
    ] {
        r.stage(lockfile, "# fixture\n");
    }
    r.commit("chore: opt every audit in");
    r
}

/// No lockfile at all: what a repository in some other language looks like
/// to the audits.
fn bare_repo() -> Repo {
    let r = Repo::new();
    r.stage("a.txt", "x\n");
    r.commit("chore: base");
    r
}

/// The point of the whole design: the same finding is a warning on a
/// branch and a refusal on a release.
#[test]
fn vulnerabilities_warn_on_a_branch_and_refuse_a_v_tag() {
    let r = repo();
    shim(&r, "cargo-audit", "exit 0"); // exists, so the check proceeds
    shim(&r, "cargo", &cargo_reaching("app v0.1.0 (/repo/app)"));

    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/heads/feat/x");
    assert_eq!(code, 0, "a branch push must not block: {out}");
    assert!(out.contains("will BLOCK a v* tag push"), "{out}");
    assert!(out.contains("RUSTSEC-2025-0001"), "{out}");

    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "a release does not ship with these: {out}");
    assert!(out.contains("does not ship"), "{out}");
}

/// A tag that merely starts with the letter v is not a release.
#[test]
fn a_vendor_tag_is_not_a_release() {
    let r = repo();
    shim(&r, "cargo-audit", "exit 0");
    shim(&r, "cargo", "echo 'ID: RUSTSEC-2025-0002'\nexit 1");
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/vendor-drop");
    assert_eq!(code, 0, "{out}");
}

/// Clean trees pass a release push, and say so.
#[test]
fn a_clean_tree_passes_a_tag_push() {
    let r = repo();
    shim(&r, "cargo-audit", "exit 0");
    shim(&r, "cargo", "echo 'ok, 312 crates checked'\nexit 0");
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v2.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("no known vulnerabilities"), "{out}");
}

/// Warning-class advisories never block, even on a release — the tree
/// carries unmaintained crates today and a gate nothing passes gets
/// deleted.
#[test]
fn warning_class_advisories_do_not_block_a_release() {
    let r = repo();
    shim(&r, "cargo-audit", "exit 0");
    shim(
        &r,
        "cargo",
        "echo 'warning: unmaintained RUSTSEC-2024-0436 paste'\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v3.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(
        out.contains("RUSTSEC-2024-0436"),
        "named, not hidden: {out}"
    );
}

/// A missing tool is loud and non-blocking — the offline case must not
/// teach --no-verify.
#[test]
fn a_missing_audit_tool_warns_and_never_blocks() {
    // No shims at all: cargo-audit absent from the fake dir. The lockfile
    // opts the audit in but is not one cargo-audit can read, so that on a
    // machine with a REAL cargo-audit on PATH — which the shim dir cannot
    // hide — the check takes the could-not-check path instead. Both
    // phrasings honour the same contract this test pins: loud, and never
    // blocking.
    let r = bare_repo();
    r.stage("Cargo.lock", "this is not a lockfile\n");
    r.commit("chore: unreadable lockfile");
    std::fs::create_dir_all(r.path(".git/toolshims")).unwrap();
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(
        out.contains("did NOT run") || out.contains("could not run") || out.contains("NOT checked"),
        "{out}"
    );
}

/// npm's summary line decides, both ways.
#[test]
fn npm_audit_summary_decides_both_ways() {
    let r = repo();
    shim(
        &r,
        "npm",
        "echo 'found 3 vulnerabilities (1 moderate, 2 high)'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("found 3 vulnerabilities"), "{out}");

    // npm 7+ dropped the verb — the summary every current npm prints. Until
    // the parser learned it, a real finding read as "could not complete"
    // and a v* tag shipped over it: the audit check was fail-open exactly
    // when it had something to say.
    shim(
        &r,
        "npm",
        "echo '17 vulnerabilities (8 moderate, 9 high)'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("17 vulnerabilities"), "{out}");
    assert!(!out.contains("could not complete"), "{out}");

    shim(&r, "npm", "echo 'found 0 vulnerabilities'\nexit 0");
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
}

/// govulncheck's GO- ids decide; the exit code says whether the analysed
/// code is affected or the finding is informational.
#[test]
fn govulncheck_ids_decide_both_ways() {
    let r = repo();
    shim(
        &r,
        "govulncheck",
        "echo 'Vulnerability #1: GO-2022-0969'\nexit 3",
    );
    let (code, out) = push_check(&r, "pre-push-audit-go", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("GO-2022-0969"), "{out}");

    shim(
        &r,
        "govulncheck",
        "echo 'No vulnerabilities found.'\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-go", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");

    // Informational — the module is vulnerable, the code never calls it:
    // named, never blocking, even on a release tag.
    shim(
        &r,
        "govulncheck",
        "echo '=== Informational ==='\necho 'Vulnerability #1: GO-2023-1840'\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-go", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("GO-2023-1840"), "{out}");
}

/// pip-audit's closing sentence decides.
#[test]
fn pip_audit_sentence_decides() {
    let r = repo();
    // The pip-style path: a requirements file is what gets audited.
    std::fs::write(r.path("requirements.txt"), "requests==2.0.0\n").expect("write");
    shim(
        &r,
        "pip-audit",
        "echo 'Found 2 known vulnerabilities in 1 package'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");

    shim(
        &r,
        "pip-audit",
        "echo 'No known vulnerabilities found'\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
}

/// A pip-compiled requirements.txt (every pin hashed) is audited without a
/// resolve, and the packages pip-audit skips are named. Resolving it on the
/// host failed on a pin with no wheel there (torch 2.14.0+cpu on Intel
/// macOS), so the file was reported NOT checked on every push (decisions
/// f108). A file without hashes still resolves.
#[test]
fn a_hashed_requirements_file_is_audited_without_a_resolve() {
    let r = repo();
    let hashed =
        "six==1.16.0 \\\n    --hash=sha256:aaaa\ntorch==2.14.0+cpu \\\n    --hash=sha256:bbbb\n";
    std::fs::write(r.path("requirements.txt"), hashed).expect("write");
    let shim_body = r#"case " $* " in
  *" --no-deps --disable-pip "*) ;;
  *) echo "ERROR: resolved: $*" >&2; exit 1 ;;
esac
echo 'No known vulnerabilities found'
echo 'Name  Skip Reason'
echo '----- -----------'
echo 'torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)'
exit 0"#;
    shim(&r, "pip-audit", shim_body);
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(!out.contains("resolved:"), "{out}");
    assert!(
        out.contains("1 private/non-PyPI package skipped (torch)"),
        "{out}"
    );

    // Every pin skipped: nothing was audited, which is never clean.
    std::fs::write(
        r.path("requirements.txt"),
        "torch==2.14.0+cpu \\\n    --hash=sha256:bbbb\n",
    )
    .expect("write");
    let (_, out) = push_check(&r, "pre-push-audit-python", "refs/heads/feat/x");
    assert!(out.contains("NOT checked"), "{out}");

    // `==` pins without hashes name the top level only: they resolve.
    std::fs::write(r.path("requirements.txt"), "six==1.16.0\n").expect("write");
    let (_, out) = push_check(&r, "pre-push-audit-python", "refs/heads/feat/x");
    assert!(out.contains("resolved: -r requirements.txt"), "{out}");
}

/// A uv project has no `requirements.txt` — it has a venv. Before this, the
/// check looked only for the file, found none, and reported "the audit did
/// NOT run" on every push forever; a whole fleet of Python repositories was
/// in that state with nobody told. Driven through the real binary, so the
/// argv it builds is what is being pinned.
#[test]
fn a_uv_project_audits_its_venv_not_a_missing_requirements_file() {
    let r = bare_repo();
    r.stage("pyproject.toml", "[project]\nname = \"x\"\n");
    r.commit("chore: uv project");
    std::fs::create_dir_all(r.path(".venv/lib/python3.13/site-packages")).expect("mkdir");
    // The shim proves the tool was actually invoked: it only speaks when
    // asked about a --path, so reaching this output means the venv route
    // was taken rather than the requirements one.
    shim(
        &r,
        "pip-audit",
        "case \"$*\" in *--path*) echo 'Found 3 known vulnerabilities in 2 packages'; exit 1;; \
         *) echo 'wrong invocation: '\"$*\"; exit 2;; esac",
    );
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "a release must refuse a vulnerable tree: {out}");
    assert!(
        out.contains("Found 3 known vulnerabilities"),
        "the tool's own sentence should decide: {out}"
    );

    // A Python project with neither a requirements file nor a venv to
    // audit: it still says so rather than inventing one.
    let bare = bare_repo();
    bare.stage("pyproject.toml", "[project]\nname = \"x\"\n");
    bare.commit("chore: uv project, no venv");
    shim(
        &bare,
        "pip-audit",
        "echo 'No known vulnerabilities found'\nexit 0",
    );
    let (code, out) = push_check(&bare, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "unavailable never blocks: {out}");
    assert!(
        out.contains("did NOT run"),
        "silence would be the bug this fixes: {out}"
    );
}

/// The registry calls an audit "inert here — needs go.sum" in a repository
/// without one; the push gate used to run it anyway, find govulncheck
/// missing, and warn on every push that it "could not run". A repository
/// in another language is not an audit that could not run: it is nothing
/// to audit, and nothing is said.
#[test]
fn an_audit_whose_lockfile_the_repository_lacks_is_silent_not_could_not_run() {
    let r = bare_repo();
    r.stage("Cargo.lock", "# only rust here\n");
    r.commit("chore: rust only");
    // Every tool present and vulnerable-by-default: if any of the three
    // foreign audits ran, it would say so loudly.
    for tool in ["govulncheck", "npm", "pnpm", "pip-audit"] {
        shim(
            &r,
            tool,
            "echo 'Vulnerability #1: GO-2024-0001 found 9 vulnerabilities'; exit 1",
        );
    }
    shim(
        &r,
        "cargo-audit",
        "echo 'Success No vulnerable packages found'; exit 0",
    );
    shim(
        &r,
        "cargo",
        "echo 'Success No vulnerable packages found'; exit 0",
    );
    for check in [
        "pre-push-audit-go",
        "pre-push-audit-js",
        "pre-push-audit-python",
    ] {
        let (code, out) = push_check(&r, check, "refs/tags/v1.0.0");
        assert_eq!(code, 0, "{check}: inert never blocks: {out}");
        assert!(
            !out.contains("could not run")
                && !out.contains("did NOT run")
                && !out.contains("NOT checked")
                && !out.contains("vulnerabilit"),
            "{check} has no lockfile here and should say nothing: {out}"
        );
    }
    // The one audit the repository DID opt into still runs.
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(
        !out.contains("could not run") && !out.contains("did NOT run"),
        "audit-rust has its lockfile and a tool: {out}"
    );
}

/// npm resolves a project from its own directory. A repository whose
/// packages live in subdirectories has no lockfile at the root, so the one
/// root-level `npm audit` answered ENOLOCK and the check said "could not
/// complete" — a tree with 17 real vulnerabilities (cluster-vision's web/)
/// was never audited. Each lockfile's directory is audited, and a finding
/// in any of them decides.
#[test]
fn audit_js_runs_in_every_lockfile_directory() {
    let r = bare_repo();
    r.stage("web/package-lock.json", "{}\n");
    r.stage("mcp/package-lock.json", "{}\n");
    r.commit("chore: two npm projects, none at the root");

    // The fake npm answers by the directory it runs in, and refuses the
    // root like the real one (no lockfile there).
    shim(
        &r,
        "npm",
        r#"case "$PWD" in
  */web) echo '17 vulnerabilities (8 moderate, 9 high)'; exit 1 ;;
  */mcp) echo 'found 0 vulnerabilities'; exit 0 ;;
  *) echo 'npm error code ENOLOCK' >&2; exit 1 ;;
esac"#,
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_ne!(
        code, 0,
        "a v* tag must not ship over web/'s findings: {out}"
    );
    assert!(out.contains("web: 17 vulnerabilities"), "{out}");
    assert!(!out.contains("could not complete"), "{out}");

    shim(
        &r,
        "npm",
        r#"case "$PWD" in
  */web|*/mcp) echo 'found 0 vulnerabilities'; exit 0 ;;
  *) echo 'npm error code ENOLOCK' >&2; exit 1 ;;
esac"#,
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(!out.contains("could not complete"), "{out}");
}

/// The same bug, still live for Rust (amont#305): a repository whose only
/// `Cargo.lock` is in a subdirectory — a Tauri app's `apps/ui/src-tauri` —
/// was audited at the root, where cargo-audit exits 2 ("entity not found"),
/// and the check said "could not complete" with no reason, over a tree that
/// carried 19 known vulnerabilities.
#[test]
fn audit_rust_runs_in_every_lockfile_directory() {
    let r = bare_repo();
    r.stage("apps/ui/src-tauri/Cargo.lock", "# fixture\n");
    r.commit("chore: a nested cargo project, none at the root");
    shim(&r, "cargo-audit", "exit 0");
    shim(
        &r,
        "cargo",
        r#"case "$1" in
  audit) case "$PWD" in
    */src-tauri) echo 'Crate: bad'; echo 'Version: 1.0.0'; echo 'ID: RUSTSEC-2025-0001'; echo 'error: 1 vulnerability found'; exit 1 ;;
    *) echo 'error: I/O operation failed: entity not found' >&2; exit 2 ;;
  esac ;;
  tree) printf 'bad v1.0.0\n└── app v0.1.0 (/repo/app)\n'; exit 0 ;;
esac
exit 0"#,
    );
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/heads/feat/x");
    assert_eq!(code, 0, "a branch push must not block: {out}");
    assert!(
        out.contains("apps/ui/src-tauri: RUSTSEC-2025-0001"),
        "{out}"
    );
    assert!(!out.contains("could not complete"), "{out}");

    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v1.0.0");
    assert_ne!(
        code, 0,
        "a v* tag must not ship over the nested findings: {out}"
    );
}

/// Go and Python had the same root-only runner.
#[test]
fn audit_go_and_python_run_in_every_lockfile_directory() {
    let r = bare_repo();
    r.stage("svc/go.sum", "# fixture\n");
    r.stage("tools/requirements.txt", "# fixture\n");
    r.commit("chore: a nested go module and python project");
    shim(
        &r,
        "govulncheck",
        r#"case "$PWD" in
  */svc) echo 'Vulnerability #1: GO-2025-0001'; echo 'Your code is affected by 1 vulnerability'; exit 3 ;;
  *) echo 'go: no go.mod file found' >&2; exit 1 ;;
esac"#,
    );
    let (_, out) = push_check(&r, "pre-push-audit-go", "refs/heads/feat/x");
    assert!(out.contains("svc: GO-2025-0001"), "{out}");
    assert!(!out.contains("could not complete"), "{out}");

    shim(
        &r,
        "pip-audit",
        r#"case "$PWD" in
  */tools) echo 'Found 1 known vulnerability in 1 package'; echo 'Name Version ID Fix Versions'; echo 'jinja2 2.0 PYSEC-2025-1 3.0'; exit 1 ;;
  *) echo 'ERROR: requirements.txt not found' >&2; exit 1 ;;
esac"#,
    );
    let (_, out) = push_check(&r, "pre-push-audit-python", "refs/heads/feat/x");
    assert!(out.contains("tools: Found 1 known vulnerability"), "{out}");
    assert!(!out.contains("could not complete"), "{out}");
}

/// "Could not complete" says why: the tool's own last error line.
#[test]
fn an_audit_that_cannot_answer_names_the_tools_error() {
    let r = bare_repo();
    r.stage("Cargo.lock", "# fixture\n");
    r.commit("chore: a cargo project");
    shim(&r, "cargo-audit", "exit 0");
    shim(
        &r,
        "cargo",
        "echo 'Fetching advisory database'; echo 'error: failed to fetch advisory database: network unreachable' >&2; exit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/heads/feat/x");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("could not complete"), "{out}");
    assert!(
        out.contains("failed to fetch advisory database: network unreachable"),
        "the reason must be printed: {out}"
    );
}

/// A pnpm workspace has no package-lock.json, so audit-js — which only knew
/// npm — never audited it and said nothing: one such tree carried 28
/// vulnerable versions, two critical, release after release. pnpm audits
/// its own lockfile; its summary decides, both ways.
#[test]
fn audit_js_audits_a_pnpm_workspace() {
    let r = bare_repo();
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.commit("chore: a pnpm workspace");
    // npm must not be asked: there is no package-lock.json.
    shim(&r, "npm", "echo 'npm must not run here' >&2; exit 1");
    shim(
        &r,
        "pnpm",
        "echo '107 vulnerabilities found'\necho 'Severity: 6 low | 45 moderate | 54 high | 2 critical'\nexit 1",
    );

    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/heads/feat/x");
    assert_eq!(code, 0, "a branch push must not block: {out}");
    assert!(out.contains("will BLOCK a v* tag push"), "{out}");
    assert!(
        out.contains(".: 107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)"),
        "{out}"
    );
    assert!(!out.contains("npm must not run"), "{out}");

    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "a release does not ship with these: {out}");

    shim(&r, "pnpm", "echo 'No known vulnerabilities found'\nexit 0");
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("no known vulnerabilities"), "{out}");
}

/// Both package managers in one repository: each lockfile's directory is
/// audited by its own tool, and a finding in either decides.
#[test]
fn audit_js_audits_npm_and_pnpm_projects_side_by_side() {
    let r = bare_repo();
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.stage("spike/package-lock.json", "{}\n");
    r.commit("chore: a pnpm workspace with an npm spike");
    shim(&r, "pnpm", "echo 'No known vulnerabilities found'\nexit 0");
    shim(
        &r,
        "npm",
        r#"case "$PWD" in
  */spike) echo '1 vulnerability (1 high)'; exit 1 ;;
  *) echo 'npm error code ENOLOCK' >&2; exit 1 ;;
esac"#,
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "the npm spike's finding still decides: {out}");
    assert!(out.contains("spike: 1 vulnerability (1 high)"), "{out}");
}

/// pnpm answers for the workspace it finds above a directory: a standalone
/// project with its own pnpm-lock.yaml inside a workspace (a spike) was
/// reported with the WORKSPACE ROOT's findings under its own name. Such a
/// project is audited with --ignore-workspace; the workspace root — which
/// tracks pnpm-workspace.yaml — is audited as the workspace, members and all.
#[test]
fn a_nested_pnpm_project_is_audited_on_its_own_lockfile() {
    let r = bare_repo();
    r.stage("pnpm-workspace.yaml", "packages:\n  - apps/*\n");
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.stage("spikes/s3/pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.commit("chore: a workspace with a standalone spike");
    // The fake pnpm answers like the real one: without --ignore-workspace it
    // reports the workspace, wherever it runs.
    shim(
        &r,
        "pnpm",
        r#"case "$*" in
  *--ignore-workspace*) case "$PWD" in
      */spikes/s3) echo '1 vulnerabilities found'; echo 'Severity: 1 moderate'; exit 1 ;;
      *) echo 'root audited with --ignore-workspace' >&2; exit 2 ;;
    esac ;;
  *) echo '107 vulnerabilities found'; echo 'Severity: 2 critical'; exit 1 ;;
esac"#,
    );
    let (_, out) = push_check(&r, "pre-push-audit-js", "refs/heads/feat/x");
    assert!(
        out.contains(".: 107 vulnerabilities found (2 critical)"),
        "the root is audited as the workspace: {out}"
    );
    assert!(
        out.contains("spikes/s3: 1 vulnerabilities found (1 moderate)"),
        "the spike reads its own lockfile: {out}"
    );
    assert!(!out.contains("spikes/s3: 107"), "{out}");
    assert!(
        !out.contains("root audited with --ignore-workspace"),
        "{out}"
    );
}

/// A release blocks on what it SHIPS. A finding only in the dev tree — the
/// registry builder's ts-morph pulling an unpatched `braces` — is named, but
/// nobody installing the package installs it, so the tag goes out.
#[test]
fn a_release_is_not_blocked_by_dev_only_findings() {
    let r = bare_repo();
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.commit("chore: a pnpm workspace");
    shim(
        &r,
        "pnpm",
        "case \" $* \" in *' --prod '*) echo 'No known vulnerabilities found'; exit 0;; esac\n\
         echo '5 vulnerabilities found'\necho 'Severity: 4 moderate | 1 high'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_eq!(
        code, 0,
        "dev-only findings must not refuse a release: {out}"
    );
    assert!(out.contains("only in development dependencies"), "{out}");
    assert!(out.contains("5 vulnerabilities found"), "{out}");
}

/// What ships still blocks, and the refusal shows the production audit.
#[test]
fn a_release_is_blocked_by_shipped_findings() {
    let r = bare_repo();
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.commit("chore: a pnpm workspace");
    shim(
        &r,
        "pnpm",
        "case \" $* \" in *' --prod '*) echo '1 vulnerabilities found'; echo 'Severity: 1 high'; exit 1;; esac\n\
         echo '5 vulnerabilities found'\necho 'Severity: 4 moderate | 1 high'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_ne!(code, 0, "a shipped vulnerability refuses the tag: {out}");
    assert!(out.contains("1 vulnerabilities found (1 high)"), "{out}");
    assert!(out.contains("audit --prod"), "{out}");
}

/// A production re-audit that cannot answer is not a pass: the full
/// finding still blocks.
#[test]
fn a_release_whose_prod_audit_cannot_answer_still_blocks() {
    let r = bare_repo();
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.commit("chore: a pnpm workspace");
    shim(
        &r,
        "pnpm",
        "case \" $* \" in *' --prod '*) echo 'ERR_PNPM_AUDIT_BAD_RESPONSE' >&2; exit 1;; esac\n\
         echo '5 vulnerabilities found'\necho 'Severity: 4 moderate | 1 high'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_ne!(code, 0, "an unknown is not a pass: {out}");
}

/// npm takes `--omit=dev` for the same question.
#[test]
fn an_npm_release_audits_what_it_ships() {
    let r = bare_repo();
    r.stage("package-lock.json", "{}\n");
    r.commit("chore: an npm project");
    shim(
        &r,
        "npm",
        "case \" $* \" in *' --omit=dev '*) echo 'found 0 vulnerabilities'; exit 0;; esac\n\
         echo '2 vulnerabilities (1 moderate, 1 high)'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("only in development dependencies"), "{out}");

    // A branch push is unchanged: named, never blocking, no second audit.
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/heads/feat/x");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("will BLOCK a v* tag push"), "{out}");
}

/// Rust: a crate only a dev-dependency reaches does not refuse a release.
#[test]
fn a_rust_release_is_not_blocked_by_a_dev_only_crate() {
    let r = repo();
    shim(&r, "cargo-audit", "exit 0");
    shim(&r, "cargo", &cargo_reaching(""));
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("only in development dependencies"), "{out}");
    assert!(out.contains("RUSTSEC-2025-0001"), "{out}");
}

/// Python: a vulnerable package outside `uv export --no-dev` is dev-only.
#[test]
fn a_python_release_is_audited_on_what_uv_ships() {
    let r = bare_repo();
    r.stage("pyproject.toml", "[project]\nname = 'app'\n");
    r.stage("uv.lock", "version = 1\n");
    r.commit("chore: a uv project");
    std::fs::create_dir_all(r.path(".venv/lib/python3.12/site-packages")).unwrap();
    let table = "echo 'Name    Version ID                  Fix Versions'\n\
                 echo '------- ------- ------------------- ------------'\n\
                 echo 'pytest_cov 4.0.0 GHSA-aaaa-bbbb-cccc 4.1.0'\n\
                 echo 'Found 1 known vulnerability in 1 package'\nexit 1";
    shim(&r, "pip-audit", table);
    shim(
        &r,
        "uv",
        "echo 'requests==2.32.3'\necho '    # via app'\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("only in development dependencies"), "{out}");
    assert!(out.contains("pytest-cov"), "{out}");

    // The same package in the production set refuses the tag.
    shim(&r, "uv", "echo 'pytest-cov==4.0.0'\nexit 0");
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");

    // No uv to ask: an unknown is not a pass.
    std::fs::remove_file(r.path(".git/toolshims/uv")).unwrap();
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");
}

/// Go is audited on what ships already: no `-test`, so test-only code and
/// its imports are never counted.
#[test]
fn go_is_audited_without_test_code() {
    let r = repo();
    shim(
        &r,
        "govulncheck",
        "case \" $* \" in *' -test '*) echo 'must not audit tests'; exit 3;; esac\necho 'No vulnerabilities found.'\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-go", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(!out.contains("must not audit tests"), "{out}");
}

/// `YYYY-MM-DD`, `offset` days from today (UTC) — Hinnant's civil_from_days.
fn date_in(offset: i64) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
        / 86_400;
    let z = now + offset + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    format!("{y:04}-{m:02}-{d:02}")
}

/// A pnpm workspace whose PRODUCTION audit names one GHSA advisory.
fn shipped_braces_repo(waivers: Option<String>) -> Repo {
    shipped_braces_repo_files(waivers.map(|w| (".greengate-audit-waivers", w)).into_iter())
}

/// The same, with waiver files under whatever names the test gives.
fn shipped_braces_repo_files<'a>(files: impl Iterator<Item = (&'a str, String)>) -> Repo {
    let r = bare_repo();
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    for (name, w) in files {
        r.stage(name, &w);
    }
    r.commit("chore: a pnpm workspace");
    shim(
        &r,
        "pnpm",
        "echo '│ More info │ https://github.com/advisories/GHSA-3gc7-fjrx-p6mg │'\n\
         echo '1 vulnerabilities found'\necho 'Severity: 1 high'\nexit 1",
    );
    r
}

/// An unfixable shipped advisory passes a release under a dated, reasoned
/// waiver — and the push says so.
#[test]
fn a_waived_advisory_ships_until_its_waiver_expires() {
    let r = shipped_braces_repo(Some(format!(
        "# id expires reason\nGHSA-3gc7-fjrx-p6mg {} braces via react-strict-dom; no patched version\n",
        date_in(30)
    )));
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("under a reviewed waiver"), "{out}");
    assert!(out.contains("GHSA-3gc7-fjrx-p6mg until"), "{out}");
    assert!(
        out.contains("(.greengate-audit-waivers)"),
        "the file read is quoted: {out}"
    );
}

/// A repository that only has the pre-4.3 file still waives, and the message
/// quotes the file it read. Fails without the fallback read.
#[test]
fn a_waivers_file_under_the_old_name_still_waives() {
    let old = format!("GHSA-3gc7-fjrx-p6mg {} braces; no patch\n", date_in(30));
    let r = shipped_braces_repo_files([(".amont-audit-waivers", old)].into_iter());
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("(.amont-audit-waivers)"), "{out}");
}

/// With both files the new one wins and the old one is ignored, with a
/// warning naming it: an expired new file refuses the release even though
/// the old one is valid.
#[test]
fn with_both_waiver_files_the_new_one_wins() {
    let valid = format!("GHSA-3gc7-fjrx-p6mg {} braces; no patch\n", date_in(30));
    let expired = format!("GHSA-3gc7-fjrx-p6mg {} braces; no patch\n", date_in(-1));
    let r = shipped_braces_repo_files(
        [
            (".greengate-audit-waivers", expired),
            (".amont-audit-waivers", valid),
        ]
        .into_iter(),
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("expired on"), "{out}");
    assert!(
        out.contains(".amont-audit-waivers is ignored"),
        "the old file is named: {out}"
    );
}

/// Expired, or waiving some other advisory: the tag is refused, and why.
#[test]
fn an_expired_or_unrelated_waiver_refuses_the_release() {
    let r = shipped_braces_repo(Some(format!(
        "GHSA-3gc7-fjrx-p6mg {} braces; no patch\n",
        date_in(-1)
    )));
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("expired on"), "{out}");
    assert!(out.contains("not waived: GHSA-3gc7-fjrx-p6mg"), "{out}");

    let r = shipped_braces_repo(Some(format!(
        "GHSA-aaaa-bbbb-cccc {} something else\n",
        date_in(30)
    )));
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_ne!(code, 0, "{out}");

    let r = shipped_braces_repo(None);
    let (code, _) = push_check(&r, "pre-push-audit-js", "refs/tags/v4.3.0");
    assert_ne!(code, 0);
}

/// A shipped-edges tree that cannot be read is not "dev-only": cargo
/// erroring (an ambiguous spec, a stale lock) prints no local crate either.
#[test]
fn a_rust_release_blocks_when_the_tree_cannot_answer() {
    let r = repo();
    shim(&r, "cargo-audit", "exit 0");
    shim(
        &r,
        "cargo",
        "case \"$1\" in\n\
         audit) echo 'Crate: bad'; echo 'Version: 1.0.0'; echo 'ID: RUSTSEC-2025-0001'; echo 'error: 1 vulnerability found'; exit 1;;\n\
         tree) echo 'error: failed to load manifest' >&2; exit 101;;\n\
         esac\nexit 0",
    );
    let (code, out) = push_check(&r, "pre-push-audit-rust", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "an unknown is not a pass: {out}");
}

/// A waiver never vouches for a project the audit could not check.
#[test]
fn a_waiver_does_not_cover_an_unchecked_project() {
    let r = bare_repo();
    r.stage("pnpm-workspace.yaml", "packages:\n  - apps/*\n");
    r.stage("pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.stage("spikes/s3/pnpm-lock.yaml", "lockfileVersion: '9.0'\n");
    r.stage(
        ".greengate-audit-waivers",
        &format!("GHSA-3gc7-fjrx-p6mg {} braces; no patch\n", date_in(30)),
    );
    r.commit("chore: a workspace with a spike");
    shim(
        &r,
        "pnpm",
        "case \" $* \" in *' --ignore-workspace '*) echo 'ERR_PNPM_AUDIT_BAD_RESPONSE' >&2; exit 1;; esac\n\
         echo 'https://github.com/advisories/GHSA-3gc7-fjrx-p6mg'\n\
         echo '1 vulnerabilities found'\necho 'Severity: 1 high'\nexit 1",
    );
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("NOT checked"), "{out}");
}

/// A branch push names the waiver instead of promising a refusal.
#[test]
fn a_branch_push_names_the_waiver() {
    let r = shipped_braces_repo(Some(format!(
        "GHSA-3gc7-fjrx-p6mg {} braces; no patch\n",
        date_in(30)
    )));
    let (code, out) = push_check(&r, "pre-push-audit-js", "refs/heads/feat/x");
    assert_eq!(code, 0, "{out}");
    assert!(
        out.contains("a v* tag push will pass while it holds"),
        "{out}"
    );
    assert!(!out.contains("will BLOCK"), "{out}");
}

const PYPI_BLOCK: &str = "[[package]]\nname = \"NAME\"\nversion = \"1.0.0\"\nsource = { registry = \"https://pypi.org/simple\" }\n\n";
const PRIVATE_BLOCK: &str = "[[package]]\nname = \"platform-kernel\"\nversion = \"0.1.0\"\nsource = { registry = \"https://git.example.test/simple\" }\n\n";

/// A uv project with no `.venv`: committed `pyproject.toml` and `uv.lock`
/// (one shipped PyPI package, one dev-only PyPI package, one private one).
fn uv_lock_repo(lock_dir: &str) -> Repo {
    let r = bare_repo();
    let prefix = if lock_dir.is_empty() {
        String::new()
    } else {
        format!("{lock_dir}/")
    };
    r.stage(
        &format!("{prefix}pyproject.toml"),
        "[project]\nname = \"x\"\n",
    );
    let lock = [
        PYPI_BLOCK.replace("NAME", "certifi"),
        PYPI_BLOCK.replace("NAME", "dev-tool"),
        PRIVATE_BLOCK.to_string(),
    ]
    .concat();
    r.stage(&format!("{prefix}uv.lock"), &lock);
    r.commit("chore: uv project");
    // The export (with `-o`) lists everything; without `-o` it is the
    // production list the release split asks for.
    // Each call's arguments are appended to `.git/uv-calls`.
    shim(
        &r,
        "uv",
        r#"echo "$*" >> "$(git rev-parse --git-dir)/uv-calls"
out=; prev=
for a in "$@"; do [ "$prev" = -o ] && out=$a; prev=$a; done
if [ -n "$out" ]; then
  printf 'certifi==1.0.0 ; python_full_version >= "3.8"\ndev-tool==1.0.0\nplatform-kernel==0.1.0\n' > "$out"
else
  printf 'certifi==1.0.0\n'
fi"#,
    );
    r
}

/// A `pip-audit` that answers only to `--no-deps`, `--disable-pip` and
/// `-r <file>` in any order, records the file and the directory it ran in,
/// and reports `rows` as vulnerable.
fn lock_pip_audit(r: &Repo, rows: &str) {
    let record = r.path(".git/recorded");
    let _ = std::fs::remove_file(&record); // best effort: no record yet is the usual case
    shim(
        r,
        "pip-audit",
        &format!(
            r#"nd=0; di=0; rf=; prev=
for a in "$@"; do
  case "$a" in --no-deps) nd=1;; --disable-pip) di=1;; esac
  [ "$prev" = -r ] && rf=$a
  prev=$a
done
if [ $nd = 1 ] && [ $di = 1 ] && [ -n "$rf" ]; then :; else echo "wrong invocation: $*"; exit 2; fi
cat "$rf" >> {record}
pwd >> {record}
if [ -n '{rows}' ]; then
  echo 'Found 1 known vulnerability in 1 package'
  echo 'Name Version ID Fix Versions'
  echo '{rows}'
  exit 1
fi
echo 'No known vulnerabilities found'"#,
            record = record.display(),
            rows = rows
        ),
    );
}

fn recorded(r: &Repo) -> String {
    std::fs::read_to_string(r.path(".git/recorded")).unwrap_or_default()
}

fn scratch_tmp(r: &Repo) -> std::path::PathBuf {
    let scratch_dir = r.path(".git/scratch-scratch_dir");
    std::fs::create_dir_all(&scratch_dir).expect("mkdir");
    scratch_dir
}

fn leftovers(scratch_dir: &std::path::Path) -> Vec<String> {
    std::fs::read_dir(scratch_dir)
        .expect("read")
        .flatten()
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .collect()
}

#[test]
fn a_uv_lock_without_a_venv_is_audited_and_a_vulnerable_one_refuses_a_tag() {
    let r = uv_lock_repo("");
    lock_pip_audit(&r, "certifi 1.0.0 PYSEC-2024-1 1.0.1");
    let scratch_dir = scratch_tmp(&r);
    let (code, out) = push_check_in(
        &r,
        "pre-push-audit-python",
        "refs/tags/v1.0.0",
        Some(&scratch_dir),
    );
    assert_ne!(code, 0, "a shipped finding must refuse the tag: {out}");
    assert!(out.contains("certifi"), "{out}");
    assert!(
        out.contains("audit-python: audited uv.lock (2 package versions, 1 skipped)"),
        "{out}"
    );
    assert!(
        out.contains("1 private/non-PyPI package skipped (platform-kernel)"),
        "{out}"
    );
    assert!(!out.contains("did NOT run"), "{out}");
    assert!(
        !out.contains(scratch_dir.to_str().unwrap()),
        "temp path leaked: {out}"
    );
    let sent = recorded(&r);
    assert!(sent.contains("certifi==1.0.0"), "{sent}");
    assert!(
        !sent.contains("platform-kernel"),
        "a private name was sent: {sent}"
    );
    assert!(!sent.contains(';'), "markers must be stripped: {sent}");
    assert_eq!(
        leftovers(&scratch_dir),
        Vec::<String>::new(),
        "temp dir must be removed"
    );

    lock_pip_audit(&r, "");
    let (code, out) = push_check_in(
        &r,
        "pre-push-audit-python",
        "refs/tags/v1.0.0",
        Some(&scratch_dir),
    );
    assert_eq!(code, 0, "{out}");
    assert_eq!(
        leftovers(&scratch_dir),
        Vec::<String>::new(),
        "temp dir must be removed"
    );
}

/// How many `uv export --no-dev` calls the shim saw.
fn production_exports(repo: &Repo) -> usize {
    std::fs::read_to_string(repo.path(".git/uv-calls"))
        .unwrap_or_default()
        .lines()
        .filter(|call| call.contains("--no-dev"))
        .count()
}

#[test]
fn a_release_asks_what_ships_only_when_a_batch_has_findings() {
    let repo = uv_lock_repo("");
    lock_pip_audit(&repo, "");
    let (code, out) = push_check(&repo, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert_eq!(
        production_exports(&repo),
        0,
        "a clean lock needs no split: {out}"
    );

    lock_pip_audit(&repo, "dev-tool 1.0.0 PYSEC-2024-2 1.0.1");
    let (code, out) = push_check(&repo, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert_eq!(production_exports(&repo), 1, "{out}");
}

#[test]
fn a_dev_only_finding_in_the_lock_passes_a_tag() {
    let r = uv_lock_repo("");
    lock_pip_audit(&r, "dev-tool 1.0.0 PYSEC-2024-2 1.0.1");
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("dev-only"), "{out}");
}

#[test]
fn an_all_private_lock_did_not_run_and_never_blocks() {
    let r = bare_repo();
    r.stage("pyproject.toml", "[project]\nname = \"x\"\n");
    r.stage("uv.lock", PRIVATE_BLOCK);
    r.commit("chore: private-only uv project");
    shim(&r, "uv", "o=; p=; for a in \"$@\"; do [ \"$p\" = -o ] && o=$a; p=$a; done\n[ -n \"$o\" ] && echo 'platform-kernel==0.1.0' > \"$o\"");
    lock_pip_audit(&r, "certifi 1.0.0 PYSEC-2024-1 1.0.1");
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "unavailable never blocks: {out}");
    assert!(out.contains("did NOT run"), "{out}");
    assert!(out.contains("1 private/non-PyPI package skipped"), "{out}");
    assert_eq!(recorded(&r), "", "pip-audit must not have been called");
}

#[test]
fn a_failed_export_warns_and_does_not_block() {
    let r = uv_lock_repo("");
    shim(
        &r,
        "uv",
        "echo 'error: lockfile needs to be updated' >&2\nexit 2",
    );
    lock_pip_audit(&r, "certifi 1.0.0 PYSEC-2024-1 1.0.1");
    let scratch_dir = scratch_tmp(&r);
    let (code, out) = push_check_in(
        &r,
        "pre-push-audit-python",
        "refs/tags/v1.0.0",
        Some(&scratch_dir),
    );
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("did NOT run"), "{out}");
    assert!(out.contains("lockfile needs to be updated"), "{out}");
    assert!(
        out.contains("Next: `uv export --frozen` at the repo root"),
        "{out}"
    );
    assert_eq!(recorded(&r), "");
    assert_eq!(
        leftovers(&scratch_dir),
        Vec::<String>::new(),
        "temp dir must be removed"
    );
}

#[test]
fn a_nested_uv_lock_is_audited_from_its_own_directory() {
    let r = uv_lock_repo("a");
    lock_pip_audit(&r, "certifi 1.0.0 PYSEC-2024-1 1.0.1");
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "{out}");
    assert!(out.contains("audited a/uv.lock"), "{out}");
    assert!(recorded(&r).trim_end().ends_with("/a"), "{}", recorded(&r));
}

/// The first batch's `pip-audit` answer: one vulnerable row.
const FIRST_BATCH_VULNERABLE: &str = "echo 'Found 1 known vulnerability in 1 package'; echo 'Name Version ID Fix Versions'; echo 'certifi 1.0.0 PYSEC-2024-1 1.0.1'; exit 1";
/// The first batch's `pip-audit` answer: clean.
const FIRST_BATCH_CLEAN: &str = "echo 'No known vulnerabilities found'; exit 0";

/// A lock exporting two versions of one PyPI name, so two batches. The
/// `pip-audit` shim answers the file naming 1.0.0 with `first_batch_answer`
/// and exits 2 with no output for the other.
fn two_batch_repo(first_batch_answer: &str) -> Repo {
    let r = bare_repo();
    r.stage("pyproject.toml", "[project]\nname = \"x\"\n");
    let lock = [
        PYPI_BLOCK.replace("NAME", "certifi"),
        PYPI_BLOCK.replace("NAME", "certifi"),
    ]
    .concat();
    r.stage("uv.lock", &lock);
    r.commit("chore: uv project");
    shim(
        &r,
        "uv",
        r#"out=; prev=
for a in "$@"; do [ "$prev" = -o ] && out=$a; prev=$a; done
if [ -n "$out" ]; then
  printf 'certifi==1.0.0\ncertifi==2.0.0\n' > "$out"
else
  printf 'certifi==1.0.0\ncertifi==2.0.0\n'
fi"#,
    );
    shim(
        &r,
        "pip-audit",
        &format!(
            r#"rf=; prev=
for a in "$@"; do [ "$prev" = -r ] && rf=$a; prev=$a; done
if grep -q '1.0.0' "$rf"; then
  {first_batch_answer}
fi
exit 2"#
        ),
    );
    r
}

#[test]
fn a_batch_that_could_not_answer_never_reads_as_a_clean_pass() {
    let r = two_batch_repo(FIRST_BATCH_VULNERABLE);
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_ne!(code, 0, "the vulnerable batch refuses the tag: {out}");
    assert!(out.contains("certifi"), "{out}");
    assert!(out.contains("could not answer"), "{out}");
    assert!(out.contains("(no output)"), "{out}");
    assert!(
        out.contains("Next: `pip-audit --version` to check the install"),
        "a silent failure is not blamed on the network: {out}"
    );

    let r = two_batch_repo(FIRST_BATCH_CLEAN);
    let (code, out) = push_check(&r, "pre-push-audit-python", "refs/tags/v1.0.0");
    assert_eq!(code, 0, "unavailable never blocks: {out}");
    assert!(out.contains("NOT fully checked"), "{out}");
    assert!(out.contains("(no output)"), "{out}");
}