trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
//! #8596, #8248: a credential value never reaches tool output. Every command
//! here uses a fake service name; none is ever run.

use super::evaluate_credential_print_command;

/// Assert every row gets the wanted verdict, reporting all misses at once.
fn check(want_deny: bool, rows: &[&str]) {
    let wrong: Vec<String> = rows
        .iter()
        .filter_map(|c| {
            let got = evaluate_credential_print_command(c);
            (got.is_some() != want_deny).then(|| format!("{c:?} -> {got:?}"))
        })
        .collect();
    let verdict = if want_deny { "refused" } else { "allowed" };
    assert!(
        wrong.is_empty(),
        "expected {verdict}:\n{}",
        wrong.join("\n")
    );
}

/// The two reported leaks and the shapes one step away from them.
#[test]
fn denies_the_reported_leaks() {
    check(
        true,
        &[
            // #8596: the incident — the value is shorter than 50 bytes.
            "security find-generic-password -s fake-svc -a fake-acct -w | head -c 50",
            "security find-generic-password -s fake-svc -w",
            "/usr/bin/security find-internet-password -s example.test -w",
            "security find-generic-password -ws fake-svc",
            "security find-generic-password -s fake-svc -w | cut -c1-8",
            "security find-generic-password -s fake-svc -w | tee /tmp/fake-out",
            "security find-generic-password -s fake-svc -w > /dev/stdout",
            // `-g` prints the value on STDERR.
            "security find-generic-password -g -s fake-svc",
            "security find-generic-password -g -s fake-svc >/dev/null",
            "security find-generic-password -g -s fake-svc 2>&1 | head -c 20",
            // #8248: the incident, and its siblings.
            "gcloud auth application-default print-access-token",
            "gcloud auth print-access-token",
            "gcloud auth print-identity-token --audiences=https://example.test",
            "gcloud --project fake-proj auth print-access-token | head -c 12",
            "timeout 5 gcloud auth print-access-token",
            "cd /tmp && gcloud auth print-access-token",
            // A captured value handed back to the terminal.
            "echo \"$(gcloud auth print-access-token)\"",
            "printf '%s' `security find-generic-password -s fake-svc -w`",
            "cat <(gcloud auth print-access-token)",
            "$(gcloud auth print-access-token)",
            "cat <<< \"$(gcloud auth print-access-token)\"",
            "gcloud auth print-access-token | xargs echo",
            // #8596 finding 10 narrows xargs to printing programs only.
            "gcloud auth print-access-token | xargs -I{} echo {}",
            "gcloud auth print-access-token | xargs -I{} sh -c 'echo {}'",
            "gcloud auth print-access-token | xargs -I{} {}",
            "gcloud auth print-access-token | xargs",
            "bash -c 'gcloud auth print-access-token'",
            // #8735 round 2: `wrapped_command` now reads the string behind
            // `sudo -u fake`, so this refuses as a print, like the row above.
            "sudo -u fake bash -c 'gcloud auth print-access-token'",
            "sh -c \"security find-generic-password -s fake-svc -w\" | head",
            "X=$(echo \"$(gcloud auth print-access-token)\" | head -c 5); echo hi; gcloud auth print-access-token",
        ],
    );
}

/// The capturing forms legitimate flows need keep working.
#[test]
fn allows_the_capturing_forms() {
    check(
        false,
        &[
            // Existence check by exit status (#8596's proposed pattern).
            "security find-generic-password -s fake-svc >/dev/null 2>&1 && echo present",
            "security find-generic-password -s fake-svc -a fake-acct",
            "security find-generic-password -s fake-svc -w >/dev/null 2>&1",
            "security find-generic-password -s fake-svc -g &>/dev/null",
            "security find-generic-password -s w -a g",
            // A token consumed inside the command that needs it (#8248).
            "curl -sS -H \"Authorization: Bearer $(gcloud auth print-access-token)\" https://example.test/v1",
            "TOKEN=$(gcloud auth print-access-token)",
            "export FAKE_TOKEN=$(security find-generic-password -s fake-svc -w)",
            "FAKE=$(gcloud auth application-default print-access-token) curl -H \"x: $FAKE\" https://example.test",
            "gcloud auth print-access-token | docker login -u oauth2accesstoken --password-stdin https://example.test",
            "security find-generic-password -s fake-svc -w | pbcopy",
            "security find-generic-password -s fake-svc -w | wc -c",
            "security find-generic-password -s fake-svc -w | grep -q .",
            "gcloud auth print-access-token > /tmp/fake-token-file",
            "X=$(echo \"$(gcloud auth print-access-token)\")",
            // Naming the commands as text runs none of them.
            "git commit -m 'docs: never run gcloud auth print-access-token bare'",
            "grep -rn 'find-generic-password' crates/",
            "rg print-access-token docs/",
            "echo 'security find-generic-password -s x -w'",
            "gcloud auth list",
        ],
    );
}

/// #8596 round 2: every bypass the code-critic found. Each row was allowed at
/// f61a451ae.
#[test]
fn denies_the_round_two_bypasses() {
    check(
        true,
        &[
            // 1: a `<(…)` file is printed by any reader.
            "head -c 8 <(security find-generic-password -s fake-svc -w)",
            "diff <(gcloud auth print-access-token) want.txt",
            "sort < <(gcloud auth print-access-token)",
            // 2: a substitution the outer shell lifted, inside a wrapper.
            "bash -c \"echo $(gcloud auth print-access-token)\"",
            "echo x | xargs echo $(gcloud auth print-access-token)",
            "env -S \"echo $(gcloud auth print-access-token)\"",
            // 3: a copy through a descriptor the rule did not track.
            "security find-generic-password -s fake-svc -w 3>&1 1>&3",
            "security find-generic-password -s fake-svc -w 3>&1 1>&3-",
            "security find-generic-password -s fake-svc -w 1>&4",
            "gcloud auth print-access-token >& 1",
            // 4: APFS is case-insensitive.
            "SECURITY find-generic-password -s fake-svc -w",
            "GCloud auth print-access-token",
            // Subshell grouping and a keyword before a run-time program.
            "(gcloud auth print-access-token)",
            "if true; then $(gcloud auth print-access-token); fi",
            // 6: consumers accepted only where they really consume.
            "gcloud auth print-access-token | tee --password-stdin",
            "gcloud auth print-access-token | cat --with-token",
            "gcloud auth print-access-token | grep -eq .",
            "gcloud auth print-access-token | rg -rq .",
            "gcloud auth print-access-token | wc --files0-from=-",
            "gcloud auth print-access-token | wc -c -L --files0-from -",
            // 7: xtrace prints expanded values.
            "set -x; TOKEN=$(gcloud auth print-access-token)",
            "set -o xtrace; curl -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "set -euxo pipefail; T=$(gcloud auth print-access-token)",
            "bash -x -c 'T=$(gcloud auth print-access-token)'",
            "bash -xc 'T=$(gcloud auth print-access-token)'",
            "SHELLOPTS=xtrace bash -c 'T=$(gcloud auth print-access-token)'",
            // 8: more credential-printing calls.
            "gcloud config config-helper --format='value(credential.access_token)'",
            "gcloud config config-helper --format=json",
            "gcloud config config-helper",
            "security dump-keychain -d",
            "security dump-keychain -d login.keychain | head",
        ],
    );
}

/// #8596 round 2, finding 5: credential-command text handed to something that
/// runs it, or a program named at run time. The guard cannot follow the value,
/// so it refuses as unreadable.
#[test]
fn denies_evaluated_trigger_text() {
    let rows = [
        "S=security; $S find-generic-password -s fake-svc -w",
        "G=gcloud; timeout 5 $G auth print-access-token",
        "C='gcloud auth print-access-token'; $C",
        "eval \"security find-generic-password -s fake-svc -w\"",
        "bash <<< 'gcloud auth print-access-token'",
        "echo 'gcloud auth print-access-token' | sh",
        "osascript -e 'do shell script \"security find-generic-password -s fake-svc -w\"'",
        "python3 -c 'import os; os.system(\"gcloud auth print-access-token\")'",
        "ssh fake-host 'security find-generic-password -s fake-svc -w'",
        "bash <<'EOF'\ngcloud auth print-access-token\nEOF",
        "python3 <<'PY'\nimport os; os.system('gcloud auth print-access-token')\nPY",
        "python3 <<PY\nimport os; os.system(\"gcloud auth print-access-token\")\nPY",
    ];
    let wrong: Vec<String> = rows
        .iter()
        .filter_map(|c| {
            let reason = evaluate_credential_print_command(c);
            (!reason.as_deref().is_some_and(|r| r.contains("cannot read")))
                .then(|| format!("{c:?} -> {reason:?}"))
        })
        .collect();
    assert!(
        wrong.is_empty(),
        "expected unreadable:\n{}",
        wrong.join("\n")
    );
    // An unquoted body is shell source: its credential call is judged as one.
    check(true, &["bash <<EOF\ngcloud auth print-access-token\nEOF"]);
}

/// #8596 round 2, findings 9 and 10: data here-documents and a non-printing
/// xargs program are allowed; so are the mentions finding 5 must not catch.
#[test]
fn allows_quoted_heredoc_bodies() {
    check(
        false,
        &[
            "gh issue comment 1 --body-file - <<'EOF'\nNever run gcloud auth print-access-token bare; it's a leak.\nEOF",
            "cat > notes.md <<'EOF'\nsecurity find-generic-password -s x -w | head -c 50 (don't)\nEOF",
            "gh pr create --title t --body \"$(cat <<'EOF'\nuse `security find-generic-password -s x >/dev/null`, isn't that it\nEOF\n)\"",
            "gcloud auth print-access-token | xargs -I{} curl -H \"Authorization: Bearer {}\" https://example.test",
            "gcloud auth print-access-token | xargs -I % curl -sS -H 'Authorization: Bearer %' https://example.test",
            "git log --grep print-access-token",
            "git grep -n find-generic-password",
            "gh issue create --title x --body 'gcloud auth print-access-token leaked'",
            "gcloud auth print-access-token | gh auth login --with-token",
            "gcloud auth print-access-token | podman login -u oauth2accesstoken --password-stdin example.test",
            "gcloud auth print-access-token | grep -cq .",
            "gcloud auth print-access-token | wc -lc",
            "wc -c <(gcloud auth print-access-token)",
            "gcloud config config-helper --format='value(configuration.properties.core.project)'",
            "security find-generic-password -s fake-svc -w 3>/dev/null 1>&3",
            "set +x; T=$(gcloud auth print-access-token)",
        ],
    );
}

/// #8596 round 3: every bypass the second code-critic round found. Each row
/// was allowed at 99bc6da75.
#[test]
fn denies_the_round_three_bypasses() {
    check(
        true,
        &[
            // 1: a comment hid a heredoc operator or held an apostrophe.
            "true # <<'X'\ngcloud auth print-access-token\nX",
            "# don't print it\ngcloud auth print-access-token\n# that's all",
            "# don't\ngcloud auth print-access-token >/dev/null; gcloud auth print-access-token\n# that's all",
            "echo ${X:-<<'E'}\ngcloud auth print-access-token\nE",
            "echo ${X:-<<'E' }\ngcloud auth print-access-token\nE",
            // 2: a file-name argument that names the terminal.
            "gcloud auth print-access-token | tee /dev/stderr | docker login -u x --password-stdin r.test",
            "gcloud auth print-access-token | tee /dev/tty >/dev/null",
            "gcloud auth print-access-token | tee >(cat) >/dev/null",
            "cp <(gcloud auth print-access-token) /dev/stderr >/dev/null",
            "gcloud auth print-access-token | dd of=/dev/stderr status=none >/dev/null",
            "gcloud auth print-access-token | tee /dev/fd/2 >/dev/null",
            // 3: program text flowing through a filter into an evaluator.
            "echo 'gcloud auth print-access-token' | cat | sh",
            "cat <<'EOF' | tee /dev/null | bash\ngcloud auth print-access-token\nEOF",
            // 4: input-side copies, read-write opens, a run-time descriptor.
            "security find-generic-password -s x -w >/dev/null 1<&2",
            "security find-generic-password -s x -w >/dev/null 1<>/dev/tty",
            "exec {fd}>&1; gcloud auth print-access-token >&$fd",
            // 5: `-o` at the end of a cluster, and option-name spelling.
            "set -eo xtrace; T=$(gcloud auth print-access-token)",
            "set -o XTRACE; T=$(gcloud auth print-access-token)",
            "set -o x_trace; T=$(gcloud auth print-access-token)",
        ],
    );
}

/// #8730: zsh's clobber spellings `>!`/`>>!` (and `>&!`/`>&|`) left the `!`
/// or `|` glued to the target, so `/dev/tty` read as the file `!/dev/tty` and
/// the value was taken as discarded. Each row was allowed at 6a1aeb2b0.
#[test]
fn denies_a_clobber_redirect_to_the_terminal_8730() {
    check(
        true,
        &[
            "security find-generic-password -s x -w >!/dev/tty",
            "security find-generic-password -s x -w >>!/dev/tty",
            "security find-generic-password -s x -w >!/dev/stdout",
            "security find-generic-password -s x -w >&!/dev/tty",
            "security find-generic-password -s x -w >&|/dev/tty",
            "security find-generic-password -s x -w >| /dev/tty",
        ],
    );
}

/// #8730: a clobber redirect to an ordinary file is a file write. The `>|`
/// rows were refused as unreadable at 6a1aeb2b0: the stage split cut at the
/// operator's `|` as if it were a pipe.
#[test]
fn allows_a_clobber_redirect_to_a_file_8730() {
    check(
        false,
        &[
            "security find-generic-password -s x -w >!/tmp/fake-out",
            "security find-generic-password -s x -w >>!/tmp/fake-out",
            "security find-generic-password -s x -w >|/tmp/fake-out",
            "security find-generic-password -s x -w >>| /tmp/fake-out",
        ],
    );
}

/// #8596 round 3, finding 6: only an evaluator's code operand is judged, so a
/// script-path operand is an ordinary argument; a comment, or a `#` inside a
/// word, changes nothing that was allowed.
#[test]
fn allows_script_operands_and_comments() {
    check(
        false,
        &[
            "T=$(gcloud auth print-access-token); python3 upload.py --token \"$T\"",
            "gcloud auth print-access-token > /tmp/fake-token # keep it out of the log",
            "cat <<'EOF' > notes.md # a note\n# don't run gcloud auth print-access-token\nEOF",
            "T=$(gcloud auth print-access-token); echo ${#T} a#b '# not a comment'",
            "gcloud auth print-access-token | tee /tmp/fake-token >/dev/null",
            "security find-generic-password -s x -w 1<>/tmp/fake-out",
        ],
    );
    check(
        true,
        &["python3 -c \"print('$(gcloud auth print-access-token)')\""],
    );
}

/// #8676: a credential captured into a shell variable and printed in a later
/// stage. The first three rows are the reported shapes; each row was allowed
/// at 62947a19f.
#[test]
fn denies_a_credential_carried_by_a_variable() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); echo \"${T:0:10}\"",
            "export K=$(security find-generic-password -s fake-svc -w) && printenv K",
            "for t in $(gcloud auth print-access-token); do echo $t; done",
            // Environment and variable dumps while a name is tainted.
            "export K=$(security find-generic-password -s fake-svc -w); env",
            "T=$(gcloud auth print-access-token) printenv T",
            "T=$(gcloud auth print-access-token); sudo -u fake env",
            "T=$(gcloud auth print-access-token); set",
            "T=$(gcloud auth print-access-token); declare -p T",
            "export T=$(gcloud auth print-access-token); export -p",
            "T=$(gcloud auth print-access-token); timeout 5 printenv",
            // Every binding form, and every stage separator.
            "T=$(gcloud auth print-access-token)\nprintf '%s\\n' \"$T\"",
            "local T=$(gcloud auth print-access-token) || echo ${T}",
            "declare -r T=`gcloud auth print-access-token`; echo ${T:-none}",
            "readonly T=$(gcloud auth print-access-token); echo ${T#ya29}",
            "f() { T=$(gcloud auth print-access-token); }; f; echo $T",
            "select t in $(gcloud auth print-access-token); do echo $t; done",
            "set -- $(gcloud auth print-access-token); echo \"$1\"",
            "set -- $(gcloud auth print-access-token); for t; do echo $t; done",
            // A copy, a nameref, a run-time name, and a loop that reprints.
            "T=$(gcloud auth print-access-token); U=\"Bearer $T\"; echo $U",
            "T=$(gcloud auth print-access-token); declare -n R=T; echo $R",
            "declare \"$N=$(gcloud auth print-access-token)\"; echo $OTHER",
            "T=$(gcloud auth print-access-token); echo ${!T}",
            "while true; do echo $T; T=$(gcloud auth print-access-token); done",
            // The value reaching the terminal through another route.
            "T=$(gcloud auth print-access-token); echo \"$(echo $T)\"",
            "T=$(gcloud auth print-access-token); echo $T | head -c 5",
            "T=$(gcloud auth print-access-token); cat <<< \"$T\"",
            "T=$(gcloud auth print-access-token); head <<EOF\n$T\nEOF",
            "T=$(gcloud auth print-access-token); bash -c \"echo $T\"",
            "export T=$(gcloud auth print-access-token); bash -c 'echo $T'",
            "T=$(gcloud auth print-access-token); echo $T >&2",
        ],
    );
}

/// #8676: a variable that holds a credential but is only measured, tested, or
/// handed to a program that does not print it.
#[test]
fn allows_a_carried_variable_that_is_never_printed() {
    check(
        false,
        &[
            "T=$(gcloud auth print-access-token); echo ${#T}",
            "T=$(gcloud auth print-access-token); echo \"len=${#T}\"",
            "T=$(gcloud auth print-access-token); python3 upload.py --token \"$T\"",
            "T=$(gcloud auth print-access-token); curl -sS -H \"Authorization: Bearer $T\" https://example.test/v1",
            "export K=$(security find-generic-password -s fake-svc -w) && printenv HOME",
            "T=$(gcloud auth print-access-token); [ -n \"$T\" ] && echo present",
            "T=$(gcloud auth print-access-token); printenv T > /tmp/fake-out",
            "T=$(gcloud auth print-access-token); set -e; echo done",
            "T=$(gcloud auth print-access-token >/dev/null); echo $T",
            "for t in a b; do echo $t; done; T=$(gcloud auth print-access-token)",
            "T=$(gcloud auth print-access-token); printf '%s' \"$T\" | docker login -u x --password-stdin r.test",
        ],
    );
}

/// No prefix of a credential command panics, and each gets a verdict: a panic
/// would exit the hook 101 and fail open.
#[test]
fn no_prefix_of_a_command_panics() {
    let commands = [
        "gh pr create --body \"$(cat <<'EOF'\nsecurity find-generic-password -s é -w\nEOF\n)\" 3>&1 1>&3- 2>& 1",
        "bash -c \"echo $(gcloud auth print-access-token)\" | xargs -I{} sh -c '{}' <<< `x` >(cat) <(y)",
        "(set -o xtrace; eval \"$(security dump-keychain -d)\") <<-\\EOF\n\tbody ünï\n\tEOF\n",
        // Round 3: comments, `${…}`, backticks and ANSI-C quotes around heredocs.
        "true # <<'X' é\n`echo # c` ${X:-<<'E'} $'it\\'s' 1<&2 1<>/dev/tty >&$fd | tee /dev/fd/3 >(cat)\ncat <<E # d\n# b ü\nE\n",
    ];
    for command in commands {
        for (end, _) in command.char_indices().chain([(command.len(), ' ')]) {
            let prefix = &command[..end];
            let outcome = std::panic::catch_unwind(|| scan_for_test(prefix));
            assert!(outcome.is_ok(), "panicked on {prefix:?}");
        }
    }
}

/// The scan without the entry point's panic guard, so a panic is visible.
fn scan_for_test(command: &str) -> bool {
    super::scan(
        command,
        super::Sink::Terminal,
        super::Sink::Terminal,
        0,
        &super::Lifted::default(),
    )
    .is_ok()
}

/// Fail-closed: a credential command the scanner cannot read is refused, and
/// the reason names the guard's blindness rather than a leak.
#[test]
fn denies_what_it_cannot_read() {
    let rows = [
        "gcloud auth print-access-token 'unterminated",
        "echo $(gcloud auth print-access-token",
        "echo `security find-generic-password -s fake-svc -w",
        "gcloud auth print-access-token >",
    ];
    for command in rows {
        let reason = evaluate_credential_print_command(command);
        assert!(
            reason.as_deref().is_some_and(|r| r.contains("cannot read")),
            "{command:?} -> {reason:?}"
        );
    }
    let deep = format!(
        "X={}gcloud auth print-access-token{}",
        "$(".repeat(12),
        ")".repeat(12)
    );
    assert!(evaluate_credential_print_command(&deep).is_some());
}

/// #8676 round 2, row 1: inline code reads an exported name with no `$`.
/// One row per `EVALUATORS` entry, plus a here-document and a pipe.
#[test]
fn denies_inline_code_reading_a_tainted_name() {
    check(
        true,
        &[
            "export T=$(gcloud auth print-access-token); eval 'printenv T'",
            "export T=$(gcloud auth print-access-token); source /dev/stdin <<< 'printenv T'",
            "export T=$(gcloud auth print-access-token); . /dev/stdin <<< 'printenv T'",
            "export T=$(gcloud auth print-access-token); osascript -e 'system attribute \"T\"'",
            "export T=$(gcloud auth print-access-token); ssh fake-host printenv T",
            "export T=$(gcloud auth print-access-token); python -c 'import os; print(os.environ[\"T\"])'",
            "export T=$(gcloud auth print-access-token); python3 -c 'import os; print(os.environ[\"T\"])'",
            "export T=$(gcloud auth print-access-token); perl -le 'print for values %ENV'",
            "export T=$(gcloud auth print-access-token); ruby -e 'puts ENV[\"T\"]'",
            "export T=$(gcloud auth print-access-token); node -e 'console.log(process.env.T)'",
            "export T=$(gcloud auth print-access-token); deno eval 'console.log(Deno.env.get(\"T\"))'",
            "export T=$(gcloud auth print-access-token); php -r 'echo getenv(\"T\");'",
            "export T=$(gcloud auth print-access-token); fish -c 'printenv T'",
            "export T=$(gcloud auth print-access-token); python3 <<'PY'\nimport os; print(os.environ['T'])\nPY",
            "export T=$(gcloud auth print-access-token); echo 'import os; print(os.environ[\"T\"])' | python3",
        ],
    );
}

/// #8676 round 2, row 2: zsh expansion flags and prefixes, and a nested `${…}`.
#[test]
fn denies_zsh_expansion_forms() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); N=T; echo ${(P)N}",
            "T=$(gcloud auth print-access-token); echo ${(U)T}",
            "T=$(gcloud auth print-access-token); echo \"${(U)T}\"",
            "T=$(gcloud auth print-access-token); echo ${^T}",
            "T=$(gcloud auth print-access-token); echo ${=T}",
            "T=$(gcloud auth print-access-token); echo ${~T}",
            "T=$(gcloud auth print-access-token); echo $=T",
            "T=$(gcloud auth print-access-token); echo $~T",
            "T=$(gcloud auth print-access-token); echo $^T",
            "T=$(gcloud auth print-access-token); echo ${${T}:0:5}",
        ],
    );
}

/// #8676 round 2, row 3: a compound array assignment copies the value.
#[test]
fn denies_array_assignment_copies() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); A=(x \"$T\"); echo ${A[1]}",
            "T=$(gcloud auth print-access-token); A+=(\"$T\"); echo ${A[@]}",
            "declare -a A=($(gcloud auth print-access-token)); echo ${A[0]}",
            "T=$(gcloud auth print-access-token); local -A M=([k]=\"$T\"); echo ${M[k]}",
        ],
    );
}

/// #8676 round 2, row 4: a word nested ~100k `${` deep. Unbounded, the
/// recursion overflows the stack, which aborts past `catch_unwind`.
#[test]
fn deep_brace_nesting_denies_without_overflow() {
    let depth = 100_000;
    let command = format!(
        "T=$(gcloud auth print-access-token); echo {}T{}",
        "${a".repeat(depth),
        "}".repeat(depth)
    );
    let started = std::time::Instant::now();
    let verdict = evaluate_credential_print_command(&command);
    let spent = started.elapsed();
    assert!(verdict.is_some(), "must deny");
    // #8676 round 4: bounded in time as well as in stack depth.
    // #8765: 5 s, not 1 s. The limit guards overflow and unbounded work, not a
    // constant factor; 1 s was a CI flake risk under #8734's 2x slowdown.
    assert!(spent < std::time::Duration::from_secs(5), "took {spent:?}");
}

/// #8676 round 2, row 5: a scan whose fixed point would take exponential work
/// refuses inside its budget. Eight substitution levels, each with an
/// eight-name copy chain seeded by a credential call; the reversed chain needs
/// one pass per name at every level. #8765: the 5 s limit guards unbounded
/// work, not a constant factor.
#[test]
fn scan_work_is_bounded() {
    let seed = "A=$(gcloud auth print-access-token)";
    let forward = format!("{seed}; B=$A; C=$B; D=$C; E=$D; F=$E; G=$F; H=$G");
    let reversed = format!("H=$G; G=$F; F=$E; E=$D; D=$C; C=$B; B=$A; {seed}");
    for chain in [forward, reversed] {
        let mut text = chain.clone();
        for _ in 0..7 {
            text = format!("{chain}; X=$({text}); echo $H");
        }
        let started = std::time::Instant::now();
        let verdict = evaluate_credential_print_command(&text);
        let spent = started.elapsed();
        assert!(verdict.is_some(), "must deny: {text}");
        // #8765: 5 s, not 1 s; 1 s was a CI flake risk under #8734's 2x slowdown.
        assert!(spent < std::time::Duration::from_secs(5), "took {spent:?}");
    }
}

/// #8676 round 2, row 6: an arithmetic context reads a bare name, and its
/// error message echoes a non-numeric value.
#[test]
fn denies_arithmetic_reads() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); echo $((T))",
            "T=$(gcloud auth print-access-token); X=$((T + 1))",
            "T=$(gcloud auth print-access-token); (( T > 0 ))",
            "T=$(gcloud auth print-access-token); let X=T+1",
            "T=$(gcloud auth print-access-token); [[ T -eq 0 ]]",
            "T=$(gcloud auth print-access-token); [ \"$T\" -gt 0 ]",
            "T=$(gcloud auth print-access-token); echo ${A[T]}",
            "T=$(gcloud auth print-access-token); A[T]=1",
        ],
    );
}

/// #8676 round 2, row 7: `=~` copies the match into the match arrays.
#[test]
fn denies_a_regex_match_copy() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); [[ $T =~ (.*) ]]; echo ${BASH_REMATCH[1]}",
            "T=$(gcloud auth print-access-token); [[ $T =~ (.*) ]] && echo $match",
            "T=$(gcloud auth print-access-token); [[ $T =~ .* ]] && echo $MATCH",
        ],
    );
}

/// #8676 round 2, row 8: a function header before a loop or a printer.
#[test]
fn denies_after_a_function_header() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); f() { echo $T; }; f",
            "T=$(gcloud auth print-access-token); function f { echo $T; }; f",
            "f() { for t in $(gcloud auth print-access-token); do echo $t; done; }; f",
            "function f() { set; }; T=$(gcloud auth print-access-token); f",
        ],
    );
}

/// #8676 round 2, row 9: environment readers that name no `$`.
#[test]
fn denies_environment_readers() {
    check(
        true,
        &[
            "export T=$(gcloud auth print-access-token); awk 'BEGIN { print ENVIRON[\"T\"] }'",
            "export T=$(gcloud auth print-access-token); jq -n env.T",
            "export T=$(gcloud auth print-access-token); jq -n '$ENV.T'",
            "export T=$(gcloud auth print-access-token); ps eww",
            "export T=$(gcloud auth print-access-token); ps -E",
            "export T=$(gcloud auth print-access-token); cat /proc/self/environ",
            "export T=$(gcloud auth print-access-token); strings /proc/$$/environ",
        ],
    );
}

/// #8676 round 2, row 10: zsh prints a name a flagless declaration names.
#[test]
fn denies_a_flagless_declaration_of_a_tainted_name() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); typeset T",
            "T=$(gcloud auth print-access-token); local T",
            "T=$(gcloud auth print-access-token); declare T",
        ],
    );
}

/// #8676 round 2: the neighbours of every row above still pass.
#[test]
fn allows_the_round_two_neighbours() {
    check(
        false,
        &[
            "T=$(gcloud auth print-access-token); python3 upload.py --token \"$T\"",
            "T=$(gcloud auth print-access-token); echo $((1 + 2))",
            "T=$(gcloud auth print-access-token); echo $(( ${#T} + 1 ))",
            "T=$(gcloud auth print-access-token); A=(x y); echo ${A[0]}",
            "T=$(gcloud auth print-access-token); f() { echo hi; }; f",
            "T=$(gcloud auth print-access-token); ps -o pid",
            "T=$(gcloud auth print-access-token); declare -x U=1",
            "T=$(gcloud auth print-access-token); [[ $T =~ ^ya29 ]] && echo ok",
            "T=$(gcloud auth print-access-token); jq -n '.x'",
            "python3 -c 'print(1)'; gcloud auth print-access-token > /tmp/fake-token",
            "T=$(gcloud auth print-access-token); echo ${#T}",
        ],
    );
}

/// A command that names no trigger is never parsed, broken quoting included.
#[test]
fn ignores_commands_that_name_no_credential_cli() {
    check(
        false,
        &[
            "echo 'unterminated",
            "security list-keychains",
            "gcloud config list",
        ],
    );
}

/// #8676 round 3, HIGH 1: brace expansion builds a declared name. Each row was
/// allowed at 90e0813e1.
#[test]
fn denies_brace_expanded_declarer_names() {
    check(
        true,
        &[
            "export {T,U}=$(gcloud auth print-access-token); printenv T",
            "declare {T,U}=$(gcloud auth print-access-token); echo $T",
            "typeset {T,U}=`gcloud auth print-access-token`; echo $U",
            "local T{,}=$(gcloud auth print-access-token); echo $T",
            "export T{,}=$(gcloud auth print-access-token); printenv T",
        ],
    );
}

/// #8676 round 3, HIGH 2: an evaluator reads its script from stdin or a
/// process substitution by path. Each row was allowed at 90e0813e1.
#[test]
fn denies_an_evaluator_reading_its_script_by_path() {
    check(
        true,
        &[
            "export T=$(gcloud auth print-access-token); echo 'printenv T' | bash /dev/stdin",
            "export T=$(gcloud auth print-access-token); echo 'printenv T' | sh /dev/fd/0",
            "export T=$(gcloud auth print-access-token); echo 'printenv T' | bash /proc/self/fd/0",
            "export T=$(gcloud auth print-access-token); bash <(echo 'printenv T')",
            "export T=$(gcloud auth print-access-token); python3 <(echo 'import os;print(os.getenv(\"T\"))')",
            "export T=$(gcloud auth print-access-token); bash < <(echo 'printenv T')",
        ],
    );
}

/// #8676 round 3, HIGH 3: arithmetic contexts bash evaluates, whose error
/// message echoes a non-numeric value. Each row was allowed at 90e0813e1.
#[test]
fn denies_arithmetic_reads_in_offsets_and_integer_declarations() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); declare -i X=T",
            "T=$(gcloud auth print-access-token); local -i X=T",
            "T=$(gcloud auth print-access-token); typeset -i X=T",
            "T=$(gcloud auth print-access-token); echo ${X:T}",
            "T=$(gcloud auth print-access-token); echo ${X:0:T}",
            "T=$(gcloud auth print-access-token); echo $[T]",
            // A name holding the bare name is evaluated recursively.
            "T=$(gcloud auth print-access-token); U=T; echo $((U))",
            "T=$(gcloud auth print-access-token); declare -i X; X=T",
        ],
    );
}

/// #8676 round 3, HIGH 4: a nameref reaches the value through a loop, a
/// subscript, or a later assignment. Each row was allowed at 90e0813e1.
#[test]
fn denies_nameref_loops_and_subscripted_namerefs() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); declare -n R; for R in T; do echo $R; done",
            "T=$(gcloud auth print-access-token); A=$T; declare -n R='A[0]'; echo $R",
            "T=$(gcloud auth print-access-token); declare -n R; R=T; echo $R",
        ],
    );
}

/// #8676 round 3, MEDIUM 5: evaluators the list missed. Each row was allowed
/// at 90e0813e1.
#[test]
fn denies_the_missing_evaluators() {
    check(
        true,
        &[
            "export T=$(gcloud auth print-access-token); trap 'echo $T' EXIT",
            "trap \"echo $(gcloud auth print-access-token)\" EXIT",
            "export T=$(gcloud auth print-access-token); python3.12 -c 'import os; print(os.getenv(\"T\"))'",
            "export T=$(gcloud auth print-access-token); /usr/local/bin/python3.11 -c 'import os; print(os.getenv(\"T\"))'",
            "export T=$(gcloud auth print-access-token); bun -e 'console.log(process.env.T)'",
            "export T=$(gcloud auth print-access-token); lua -e 'print(os.getenv(\"T\"))'",
            "export T=$(gcloud auth print-access-token); pwsh -c '$env:T'",
        ],
    );
}

/// #8676 round 3, MEDIUM 6: builtins whose output or error text echoes the
/// operand. Each row was allowed at 90e0813e1.
#[test]
fn denies_builtins_that_echo_their_operand() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); cd \"$T\"",
            "T=$(gcloud auth print-access-token); exit \"$T\"",
            "T=$(gcloud auth print-access-token); kill \"$T\"",
            "T=$(gcloud auth print-access-token); sleep \"$T\"",
            "T=$(gcloud auth print-access-token); compgen -W \"$T\"",
            "T=$(gcloud auth print-access-token); export \"$T\"",
            "T=$(gcloud auth print-access-token); unset \"$T\"",
        ],
    );
}

/// #8676 round 3: the neighbours of every row above still pass.
#[test]
fn allows_the_round_three_neighbours() {
    check(
        false,
        &[
            "export {A,B}=1; gcloud auth print-access-token > /tmp/fake-token",
            "export T=$(gcloud auth print-access-token); bash deploy.sh",
            "export T=$(gcloud auth print-access-token); python3.12 upload.py",
            "T=$(gcloud auth print-access-token); echo ${X:-T} ${X:0:2}",
            "T=$(gcloud auth print-access-token); declare -i N=5",
            "T=$(gcloud auth print-access-token); declare -n R=HOME; echo $R",
            "T=$(gcloud auth print-access-token); for f in a b; do echo $f; done",
            "T=$(gcloud auth print-access-token); cd /tmp && sleep 1; echo ${#T}",
            "T=$(gcloud auth print-access-token); cd /tmp && curl -H \"Authorization: Bearer $T\" https://example.test",
        ],
    );
}

/// #8676 round 4, HIGH 1: a brace *sequence* builds the declared names. Each
/// row was allowed at 6aa69afab.
#[test]
fn denies_brace_sequence_declarer_names() {
    check(
        true,
        &[
            "declare {A..C}=$(gcloud auth print-access-token); echo $B",
            "export {A..C}=$(gcloud auth print-access-token); printenv B",
            "local T{1..2}=$(gcloud auth print-access-token); echo $T1",
            "T=$(gcloud auth print-access-token); typeset {X..Z}=$T; echo $Y",
        ],
    );
}

/// #8676 round 4, HIGH 2: an indexed array's `[key]=` in a compound
/// assignment is arithmetic, whose error echoes a non-numeric value. Each row
/// was allowed at 6aa69afab.
#[test]
fn denies_array_keys_read_as_arithmetic() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); A=([T]=1)",
            "T=$(gcloud auth print-access-token); A=(x [T]=1)",
            "T=$(gcloud auth print-access-token); A+=([$T]=1)",
            "T=$(gcloud auth print-access-token); declare -a A=([T+1]=x)",
        ],
    );
}

/// #8676 round 4, HIGH 3: a coproc runs its command with its output on a
/// descriptor a later stage reads. Each row was allowed at 6aa69afab.
#[test]
fn denies_a_coproc_that_carries() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); coproc printf %s \"$T\"",
            "T=$(gcloud auth print-access-token); coproc NAME { echo \"$T\"; }",
            "T=$(gcloud auth print-access-token); coproc NAME ( echo \"$T\" )",
            "T=$(gcloud auth print-access-token); coproc { printf %s \"$T\"; }",
            "T=$(gcloud auth print-access-token); coproc NAME for x in $T; do echo $x; done",
        ],
    );
}

/// #8676 round 4: the neighbours of every row above still pass. #8676 round
/// 5: a coproc row moved to `denies_the_round_five_bypasses` — the round-5
/// fix refuses every coproc stage while any name is tainted, including one
/// that (like this one did) never itself reads the name.
#[test]
fn allows_the_round_four_neighbours() {
    check(
        false,
        &[
            "declare {A..C}=1; gcloud auth print-access-token > /tmp/fake-token",
            "T=$(gcloud auth print-access-token); A=([0]=x [1]=y); echo ${A[1]}",
            "coproc cat /etc/hosts; gcloud auth print-access-token > /tmp/fake-token",
            "T=$(gcloud auth print-access-token); curl --oauth2-bearer=$T https://example.test",
        ],
    );
}

/// #8676 round 4 review, round 5 fix: four HIGH shapes the round-4 coproc
/// check and the rest of the scan missed. Each row was allowed at 8cd9ba4e1.
#[test]
fn denies_the_round_five_bypasses() {
    check(
        true,
        &[
            // 1: `ungroup` leaves a coproc's NAME as the program word, so a
            // declarer, `set`, or an evaluator inside never gets judged;
            // round 4's fix only caught a word that itself carried the
            // value. Refusing every coproc while tainted closes it,
            // including the benign neighbour that never reads the name.
            "T=$(gcloud auth print-access-token); coproc X ( declare -p T )",
            "T=$(gcloud auth print-access-token); coproc X ( set )",
            "T=$(gcloud auth print-access-token); coproc X ( eval 'echo $T' )",
            "T=$(gcloud auth print-access-token); coproc NAME { sleep 1; }",
            // 2: `select NAME in WORD...` lists every WORD on stderr.
            "T=$(gcloud auth print-access-token); select x in \"$T\"; do break; done",
            // 3: `${NAME?word}`/`${NAME:?word}` writes a carrying `word` to
            // stderr at expansion time, even in a stage that is only an
            // assignment.
            "T=$(gcloud auth print-access-token); : \"${UNSET:?$T}\"",
            "T=$(gcloud auth print-access-token); Y=${UNSET?$T}",
            // 4: a plain input redirect's missing-file error names the path.
            "T=$(gcloud auth print-access-token); wc -c < \"$T\"",
            "T=$(gcloud auth print-access-token); : < \"$T\"",
        ],
    );
}

/// #8676 round 5: the neighbours of every row above still pass.
#[test]
fn allows_the_round_five_neighbours() {
    check(
        false,
        &[
            "coproc X ( declare -p PATH ); gcloud auth print-access-token > /tmp/fake-token",
            "T=$(gcloud auth print-access-token); select x in a b c; do break; done",
            "T=$(gcloud auth print-access-token); : \"${SAFE:?fallback}\"",
            "T=$(gcloud auth print-access-token); wc -c < /tmp/fake-token-file",
        ],
    );
}

/// #8676 round 6, code-critic CRITICAL on round 5: a plain input redirect's
/// missing-file error names its target the same way round 5's bare `$T`
/// does, but a command-substitution or backtick target has no `$NAME` for
/// `expands_tainted` to match — the placeholder `lift_substitutions` leaves
/// behind carries no `$`. Each row was allowed at c3778fa0b.
#[test]
fn denies_the_round_six_bypasses() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); wc -c < \"$(echo \"$T\")\"",
            "T=$(gcloud auth print-access-token); : < \"$(echo \"$T\")\"",
            "T=$(gcloud auth print-access-token); wc -c < \"`echo $T`\"",
        ],
    );
}

/// #8676 round 6: a `<(…)` target is a real descriptor bash always opens —
/// never a missing-file error — so this sink must not flag it.
#[test]
fn allows_the_round_six_neighbours() {
    check(
        false,
        &["T=$(gcloud auth print-access-token); wc -c < <(echo \"$T\")"],
    );
}

/// Work units one [`super::scan`] of `command` spends, and whether it refuses.
fn scan_units(command: &str) -> (usize, bool) {
    let lifted = super::Lifted::default();
    let sink = super::Sink::Terminal;
    let refused = super::scan(command, sink, sink, 0, &lifted).is_err();
    (lifted.spent.get(), refused)
}

/// Units a scan charges: `passes` top-level passes, each one unit, one per KiB
/// of text, and one per single-pass `$(…)` body it lifts.
fn pinned_units(passes: usize, subs: usize, kib: usize) -> usize {
    passes * (1 + subs + kib)
}

/// #8676 round 3: wide bracket runs scan in linear work; a nest deeper than
/// the cap refuses.
///
/// Why: a scan from each opener to its close took minutes on the round-two
/// nesting row. #8765: the timed form failed CI at 1.00-1.17 s once #8734's
/// fixed point added a second pass, so this counts the scan's own work units.
/// What: at n, 2n and 4n KiB of run, pins the exact units, which fixes the
/// pass count (1: #8771 rescans only when a pass judged text against an older
/// name set, and nothing here precedes the `T=` binding), the charge per KiB
/// and linear growth; then pins that a 2 MiB bound row fits one pass's budget.
/// The work-unit pins are the primary assertion. #8765: one wall-clock backstop runs first, on the
/// timed form's own input (100k `${X:0:1}` runs, bound), and exists only to
/// catch superlinear work the budget never charges; #8771 tracks the proper
/// close, a `#[cfg(test)]` byte counter. Worst CI time today is 1.17 s, and
/// the 5 s budget is about 4x that.
#[test]
fn wide_bracket_runs_scan_in_linear_work() {
    let bound = "T=$(gcloud auth print-access-token); echo ";
    // #8765: wall-clock backstop for uncharged superlinear work; see #8771.
    let command = format!("{bound}{}", "${X:0:1}".repeat(100_000));
    let started = std::time::Instant::now();
    let verdict = evaluate_credential_print_command(&command);
    let spent = started.elapsed();
    assert!(verdict.is_none(), "100k `${{X:0:1}}` runs must be allowed");
    assert!(spent < std::time::Duration::from_secs(5), "took {spent:?}");
    // #8765: the seeds stay under 1 KiB and every run body is whole KiB, so
    // the charge per pass is exact. 4n stays under `WORK_BUDGET`.
    const KIB: usize = 1_024;
    const N_KIB: usize = 128;
    let unbound = "gcloud auth print-access-token >/dev/null; echo ";
    let body = |run: &str, kib: usize| run.repeat(kib * KIB / run.len());
    // #8771: every row takes one pass; the binding is the first stage.
    for (run, deny, passes) in [
        ("A[", true, 1),
        ("$[", true, 1),
        ("${X:", true, 1),
        ("A[x]", false, 1),
        ("${X:0:1}", false, 1),
    ] {
        let mut units = Vec::new();
        for kib in [N_KIB, 2 * N_KIB, 4 * N_KIB] {
            let text = body(run, kib);
            assert_eq!(text.len(), kib * KIB, "{run:?}");
            let (got, refused) = scan_units(&format!("{bound}{text}"));
            assert_eq!(refused, deny, "{run:?} at {kib} KiB");
            // A third pass, or a costlier byte, changes this count.
            let want = pinned_units(passes, 1, kib);
            assert_eq!(got, want, "{run:?} at {kib} KiB, bound: {passes} pass(es)");
            units.push(got);
            let (got, refused) = scan_units(&format!("{unbound}{text}"));
            assert!(!refused, "{run:?} at {kib} KiB, unbound");
            let want = pinned_units(1, 0, kib);
            assert_eq!(got, want, "{run:?} at {kib} KiB, unbound: pinned 1 pass");
        }
        // Linear: doubling the run doubles the units it adds.
        let (n, n2, n4) = (units[0], units[1], units[2]);
        assert_eq!(n4 - n2, 2 * (n2 - n), "{run:?}: {units:?} not linear");
    }
    // #8771: at 2 MiB one pass fits the budget, bound or not; before the fix
    // the bound form charged a second pass and refused here.
    let text = body("${X:0:1}", 2 * KIB);
    let (got, refused) = scan_units(&format!("{bound}{text}"));
    assert!(!refused, "2 MiB bound fits one pass");
    assert_eq!(got, pinned_units(1, 1, 2 * KIB), "2 MiB bound");
    assert!(pinned_units(1, 1, 2 * KIB) <= super::WORK_BUDGET);
    let (got, refused) = scan_units(&format!("{unbound}{text}"));
    assert!(!refused, "2 MiB unbound fits in one pass");
    assert_eq!(got, pinned_units(1, 0, 2 * KIB), "2 MiB unbound");
}

/// 🔴 REGRESSION (#8771): a command that binds a credential is refused at the
/// size one pass's budget allows, as it was before #8734's rescan; past it,
/// it still refuses (fail closed). Before the fix the binding charged a
/// second whole pass, so the bound form refused at about half the size.
#[test]
fn a_bound_command_keeps_the_one_pass_threshold_8771() {
    const KIB: usize = 1_024;
    let bound = "T=$(gcloud auth print-access-token); echo ";
    let unbound = "gcloud auth print-access-token >/dev/null; echo ";
    let run = |kib: usize| "a ".repeat(kib * KIB / 2);
    // One pass costs 1 + KiB units, the lifted `$(…)` one more; the budget
    // is `WORK_BUDGET` units per pass.
    let fits = super::WORK_BUDGET - 2;
    let (got, refused) = scan_units(&format!("{bound}{}", run(fits)));
    assert!(!refused, "bound at {fits} KiB fits one pass");
    assert_eq!(
        got,
        pinned_units(1, 1, fits),
        "bound at {fits} KiB: one pass"
    );
    let (got, refused) = scan_units(&format!("{bound}{}", run(fits + 1)));
    assert!(refused, "bound past one pass's budget refuses");
    assert_eq!(got, pinned_units(1, 1, fits + 1));
    let (_, refused) = scan_units(&format!("{unbound}{}", run(fits + 1)));
    assert!(!refused, "unbound at {} KiB fits", fits + 1);
    let (_, refused) = scan_units(&format!("{unbound}{}", run(fits + 2)));
    assert!(refused, "unbound past the budget refuses");
}

/// 🔴 REGRESSION (#8771): text the shell runs after a binding but the scan
/// judged before it — a loop body, a function, a later substitution, the
/// binding's own command — still gets the rescan, and each pass carries its
/// own budget, so a large looped binding no longer refuses at half the size.
/// A chain needing more than `MAX_PASSES` refuses with bounded work.
#[test]
fn a_late_binding_still_rescans_8771() {
    check(
        true,
        &[
            "while :; do echo \"$T\"; T=$(gcloud auth print-access-token); done",
            "f(){ echo \"$T\"; }; T=$(gcloud auth print-access-token); f",
            "T=$(gcloud auth print-access-token); echo \"$(echo $T)\"",
            "T=$(gcloud auth print-access-token) printenv T",
        ],
    );
    const KIB: usize = 1_024;
    let looped = |kib: usize| {
        format!(
            "while :; do echo {}; T=$(gcloud auth print-access-token); done",
            "a ".repeat(kib * KIB / 2)
        )
    };
    let (got, refused) = scan_units(&looped(2 * KIB));
    assert!(!refused, "a 2 MiB loop fits a budget per pass");
    assert_eq!(got, pinned_units(2, 1, 2 * KIB), "two passes, each charged");
    let chain = "while :; do G=$F; F=$E; E=$D; D=$C; C=$B; B=$A; \
                 A=$(gcloud auth print-access-token); done";
    let (got, refused) = scan_units(chain);
    assert!(refused, "a chain past MAX_PASSES refuses");
    assert!(
        got <= super::credential_print_passes::MAX_PASSES * 2,
        "{got} units"
    );
}

/// #8771: the arithmetic readers touch each byte a bounded number of times —
/// at most `MAX_NEST` (32) per byte — so no rescan or reader is quadratic.
/// Counted, not timed.
#[test]
fn arithmetic_reading_stays_linear_8771() {
    use super::credential_print_taint_forms::ARITH_BYTES;
    for run in ["${X:0:1}", "A[x]", "$((x))"] {
        let command = format!(
            "T=$(gcloud auth print-access-token); echo {}",
            run.repeat(100_000)
        );
        ARITH_BYTES.with(|c| c.set(0));
        assert_eq!(evaluate_credential_print_command(&command), None, "{run}");
        let read = ARITH_BYTES.with(std::cell::Cell::get);
        assert!(read <= 32 * command.len(), "{run}: {read} bytes read");
    }
}

/// #8676 round 3: the deny reason never quotes the command, so a credential
/// literal pasted into it is not echoed back.
#[test]
fn deny_reason_never_echoes_the_command() {
    let command = "T=$(gcloud auth print-access-token); cd \"$T\" # ya29.fake-literal";
    let reason = evaluate_credential_print_command(command).unwrap_or_default();
    assert!(!reason.is_empty(), "must deny");
    assert!(!reason.contains("ya29.fake-literal"), "{reason}");
    assert!(!reason.contains("cd \""), "{reason}");
}

/// 🔴 REGRESSION (#8879, owner ruling 263): the refusal stops the action and
/// sends it to the Architect; it no longer suggests consuming the value inside
/// another command or keeping it in a file.
#[test]
fn the_refusal_says_stop_and_report_to_the_architect_8879() {
    let reason = evaluate_credential_print_command("security find-generic-password -s fake-svc -w")
        .unwrap_or_default();
    assert!(
        reason.contains("Stop and report this refusal to the Architect"),
        "{reason}"
    );
    assert!(
        reason.contains("the guard reads the body of a script a command runs"),
        "{reason}"
    );
    assert!(
        reason.contains("refuses a script whose body it cannot judge"),
        "{reason}"
    );
    for stale in ["consume a value", "umask 077", "password-stdin"] {
        assert!(!reason.contains(stale), "`{stale}` must be gone: {reason}");
    }
}

/// 🔴 REGRESSION (#8677): `security -i` (or `-p`, which implies it) runs the
/// commands its stdin carries. Each row was allowed at 27ec6fa20.
#[test]
fn denies_security_reading_commands_on_stdin_8677() {
    check(
        true,
        &[
            // The issue's reproduction.
            "echo 'find-generic-password -s s -w' | security -i",
            "printf 'find-generic-password -s fake-svc -w\\n' | security -i",
            "security -i <<< 'find-generic-password -s fake-svc -w'",
            "security -i <<'EOF'\nfind-generic-password -s fake-svc -w\nEOF",
            "echo 'dump-keychain -d' | /usr/bin/security -vi",
            "echo 'find-generic-password -s fake-svc -w' | security -q -p 'kc> '",
            "echo 'find-generic-password -s fake-svc -w' | sudo -u fake security -i",
            "echo 'find-generic-password -s fake-svc -w' | timeout 5 security -i",
            "echo 'find-generic-password -s fake-svc -w' | bash -c 'security -i'",
            // No credential subcommand is spelled out, so only `-i` shows it.
            "printf 'find-%s-password -s fake-svc -w\\n' generic | security -i",
            "security -i < fake-cmds.txt",
        ],
    );
}

/// #8677 error arm: a `security -i` whose input the guard cannot read — a
/// run-time file, broken quoting — refuses as unreadable, never allows.
#[test]
fn refuses_an_unclassifiable_interactive_security_8677() {
    for command in [
        "security -i < \"$FAKE_CMDS\"",
        "security -i <<< 'find-generic-password -s fake-svc -w",
        "security -p \"$PROMPT\" <&3",
    ] {
        let reason = evaluate_credential_print_command(command).unwrap_or_default();
        assert!(
            reason.contains("cannot read"),
            "{command:?} must refuse as unreadable: {reason:?}"
        );
    }
}

/// 🔴 REGRESSION (#8677): `curl -v` (and `--trace*`/`--libcurl`) echoes the
/// request headers, so a credential in any argument reaches tool output. Each
/// row was allowed at 27ec6fa20.
#[test]
fn denies_a_verbose_curl_carrying_a_credential_8677() {
    check(
        true,
        &[
            // The issue's reproduction.
            "curl -H \"Authorization: Bearer $(gcloud auth print-access-token)\" -v",
            "curl -v -H \"Authorization: Bearer $(gcloud auth print-access-token)\" https://example.test",
            "curl --verbose -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl -sSv -o /dev/null -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl -vsH \"x: $(gcloud auth print-access-token)\" https://example.test 2>&1 | head",
            "curl -v -u \"fake:$(security find-generic-password -s fake-svc -w)\" https://example.test",
            "T=$(gcloud auth print-access-token); curl -v -H \"Authorization: Bearer $T\" https://example.test",
            "timeout 5 curl -v -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl --trace-ascii - -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl --trace % -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl --trace /dev/tty -H \"x: $(gcloud auth print-access-token)\" https://example.test >/dev/null 2>&1",
            "curl --libcurl - -H \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl -v --stderr - -H \"x: $(gcloud auth print-access-token)\" https://example.test 2>/dev/null",
        ],
    );
}

/// 🔴 REGRESSION (#8677): a credential written to a redirect target the guard
/// cannot read (`> "$OUT"`), or to a device spelled with extra `/`, `.` or
/// `..` segments. Each row was allowed at 27ec6fa20.
#[test]
fn denies_a_credential_redirected_to_an_unread_target_8677() {
    check(
        true,
        &[
            // The issue's reproductions.
            "security find-generic-password -s fake-svc -w > \"$OUT\"",
            "security find-generic-password -s fake-svc -w > /dev//stdout",
            "security find-generic-password -s fake-svc -w > /dev/./tty",
            "gcloud auth print-access-token > $OUT",
            "gcloud auth print-access-token > \"$HOME/.gcloud-token\"",
            "gcloud auth print-access-token >> \"${OUT}/token\"",
            "gcloud auth print-access-token > `echo /dev/tty`",
            "security find-generic-password -g -s fake-svc 2> \"$ERR\"",
            // A `$(mktemp)` name rebound, or a body that is not a lone mktemp.
            "tmp=$(mktemp); tmp=/dev/tty; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); read tmp < fake-list; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); for tmp in /dev/tty; do gcloud auth print-access-token > \"$tmp\"; done",
            "tmp=$(mktemp; echo /dev/tty); gcloud auth print-access-token > \"$tmp\"",
            "gcloud auth print-access-token > /dev/../dev/tty",
            "gcloud auth print-access-token > //dev/stderr",
            "gcloud auth print-access-token >/dev//fd//1",
            "gcloud auth print-access-token > ../../../../../../dev/tty",
            "gcloud auth print-access-token > /dev/ttys001",
            "gcloud auth print-access-token > /dev/pts/0",
            "gcloud auth print-access-token > /dev/tt?",
            "gcloud auth print-access-token > /dev/stdin",
            "gcloud auth print-access-token > /proc/self/fd/2",
            "gcloud auth print-access-token 1<>/dev//tty",
            "gcloud auth print-access-token | tee /dev//tty >/dev/null",
            // A missing directory's error names the carrying target.
            "T=$(gcloud auth print-access-token); echo x > \"/nonexistent/$T\"",
            // A wrapped call's stderr piped on to a printing reader.
            "sh -c 'security find-generic-password -g -s fake-svc' 2>&1 | cat",
            "sh -c 'security find-generic-password -g -s fake-svc' 2>\"$ERR\"",
        ],
    );
}

/// 🔴 REGRESSION (#8677): the sibling secret-printing CLIs the issue lists.
/// Each row was allowed at 27ec6fa20.
#[test]
fn denies_the_sibling_credential_clis_8677() {
    check(
        true,
        &[
            "gcloud secrets versions access latest --secret=fake-secret",
            "gcloud secrets versions access 1 --secret fake-secret | head -c 10",
            "gcloud secrets versions access latest --secret=fake --out-file=/dev/stdout",
            "gh auth token",
            "gh auth token --hostname github.example.test",
            "/opt/homebrew/bin/gh auth status --show-token",
            "gh auth status -t",
            "op read op://fake-vault/fake-item/password",
            "op read --out-file /dev/stdout op://fake-vault/fake-item/password",
            "aws configure get aws_secret_access_key",
            "aws configure get aws_session_token --profile fake",
            "aws configure export-credentials --profile fake",
            "echo \"$(gh auth token)\"",
            "T=$(op read op://fake-vault/fake-item/password); echo \"$T\"",
        ],
    );
}

/// #8677: the nearest benign forms of each refused shape stay allowed.
#[test]
fn allows_the_8677_neighbours() {
    check(
        false,
        &[
            // curl with no credential, or a credential with no echo flag.
            "curl -v https://example.test",
            "T=$(gcloud auth print-access-token); curl -v https://example.test >/dev/null",
            "curl -sS -H \"Authorization: Bearer $(gcloud auth print-access-token)\" https://example.test/v1",
            "curl -sSH \"x: $(gcloud auth print-access-token)\" https://example.test",
            "curl -H \"x: $(gcloud auth print-access-token)\" -d -v https://example.test",
            "curl -s -H \"x: $(gcloud auth print-access-token)\" --trace /tmp/fake-trace https://example.test",
            // security with no `-w`/`-g`, no `-i`, or help only.
            "security -h",
            "security -h; security find-generic-password -s fake-svc >/dev/null 2>&1",
            "security -v find-generic-password -s fake-svc >/dev/null 2>&1",
            "security find-generic-password -s fake-svc",
            "security find-generic-password -s fake-svc > \"$OUT\"",
            "grep security -i notes.txt; gcloud auth print-access-token > /tmp/fake-token",
            "echo 'security -i' > notes.md",
            // Ordinary redirects of non-secret output, and plain files.
            "gcloud config list > \"$OUT\" && gcloud auth print-access-token > /tmp/fake-token",
            "echo done > \"$LOG\"; T=$(gcloud auth print-access-token)",
            "printf '%s\\n' 'never run gcloud auth print-access-token bare' > \"$OUT\"",
            "gcloud auth print-access-token > /tmp//fake-token-file",
            "gcloud auth print-access-token > ./dev-token.txt",
            "gcloud auth print-access-token > /dev//null 2>&1",
            // #8730 / #8763: clobber redirects to an ordinary file.
            "security find-generic-password -s x -w >|/tmp/fake-out",
            "security find-generic-password -s x -w >>!/tmp/fake-out",
            // Sibling CLIs that print no secret, or capture it.
            "gh auth status",
            "gh auth token | docker login ghcr.io -u fake --password-stdin",
            "GH_TOKEN=$(gh auth token) gh pr list",
            "aws configure get region",
            "aws configure list",
            "op read --out-file /tmp/fake-out op://fake-vault/fake-item/password",
            "gcloud secrets versions access latest --secret=fake --out-file=/tmp/fake-out",
            "gcloud secrets list",
            "X=$(gcloud secrets versions access latest --secret=fake)",
            "git commit -m 'docs: never run gh auth token or op read bare'",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 1): a non-identifier
/// assignment (`tmp+=`, `tmp[0]=`) rebinds a `$(mktemp)` name. Each row was
/// allowed at d8d2ec909.
#[test]
fn denies_a_temp_name_rebound_by_a_non_identifier_assignment_8677() {
    check(
        true,
        &[
            "tmp=$(mktemp -d); tmp+=/../../../../../../../../dev/stdout; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); tmp[0]=/dev/stdout; gcloud auth print-access-token > \"$tmp\"",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 2): a `$(mktemp)` name
/// rebound through quoting, a function, a computed name, or a symlink planted
/// on its file. Each row was allowed at d8d2ec909.
#[test]
fn denies_a_temp_name_rebound_out_of_sight_8677() {
    check(
        true,
        &[
            "tmp=$(mktemp); declare t\\mp=/dev/stdout; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); read t''mp <<< /dev/stdout; gcloud auth print-access-token > \"$tmp\"",
            "f() { tmp=/dev/stdout; }; tmp=$(mktemp); f; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); trap 't\\mp=/dev/stdout' DEBUG; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); ln -sf /dev/stdout \"$tmp\"; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); mv -f fake-link \"$tmp\"; gcloud auth print-access-token > \"$tmp\"",
            "n=t; tmp=$(mktemp); printf -v \"${n}mp\" %s /dev/stdout; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); read t{m,}p <<< /dev/stdout; gcloud auth print-access-token > \"$tmp\"",
            // Review round 3: an unlisted linker, inline code, a quoted
            // heredoc body, and a nameref to a name built with `+=`.
            "tmp=$(mktemp); gln -sf /dev/stdout \"$tmp\"; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); perl -e 'symlink q:/dev/stdout:, shift' \"$tmp\"; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp /tmp/fake.XXXXXX); sh <<'EOF'\nln -sf /dev/stdout /tmp/fake.*\nEOF\ngcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); declare -n r=t; declare +n r; r+=mp; declare -n r; r=/dev/stdout; gcloud auth print-access-token > \"$tmp\"",
            // Review round 3: no `$(mktemp)` carve-out; a variable target refuses.
            "tmp=$(mktemp); trap 'rm -f \"$tmp\"' EXIT; gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp); gcloud auth print-access-token > \"$tmp\"",
            "tmp=$(mktemp -t fake) && gcloud auth print-access-token > \"${tmp}\" && wc -c \"$tmp\"",
            "tmp=$(mktemp); gcloud auth print-access-token | tee \"$tmp\" >/dev/null",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 3): `security -i` behind a
/// wrapper the guard does not know. Each row was allowed at d8d2ec909.
#[test]
fn denies_interactive_security_behind_an_unknown_wrapper_8677() {
    check(
        true,
        &[
            "echo 'find-generic-password -s s -w' | arch -arm64 security -i",
            "echo 'find-generic-password -s s -w' | script -q /dev/null security -i",
            "echo 'find-generic-password -s s -w' | launchctl asuser 501 security -i",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 4): APFS matches `/DEV` to
/// `/dev`. Each row was allowed at d8d2ec909.
#[test]
fn denies_a_device_path_in_another_case_8677() {
    check(
        true,
        &[
            "gcloud auth print-access-token > /DEV/stdout",
            "gcloud auth print-access-token > /Dev/Tty",
            "gcloud auth print-access-token | tee /DEV/STDERR >/dev/null",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 5): a relative target whose
/// directory the guard cannot know. Each row was allowed at d8d2ec909.
#[test]
fn denies_a_relative_target_in_an_unknown_directory_8677() {
    check(
        true,
        &[
            "cd /dev && gcloud auth print-access-token > stdout",
            "cd /dev; gcloud auth print-access-token > fake-out",
            "pushd /dev/fd && gcloud auth print-access-token > 1",
            "cd /dev && cd /tmp && gcloud auth print-access-token > ~-/stdout",
            "gcloud auth print-access-token > ~+/stdout",
            "gcloud auth print-access-token > stdout",
            "gcloud auth print-access-token > fd/1",
            "gcloud auth print-access-token > tty",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 6): a `tee`/`dd` file operand
/// chosen at run time. Each row was allowed at d8d2ec909.
#[test]
fn denies_a_tee_operand_chosen_at_run_time_8677() {
    check(
        true,
        &[
            "OUT=/dev/stdout; gcloud auth print-access-token | tee \"$OUT\" >/dev/null",
            "gcloud auth print-access-token | tee -a \"$OUT\" >/dev/null",
            "gcloud auth print-access-token | dd of=\"$OUT\" >/dev/null 2>&1",
            "cd /dev; gcloud auth print-access-token | tee stdout >/dev/null",
        ],
    );
}

/// 🔴 REGRESSION (#8677 review round 2, finding 7): a sibling CLI's
/// subcommand chosen at run time. Each row was allowed at d8d2ec909.
#[test]
fn denies_a_cli_subcommand_chosen_at_run_time_8677() {
    check(
        true,
        &[
            "gh auth $(echo token)",
            "gh $(echo auth) token",
            "gh auth `echo token`",
            "op $(echo read) op://fake-vault/fake-item/password",
            "aws configure $(echo get) aws_secret_access_key",
            // Review round 3: a global flag's value is not a subcommand slot.
            "gh -R fake-owner/fake-repo auth $(echo token)",
            // Review round 4: an unquoted expansion inside a flag word splits
            // into the subcommand.
            "gh auth --hostname=$(printf 'github.com token')",
            "T=' token'; gh auth -hgithub.com$T",
        ],
    );
}

/// #8677 review round 2: the nearest benign forms stay allowed.
#[test]
fn allows_the_8677_round_two_neighbours() {
    check(
        false,
        &[
            "gcloud auth print-access-token | tee /tmp/fake-out >/dev/null",
            "gcloud auth print-access-token | tee -a fake-out >/dev/null",
            "gcloud auth print-access-token > ./fake-token.txt",
            // The file form the deny text advises.
            "(umask 077; gcloud auth print-access-token > ~/.gcloud-token)",
            "grep security -i notes.txt",
            "rg security -i notes.txt",
            "git commit -m 'fix: never pipe to security -i or run gh auth $(echo token)'",
            "gh pr create --title fake --body 'use gh auth token, not security -i'",
            "GH_TOKEN=$(gh auth token) gh pr view \"$N\"",
            // Review round 4: `gh auth` then `$` is parsed, not refused.
            "gh auth status --hostname \"$H\"",
            "gh api \"repos/$R/pulls\"",
            "X=$(op read \"op://fake-vault/$ITEM/password\")",
        ],
    );
}

/// #8735: a printer that reports a credential operand in its error message
/// (`cat: <value>: No such file`, `printf: <value>: invalid number`) leaks it
/// on stderr. Each row was allowed at 474acf447; the first is the reported
/// shape, where the `<(…)` body's stderr is the outer terminal.
#[test]
fn denies_a_credential_operand_reported_on_stderr_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); wc -c < <(cat \"$(echo \"$T\")\")",
            "T=$(gcloud auth print-access-token); wc -c < <(cat \"$T\")",
            "wc -c < <(cat \"$(gcloud auth print-access-token)\")",
            // `>(…)`, `$(…)` and a subshell keep the outer stderr.
            "T=$(gcloud auth print-access-token); echo hi > >(cat \"$T\" > /dev/null)",
            "T=$(gcloud auth print-access-token); X=$(cat \"$T\")",
            "T=$(gcloud auth print-access-token); (cat \"$T\" > /dev/null)",
            "T=$(gcloud auth print-access-token); { cat \"$T\" > /dev/null; }",
            // The wrappers the fd1 rule already walks.
            "T=$(gcloud auth print-access-token); env cat \"$T\" > /dev/null",
            "T=$(gcloud auth print-access-token); command cat \"$T\" > /dev/null",
            "gcloud auth print-access-token | xargs cat > /dev/null",
            // Default stderr, `2>&1` and `|&` into a printing reader.
            "T=$(gcloud auth print-access-token); cat \"$T\" > /dev/null",
            "T=$(gcloud auth print-access-token); cat -- \"$T\" 2>&1 > /dev/null | head",
            "T=$(gcloud auth print-access-token); cat \"$T\" > /dev/null |& head",
            // `printf` reports an operand a numeric conversion rejects.
            "T=$(gcloud auth print-access-token); printf '%d' \"$T\" > /dev/null",
            "T=$(gcloud auth print-access-token); printf '%*s' \"$T\" x > /dev/null",
            "T=$(gcloud auth print-access-token); printf -v \"$T\" '%s' x > /dev/null",
            "T=$(gcloud auth print-access-token); printf \"$T\" > /dev/null",
            "T=$(gcloud auth print-access-token); print -f '%d' \"$T\" > /dev/null",
        ],
    );
}

/// #8735 fail-closed: where the stderr of a reporting printer goes, or what
/// its `printf` format asks for, is chosen at run time. Each row refuses as
/// unreadable. Fails against either fail-open mutation named in the fix's
/// report: routing that stderr only when it is not `Sink::Unknown`, or
/// reading a run-time `printf` format as one that reports nothing.
#[test]
fn denies_an_unreadable_stderr_of_a_reporting_printer_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); cat \"$T\" > /dev/null 2> \"$ERR\"",
            "T=$(gcloud auth print-access-token); wc -c < <(cat \"$T\" 2> \"$ERR\")",
            "T=$(gcloud auth print-access-token); printf \"$FMT\" \"$T\" > /dev/null",
        ],
    );
}

/// #8735: the nearest benign forms stay allowed — stderr discarded or
/// captured, a printer that never reports its operand, and a `printf` format
/// that only copies text.
#[test]
fn allows_the_8735_neighbours() {
    check(
        false,
        &[
            "T=$(gcloud auth print-access-token); wc -c < <(cat \"$T\" 2>/dev/null)",
            "T=$(gcloud auth print-access-token); cat \"$T\" > /dev/null 2> /dev/null",
            "T=$(gcloud auth print-access-token); cat \"$T\" &> /dev/null",
            "T=$(gcloud auth print-access-token); cat \"$T\" > /tmp/fake-out 2> /tmp/fake-err",
            "T=$(gcloud auth print-access-token); X=$(cat \"$T\" 2>&1)",
            "T=$(gcloud auth print-access-token); cat \"$T\" |& wc -c",
            "T=$(gcloud auth print-access-token); X=$(echo \"$T\")",
            "T=$(gcloud auth print-access-token); X=$(printf '%s\\n' \"$T\")",
            "T=$(gcloud auth print-access-token); X=$(printf -- '%-10.4s|%%|%b' \"$T\" \"$T\")",
            "T=$(gcloud auth print-access-token); X=$(print -r -- \"$T\")",
            // Review round 1: `-u1` writes to the discarded stdout, and `cat`
            // names a `<(…)` file by its `/dev/fd` path, never by the value.
            "T=$(gcloud auth print-access-token); print -u1 \"$T\" >/dev/null 2>/dev/null",
            "cat <(gcloud auth print-access-token) | docker login -u x --password-stdin r.test",
        ],
    );
}

/// #8735 review round 1: zsh `print -u N` writes the value itself to
/// descriptor N, which is routed like stdout. The first three rows were
/// allowed at 57c75ed9a.
#[test]
fn denies_a_credential_written_by_print_u_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); print -u3 \"$T\" 3>&1 >/dev/null 2>/dev/null",
            "T=$(gcloud auth print-access-token); print -nu3 \"$T\" 3>&1 >/dev/null 2>/dev/null",
            "T=$(gcloud auth print-access-token); print -u 3 \"$T\" 3>&1 >/dev/null 2>/dev/null",
            "T=$(gcloud auth print-access-token); print -u2 \"$T\"",
            "T=$(gcloud auth print-access-token); print -u2 \"$T\" > /dev/null",
        ],
    );
}

/// #8735 review round 1, fail-closed: a `print -u` descriptor chosen at run
/// time, or the `-p` coprocess, refuses as unreadable. The last two rows were
/// allowed at 57c75ed9a, and fail against the fail-open mutation of that arm.
#[test]
fn denies_an_unreadable_print_unit_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); print -u \"$FD\" \"$T\"",
            "T=$(gcloud auth print-access-token); print -u \"$FD\" \"$T\" > /dev/null 2> /dev/null",
            "T=$(gcloud auth print-access-token); print -p \"$T\" > /dev/null 2> /dev/null",
        ],
    );
}

/// #8735 amendment B: a wrapper or precommand word hid the printer from the
/// credential rules. Every row printed the token and was allowed at bd712bcfa6.
#[test]
fn denies_a_printer_behind_a_wrapper_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); noglob echo \"$T\"",
            "T=$(gcloud auth print-access-token); nocorrect echo \"$T\"",
            "T=$(gcloud auth print-access-token); nice -n 5 echo \"$T\"",
            "T=$(gcloud auth print-access-token); timeout 5 echo \"$T\"",
            "T=$(gcloud auth print-access-token); timeout 5 cat \"$T\"",
            "T=$(gcloud auth print-access-token); sudo -u x timeout 5 cat \"$T\"",
            "T=$(gcloud auth print-access-token); env -i PATH=/bin cat \"$T\"",
            "T=$(gcloud auth print-access-token); time -p echo \"$T\"",
        ],
    );
}

/// #8735 fail-closed: a wrapper option the resolver cannot measure hides the
/// program, so a stage carrying a credential refuses. Allowed at bd712bcfa6,
/// and allowed again under the fail-open mutation of the unknown-option arm.
#[test]
fn denies_a_wrapper_option_it_cannot_read_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); timeout --bogus 5 cp \"$T\" /dev/null",
            "T=$(gcloud auth print-access-token); sudo -X cp \"$T\" /dev/null",
            "timeout --bogus 5 gcloud auth print-access-token > /dev/null",
        ],
    );
}

/// #8735: the wrapped forms of ordinary work, and `xargs` behind a wrapper,
/// stay allowed.
#[test]
fn allows_the_wrapped_neighbours_8735() {
    check(
        false,
        &[
            "T=$(gcloud auth print-access-token); timeout 5 echo hello",
            "T=$(gcloud auth print-access-token); timeout 30 cargo test -p x",
            "T=$(gcloud auth print-access-token); nice -n 10 cargo build",
            "T=$(gcloud auth print-access-token); echo \"$(git rev-parse HEAD)\"",
            "T=$(gcloud auth print-access-token); timeout --bogus 5 make",
            "gcloud auth print-access-token | nice xargs -I{} curl -H 'A: {}' https://example.test",
        ],
    );
}

/// #8735 round 2: a wrapper option the resolver cannot measure (`env -S`,
/// `flock -c`) left the command string unread. Every row printed the token and
/// was allowed at 7cb9de9271, and is allowed again under the fail-open
/// mutation of the unresolved scan in `wrapped_command`.
#[test]
fn denies_a_command_string_behind_a_wrapper_option_8735() {
    check(
        true,
        &[
            "T=$(gcloud auth print-access-token); timeout 5 env -S 'cat $T'",
            "timeout 5 env -S 'gcloud auth print-access-token'",
            "T=$(gcloud auth print-access-token); nice -n 5 env -S 'cat $T'",
            "flock /tmp/lock -c 'gcloud auth print-access-token'",
        ],
    );
}

/// #8735 round 2: behind an unmeasurable wrapper option, a trigger word handed
/// to a runner the guard never reads refuses. Allowed at 7cb9de9271, and under
/// the fail-open mutation of the `has_trigger` term.
#[test]
fn denies_a_trigger_word_behind_a_wrapper_option_8735() {
    check(
        true,
        &["sudo --bogus watch 'gcloud auth print-access-token'"],
    );
}

/// #8735 round 2: Homebrew's g-prefixed coreutils and the util-linux / expect
/// runners resolved as the program. Every row was allowed at 7cb9de9271.
#[test]
fn denies_a_printer_behind_a_new_wrapper_8735() {
    let rows: Vec<String> = [
        "gtimeout 5 echo",
        "gnice -n 5 echo",
        "gstdbuf -oL cat",
        "gnohup echo",
        "genv -i PATH=/bin cat",
        "setsid -f echo",
        "chrt -f 10 echo",
        "taskset -c 0-3 echo",
        "unbuffer -p echo",
        "flock -n /tmp/lock echo",
    ]
    .iter()
    .map(|w| format!("T=$(gcloud auth print-access-token); {w} \"$T\""))
    .collect();
    check(true, &rows.iter().map(String::as_str).collect::<Vec<_>>());
}

/// #8735 round 2: the same wrappers around ordinary work, and a lookup, stay
/// allowed.
#[test]
fn allows_the_new_wrapper_neighbours_8735() {
    check(
        false,
        &[
            "T=$(gcloud auth print-access-token); gtimeout 30 cargo test -p x",
            "T=$(gcloud auth print-access-token); flock /tmp/lock make",
            "T=$(gcloud auth print-access-token); timeout 5 env -S 'echo hello'",
            "command -v gcloud && gcloud auth print-access-token > /dev/null",
        ],
    );
}

/// 🔴 REGRESSION (#8931 critic round): `$((cmd) )` and `$(( (cmd) ) )` are
/// command substitutions that open with a subshell — the shell reads `$((` as
/// arithmetic only when the inner `(` closes right before the outer `)`. Each
/// row was allowed on 1cae0877eb, which left the body in place as arithmetic.
#[test]
fn denies_a_subshell_substitution_shaped_like_arithmetic_8931() {
    check(
        true,
        &[
            "X=$((gcloud auth print-access-token) ) >/dev/null; echo $X",
            "X=$((  (gcloud auth print-access-token) ) ) >/dev/null; echo $X",
            "X=$((gcloud auth print-access-token); ) >/dev/null; echo $X",
            // A quoted `)))` makes the paren count read `))` early.
            "X=$((echo ')))'; gcloud auth print-access-token) ) >/dev/null; echo $X",
        ],
    );
    check(
        false,
        &["X=$((1+2)); echo $X", "X=$(( (1+2) * 3 )); echo $X"],
    );
}

/// #9150: the walk reads a delimiter word with the here-document scanner's
/// grammar, so a word that scanner refuses (`x$y`, `A B`) strips no body, and
/// an `A\r` line never ends an `A` body. Each deny row but the unquoted one
/// was allowed on a753c016c9; the CRLF body is data like its LF form.
#[test]
fn denies_a_body_behind_a_refused_delimiter() {
    check(
        true,
        &[
            "cat <<'x$y'\ngcloud auth print-access-token\nx$y",
            "cat <<x$y\ngcloud auth print-access-token\nx$y",
            "cat <<'A B'\ngcloud auth print-access-token\nA B",
            "cat <<'A'\nx\nA\r\ncat <<'X'\nA\ngcloud auth print-access-token\nX",
        ],
    );
    check(
        false,
        &["cat > notes.md <<'EOF'\r\nNever run gcloud auth print-access-token bare.\r\nEOF\r\n"],
    );
}