autumn-cli 0.9.0

CLI tool for the Autumn web framework
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
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
//! Dependency policy evaluation shared by `autumn doctor` and `autumn dev`
//! (issue #1633).
//!
//! Detection is not re-implemented here. Doctor and dev run the same auditor
//! (`cargo deny`) against the same policy file (`deny.toml`), the same waiver
//! store (`[advisories] ignore`) and the same check list as the CI gate from
//! issue #1600. Two differences remain and are reported, not hidden: CI pins
//! its auditor version, and CI fetches the advisory database before it audits.
//! See `docs/guide/supply-chain.md`, "Part 3b — the dev loop".
//!
//! One limit follows from that. Only `cargo deny` knows its config schema. A
//! `deny.toml` that is valid TOML but breaks the schema (`yanked = "bogus"`)
//! is accepted here when `cargo deny` is absent, and CI rejects it (issue #2575).

use std::collections::HashSet;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::mpsc;
use std::time::Duration;
use std::time::SystemTime;

/// The app-level dependency policy file. Also the CI gate's config.
pub const POLICY_FILE: &str = "deny.toml";

/// Policy sections that switch on an extra cargo-deny check when present.
///
/// The scaffolded CI workflow derives its check list from the same names, so
/// uncommenting a section widens the local check and the CI gate together.
pub const OPTIONAL_CHECKS: &[&str] = &["bans", "licenses", "sources"];

/// An advisory database older than this is reported as stale.
///
/// The CI gate fetches the database on every run. A local verdict is only as
/// fresh as local data, so the window is short enough that a weekly fetch
/// keeps the two comparable.
pub const STALE_AFTER_DAYS: u64 = 7;

/// Diagnostic codes that report on the policy file, not on the dependency
/// tree. Observed from cargo-deny 0.20.2.
///
/// These are dropped only when the policy grades them below an error. A policy
/// can promote any of them (`unused-ignored-advisory = "deny"`, for one), and a
/// promoted one fails the CI gate, so dropping it by code alone would report a
/// clean tree that CI rejects.
const CONFIG_ONLY_CODES: &[&str] = &[
    "advisory-ignored",
    "advisory-not-detected",
    "unknown-advisory",
    "yanked-not-detected",
    "license-not-encountered",
    "license-exception-not-encountered",
    "unmatched-source",
    "unmatched-organization",
    "unmatched-skip",
    "unmatched-skip-root",
    "unmatched-path-bypass",
    "unmatched-glob",
    "unused-wrapper",
    "unmatched-wrapper",
    // Always paired with `unlicensed`, which names the same crate.
    "no-license-field",
    "deprecated",
];

/// Consequence of one finding.
///
/// Severity is consequence, not taxonomy: the policy decides what fails. A
/// denied finding is at least [`Severity::High`]; a warned one is at most
/// [`Severity::Medium`]. Critical/High therefore means "the CI gate fails".
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    Low,
    Medium,
    High,
    Critical,
}

impl Severity {
    pub const fn label(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Critical => "critical",
        }
    }
}

/// One advisory or policy violation against the app's lockfile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    /// `RUSTSEC-YYYY-NNNN` for an advisory, else the cargo-deny code.
    pub id: String,
    /// The cargo-deny diagnostic code, e.g. `vulnerability` or `banned`.
    pub code: String,
    /// `name version`, empty when the auditor did not name a crate.
    pub package: String,
    pub title: String,
    pub severity: Severity,
    /// Waived by an `[advisories] ignore` entry in the policy file.
    pub waived: bool,
    /// The auditor graded this an error, so the CI gate fails on it.
    pub blocking: bool,
}

/// What an evaluation of the app's dependency policy produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Evaluation {
    /// No policy file. The CI gate fails on this too.
    NoPolicy,
    /// `cargo deny` is not on PATH.
    AuditorMissing { checks: Vec<String> },
    /// The `RustSec` database was never fetched, so nothing can be verified.
    DatabaseMissing { checks: Vec<String> },
    /// The auditor produced a verdict.
    Audited {
        findings: Vec<Finding>,
        checks: Vec<String>,
        db_age_days: Option<u64>,
        /// The auditor version, as it reported itself.
        auditor: String,
    },
    /// The auditor ran but produced no verdict.
    Unavailable { reason: String, checks: Vec<String> },
}

/// The cargo-deny checks this policy file activates, in command order.
///
/// Advisories are always checked: they are the gate from issue #1600. The
/// optional sections are opt-in, so an app that leaves them commented out gets
/// the same command locally that its CI runs.
pub fn policy_checks(policy: &str) -> Vec<String> {
    let declared = declared_sections(policy);
    let mut checks = vec!["advisories".to_owned()];
    checks.extend(
        OPTIONAL_CHECKS
            .iter()
            .filter(|section| declared.iter().any(|key| key == *section))
            .map(|section| (*section).to_owned()),
    );
    checks
}

/// Optional checks that doctor and the scaffolded workflow list differently.
///
/// Doctor parses TOML. The workflow greps, because a shell cannot parse TOML.
/// They agree on every hand-written policy. They differ in two cases:
///
/// - Only TOML sees the check: an escaped key (`["ban\u0073"]`).
/// - Only the grep sees the check: header-like text inside a string.
pub fn derivations_disagree(policy: &str) -> Vec<String> {
    let parsed = declared_sections(policy);
    OPTIONAL_CHECKS
        .iter()
        .filter(|section| {
            let by_parse = parsed.iter().any(|key| key == *section);
            let by_scan = policy
                .lines()
                .any(|line| line_declares(code_of(line), section));
            by_parse != by_scan
        })
        .map(|section| (*section).to_owned())
        .collect()
}

/// The top-level table keys the policy declares.
///
/// Parsed as TOML, so every spelling that reaches cargo-deny is seen the same
/// way: `[bans]`, `[ bans ]`, `["bans"]`, `[bans.build]`, `[[bans.deny]]`,
/// `bans.deny = …` and `bans = { … }` all declare the key `bans`.
///
/// A policy that does not parse falls back to a line scan. cargo-deny refuses
/// to load such a file anyway, so the fallback only has to avoid claiming the
/// sections vanished.
fn declared_sections(policy: &str) -> Vec<String> {
    if let Ok(table) = policy.parse::<toml::Table>() {
        return table.keys().cloned().collect();
    }
    OPTIONAL_CHECKS
        .iter()
        .filter(|section| {
            policy
                .lines()
                .any(|line| line_declares(code_of(line), section))
        })
        .map(|section| (*section).to_owned())
        .collect()
}

/// True when one policy line declares `section`, in any TOML spelling.
///
/// The fallback for an unparseable policy, and the rule the scaffolded workflow
/// mirrors in shell — grep cannot parse TOML.
fn line_declares(code: &str, section: &str) -> bool {
    let body = code
        .strip_prefix("[[")
        .or_else(|| code.strip_prefix('['))
        .map_or(code, ascii_trim_start);
    // Each quote is optional on its own, as in the workflow's grep.
    let body = body.strip_prefix(['"', '\'']).unwrap_or(body);
    let Some(rest) = body.strip_prefix(section) else {
        return false;
    };
    let rest = rest.strip_prefix(['"', '\'']).unwrap_or(rest);
    matches!(ascii_trim_start(rest).chars().next(), Some(']' | '.' | '='))
}

/// The code part of one policy line: comment stripped, trimmed.
///
/// ASCII whitespace only. Rust's `trim` also strips U+00A0, which POSIX
/// `[[:space:]]` does not, and a rule the workflow cannot mirror is a rule the
/// two derivations disagree on.
fn code_of(line: &str) -> &str {
    let line = ascii_trim(line);
    if line.starts_with('#') {
        return "";
    }
    ascii_trim(line.split('#').next().unwrap_or(""))
}

fn ascii_trim(text: &str) -> &str {
    text.trim_matches(|c: char| c.is_ascii_whitespace())
}

fn ascii_trim_start(text: &str) -> &str {
    text.trim_start_matches(|c: char| c.is_ascii_whitespace())
}

/// A custom `db-path` declared by the policy, if any.
///
/// Parsed as TOML, so quoting and escapes are the parser's problem rather than
/// this code's. `~` and `$CARGO_HOME` are expanded, as cargo-deny expands them.
pub fn policy_db_path(policy: &str) -> Option<String> {
    let value = policy
        .parse::<toml::Table>()
        .ok()?
        .get("advisories")?
        .get("db-path")?
        .as_str()?
        .to_owned();
    (!value.is_empty()).then(|| expand_path(&value))
}

/// Expand the path prefixes cargo-deny accepts in `db-path`.
fn expand_path(path: &str) -> String {
    let home =
        directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_string_lossy().into_owned());
    let cargo_home = crate::upgrade::cargo_home().map(|dir| dir.to_string_lossy().into_owned());
    expand_path_with(path, home.as_deref(), cargo_home.as_deref())
}

/// [`expand_path`], with the environment injected. Pure, so it is testable
/// without mutating the process environment.
pub fn expand_path_with(path: &str, home: Option<&str>, cargo_home: Option<&str>) -> String {
    // Longest prefix first: `${CARGO_HOME}` also starts with `$CARGO_HOME`.
    for (prefix, value) in [
        ("${CARGO_HOME}", cargo_home),
        ("$CARGO_HOME", cargo_home),
        ("~", home),
    ] {
        if let Some(rest) = path.strip_prefix(prefix)
            && let Some(value) = value
        {
            return format!("{value}{rest}");
        }
    }
    path.to_owned()
}

// ── CVSS v3 base score ───────────────────────────────────────────────────────

/// CVSS v3 base score for `vector`, or `None` when it is not a complete v3
/// vector. CVSS v3.1 specification, section 8.1.
///
/// Do not fuse the multiplications. The score is rounded up to one decimal, so
/// a more accurate intermediate can cross a band boundary that every reference
/// implementation stays on the near side of. For the same reason the vector's
/// minor version selects the changed-scope impact equation rather than one
/// standing in for both.
#[allow(
    clippy::suboptimal_flops,
    reason = "matches the CVSS reference implementations"
)]
pub fn cvss3_base_score(vector: &str) -> Option<f64> {
    // The scope-changed impact equation differs between the two minor
    // versions, so the prefix is not decoration — it selects the formula.
    let (body, v31) = match vector.strip_prefix("CVSS:3.1/") {
        Some(body) => (body, true),
        None => (vector.strip_prefix("CVSS:3.0/")?, false),
    };

    let (mut av, mut ac, mut pr, mut ui) = (None, None, None, None);
    let (mut scope, mut conf, mut integ, mut avail) = (None, None, None, None);
    for part in body.split('/') {
        let (key, value) = part.split_once(':')?;
        let slot = match key {
            "AV" => &mut av,
            "AC" => &mut ac,
            "PR" => &mut pr,
            "UI" => &mut ui,
            "S" => &mut scope,
            "C" => &mut conf,
            "I" => &mut integ,
            "A" => &mut avail,
            // Temporal and environmental metrics do not change the base score.
            _ => continue,
        };
        *slot = Some(value);
    }

    let changed = match scope? {
        "U" => false,
        "C" => true,
        _ => return None,
    };
    let av = match av? {
        "N" => 0.85,
        "A" => 0.62,
        "L" => 0.55,
        "P" => 0.2,
        _ => return None,
    };
    let ac = match ac? {
        "L" => 0.77,
        "H" => 0.44,
        _ => return None,
    };
    // Privileges Required is scored higher when the scope changes.
    let pr = match (pr?, changed) {
        ("N", _) => 0.85,
        ("L", false) => 0.62,
        ("L", true) => 0.68,
        ("H", false) => 0.27,
        ("H", true) => 0.50,
        _ => return None,
    };
    let ui = match ui? {
        "N" => 0.85,
        "R" => 0.62,
        _ => return None,
    };
    let impact_metric = |value: &str| match value {
        "H" => Some(0.56),
        "L" => Some(0.22),
        "N" => Some(0.0),
        _ => None,
    };
    let conf = impact_metric(conf?)?;
    let integ = impact_metric(integ?)?;
    let avail = impact_metric(avail?)?;

    let iss: f64 = 1.0 - (1.0 - conf) * (1.0 - integ) * (1.0 - avail);
    // v3.1 revised the changed-scope impact equation (spec §7.1) to remove a
    // rounding artefact: the exponent dropped from 15 to 13 and the base gained
    // the 0.9731 factor. It moves scores near a band boundary — the vector in
    // `the_two_minor_versions_disagree_across_a_band_boundary` is 7.0 (high)
    // under v3.0 and 6.9 (medium) under v3.1 — so the version must pick the
    // equation rather than one standing in for both.
    let impact = if changed {
        if v31 {
            7.52 * (iss - 0.029) - 3.25 * (iss * 0.9731 - 0.02).powi(13)
        } else {
            7.52 * (iss - 0.029) - 3.25 * (iss - 0.02).powi(15)
        }
    } else {
        6.42 * iss
    };
    if impact <= 0.0 {
        return Some(0.0);
    }
    let exploitability: f64 = 8.22 * av * ac * pr * ui;
    let raw = if changed {
        1.08 * (impact + exploitability)
    } else {
        impact + exploitability
    };
    Some(roundup(raw.min(10.0)))
}

/// Round up to one decimal place, per CVSS v3.1 appendix A.
fn roundup(value: f64) -> f64 {
    let scaled = (value * 100_000.0).round();
    if scaled % 10_000.0 == 0.0 {
        scaled / 100_000.0
    } else {
        ((scaled / 10_000.0).floor() + 1.0) / 10.0
    }
}

/// CVSS v3 severity band for `vector`. A zero score has no band.
pub fn severity_from_cvss(vector: Option<&str>) -> Option<Severity> {
    let score = cvss3_base_score(vector?)?;
    Some(match score {
        s if s >= 9.0 => Severity::Critical,
        s if s >= 7.0 => Severity::High,
        s if s >= 4.0 => Severity::Medium,
        s if s > 0.0 => Severity::Low,
        _ => return None,
    })
}

// ── Diagnostic stream ────────────────────────────────────────────────────────

/// Findings in one cargo-deny JSON diagnostic stream.
///
/// `None` when the stream carries no summary: the auditor did not finish, so
/// "no findings" would be a false all-clear.
pub fn parse_audit(ndjson: &str) -> Option<Vec<Finding>> {
    let mut finished = false;
    let mut waived: HashSet<String> = HashSet::new();
    let mut diagnostics: Vec<serde_json::Value> = Vec::new();

    for line in ndjson.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(entry) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        match entry.get("type").and_then(serde_json::Value::as_str) {
            Some("summary") => finished = true,
            Some("diagnostic") => {
                let Some(fields) = entry.get("fields") else {
                    continue;
                };
                if code(fields) == "advisory-ignored" {
                    if let Some(id) = waived_id(fields) {
                        waived.insert(id);
                    }
                } else {
                    diagnostics.push(fields.clone());
                }
            }
            _ => {}
        }
    }
    if !finished {
        return None;
    }
    Some(
        diagnostics
            .iter()
            .filter_map(|fields| finding_from(fields, &waived))
            .collect(),
    )
}

fn code(fields: &serde_json::Value) -> &str {
    fields
        .get("code")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default()
}

/// The advisory id an `advisory-ignored` marker names.
fn waived_id(fields: &serde_json::Value) -> Option<String> {
    let labels = fields.get("labels")?.as_array()?;
    let span_of = |label: &serde_json::Value| {
        label
            .get("span")
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned)
    };
    // The second label on this diagnostic is the developer's `reason` text.
    // Falling back to it blindly would let a reason of "yanked" mark real
    // findings waived, so the fallback requires an id-shaped span.
    labels
        .iter()
        .find(|label| {
            label.get("message").and_then(serde_json::Value::as_str)
                == Some("advisory ignored here")
        })
        .and_then(span_of)
        .or_else(|| {
            labels
                .iter()
                .filter_map(span_of)
                .find(|span| is_advisory_id(span))
        })
}

/// True when `span` is shaped like an advisory id rather than prose.
fn is_advisory_id(span: &str) -> bool {
    !span.is_empty()
        && span.len() <= 64
        && span
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

/// One finding, or `None` when the diagnostic reports on the policy file
/// rather than on the dependency tree.
fn finding_from(fields: &serde_json::Value, waived: &HashSet<String>) -> Option<Finding> {
    let code = code(fields);
    let level = fields
        .get("severity")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("note");
    let advisory = fields.get("advisory").filter(|value| !value.is_null());
    // A finding is what the policy graded: an error or a warning. Notes and
    // helps are context, one per private workspace crate. A waived advisory is
    // the exception: it is graded down to a note but still carries its advisory.
    if !matches!(level, "error" | "warning") && advisory.is_none() {
        return None;
    }
    let blocking = level == "error";
    // Config diagnostics report on the policy file, not on the tree. They are
    // noise — until the policy grades one an error, which is what turns the CI
    // gate red. Dropping those by code would report a tree CI rejects as clean.
    if CONFIG_ONLY_CODES.contains(&code) && !blocking {
        return None;
    }
    let code = if code.is_empty() { "finding" } else { code };

    let id = advisory
        .and_then(|advisory| advisory.get("id"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or(code)
        .to_owned();
    let message = fields
        .get("message")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    let title = one_line(
        &advisory
            .and_then(|advisory| advisory.get("title"))
            .and_then(serde_json::Value::as_str)
            .map_or_else(|| labelled_title(fields, message), str::to_owned),
    );

    let waived = waived.contains(&id);
    Some(Finding {
        code: code.to_owned(),
        package: package_of(fields, advisory),
        title,
        severity: grade(advisory, blocking, waived),
        waived,
        blocking,
        id,
    })
}

/// Longest finding title doctor renders. A diagnostic label can carry one
/// lock entry per line; doctor renders one line per finding.
pub const TITLE_MAX_CHARS: usize = 160;

/// Collapse whitespace runs to single spaces and bound the length.
pub fn one_line(text: &str) -> String {
    let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if collapsed.chars().count() <= TITLE_MAX_CHARS {
        return collapsed;
    }
    let kept: String = collapsed.chars().take(TITLE_MAX_CHARS - 1).collect();
    format!("{kept}\u{2026}")
}

/// The diagnostic message, plus the label that says what was violated.
///
/// A policy violation names the crate in `message` but the violated rule — a
/// rejected license, for one — only in a label.
fn labelled_title(fields: &serde_json::Value, message: &str) -> String {
    let span = fields
        .get("labels")
        .and_then(serde_json::Value::as_array)
        .into_iter()
        .flatten()
        .find(|label| {
            !label
                .get("message")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .is_empty()
        })
        .and_then(|label| label.get("span"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    if span.is_empty() || message.contains(span) {
        return message.to_owned();
    }
    format!("{message}: {span}")
}

/// `name version` for the crate a diagnostic is about.
fn package_of(fields: &serde_json::Value, advisory: Option<&serde_json::Value>) -> String {
    let krate = fields
        .get("graphs")
        .and_then(serde_json::Value::as_array)
        .and_then(|graphs| graphs.first())
        .and_then(|graph| graph.get("Krate"));
    if let Some(krate) = krate {
        let name = krate
            .get("name")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        let version = krate
            .get("version")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        if !name.is_empty() {
            return if version.is_empty() {
                one_line(name)
            } else {
                one_line(&format!("{name} {version}"))
            };
        }
    }
    advisory
        .and_then(|advisory| advisory.get("package"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default()
        .to_owned()
}

/// Grade one finding.
///
/// Severity is consequence, so the policy decides it: a denied finding is at
/// least high, a warned one at most medium. CVSS only separates critical from
/// high inside what the policy already denies.
///
/// A waived finding has no consequence to grade, so it is graded by its own
/// CVSS band or kind. It can therefore read lower than the same finding
/// unwaived: the number describes the advisory, not the gate.
fn grade(advisory: Option<&serde_json::Value>, blocking: bool, waived: bool) -> Severity {
    let base = advisory.map_or(Severity::Low, |advisory| {
        match advisory
            .get("informational")
            .and_then(serde_json::Value::as_str)
        {
            // A vulnerability with no scorable CVSS is treated as high.
            None => severity_from_cvss(advisory.get("cvss").and_then(serde_json::Value::as_str))
                .unwrap_or(Severity::High),
            Some("unsound") => Severity::Medium,
            Some(_) => Severity::Low,
        }
    });
    if waived {
        base
    } else if blocking {
        base.max(Severity::High)
    } else {
        base.min(Severity::Medium)
    }
}

// ── Advisory database age ────────────────────────────────────────────────────

/// Whole days between `then` and `now`. A clock that moved backwards reads as
/// fresh rather than as a huge age.
pub fn age_days(then: SystemTime, now: SystemTime) -> u64 {
    now.duration_since(then)
        .map_or(0, |elapsed| elapsed.as_secs() / 86_400)
}

/// Newest modification time among the database checkouts under `dbs_dir`.
///
/// Three candidates per checkout, newest wins:
///
/// * `.git/FETCH_HEAD` — written by every fetch, including one that finds
///   nothing new, so it answers "when did we last fetch" rather than "when did
///   the data last change". Absent after a fresh clone.
/// * `.git` — updated when a fetch writes refs or objects.
/// * the checkout root — updated when a fetch rewrites the working tree.
///
/// Measured against cargo-deny 0.20.2, whose gix-based fetch updates all three;
/// the root alone would still be the clone date on a fetch that only wrote
/// inside `.git`.
pub fn newest_db_mtime(dbs_dir: &Path) -> Option<SystemTime> {
    std::fs::read_dir(dbs_dir)
        .ok()?
        .filter_map(Result::ok)
        .filter(|entry| entry.path().is_dir())
        .filter_map(|entry| {
            let checkout = entry.path();
            let git = checkout.join(".git");
            [git.join("FETCH_HEAD"), git, checkout]
                .into_iter()
                .filter_map(|path| path.metadata().ok()?.modified().ok())
                .max()
        })
        .max()
}

/// Where cargo-deny keeps the `RustSec` database when the policy names no path.
///
/// Cargo's own home, resolved the way Cargo resolves it: on Windows `$HOME` is
/// normally unset and the home comes from the user profile.
fn default_db_dir() -> PathBuf {
    crate::upgrade::cargo_home()
        .unwrap_or_else(|| PathBuf::from(".cargo"))
        .join("advisory-dbs")
}

// ── Dev-loop output ──────────────────────────────────────────────────────────

/// How many critical ids the startup banner names before it truncates.
const BANNER_ID_LIMIT: usize = 5;

/// Lines `autumn dev` prints at startup. Empty means silent.
///
/// Only findings the policy denies are reported: those are the ones that turn
/// the CI gate red. A warned finding — a duplicate crate, a yanked crate — is
/// doctor's to report. A clean tree, a fully waived tree, and every state where
/// the policy could not be evaluated are all silent.
pub fn dev_lines(eval: &Evaluation) -> Vec<String> {
    let Evaluation::Audited { findings, .. } = eval else {
        return Vec::new();
    };
    let blocking: Vec<&Finding> = findings
        .iter()
        .filter(|finding| !finding.waived && finding.blocking)
        .collect();
    let count = blocking.len();
    if count == 0 {
        return Vec::new();
    }
    let plural = if count == 1 { "" } else { "s" };
    let worst = blocking
        .iter()
        .map(|finding| finding.severity)
        .max()
        .unwrap_or(Severity::High);

    if worst < Severity::Critical {
        return vec![format!(
            "  \u{26A0}\u{FE0F}  {count} blocking dependency finding{plural} (worst: {}) \u{2014} run `autumn doctor` for detail.",
            worst.label()
        )];
    }

    let critical: Vec<&str> = blocking
        .iter()
        .filter(|finding| finding.severity == Severity::Critical)
        .map(|finding| finding.id.as_str())
        .collect();
    vec![
        "  \u{26A0}\u{FE0F}  CRITICAL DEPENDENCY ADVISORY".to_owned(),
        format!(
            "     {count} blocking finding{plural}, {} critical: {}",
            critical.len(),
            name_some(&critical, BANNER_ID_LIMIT)
        ),
        "     Run `autumn doctor` for detail. `deny.toml` holds the policy and the waivers."
            .to_owned(),
    ]
}

/// Name up to `limit` ids, then count the rest.
pub fn name_some(ids: &[&str], limit: usize) -> String {
    let mut named = ids
        .iter()
        .take(limit)
        .copied()
        .collect::<Vec<_>>()
        .join(", ");
    if ids.len() > limit {
        let _ = write!(named, ", and {} more", ids.len() - limit);
    }
    named
}

// ── Evaluation ───────────────────────────────────────────────────────────────

/// How long `autumn doctor` waits for a verdict.
///
/// Offline is not the same as bounded: the auditor runs `cargo metadata`,
/// which waits on Cargo's package-cache lock while another build holds it.
/// Doctor reports a verdict or reports that it got none. It never hangs.
pub const DOCTOR_BUDGET: Duration = Duration::from_secs(30);

/// A running evaluation: the verdict channel and the means to stop it.
pub struct Running {
    /// Delivers the verdict. Closed without one if the audit was stopped.
    pub receiver: mpsc::Receiver<Evaluation>,
    /// Ends the auditor process. Call it when you give up on the verdict.
    pub stop: StopHandle,
}

/// Run the evaluation on its own thread.
///
/// The caller decides how long to wait. A caller that gives up must call
/// [`StopHandle::stop`], or the auditor keeps running.
pub fn spawn_evaluation(root: &Path) -> Running {
    spawn(root, None)
}

/// Run the evaluation on its own thread, and stop it after `deadline`.
///
/// A watchdog thread enforces the deadline. It does not depend on the caller
/// polling, so it holds while the caller is busy (for example in a rebuild).
pub fn spawn_evaluation_with_deadline(root: &Path, deadline: Duration) -> Running {
    spawn(root, Some(deadline))
}

fn spawn(root: &Path, deadline: Option<Duration>) -> Running {
    let (sender, receiver) = mpsc::channel();
    let root = root.to_path_buf();
    let stop = StopHandle::default();
    ACTIVE.register(&stop);
    let finished = deadline.map(|deadline| watchdog(stop.clone(), deadline));
    let worker_stop = stop.clone();
    std::thread::spawn(move || {
        // A closed receiver means the caller moved on. Nothing to report.
        let _ = sender.send(evaluate_with(&root, &worker_stop));
        // Dropping this ends the watchdog without a stop.
        drop(finished);
    });
    Running { receiver, stop }
}

/// Stop `stop` after `deadline`, unless the returned sender is dropped first.
fn watchdog(stop: StopHandle, deadline: Duration) -> mpsc::Sender<()> {
    let (finished, wait) = mpsc::channel::<()>();
    std::thread::spawn(move || {
        if wait.recv_timeout(deadline) == Err(mpsc::RecvTimeoutError::Timeout) {
            stop.stop();
        }
    });
    finished
}

/// Wait up to `budget` for a spawned evaluation. `None` means it did not
/// finish.
pub fn await_evaluation(
    receiver: &mpsc::Receiver<Evaluation>,
    budget: Duration,
) -> Option<Evaluation> {
    receiver.recv_timeout(budget).ok()
}

/// Evaluate the policy, giving up after `budget`.
///
/// A budget that expires is reported as no verdict, never as a clean tree.
/// The auditor process is stopped at that point, not before.
pub fn evaluate_within(root: &Path, budget: Duration) -> Evaluation {
    await_or_stop(&spawn_evaluation(root), budget)
}

/// Wait up to `budget` for `running`. On expiry, stop it and report no verdict.
fn await_or_stop(running: &Running, budget: Duration) -> Evaluation {
    await_evaluation(&running.receiver, budget).unwrap_or_else(|| {
        running.stop.stop();
        Evaluation::Unavailable {
            reason: format!("the audit did not finish within {}s", budget.as_secs()),
            checks: Vec::new(),
        }
    })
}

/// The audits that may still be running.
static ACTIVE: Registry = Registry(std::sync::Mutex::new(Vec::new()));

/// Stop every audit this process started.
///
/// A process that dies on Ctrl+C runs no destructors, and each auditor leads
/// its own process group, so the terminal does not reach it. The interrupt
/// handler calls this first.
pub fn stop_all() {
    ACTIVE.stop_all();
}

/// A list of audits to stop together.
struct Registry(std::sync::Mutex<Vec<StopHandle>>);

impl Registry {
    fn register(&self, stop: &StopHandle) {
        let mut handles = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        handles.push(stop.clone());
    }

    fn stop_all(&self) {
        let handles = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        for stop in handles.iter() {
            stop.stop();
        }
    }
}

/// State shared by an audit thread and the caller that may stop it.
#[derive(Default)]
struct Slot {
    child: Option<std::process::Child>,
    stopped: bool,
}

/// Ends an audit's auditor process.
///
/// Call it after the deadline, or when the caller ends. On the normal path the
/// verdict arrives and the process has already exited. Killing a live `cargo metadata` is safe for
/// Cargo's package-cache lock: the OS releases the lock when its holder dies.
#[derive(Clone, Default)]
pub struct StopHandle(std::sync::Arc<std::sync::Mutex<Slot>>);

impl StopHandle {
    fn slot(&self) -> std::sync::MutexGuard<'_, Slot> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Kill the auditor and its children. Safe to call at any time, and more
    /// than once. A call before the process starts prevents it from running.
    pub fn stop(&self) {
        let mut slot = self.slot();
        slot.stopped = true;
        if let Some(child) = slot.child.as_mut() {
            kill_tree(child);
        }
    }

    /// True after [`stop`](Self::stop).
    #[cfg(test)]
    pub fn is_stopped(&self) -> bool {
        self.slot().stopped
    }
}

/// Kill a child and every process it started.
///
/// The auditor runs `cargo metadata` as its own child. Killing only the
/// auditor leaves that process holding the package-cache lock. On Unix the
/// child leads its own process group (see `run_stoppable`). On Windows the
/// sweep walks the process tree.
fn kill_tree(child: &mut std::process::Child) {
    crate::process::force_kill_group(child.id());
    let _ = child.kill();
}

/// How long to wait for output after the auditor exits. A descendant that
/// outlives it can hold the pipe open.
const DRAIN_GRACE: Duration = Duration::from_secs(2);

/// How often a running auditor is checked for exit.
const POLL: Duration = Duration::from_millis(10);

/// Run `command` to completion, unless `stop` ends it first.
///
/// A stopped run returns an `Interrupted` error.
fn run_stoppable(
    command: &mut Command,
    stop: &StopHandle,
) -> std::io::Result<std::process::Output> {
    use std::io::Read;
    use std::process::Stdio;

    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    // Own process group, so `stop` reaches the auditor's children too.
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(command, 0);
    let mut child = command.spawn()?;
    let drain = |pipe: Option<Box<dyn Read + Send>>| {
        let (sender, receiver) = mpsc::channel();
        std::thread::spawn(move || {
            let mut bytes = Vec::new();
            if let Some(mut pipe) = pipe {
                let _ = pipe.read_to_end(&mut bytes);
            }
            let _ = sender.send(bytes);
        });
        receiver
    };
    let stdout = drain(child.stdout.take().map(|p| Box::new(p) as _));
    let stderr = drain(child.stderr.take().map(|p| Box::new(p) as _));

    {
        let mut slot = stop.slot();
        if slot.stopped {
            kill_tree(&mut child);
        }
        slot.child = Some(child);
    }
    let status = loop {
        let mut slot = stop.slot();
        let waited = slot.child.as_mut().map(std::process::Child::try_wait);
        match waited {
            Some(Ok(Some(status))) => {
                slot.child = None;
                if slot.stopped {
                    return Err(std::io::ErrorKind::Interrupted.into());
                }
                break status;
            }
            Some(Ok(None)) => {}
            Some(Err(error)) => return Err(error),
            None => return Err(std::io::ErrorKind::Interrupted.into()),
        }
        drop(slot);
        std::thread::sleep(POLL);
    };
    Ok(std::process::Output {
        status,
        stdout: stdout.recv_timeout(DRAIN_GRACE).unwrap_or_default(),
        stderr: stderr.recv_timeout(DRAIN_GRACE).unwrap_or_default(),
    })
}

/// The directory holding the app's policy file, searching upward from `start`.
///
/// The CI gate runs at the repository root, so the outermost policy wins over
/// a workspace member's own. The search stops at the `.git` folder or at a
/// `[workspace]` root, whose graph an outer policy does not cover. With
/// neither boundary, the nearest policy wins: a stray file higher up is not
/// part of the app.
pub fn find_policy_root(start: &Path) -> Option<PathBuf> {
    let start = start.canonicalize().ok()?;
    let mut nearest = None;
    let mut outermost = None;
    let mut bounded = false;
    for dir in start.ancestors() {
        if dir.join(POLICY_FILE).is_file() {
            nearest.get_or_insert_with(|| dir.to_path_buf());
            outermost = Some(dir.to_path_buf());
        }
        if dir.join(".git").exists() || is_workspace_root(dir) {
            bounded = true;
            break;
        }
    }
    if bounded { outermost } else { nearest }
}

/// Whether `dir` holds a `Cargo.toml` with a `[workspace]` table.
fn is_workspace_root(dir: &Path) -> bool {
    std::fs::read_to_string(dir.join("Cargo.toml"))
        .ok()
        .and_then(|manifest| manifest.parse::<toml::Table>().ok())
        .is_some_and(|manifest| manifest.contains_key("workspace"))
}

/// Evaluate the dependency policy for the app rooted at `root`.
///
/// Always offline: the advisory database is never fetched here, so this cannot
/// depend on the network. `cargo deny fetch db` refreshes it.
#[cfg(test)]
pub fn evaluate(root: &Path) -> Evaluation {
    evaluate_with(root, &StopHandle::default())
}

fn evaluate_with(root: &Path, stop: &StopHandle) -> Evaluation {
    let Some(root) = find_policy_root(root) else {
        return Evaluation::NoPolicy;
    };
    let Ok(policy) = std::fs::read_to_string(root.join(POLICY_FILE)) else {
        return Evaluation::NoPolicy;
    };
    let checks = policy_checks(&policy);

    // Both states below are reported BEFORE the optional-tool checks. Those
    // report "not evaluated" and pass, which would be a green local run on a
    // repository the CI gate rejects.
    //
    // cargo-deny loads the policy before it audits anything, so a policy that
    // is not valid TOML fails the gate outright.
    if let Err(error) = policy.parse::<toml::Table>() {
        return Evaluation::Unavailable {
            reason: one_line(&format!("{POLICY_FILE} is not valid TOML: {error}")),
            checks,
        };
    }
    // One derivation sees a section that the other does not. The local and CI
    // check lists differ, so doctor gives no verdict.
    let split = derivations_disagree(&policy);
    if !split.is_empty() {
        return Evaluation::Unavailable {
            reason: format!(
                "{POLICY_FILE} gives doctor and the CI workflow different check lists for {}. Write each as a plain [{}] header. Do not put header-like text in strings.",
                split.join(", "),
                split.join("], [")
            ),
            checks,
        };
    }

    let auditor = match auditor_version() {
        Auditor::Version(version) => version,
        Auditor::NotInstalled => return Evaluation::AuditorMissing { checks },
        Auditor::Broken(reason) => {
            return Evaluation::Unavailable {
                reason: format!("{AUDITOR} is installed but not usable: {reason}"),
                checks,
            };
        }
    };

    // A policy that names its own database is cargo-deny's to resolve: this
    // pre-check only guards the default location, so an unreadable custom path
    // reports whatever the auditor says rather than a database that is missing.
    let custom_db = policy_db_path(&policy);
    let mtime = newest_db_mtime(&resolve_db_dir(custom_db, &root));
    if mtime.is_none() && !policy_declares_db_path(&policy) {
        return Evaluation::DatabaseMissing { checks };
    }

    let mut command = Command::new(AUDITOR);
    command
        .args([
            "--offline",
            "--format",
            "json",
            "--log-level",
            "info",
            "check",
        ])
        .args(&checks)
        .current_dir(&root);
    no_toolchain_installs(&mut command);
    let output = match run_stoppable(&mut command, stop) {
        Ok(output) => output,
        Err(error) => {
            return Evaluation::Unavailable {
                reason: one_line(&format!("could not run cargo-deny: {error}")),
                checks,
            };
        }
    };
    // cargo-deny writes its diagnostic stream to stderr.
    let stream = String::from_utf8_lossy(&output.stderr);
    let Some(findings) = parse_audit(&stream) else {
        return Evaluation::Unavailable {
            reason: first_error(&stream),
            checks,
        };
    };
    // The auditor's exit code is what the CI gate acts on. A rejection this
    // parse cannot account for means the stream was read wrongly, so report no
    // verdict rather than a clean tree.
    if !output.status.success() && !findings.iter().any(|finding| finding.blocking) {
        return Evaluation::Unavailable {
            reason: "the auditor rejected this tree for a reason that could not be read; run `cargo deny check` to see it".to_owned(),
            checks,
        };
    }
    Evaluation::Audited {
        findings,
        checks,
        db_age_days: mtime.map(|mtime| age_days(mtime, SystemTime::now())),
        auditor,
    }
}

/// The advisory database directory to age.
///
/// cargo-deny runs in the policy root. A relative `db-path` is therefore
/// relative to that root, not to the process directory.
fn resolve_db_dir(custom: Option<String>, root: &Path) -> PathBuf {
    custom.map_or_else(default_db_dir, |path| root.join(path))
}

/// True when the policy names its own advisory database location.
fn policy_declares_db_path(policy: &str) -> bool {
    policy_db_path(policy).is_some()
}

/// The auditor binary, invoked directly rather than as `cargo deny`.
///
/// `cargo` on PATH is rustup's shim: it reads the *project's*
/// `rust-toolchain.toml` and installs that toolchain before running anything.
/// Doctor runs inside the user's project, so going through the shim turns a
/// read-only check into a toolchain download — and an interrupted one leaves a
/// half-installed toolchain that breaks the next real `cargo build`. It also
/// misreports: a shim failure surfaced here as "cargo-deny is not installed".
/// cargo subcommands are plain `cargo-<name>` executables on PATH, so calling
/// the binary skips rustup entirely and behaves identically (issue #1633).
const AUDITOR: &str = "cargo-deny";

/// Forbid a child from installing a Rust toolchain.
///
/// cargo-deny shells out to `cargo metadata`, which is rustup's shim again: on
/// a project pinning a toolchain this machine lacks, that call *downloads* it.
/// `autumn doctor` is a read-only check and must never mutate the user's
/// toolchain — least of all halfway, which is what leaves the next `cargo
/// build` broken. With this set, rustup errors instead, and the audit reports
/// no verdict (issue #1633).
pub fn no_toolchain_installs(command: &mut Command) {
    command.env("RUSTUP_AUTO_INSTALL", "0");
}

/// What probing the auditor found.
///
/// A missing optional tool and a broken one are different answers: the first is
/// a pass reading "not evaluated", the second a warning. Collapsing them makes
/// a corrupt install read as one that was simply never done (issue #1633).
enum Auditor {
    /// Installed and answering; the reported version string.
    Version(String),
    /// Not on PATH at all.
    NotInstalled,
    /// Present but unusable — the reason, for the reader.
    Broken(String),
}

/// Probe the auditor.
///
/// Its version is reported alongside the verdict: the scaffolded CI pins its
/// auditor, a local run uses whatever is installed, and a reader comparing the
/// two needs both.
fn auditor_version() -> Auditor {
    let mut command = Command::new(AUDITOR);
    no_toolchain_installs(&mut command);
    let output = match command.arg("--version").output() {
        Ok(output) => output,
        // Only "no such file" means the optional tool was never installed. Any
        // other spawn error — not executable, wrong architecture, a permission
        // denial — is a broken install, and reporting that as "not installed"
        // turns it into a pass.
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Auditor::NotInstalled;
        }
        Err(error) => return Auditor::Broken(one_line(&error.to_string())),
    };
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let detail = stderr.lines().find(|line| !line.trim().is_empty());
        return Auditor::Broken(match detail {
            Some(line) => one_line(line),
            None => format!("`{AUDITOR} --version` exited with {}", output.status),
        });
    }
    let reported = String::from_utf8_lossy(&output.stdout);
    Auditor::Version(one_line(reported.lines().next().unwrap_or("cargo-deny")))
}

/// The first error the auditor logged, for an evaluation that produced no
/// verdict.
fn first_error(stream: &str) -> String {
    stream
        .lines()
        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line.trim()).ok())
        .find(|entry| {
            entry.get("fields").and_then(|fields| fields.get("level"))
                == Some(&serde_json::Value::String("ERROR".to_owned()))
        })
        .and_then(|entry| Some(one_line(entry.get("fields")?.get("message")?.as_str()?)))
        .unwrap_or_else(|| "cargo-deny produced no verdict".to_owned())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// One `vulnerability` diagnostic plus the summary that proves the run
    /// finished. Shaped after real `cargo deny 0.20.2 --format json` output.
    const CRITICAL_VULN: &str = r#"
{"fields":{"level":"INFO","message":"checking advisories..."},"type":"log"}
{"fields":{"advisory":{"cvss":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H","id":"RUSTSEC-2099-0001","informational":null,"package":"badcrate","title":"remote code execution"},"code":"vulnerability","graphs":[{"Krate":{"name":"badcrate","version":"1.2.3"}}],"message":"remote code execution","severity":"error"},"type":"diagnostic"}
{"fields":{"advisories":{"errors":1,"helps":0,"notes":0,"warnings":0}},"type":"summary"}
"#;

    /// A waived advisory: the `advisory-ignored` marker plus the advisory
    /// itself, downgraded to a note.
    const WAIVED_UNMAINTAINED: &str = r#"
{"fields":{"code":"advisory-ignored","labels":[{"column":13,"line":64,"message":"advisory ignored here","span":"RUSTSEC-2024-0384"},{"column":43,"line":64,"message":"ignore reason","span":"instant unmaintained"}],"message":"advisory ignored","severity":"note"},"type":"diagnostic"}
{"fields":{"advisory":{"cvss":null,"id":"RUSTSEC-2024-0384","informational":"unmaintained","package":"instant","title":"`instant` is unmaintained"},"code":"unmaintained","graphs":[{"Krate":{"name":"instant","version":"0.1.13"}}],"message":"`instant` is unmaintained","severity":"note"},"type":"diagnostic"}
{"fields":{"advisories":{"errors":0,"helps":0,"notes":2,"warnings":0}},"type":"summary"}
"#;

    /// A yanked crate the policy only warns about.
    const YANKED_WARNING: &str = r#"
{"fields":{"code":"yanked","graphs":[{"Krate":{"name":"oldcrate","version":"0.3.1"}}],"message":"detected yanked crate","severity":"warning"},"type":"diagnostic"}
{"fields":{"advisories":{"errors":0,"helps":0,"notes":0,"warnings":1}},"type":"summary"}
"#;

    /// Policy violations from the licenses, bans and sources checks.
    const POLICY_VIOLATIONS: &str = r#"
{"fields":{"code":"banned","graphs":[{"Krate":{"name":"serde","version":"1.0.229"}}],"labels":[{"column":20,"line":4,"message":"banned here","span":"serde"}],"message":"crate 'serde = 1.0.229' is explicitly banned","severity":"error"},"type":"diagnostic"}
{"fields":{"code":"rejected","graphs":[{"Krate":{"name":"brotli","version":"8.0.4"}}],"labels":[{"column":12,"line":28,"message":"rejected: license is not explicitly allowed","span":"BSD-3-Clause"}],"message":"failed to satisfy license requirements","severity":"error"},"type":"diagnostic"}
{"fields":{"code":"source-not-allowed","graphs":[{"Krate":{"name":"adler2","version":"2.0.1"}}],"message":"detected 'registry' source not explicitly allowed","severity":"error"},"type":"diagnostic"}
{"fields":{"code":"license-not-encountered","message":"license 'Zlib' was not encountered","severity":"warning"},"type":"diagnostic"}
{"fields":{"licenses":{"errors":2,"helps":0,"notes":0,"warnings":1}},"type":"summary"}
"#;

    /// Informational notes a real run emits in bulk. cargo-deny prints one per
    /// private workspace crate — 94 of them in this workspace.
    const INFORMATIONAL_NOTES: &str = r#"
{"fields":{"code":"skipped-private-workspace-crate","graphs":[{"Krate":{"name":"blog","version":"0.1.0"}}],"message":"skipping private workspace crate 'blog = 0.1.0'","severity":"note"},"type":"diagnostic"}
{"fields":{"code":"skipped-private-workspace-crate","graphs":[{"Krate":{"name":"hello","version":"0.1.0"}}],"message":"skipping private workspace crate 'hello = 0.1.0'","severity":"note"},"type":"diagnostic"}
{"fields":{"licenses":{"errors":0,"helps":0,"notes":2,"warnings":0}},"type":"summary"}
"#;

    /// A real `duplicate` diagnostic: its label span carries one lock entry per
    /// line, so the label text is multi-line.
    const MULTILINE_LABEL: &str = r#"
{"fields":{"code":"duplicate","graphs":[{"Krate":{"name":"base64","version":"0.21.7"}}],"labels":[{"column":1,"line":3,"message":"lock entries","span":"base64 0.21.7 registry+https://github.com/rust-lang/crates.io-index\nbase64 0.22.1 registry+https://github.com/rust-lang/crates.io-index\nbase64 0.23.1 registry+https://github.com/rust-lang/crates.io-index"}],"message":"found 3 duplicate entries for crate 'base64'","severity":"warning"},"type":"diagnostic"}
{"fields":{"bans":{"errors":0,"helps":0,"notes":0,"warnings":1}},"type":"summary"}
"#;

    /// A waived vulnerability. cargo-deny grades a waived advisory down to a
    /// note, so the emitted severity says nothing about the advisory itself.
    const WAIVED_VULNERABILITY: &str = r#"
{"fields":{"code":"advisory-ignored","labels":[{"column":13,"line":6,"message":"advisory ignored here","span":"RUSTSEC-2099-0001"}],"message":"advisory ignored","severity":"note"},"type":"diagnostic"}
{"fields":{"advisory":{"cvss":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H","id":"RUSTSEC-2099-0001","informational":null,"package":"badcrate","title":"remote code execution"},"code":"vulnerability","graphs":[{"Krate":{"name":"badcrate","version":"1.2.3"}}],"message":"remote code execution","severity":"note"},"type":"diagnostic"}
{"fields":{"advisories":{"errors":0,"helps":0,"notes":2,"warnings":0}},"type":"summary"}
"#;

    /// A vulnerability scored with CVSS v4.0. 64 of the 432 scored advisories
    /// in the `RustSec` database use v4 vectors, which this code does not score.
    const V4_VULNERABILITY: &str = r#"
{"fields":{"advisory":{"cvss":"CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N","id":"RUSTSEC-2099-0002","informational":null,"package":"newcrate","title":"remote code execution"},"code":"vulnerability","graphs":[{"Krate":{"name":"newcrate","version":"2.0.0"}}],"message":"remote code execution","severity":"error"},"type":"diagnostic"}
{"fields":{"advisories":{"errors":1,"helps":0,"notes":0,"warnings":0}},"type":"summary"}
"#;

    /// A stale waiver, under a policy that promotes it to an error.
    /// `unused-ignored-advisory = "deny"` makes cargo-deny exit 1 on this.
    const PROMOTED_CONFIG_DIAGNOSTIC: &str = r#"
{"fields":{"code":"advisory-not-detected","labels":[{"column":13,"line":4,"message":"no crate matched advisory criteria","span":"RUSTSEC-2020-0071"}],"message":"advisory was not encountered","severity":"error"},"type":"diagnostic"}
{"fields":{"advisories":{"errors":1,"helps":0,"notes":0,"warnings":0}},"type":"summary"}
"#;

    fn audited(findings: Vec<Finding>) -> Evaluation {
        Evaluation::Audited {
            findings,
            checks: vec!["advisories".to_owned()],
            db_age_days: Some(1),
            auditor: "cargo-deny 0.20.2".to_owned(),
        }
    }

    fn finding(id: &str, severity: Severity, waived: bool, blocking: bool) -> Finding {
        Finding {
            id: id.to_owned(),
            code: "vulnerability".to_owned(),
            package: "badcrate 1.2.3".to_owned(),
            title: "boom".to_owned(),
            severity,
            waived,
            blocking,
        }
    }

    // ── policy_checks ────────────────────────────────────────────────────────

    #[test]
    fn policy_with_only_advisories_checks_advisories() {
        let policy = "[advisories]\nyanked = \"warn\"\n";
        assert_eq!(policy_checks(policy), vec!["advisories".to_owned()]);
    }

    #[test]
    fn commented_sections_do_not_widen_the_check_list() {
        // The scaffold ships these sections commented out. A commented section
        // must not widen the local check, or doctor would fail where CI passes.
        let policy = "[advisories]\n# [licenses]\n# allow = [\"MIT\"]\n#[bans]\n";
        assert_eq!(policy_checks(policy), vec!["advisories".to_owned()]);
    }

    #[test]
    fn declared_sections_widen_the_check_list_in_command_order() {
        let policy = "[sources]\n[advisories]\n[licenses]\nallow = []\n[bans]\n";
        assert_eq!(
            policy_checks(policy),
            vec![
                "advisories".to_owned(),
                "bans".to_owned(),
                "licenses".to_owned(),
                "sources".to_owned()
            ]
        );
    }

    #[test]
    fn advisories_are_checked_even_when_the_section_is_absent() {
        // Advisories are the gate from #1600. They are never optional.
        assert_eq!(policy_checks("[bans]\n"), vec!["advisories", "bans"]);
    }

    #[test]
    fn a_custom_db_path_is_read_from_the_policy() {
        let policy = "[advisories]\ndb-path = \"/srv/advisory-db\"\n";
        assert_eq!(policy_db_path(policy).as_deref(), Some("/srv/advisory-db"));
    }

    // ── CVSS v3 base score ───────────────────────────────────────────────────

    #[test]
    fn marvin_attack_vector_scores_medium() {
        // RUSTSEC-2023-0071 / CVE-2023-49092. NVD publishes 5.9 MEDIUM.
        let v = "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N";
        let score = cvss3_base_score(v).expect("v3.1 vector must parse");
        assert!((score - 5.9).abs() < 0.05, "expected 5.9, got {score}");
        assert_eq!(severity_from_cvss(Some(v)), Some(Severity::Medium));
    }

    #[test]
    fn worst_case_unchanged_scope_vector_scores_critical() {
        let v = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H";
        let score = cvss3_base_score(v).expect("v3.1 vector must parse");
        assert!((score - 9.8).abs() < 0.05, "expected 9.8, got {score}");
        assert_eq!(severity_from_cvss(Some(v)), Some(Severity::Critical));
    }

    #[test]
    fn changed_scope_raises_the_score() {
        let v = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H";
        let score = cvss3_base_score(v).expect("v3.1 vector must parse");
        assert!((score - 10.0).abs() < 0.05, "expected 10.0, got {score}");
    }

    #[test]
    fn a_vector_with_no_impact_scores_none() {
        let v = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N";
        assert_eq!(cvss3_base_score(v), Some(0.0));
        assert_eq!(severity_from_cvss(Some(v)), None);
    }

    #[test]
    fn v30_vectors_parse_too() {
        let v = "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H";
        let score = cvss3_base_score(v).expect("v3.0 vector must parse");
        assert!((score - 7.8).abs() < 0.05, "expected 7.8, got {score}");
    }

    #[test]
    fn non_v3_and_malformed_vectors_are_not_scored() {
        // A v4 vector, a truncated vector and prose must all decline rather
        // than invent a band.
        assert_eq!(cvss3_base_score("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N"), None);
        assert_eq!(cvss3_base_score("CVSS:3.1/AV:N/AC:L"), None);
        assert_eq!(cvss3_base_score("high"), None);
        assert_eq!(severity_from_cvss(None), None);
    }

    // ── parse_audit ──────────────────────────────────────────────────────────

    #[test]
    fn a_stream_without_a_summary_is_not_a_verdict() {
        // No summary means the auditor did not finish. Reporting "no findings"
        // there would be a false all-clear.
        assert_eq!(parse_audit(""), None);
        assert_eq!(
            parse_audit(r#"{"fields":{"level":"ERROR","message":"boom"},"type":"log"}"#),
            None
        );
    }

    #[test]
    fn a_clean_run_yields_a_verdict_with_no_findings() {
        let clean = r#"{"fields":{"advisories":{"errors":0,"helps":0,"notes":0,"warnings":0}},"type":"summary"}"#;
        assert_eq!(parse_audit(clean), Some(Vec::new()));
    }

    #[test]
    fn a_vulnerability_carries_its_id_package_title_and_severity() {
        let findings = parse_audit(CRITICAL_VULN).expect("summary present");
        assert_eq!(findings.len(), 1);
        let f = &findings[0];
        assert_eq!(f.id, "RUSTSEC-2099-0001");
        assert_eq!(f.code, "vulnerability");
        assert_eq!(f.package, "badcrate 1.2.3");
        assert_eq!(f.title, "remote code execution");
        assert_eq!(f.severity, Severity::Critical);
        assert!(f.blocking);
        assert!(!f.waived);
    }

    #[test]
    fn a_waived_advisory_is_reported_as_waived_not_as_a_failure() {
        let findings = parse_audit(WAIVED_UNMAINTAINED).expect("summary present");
        // The `advisory-ignored` marker is not itself a finding.
        assert_eq!(findings.len(), 1, "got {findings:?}");
        let f = &findings[0];
        assert_eq!(f.id, "RUSTSEC-2024-0384");
        assert!(f.waived);
        assert!(!f.blocking);
    }

    #[test]
    fn a_warned_finding_never_exceeds_medium() {
        let findings = parse_audit(YANKED_WARNING).expect("summary present");
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].code, "yanked");
        assert_eq!(findings[0].package, "oldcrate 0.3.1");
        assert!(!findings[0].blocking);
        assert!(findings[0].severity <= Severity::Medium);
    }

    #[test]
    fn a_denied_finding_is_at_least_high() {
        // Severity is consequence: whatever the taxonomy, a finding that fails
        // the CI gate is reported as high or critical.
        let findings = parse_audit(POLICY_VIOLATIONS).expect("summary present");
        let codes: Vec<&str> = findings.iter().map(|f| f.code.as_str()).collect();
        assert_eq!(codes, vec!["banned", "rejected", "source-not-allowed"]);
        for f in &findings {
            assert!(f.blocking, "{} must block", f.code);
            assert!(f.severity >= Severity::High, "{} severity too low", f.code);
        }
    }

    #[test]
    fn a_policy_violation_names_the_crate_and_the_violated_rule() {
        let findings = parse_audit(POLICY_VIOLATIONS).expect("summary present");
        let rejected = findings
            .iter()
            .find(|f| f.code == "rejected")
            .expect("rejected");
        assert_eq!(rejected.package, "brotli 8.0.4");
        assert_eq!(rejected.id, "rejected");
        assert!(
            rejected.title.contains("BSD-3-Clause"),
            "the rejected license must be named: {}",
            rejected.title
        );
    }

    #[test]
    fn config_only_diagnostics_are_not_findings() {
        // `license-not-encountered` reports on the policy file, not the tree.
        let findings = parse_audit(POLICY_VIOLATIONS).expect("summary present");
        assert!(
            findings.iter().all(|f| f.code != "license-not-encountered"),
            "config-only diagnostics must not be reported"
        );
    }

    #[test]
    fn informational_notes_are_not_findings() {
        // Regression: a real run against this workspace emitted 94
        // `skipped-private-workspace-crate` notes. A note the policy did not
        // grade is not a finding, and reporting it buries the ones that are.
        assert_eq!(parse_audit(INFORMATIONAL_NOTES), Some(Vec::new()));
    }

    #[test]
    fn a_waived_advisory_survives_the_note_filter() {
        // Waived advisories are also emitted at note level. They carry an
        // advisory, so they stay reportable — as waived.
        let findings = parse_audit(WAIVED_UNMAINTAINED).expect("summary present");
        assert_eq!(findings.len(), 1);
        assert!(findings[0].waived);
    }

    #[test]
    fn a_finding_is_always_one_line() {
        // Regression: a real `duplicate` diagnostic carries one lock entry per
        // line in its label. Doctor renders one line per finding and caps the
        // list, so a finding that expands to four lines defeats the cap.
        let findings = parse_audit(MULTILINE_LABEL).expect("summary present");
        assert_eq!(findings.len(), 1);
        let finding = &findings[0];
        assert!(!finding.title.contains('\n'), "title: {}", finding.title);
        assert!(
            !finding.package.contains('\n'),
            "package: {}",
            finding.package
        );
        assert!(
            finding.title.chars().count() <= TITLE_MAX_CHARS,
            "an unbounded title floods the line: {}",
            finding.title
        );
        assert!(
            finding.title.contains("base64"),
            "the crate must survive the trim: {}",
            finding.title
        );
    }

    #[test]
    fn a_waived_finding_is_graded_by_its_own_severity() {
        // A waived finding has no consequence to grade, so the number
        // describes the advisory rather than the gate.
        let findings = parse_audit(WAIVED_VULNERABILITY).expect("summary present");
        assert_eq!(findings.len(), 1);
        let finding = &findings[0];
        assert!(finding.waived);
        assert!(!finding.blocking);
        assert_eq!(finding.severity, Severity::Critical);
        // It is still not dev-loop noise.
        assert!(dev_lines(&audited(findings)).is_empty());
    }

    #[test]
    fn an_unscorable_vulnerability_is_treated_as_high_not_as_low() {
        // A CVSS v4.0 vector is not scored here. The fallback must be
        // conservative: an unscorable vulnerability still fails doctor, it
        // just does not earn the dev-loop banner.
        let findings = parse_audit(V4_VULNERABILITY).expect("summary present");
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].severity, Severity::High);
        assert!(findings[0].blocking);
    }

    #[test]
    fn a_malformed_policy_is_reported_before_the_optional_tool_checks() {
        // Regression, reproduced: with a malformed `deny.toml` and no
        // cargo-deny installed, doctor reported "not evaluated" and PASSED,
        // while cargo-deny — and so the CI gate — exits 1 loading the file.
        let root = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            root.path().join(POLICY_FILE),
            "[advisories]\nthis is not toml =\n",
        )
        .expect("policy");
        match evaluate(root.path()) {
            Evaluation::Unavailable { reason, .. } => {
                assert!(reason.contains("not valid TOML"), "{reason}");
            }
            other => panic!("a malformed policy must not read as evaluable: {other:?}"),
        }
    }

    #[test]
    fn a_spelling_only_doctor_can_see_is_reported_rather_than_diverging() {
        // Doctor parses TOML; the scaffolded workflow greps. A basic key with
        // an escape decodes for one and not the other, so the two check lists
        // would differ — the one thing this design exists to prevent.
        let escaped = "[advisories]\n[\"ban\\u0073\"]\n";
        assert!(
            policy_checks(escaped).contains(&"bans".to_owned()),
            "the TOML parse must decode the key"
        );
        assert_eq!(derivations_disagree(escaped), vec!["bans".to_owned()]);

        let root = tempfile::tempdir().expect("tempdir");
        std::fs::write(root.path().join(POLICY_FILE), escaped).expect("policy");
        match evaluate(root.path()) {
            Evaluation::Unavailable { reason, .. } => {
                assert!(reason.contains("bans"), "{reason}");
                assert!(reason.contains("[bans]"), "the fix must be named: {reason}");
            }
            other => panic!("a divergent spelling must not read as evaluable: {other:?}"),
        }
    }

    #[test]
    fn section_text_inside_a_string_is_reported_as_a_phantom() {
        // Issue #2572: the workflow greps, so a header quoted in prose counts
        // for CI. The TOML parse sees one string, so doctor never checks it.
        let phantom = "[advisories]\nignore = [\n    { id = \"RUSTSEC-2020-0071\", reason = \"\"\"\nno fix; this is prose:\n[bans]\nreview-by 2026-12-01\"\"\" },\n]\n";
        assert_eq!(policy_checks(phantom), vec!["advisories".to_owned()]);
        assert_eq!(derivations_disagree(phantom), vec!["bans".to_owned()]);

        let root = tempfile::tempdir().expect("tempdir");
        std::fs::write(root.path().join(POLICY_FILE), phantom).expect("policy");
        match evaluate(root.path()) {
            Evaluation::Unavailable { reason, .. } => {
                assert!(reason.contains("bans"), "{reason}");
                assert!(reason.contains("strings"), "{reason}");
            }
            other => panic!("a phantom section must not read as evaluable: {other:?}"),
        }
    }

    #[test]
    fn a_header_quoted_in_any_string_is_a_phantom_for_every_optional_check() {
        for section in OPTIONAL_CHECKS {
            for quote in ["\"\"\"", "'''"] {
                let policy = format!(
                    "[advisories]\nignore = [{{ id = \"X\", reason = {quote}\n[{section}]\n{quote} }}]\n"
                );
                assert_eq!(derivations_disagree(&policy), vec![(*section).to_owned()]);
            }
        }
    }

    #[test]
    fn a_real_header_plus_quoted_text_is_not_a_split() {
        let policy =
            "[bans]\n[advisories]\nignore = [{ id = \"X\", reason = \"\"\"\n[bans]\n\"\"\" }]\n";
        assert!(derivations_disagree(policy).is_empty());
        assert!(derivations_disagree("[advisories]\n# [bans]\n").is_empty());
    }

    #[test]
    fn unpaired_quotes_in_a_string_match_the_grep() {
        // The grep makes each quote optional, so `["bans']` matches it.
        let policy = "[advisories]\nnote = \"\"\"\n[\"bans']\n\"\"\"\n";
        assert_eq!(derivations_disagree(policy), vec!["bans".to_owned()]);
    }

    #[test]
    fn invalid_toml_falls_back_to_the_scan_and_agrees() {
        assert!(derivations_disagree("[bans\n[sources]\n").is_empty());
    }

    #[test]
    fn a_relative_db_path_is_resolved_against_the_policy_root() {
        let root = tempfile::tempdir().expect("tempdir");
        let abs = tempfile::tempdir().expect("tempdir");
        assert_eq!(
            resolve_db_dir(Some("advisory-dbs".to_owned()), root.path()),
            root.path().join("advisory-dbs")
        );
        // An absolute path stays as written.
        let abs_path = abs.path().to_string_lossy().into_owned();
        assert_eq!(resolve_db_dir(Some(abs_path), root.path()), abs.path());
        assert_eq!(resolve_db_dir(None, root.path()), default_db_dir());
    }

    #[test]
    fn every_hand_written_spelling_is_visible_to_both_derivations() {
        for policy in [
            "[bans]\n",
            "[ bans ]\n",
            "[bans] # note\n",
            "[bans.build]\n",
            "[[bans.deny]]\n",
            "bans.deny = []\n",
            "[\"bans\"]\n",
            "['bans']\n",
        ] {
            assert!(
                derivations_disagree(policy).is_empty(),
                "wrongly reported as a disagreement: {policy:?}"
            );
        }
    }

    #[cfg(unix)]
    mod stoppable {
        use super::*;

        fn alive(pid: i32) -> bool {
            nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None).is_ok()
        }

        fn sh(script: &str) -> Command {
            let mut command = Command::new("sh");
            command.args(["-c", script]);
            command
        }

        #[test]
        fn a_finished_audit_returns_its_output_and_is_not_killed() {
            let stop = StopHandle::default();
            let output = run_stoppable(&mut sh("echo out; echo err >&2"), &stop).expect("run");
            assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "out");
            assert_eq!(String::from_utf8_lossy(&output.stderr).trim(), "err");
            assert!(!stop.is_stopped(), "the normal path never stops");
        }

        #[test]
        fn stopping_kills_the_auditor_and_its_children() {
            let dir = tempfile::tempdir().expect("tempdir");
            let pid_file = dir.path().join("grandchild.pid");
            let tmp_file = dir.path().join("grandchild.tmp");
            // Write, then rename: the reader never sees a partial pid.
            let script = format!(
                "sleep 60 & echo $! > {tmp}; mv {tmp} {pid}; wait",
                tmp = tmp_file.display(),
                pid = pid_file.display()
            );
            let stop = StopHandle::default();
            let stopper = stop.clone();
            let runner = std::thread::spawn(move || run_stoppable(&mut sh(&script), &stopper));
            let mut grandchild = None;
            for _ in 0..500 {
                if let Ok(text) = std::fs::read_to_string(&pid_file) {
                    grandchild = text.trim().parse::<i32>().ok();
                    break;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            let Some(grandchild) = grandchild else {
                stop.stop();
                panic!("the auditor never started its child");
            };
            // Kill the child on any failure below.
            let _cleanup = Cleanup(grandchild);
            assert!(alive(grandchild));
            stop.stop();
            let result = runner.join().expect("join");
            assert_eq!(
                result.expect_err("stopped").kind(),
                std::io::ErrorKind::Interrupted
            );
            // Reaping is up to init; allow it a moment.
            for _ in 0..1000 {
                if !alive(grandchild) {
                    return;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            panic!("the auditor's child outlived the stop");
        }

        /// Kills a leftover process when a test fails early.
        struct Cleanup(i32);

        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = nix::sys::signal::kill(
                    nix::unistd::Pid::from_raw(self.0),
                    nix::sys::signal::Signal::SIGKILL,
                );
            }
        }

        #[test]
        fn stop_all_stops_every_registered_audit() {
            let registry = Registry(std::sync::Mutex::new(Vec::new()));
            let (first, second) = (StopHandle::default(), StopHandle::default());
            registry.register(&first);
            registry.register(&second);
            registry.stop_all();
            assert!(first.is_stopped() && second.is_stopped());
        }

        #[test]
        fn the_watchdog_stops_an_audit_that_outlives_its_deadline() {
            let stop = StopHandle::default();
            let _finished = watchdog(stop.clone(), Duration::from_millis(20));
            for _ in 0..500 {
                if stop.is_stopped() {
                    return;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            panic!("the deadline did not stop the audit");
        }

        #[test]
        fn the_watchdog_leaves_a_finished_audit_alone() {
            let stop = StopHandle::default();
            drop(watchdog(stop.clone(), Duration::from_millis(50)));
            std::thread::sleep(Duration::from_millis(200));
            assert!(!stop.is_stopped());
        }

        #[test]
        fn a_stop_twice_is_harmless() {
            let stop = StopHandle::default();
            stop.stop();
            stop.stop();
            assert!(stop.is_stopped());
        }

        #[test]
        fn output_larger_than_a_pipe_buffer_is_drained() {
            let stop = StopHandle::default();
            let output = run_stoppable(&mut sh("head -c 300000 /dev/zero"), &stop).expect("run");
            assert_eq!(output.stdout.len(), 300_000);
        }

        #[test]
        fn a_budget_that_expires_stops_the_audit() {
            let (_sender, receiver) = mpsc::channel();
            let stop = StopHandle::default();
            let running = Running {
                receiver,
                stop: stop.clone(),
            };
            let eval = await_or_stop(&running, Duration::from_millis(10));
            assert!(matches!(eval, Evaluation::Unavailable { .. }));
            assert!(stop.is_stopped(), "expiry must stop the auditor");
        }

        #[test]
        fn a_stop_before_the_start_prevents_the_run() {
            let stop = StopHandle::default();
            stop.stop();
            let error = run_stoppable(&mut sh("sleep 60"), &stop).expect_err("stopped");
            assert_eq!(error.kind(), std::io::ErrorKind::Interrupted);
        }
    }

    #[test]
    fn the_auditor_is_never_invoked_through_the_rustup_shim() {
        // Regression, caught by the Windows Tier 1 journey: `cargo` on PATH is
        // rustup's shim, which reads the *project's* `rust-toolchain.toml` and
        // installs that toolchain before running anything. Doctor runs inside
        // the user's project, so `cargo deny` there turned a read-only check
        // into a toolchain download; the next `cargo build` then failed with
        // "the 'cargo.exe' binary ... is not applicable to the '1.88.0-...'
        // toolchain". Invoking `cargo-deny` skips rustup entirely.
        let source = include_str!("deps.rs");
        let code = &source[..source.find("#[cfg(test)]").expect("test module")];
        assert!(
            !code.contains("Command::new(\"cargo\")"),
            "this module must not run anything through the `cargo` shim"
        );
        assert_eq!(AUDITOR, "cargo-deny");
        // cargo-deny reaches `cargo metadata` on its own, so every spawn must
        // also forbid an install. One guard call per spawned command.
        assert_eq!(
            code.matches("Command::new(").count(),
            code.matches("no_toolchain_installs(&mut").count(),
            "every command this module spawns must be guarded"
        );
    }

    #[test]
    fn a_read_only_check_never_installs_a_toolchain() {
        let mut command = Command::new(AUDITOR);
        no_toolchain_installs(&mut command);
        let set: Vec<_> = command
            .get_envs()
            .filter(|(key, _)| *key == "RUSTUP_AUTO_INSTALL")
            .collect();
        assert_eq!(set.len(), 1, "the guard must be set exactly once");
        assert_eq!(set[0].1, Some(std::ffi::OsStr::new("0")));
    }

    #[test]
    fn the_two_minor_versions_disagree_across_a_band_boundary() {
        // v3.1 revised the changed-scope impact equation. This vector is the
        // discriminating case: 7.0 (high) under v3.0, 6.9 (medium) under v3.1.
        // Every other vector in this suite scores identically under both, which
        // is exactly why using one equation for both went unnoticed.
        const METRICS: &str = "AV:P/AC:H/PR:L/UI:N/S:C/C:H/I:H/A:L";
        assert_eq!(cvss3_base_score(&format!("CVSS:3.0/{METRICS}")), Some(7.0));
        assert_eq!(cvss3_base_score(&format!("CVSS:3.1/{METRICS}")), Some(6.9));
        // And the band each lands in differs, which is the reason it matters.
        assert_eq!(
            severity_from_cvss(Some(&format!("CVSS:3.0/{METRICS}"))),
            Some(Severity::High)
        );
        assert_eq!(
            severity_from_cvss(Some(&format!("CVSS:3.1/{METRICS}"))),
            Some(Severity::Medium)
        );
    }

    #[test]
    fn a_broken_auditor_is_not_reported_as_a_missing_one() {
        // `AuditorMissing` passes, because no Autumn install path provides
        // cargo-deny. A cargo-deny that is present but unusable — corrupt,
        // wrong architecture, not executable — is a different answer, and
        // grading it as the optional-tool pass hides a machine whose CI-parity
        // claim is broken.
        let broken = Evaluation::Unavailable {
            reason: format!("{AUDITOR} is installed but not usable: Exec format error"),
            checks: vec!["advisories".to_owned()],
        };
        let result = crate::doctor::check_dependencies_impl(&broken);
        assert_eq!(result.status, crate::doctor::CheckStatus::Warn);

        // …whereas a genuinely absent tool still passes.
        let absent = Evaluation::AuditorMissing {
            checks: vec!["advisories".to_owned()],
        };
        assert_eq!(
            crate::doctor::check_dependencies_impl(&absent).status,
            crate::doctor::CheckStatus::Pass
        );
    }

    // ── Bounded waiting ──────────────────────────────────────────────────────

    #[test]
    fn a_verdict_that_arrives_in_time_is_returned() {
        let (sender, receiver) = mpsc::channel();
        sender.send(Evaluation::NoPolicy).expect("send");
        assert_eq!(
            await_evaluation(&receiver, Duration::from_secs(5)),
            Some(Evaluation::NoPolicy)
        );
    }

    #[test]
    fn a_verdict_that_outruns_its_budget_is_not_returned() {
        // Offline is not the same as bounded: the auditor runs `cargo
        // metadata`, which waits on Cargo's package-cache lock while another
        // build holds it.
        let (sender, receiver) = mpsc::channel::<Evaluation>();
        let result = await_evaluation(&receiver, Duration::from_millis(20));
        assert_eq!(result, None);
        drop(sender);
    }

    #[test]
    fn an_expired_budget_never_reads_as_a_clean_tree() {
        let dir = tempfile::tempdir().expect("tempdir");
        // No policy file, so this returns before any budget can matter — the
        // point is the shape of the timeout verdict, asserted below.
        assert_eq!(
            evaluate_within(dir.path(), Duration::from_secs(5)),
            Evaluation::NoPolicy
        );
        assert!(
            dev_lines(&Evaluation::Unavailable {
                reason: "the audit did not finish within 30s".to_owned(),
                checks: Vec::new(),
            })
            .is_empty()
        );
    }

    #[test]
    fn the_doctor_budget_is_bounded() {
        // A doctor run that stalls on an auditor is worse than one that says
        // it got no verdict.
        assert!(DOCTOR_BUDGET <= Duration::from_secs(60));
    }

    #[test]
    fn a_config_diagnostic_the_policy_promoted_is_a_finding() {
        // Regression, reproduced against cargo-deny 0.20.2: with
        // `unused-ignored-advisory = "deny"` a stale waiver is an ERROR and the
        // CI gate exits 1. Dropping it by code reported "all clear" on a tree
        // CI rejects.
        let findings = parse_audit(PROMOTED_CONFIG_DIAGNOSTIC).expect("summary present");
        assert_eq!(findings.len(), 1, "got {findings:?}");
        assert!(findings[0].blocking);
        assert!(findings[0].severity >= Severity::High);
    }

    #[test]
    fn the_same_config_diagnostic_below_error_is_still_noise() {
        let warned = PROMOTED_CONFIG_DIAGNOSTIC
            .replace(r#""severity":"error""#, r#""severity":"warning""#)
            .replace(r#""errors":1"#, r#""errors":0"#);
        assert_eq!(parse_audit(&warned), Some(Vec::new()));
    }

    #[test]
    fn every_toml_spelling_of_a_section_widens_the_check_list() {
        // All of these configure cargo-deny's `bans` check. A spelling the
        // derivation misses is a policy the team believes is enforced and is
        // not — silently, on both sides.
        for policy in [
            "[bans]\n",
            "[ bans ]\n",
            "[bans] # inline note\n",
            "[bans.build]\n",
            "[[bans.deny]]\n",
            "bans.deny = []\n",
            "bans = { multiple-versions = \"allow\" }\n",
            "[\"bans\"]\n",
            "['bans']\n",
        ] {
            assert!(
                policy_checks(policy).contains(&"bans".to_owned()),
                "not detected: {policy:?}"
            );
        }
        // And these do not.
        for policy in ["[bansible]\n", "[advisories]\n", "# [bans]\n", "#[bans]\n"] {
            assert_eq!(
                policy_checks(policy),
                vec!["advisories".to_owned()],
                "wrongly detected: {policy:?}"
            );
        }
    }

    #[test]
    fn an_unparseable_policy_falls_back_to_a_line_scan() {
        // cargo-deny refuses to load such a file, so the fallback only has to
        // avoid claiming the declared sections vanished.
        let broken = "[bans]\nthis is not toml =\n";
        assert!(broken.parse::<toml::Table>().is_err());
        assert!(policy_checks(broken).contains(&"bans".to_owned()));
    }

    #[test]
    fn the_line_scan_fallback_ignores_non_ascii_indentation() {
        // Rust's `trim` strips U+00A0; POSIX `[[:space:]]` does not. The
        // fallback is the rule the scaffolded workflow mirrors in shell, so it
        // must not see what grep cannot.
        assert!(!line_declares(code_of("\u{00A0}[bans]"), "bans"));
        assert!(line_declares(code_of("  [bans]"), "bans"));
    }

    #[test]
    fn a_home_or_cargo_home_prefix_is_expanded() {
        // cargo-deny expands these; reading them literally makes doctor report
        // a database that exists as never fetched.
        let home = Some("/home/tester");
        let cargo = Some("/home/tester/.cargo");
        assert_eq!(
            expand_path_with("~/mirror", home, cargo),
            "/home/tester/mirror"
        );
        assert_eq!(
            expand_path_with("$CARGO_HOME/advisory-dbs", home, cargo),
            "/home/tester/.cargo/advisory-dbs"
        );
        assert_eq!(
            expand_path_with("${CARGO_HOME}/advisory-dbs", home, cargo),
            "/home/tester/.cargo/advisory-dbs"
        );
        assert_eq!(expand_path_with("/srv/db", home, cargo), "/srv/db");
        // No HOME to expand with: the path is left alone rather than mangled.
        assert_eq!(expand_path_with("~/mirror", None, None), "~/mirror");
    }

    #[test]
    fn a_db_path_is_read_through_quoting_and_comments() {
        // The parser handles TOML literal strings, escapes and trailing
        // comments; hand-slicing the source text did not.
        assert_eq!(
            policy_db_path("[advisories]\ndb-path = '/srv/db#1'\n").as_deref(),
            Some("/srv/db#1")
        );
        assert_eq!(
            policy_db_path("[advisories]\ndb-path = \"/srv/db\" # mirrored nightly\n").as_deref(),
            Some("/srv/db")
        );
        // cargo-deny reads this key from `[advisories]`; a stray top-level one
        // configures nothing.
        assert_eq!(policy_db_path("db-path = \"/srv/db\"\n"), None);
        assert_eq!(policy_db_path("[advisories]\n"), None);
        assert_eq!(policy_db_path("# db-path = \"/nope\"\n"), None);
    }

    #[test]
    fn the_policy_is_found_from_inside_a_workspace_member() {
        // CI runs the audit at the repository root. A developer in a member
        // crate must get that graph, not "no policy".
        let root = tempfile::tempdir().expect("tempdir");
        std::fs::write(root.path().join(POLICY_FILE), "[advisories]\n").expect("policy");
        let member = root.path().join("crates").join("app");
        std::fs::create_dir_all(&member).expect("member");
        assert_eq!(
            find_policy_root(&member).map(|found| found.canonicalize().expect("canonical")),
            Some(root.path().canonicalize().expect("canonical"))
        );
    }

    #[test]
    fn the_outermost_policy_wins_over_a_workspace_members() {
        // CI reads the root policy. A member policy must not replace it.
        let root = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(root.path().join(".git")).expect("git");
        std::fs::write(root.path().join(POLICY_FILE), "[advisories]\n").expect("policy");
        let member = root.path().join("crates").join("app");
        std::fs::create_dir_all(&member).expect("member");
        std::fs::write(member.join(POLICY_FILE), "[bans]\n").expect("member policy");
        assert_eq!(
            find_policy_root(&member).map(|found| found.canonicalize().expect("canonical")),
            Some(root.path().canonicalize().expect("canonical"))
        );
    }

    #[test]
    fn the_outermost_policy_search_still_stops_at_the_repository_root() {
        // A policy above the `.git` boundary is not part of this repository.
        let outer = tempfile::tempdir().expect("tempdir");
        std::fs::write(outer.path().join(POLICY_FILE), "[bans]\n").expect("outer policy");
        let repo = outer.path().join("repo");
        std::fs::create_dir_all(repo.join(".git")).expect("git");
        std::fs::write(repo.join(POLICY_FILE), "[advisories]\n").expect("policy");
        assert_eq!(
            find_policy_root(&repo).map(|found| found.canonicalize().expect("canonical")),
            Some(repo.canonicalize().expect("canonical"))
        );
    }

    #[test]
    fn without_a_repository_root_the_nearest_policy_wins() {
        // No `.git` bounds the walk, so an outer policy may be a stray file.
        let outer = tempfile::tempdir().expect("tempdir");
        std::fs::write(outer.path().join(POLICY_FILE), "[bans]\n").expect("outer policy");
        let app = outer.path().join("app");
        std::fs::create_dir_all(&app).expect("app");
        std::fs::write(app.join(POLICY_FILE), "[advisories]\n").expect("policy");
        assert_eq!(
            find_policy_root(&app).map(|found| found.canonicalize().expect("canonical")),
            Some(app.canonicalize().expect("canonical"))
        );
    }

    #[test]
    fn the_outermost_of_three_policies_wins() {
        let root = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(root.path().join(".git")).expect("git");
        let member = root.path().join("crates").join("app");
        std::fs::create_dir_all(&member).expect("member");
        for dir in [root.path(), &root.path().join("crates"), &member] {
            std::fs::write(dir.join(POLICY_FILE), "[advisories]\n").expect("policy");
        }
        assert_eq!(
            find_policy_root(&member).map(|found| found.canonicalize().expect("canonical")),
            Some(root.path().canonicalize().expect("canonical"))
        );
    }

    #[test]
    fn a_nested_workspace_keeps_its_own_policy() {
        // A nested workspace has its own lockfile and graph. The outer policy
        // does not cover it.
        let root = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(root.path().join(".git")).expect("git");
        std::fs::write(root.path().join(POLICY_FILE), "[bans]\n").expect("policy");
        let nested = root.path().join("examples").join("flock");
        std::fs::create_dir_all(&nested).expect("nested");
        std::fs::write(nested.join(POLICY_FILE), "[advisories]\n").expect("nested policy");
        std::fs::write(nested.join("Cargo.toml"), "[workspace]\nmembers = []\n").expect("manifest");
        assert_eq!(
            find_policy_root(&nested).map(|found| found.canonicalize().expect("canonical")),
            Some(nested.canonicalize().expect("canonical"))
        );
    }

    #[test]
    fn the_search_for_a_policy_stops_at_the_repository_root() {
        let outer = tempfile::tempdir().expect("tempdir");
        std::fs::write(outer.path().join(POLICY_FILE), "[advisories]\n").expect("policy");
        let repo = outer.path().join("repo");
        std::fs::create_dir_all(repo.join(".git")).expect("git");
        assert_eq!(find_policy_root(&repo), None);
    }

    #[test]
    fn a_fetch_marker_newer_than_the_checkout_sets_the_age() {
        // `.git/FETCH_HEAD` is written by every fetch, including one that finds
        // nothing new. It is the freshest signal available and must win over an
        // older checkout directory.
        let dbs = tempfile::tempdir().expect("tempdir");
        let git = dbs.path().join("advisory-db-abc").join(".git");
        std::fs::create_dir_all(&git).expect("git dir");
        let from_dirs = newest_db_mtime(dbs.path()).expect("mtime");
        std::thread::sleep(std::time::Duration::from_millis(20));
        std::fs::write(git.join("FETCH_HEAD"), "ref").expect("fetch marker");
        let from_marker = newest_db_mtime(dbs.path()).expect("mtime");
        assert!(
            from_marker >= from_dirs,
            "the fetch marker must not read older than the checkout"
        );
    }

    #[test]
    fn a_fetch_into_an_existing_checkout_refreshes_the_age() {
        // A fetch writes inside `.git` and never touches the checkout's own
        // directory, so reading the root alone reports this morning's fetch as
        // months old.
        let dbs = tempfile::tempdir().expect("tempdir");
        let checkout = dbs.path().join("advisory-db-abc");
        std::fs::create_dir(&checkout).expect("checkout");
        let root_mtime = newest_db_mtime(dbs.path()).expect("mtime");
        std::fs::create_dir(checkout.join(".git")).expect("git");
        let fetched = newest_db_mtime(dbs.path()).expect("mtime");
        assert!(
            fetched >= root_mtime,
            "a fetch must not read as older than the clone"
        );
    }

    // ── age_days ─────────────────────────────────────────────────────────────

    #[test]
    fn age_is_whole_days_and_never_negative() {
        let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(90 * 86_400);
        let then = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(88 * 86_400 + 100);
        assert_eq!(age_days(then, now), 1);
        // A clock that moved backwards reads as fresh, never as a huge age.
        assert_eq!(age_days(now, then), 0);
    }

    #[test]
    fn a_missing_database_directory_has_no_mtime() {
        let dir = tempfile::tempdir().expect("tempdir");
        assert_eq!(newest_db_mtime(&dir.path().join("absent")), None);
        // An empty directory holds no database either.
        assert_eq!(newest_db_mtime(dir.path()), None);
    }

    #[test]
    fn the_newest_database_checkout_sets_the_age() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(dir.path().join("advisory-db-1")).expect("mkdir");
        assert!(newest_db_mtime(dir.path()).is_some());
    }

    // ── dev_lines ────────────────────────────────────────────────────────────

    #[test]
    fn a_clean_tree_adds_no_lines_to_dev_output() {
        assert!(dev_lines(&audited(Vec::new())).is_empty());
    }

    #[test]
    fn dev_stays_silent_when_the_policy_cannot_be_evaluated() {
        // Offline, no auditor, no policy: dev says nothing. Doctor is where
        // those are reported.
        for eval in [
            Evaluation::NoPolicy,
            Evaluation::AuditorMissing { checks: Vec::new() },
            Evaluation::DatabaseMissing { checks: Vec::new() },
            Evaluation::Unavailable {
                reason: "cargo metadata failed".to_owned(),
                checks: Vec::new(),
            },
        ] {
            assert!(dev_lines(&eval).is_empty(), "{eval:?} must be silent");
        }
    }

    #[test]
    fn dev_stays_silent_when_every_finding_is_waived() {
        let eval = audited(vec![finding("RUSTSEC-1", Severity::Critical, true, false)]);
        assert!(dev_lines(&eval).is_empty());
    }

    #[test]
    fn a_non_critical_tree_gets_exactly_one_dev_line() {
        let eval = audited(vec![
            finding("RUSTSEC-1", Severity::High, false, true),
            finding("RUSTSEC-2", Severity::Low, false, false),
        ]);
        let lines = dev_lines(&eval);
        assert_eq!(lines.len(), 1, "got {lines:?}");
        assert!(
            lines[0].contains('1'),
            "the count must appear: {}",
            lines[0]
        );
        assert!(
            lines[0].contains("high"),
            "the worst severity must appear: {}",
            lines[0]
        );
        assert!(
            lines[0].contains("autumn doctor"),
            "the line must say where detail lives: {}",
            lines[0]
        );
    }

    #[test]
    fn a_critical_finding_gets_a_loud_banner() {
        let eval = audited(vec![finding(
            "RUSTSEC-2099-0001",
            Severity::Critical,
            false,
            true,
        )]);
        let lines = dev_lines(&eval);
        assert!(
            lines.len() > 1,
            "a critical finding is not a one-liner: {lines:?}"
        );
        let banner = lines.join("\n");
        assert!(banner.contains("CRITICAL"), "{banner}");
        assert!(banner.contains("RUSTSEC-2099-0001"), "{banner}");
        assert!(banner.contains("autumn doctor"), "{banner}");
    }
}