Skip to main content

greengate_runtime/hooks/
audit.rs

1//! Dependency-vulnerability audits, with the severity the push deserves.
2//!
3//! The same policy the release workflow enforces in CI, brought to the
4//! machine where the push starts: an advisory against the dependency tree
5//! is INFORMATION on a branch push — named, never blocking, retried for
6//! free tomorrow — and a REFUSAL on a push that carries a `v*` tag, because
7//! a tag is a release leaving the building and immutable registries do not
8//! take anything back. The hook advises early; CI (for repositories that
9//! have it) enforces finally.
10//!
11//! One check per ecosystem amont already speaks — `cargo audit` for Rust,
12//! `npm audit` / `pnpm audit` for JS, `pip-audit` for Python — each opted
13//! in by the lockfile its tool actually audits. No lockfile, no check: an audit
14//! without a resolved tree audits a guess.
15//!
16//! Three verdicts, learned the hard way in ci.yaml's advisory job and kept
17//! here: the tools' OUTPUT decides, not the exit code alone, because every
18//! one of them conflates "found vulnerabilities" with "could not fetch the
19//! advisory database" in its exit status. And "could not check" is spoken
20//! loudly but never blocks — [`crate::check::Outcome::Unavailable`]'s
21//! contract: a hook may be offline, and a push gate that fails on a captive
22//! portal teaches `--no-verify`. The release workflow, which is never
23//! offline, is where an unchecked tree refuses to ship.
24
25use crate::check::Outcome;
26use crate::pushrefs::PushRef;
27
28use super::common;
29
30/// What an audit's output said, before the push's stakes are applied.
31#[derive(Debug, Clone, PartialEq, Eq)]
32enum Report {
33    Clean,
34    /// Warning-class advisories (unmaintained/unsound) — named, never
35    /// blocking anywhere: a gate nothing can pass is a gate people delete.
36    Advisories(Vec<String>),
37    /// Real vulnerabilities. Blocking iff the push carries a `v*` tag.
38    Vulnerabilities(Vec<String>),
39    /// The tool ran but could not answer (no network, no database).
40    CouldNotCheck,
41}
42
43/// Does this push carry a release? `v` + digit, so `v1.6.6` and `v2` gate
44/// while a tag that merely starts with a letter v (`vendor-drop`) does not.
45/// Deletes push no code and carry nothing.
46fn releasing(refs: &[PushRef]) -> bool {
47    refs.iter().any(|r| {
48        r.remote_ref
49            .strip_prefix("refs/tags/")
50            .and_then(|t| t.strip_prefix('v'))
51            .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
52    })
53}
54
55/// Apply the push's stakes to the tool's report. `full` is the captured
56/// output, reprinted only when the verdict blocks — that is the moment the
57/// reader needs the table, and the only moment worth the scrollback.
58/// `waivable` is false when something in the report
59/// could not be attributed (a project the audit could not answer for, a
60/// finding without a recognised id): a waiver must never vouch for what
61/// nobody saw.
62fn conclude_waivable(
63    settings: &crate::config::Settings,
64    tool: &str,
65    report: Report,
66    releasing: bool,
67    full: &str,
68    waivable: bool,
69) -> Outcome {
70    match report {
71        Report::Clean => {
72            common::ok(settings, &format!("{tool}: no known vulnerabilities"));
73            Outcome::Passed
74        }
75        Report::Advisories(ids) => {
76            common::warn(&format!(
77                "{tool}: advisories against the dependency tree (warnings — unmaintained/unsound): {}",
78                ids.join(", ")
79            ));
80            Outcome::Warned
81        }
82        Report::Vulnerabilities(what) => {
83            let waivers = Waivers::load(&common::repo_root(), today());
84            // The ids the verdict names first; the tool's report when the
85            // verdict is a summary line (npm, pnpm).
86            let mut ids = advisory_ids(&what.join(" "));
87            if ids.is_empty() {
88                ids = advisory_ids(full);
89            }
90            let unwaived: Vec<&String> = ids.iter().filter(|id| !waivers.covers(id)).collect();
91            let all_waived = waivable && !ids.is_empty() && unwaived.is_empty();
92            if releasing {
93                if all_waived {
94                    common::warn(&format!(
95                        "{tool}: known vulnerabilities shipped under a reviewed waiver \
96                         ({WAIVERS_FILE}) — not blocking this release: {}",
97                        ids.iter()
98                            .map(|id| waivers.describe(id))
99                            .collect::<Vec<_>>()
100                            .join("; ")
101                    ));
102                    return Outcome::Warned;
103                }
104                for line in full.lines() {
105                    crate::say!("{line}");
106                }
107                for note in waivers.problems() {
108                    common::warn(&format!("{tool}: {note}"));
109                }
110                common::fail(&format!(
111                    "{tool}: known vulnerabilities in the dependency tree — a v* tag \
112                     does not ship with these: {}{}",
113                    what.join(", "),
114                    if ids.is_empty() {
115                        " (no advisory id to match a waiver against)".to_string()
116                    } else {
117                        format!(
118                            " — not waived: {}",
119                            unwaived
120                                .iter()
121                                .map(|s| s.as_str())
122                                .collect::<Vec<_>>()
123                                .join(", ")
124                        )
125                    }
126                ));
127                Outcome::Failed
128            } else if all_waived {
129                common::warn(&format!(
130                    "{tool}: known vulnerabilities ({}) — covered by a reviewed waiver \
131                     ({WAIVERS_FILE}), so a v* tag push will pass while it holds: {}",
132                    what.join(", "),
133                    ids.iter()
134                        .map(|id| waivers.describe(id))
135                        .collect::<Vec<_>>()
136                        .join("; ")
137                ));
138                Outcome::Warned
139            } else {
140                common::warn(&format!(
141                    "{tool}: known vulnerabilities in the dependency tree ({}) — \
142                     this will BLOCK a v* tag push",
143                    what.join(", ")
144                ));
145                Outcome::Warned
146            }
147        }
148        Report::CouldNotCheck => {
149            common::warn(&format!(
150                "{tool} could not complete — the dependency tree was NOT checked. \
151                 This is not a clean result."
152            ));
153            Outcome::Unavailable
154        }
155    }
156}
157
158/// Where a repository records the advisories a release may ship anyway.
159const WAIVERS_FILE: &str = ".amont-audit-waivers";
160
161/// How far ahead a waiver may run. A waiver is a decision to revisit, not
162/// an exemption: one dated further out is void, so nothing is waived for
163/// good by accident.
164const MAX_WAIVER_DAYS: i64 = 90;
165
166/// One line of the waiver file: `<advisory id> <expires YYYY-MM-DD> <reason>`.
167#[derive(Debug)]
168struct Waiver {
169    id: String,
170    expires: String,
171    reason: String,
172    valid: bool,
173}
174
175/// The repository's reviewed waivers, judged against today.
176///
177/// A waiver lets a RELEASE ship a known vulnerability nobody can fix yet —
178/// an advisory with no patched version, on a path the project cannot
179/// replace. It is committed (so it is reviewed like code), names its
180/// reason, and expires: past its date, or dated more than
181/// [`MAX_WAIVER_DAYS`] ahead, it waives nothing and the tag is refused
182/// again. Branch pushes never consult it — they never block.
183#[derive(Debug, Default)]
184struct Waivers {
185    entries: Vec<Waiver>,
186    problems: Vec<String>,
187}
188
189impl Waivers {
190    fn load(root: &str, today: i64) -> Self {
191        match std::fs::read_to_string(std::path::Path::new(root).join(WAIVERS_FILE)) {
192            Ok(text) => Self::parse(&text, today),
193            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
194            Err(e) => Self {
195                entries: Vec::new(),
196                problems: vec![format!(
197                    "{WAIVERS_FILE} could not be read ({e}) — it waives nothing"
198                )],
199            },
200        }
201    }
202
203    fn parse(text: &str, today: i64) -> Self {
204        let mut w = Self::default();
205        for line in text.lines().map(str::trim) {
206            if line.is_empty() || line.starts_with('#') {
207                continue;
208            }
209            let mut parts = line.splitn(3, char::is_whitespace);
210            let id = parts.next().unwrap_or_default().to_string();
211            let expires = parts.next().unwrap_or_default().trim().to_string();
212            let reason = parts.next().unwrap_or_default().trim().to_string();
213            let valid = match days_from_date(&expires) {
214                None => {
215                    w.problems.push(format!(
216                        "waiver for {id} has no readable expiry date (YYYY-MM-DD) — it waives nothing"
217                    ));
218                    false
219                }
220                Some(_) if reason.is_empty() => {
221                    w.problems.push(format!(
222                        "waiver for {id} gives no reason — it waives nothing"
223                    ));
224                    false
225                }
226                Some(d) if d < today => {
227                    w.problems
228                        .push(format!("waiver for {id} expired on {expires}"));
229                    false
230                }
231                Some(d) if d - today > MAX_WAIVER_DAYS => {
232                    w.problems.push(format!(
233                        "waiver for {id} runs to {expires}, more than {MAX_WAIVER_DAYS} days \
234                         ahead — it waives nothing; date it sooner and revisit"
235                    ));
236                    false
237                }
238                Some(_) => true,
239            };
240            w.entries.push(Waiver {
241                id,
242                expires,
243                reason,
244                valid,
245            });
246        }
247        w
248    }
249
250    fn covers(&self, id: &str) -> bool {
251        self.entries.iter().any(|w| w.valid && w.id == id)
252    }
253
254    fn describe(&self, id: &str) -> String {
255        match self.entries.iter().find(|w| w.valid && w.id == id) {
256            Some(w) => format!("{id} until {} ({})", w.expires, w.reason),
257            None => id.to_string(),
258        }
259    }
260
261    fn problems(&self) -> &[String] {
262        &self.problems
263    }
264}
265
266/// Days since 1970-01-01 for a `YYYY-MM-DD` date (proleptic Gregorian).
267fn days_from_date(date: &str) -> Option<i64> {
268    let mut it = date.split('-');
269    let (y, m, d): (i64, i64, i64) = (
270        it.next()?.parse().ok()?,
271        it.next()?.parse().ok()?,
272        it.next()?.parse().ok()?,
273    );
274    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
275    let month_days = [
276        31,
277        if leap { 29 } else { 28 },
278        31,
279        30,
280        31,
281        30,
282        31,
283        31,
284        30,
285        31,
286        30,
287        31,
288    ];
289    if it.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > month_days[(m - 1) as usize] {
290        return None;
291    }
292    // Howard Hinnant's days_from_civil.
293    let y = if m <= 2 { y - 1 } else { y };
294    let era = if y >= 0 { y } else { y - 399 } / 400;
295    let yoe = y - era * 400;
296    let mp = (m + 9) % 12;
297    let doy = (153 * mp + 2) / 5 + d - 1;
298    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
299    Some(era * 146_097 + doe - 719_468)
300}
301
302/// Today, in days since the epoch (UTC).
303fn today() -> i64 {
304    std::time::SystemTime::now()
305        .duration_since(std::time::UNIX_EPOCH)
306        .map(|d| (d.as_secs() / 86_400) as i64)
307        .unwrap_or(0)
308}
309
310/// Every advisory id in `text`: GitHub (`GHSA-xxxx-xxxx-xxxx`), RustSec,
311/// Go, PyPA and CVE ids, wherever they sit (a URL, a table cell).
312fn advisory_ids(text: &str) -> Vec<String> {
313    let mut ids: Vec<String> = text
314        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
315        .filter(|w| {
316            let parts: Vec<&str> = w.split('-').collect();
317            match parts.as_slice() {
318                ["GHSA", a, b, c] => [a, b, c]
319                    .iter()
320                    .all(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphanumeric())),
321                ["RUSTSEC" | "GO" | "PYSEC" | "CVE" | "OSV", year, num] => {
322                    year.len() == 4
323                        && year.bytes().all(|b| b.is_ascii_digit())
324                        && !num.is_empty()
325                        && num.bytes().all(|b| b.is_ascii_digit())
326                }
327                _ => false,
328            }
329        })
330        .map(str::to_string)
331        .collect();
332    ids.sort();
333    ids.dedup();
334    ids
335}
336
337/// Is this word a RUSTSEC id? `RUSTSEC-` + 4 digits + `-` + 4 digits.
338fn is_advisory_id(w: &str) -> bool {
339    w.len() == 17
340        && w.starts_with("RUSTSEC-")
341        && w[8..12].bytes().all(|b| b.is_ascii_digit())
342        && w.as_bytes()[12] == b'-'
343        && w[13..17].bytes().all(|b| b.is_ascii_digit())
344}
345
346/// Pair each advisory with the crate it was raised against.
347///
348/// `cargo audit`'s terminal report is blocks — `Crate:` … `ID:` — and the
349/// id alone does not say which crate carries it, let alone which of YOUR
350/// crates depends on that. Answering "is this on the commit path or only in
351/// an opt-in tool?" meant running `cargo tree -i` by hand every time.
352///
353/// A `Crate:` binds to the next `ID:` and is then spent, so an id appearing
354/// outside a block — a summary line, a URL — reports no crate rather than
355/// inheriting the previous block's.
356fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
357    let mut pairs: Vec<(String, Option<String>)> = Vec::new();
358    let mut pending: Option<String> = None;
359    for line in out.lines() {
360        let t = line.trim();
361        if let Some(rest) = t.strip_prefix("Crate:") {
362            pending = rest.split_whitespace().next().map(str::to_string);
363            continue;
364        }
365        if let Some(rest) = t.strip_prefix("ID:") {
366            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
367                pairs.push((id.to_string(), pending.take()));
368                continue;
369            }
370        }
371        // Ids outside a block still count — the older summary-line shapes
372        // and anything cargo audit prints loose.
373        for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
374            pairs.push((w.to_string(), None));
375        }
376    }
377    pairs
378}
379
380/// Which of THIS workspace's crates reach `crate`, read from `cargo tree -i`.
381///
382/// Cargo prints a local package with its path in parentheses and a registry
383/// package without one, which is the only discriminator needed and works in
384/// any repository — the hook cannot know a given workspace's member names.
385///
386/// An empty result is an answer, not a failure: `cargo tree` prints
387/// "nothing to print" for a crate that is in `Cargo.lock` but not in the
388/// build graph. `cargo audit` reads the lock file, so an advisory can name a
389/// crate nothing compiles — an optional dependency of a feature nobody
390/// enabled. Saying so is more useful than naming no crate at all.
391fn local_dependents(tree_out: &str) -> Vec<String> {
392    let mut names: Vec<String> = tree_out
393        .lines()
394        .filter(|l| l.contains(" (/"))
395        .filter_map(|l| {
396            l.split_whitespace()
397                .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
398                .map(str::to_string)
399        })
400        .collect();
401    names.sort();
402    names.dedup();
403    names
404}
405
406/// One advisory, said in full: the id, the crate it is against, and which of
407/// this workspace's crates actually reach it.
408fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
409    match (krate, reaches.is_empty()) {
410        (None, _) => id.to_string(),
411        (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
412        (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
413    }
414}
415
416/// `cargo audit`, ci.yaml's rules verbatim: the RUSTSEC ids decide, the
417/// exit code only says which class they are.
418fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
419    let mut ids: Vec<String> = out
420        .split_whitespace()
421        .filter(|w| {
422            w.len() == 17
423                && w.starts_with("RUSTSEC-")
424                && w[8..12].bytes().all(|b| b.is_ascii_digit())
425                && w.as_bytes()[12] == b'-'
426                && w[13..17].bytes().all(|b| b.is_ascii_digit())
427        })
428        .map(|w| w.to_string())
429        .collect();
430    ids.sort();
431    ids.dedup();
432    match (ids.is_empty(), exit_ok) {
433        (true, true) => Report::Clean,
434        (true, false) => Report::CouldNotCheck,
435        (false, true) => Report::Advisories(ids),
436        (false, false) => Report::Vulnerabilities(ids),
437    }
438}
439
440/// `npm audit`: the summary line decides. A clean tree is `found 0
441/// vulnerabilities` on every npm. A finding is `found N vulnerabilities`
442/// on npm 6 and `N vulnerabilities (a moderate, b high)` — the verb dropped,
443/// `1 vulnerability` in the singular — on npm 7 and later, which is every
444/// npm shipped since 2020. No recognisable summary plus a refusal to exit
445/// clean is a tool that never answered.
446fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
447    let summary = out.lines().rev().map(str::trim).find(|l| {
448        l.contains("vulnerabilit")
449            && (l.starts_with("found ")
450                || l.split_whitespace()
451                    .next()
452                    .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
453    });
454    match summary {
455        Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
456        Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
457        None if exit_ok => Report::Clean,
458        None => Report::CouldNotCheck,
459    }
460}
461
462/// `pnpm audit`: the summary line decides. A clean tree is `No known
463/// vulnerabilities found`; a finding is `N vulnerabilities found` followed by
464/// `Severity: a low | b moderate | …`, which is carried along so the warning
465/// says how bad. No recognisable summary plus a refusal to exit clean is a
466/// tool that never answered (`ERR_PNPM_AUDIT_BAD_RESPONSE`, no network).
467fn read_pnpm_audit(exit_ok: bool, out: &str) -> Report {
468    let lines: Vec<&str> = out.lines().map(str::trim).collect();
469    if lines
470        .iter()
471        .any(|l| l.starts_with("No known vulnerabilities found"))
472    {
473        return Report::Clean;
474    }
475    let found = lines.iter().enumerate().rev().find(|(_, l)| {
476        let mut w = l.split_whitespace();
477        w.next()
478            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
479            && w.next().is_some_and(|v| v.starts_with("vulnerabilit"))
480            && w.next() == Some("found")
481    });
482    match found {
483        Some((_, l)) if l.starts_with("0 ") => Report::Clean,
484        Some((i, l)) => {
485            let severity = lines
486                .get(i + 1)
487                .and_then(|n| n.strip_prefix("Severity:"))
488                .map(str::trim);
489            Report::Vulnerabilities(vec![match severity {
490                Some(sev) => format!("{l} ({sev})"),
491                None => l.to_string(),
492            }])
493        }
494        None if exit_ok => Report::Clean,
495        None => Report::CouldNotCheck,
496    }
497}
498
499/// `govulncheck`: the GO- ids decide, the exit code classifies them — the
500/// same split cargo-audit taught. The tool exits non-zero only when the
501/// analysed CODE is affected; ids with a clean exit are the informational
502/// section (vulnerable modules whose functions are never called), which is
503/// advisory-grade. No ids plus a refusal to exit clean is a tool that never
504/// answered (no network, no vulnerability database).
505fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
506    let mut ids: Vec<String> = out
507        .split_whitespace()
508        .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
509        .filter(|w| {
510            w.len() >= 12
511                && w.starts_with("GO-")
512                && w[3..7].bytes().all(|b| b.is_ascii_digit())
513                && w.as_bytes()[7] == b'-'
514                && w[8..].bytes().all(|b| b.is_ascii_digit())
515        })
516        .map(|w| w.to_string())
517        .collect();
518    ids.sort();
519    ids.dedup();
520    match (ids.is_empty(), exit_ok) {
521        (true, true) => Report::Clean,
522        (true, false) => Report::CouldNotCheck,
523        (false, true) => Report::Advisories(ids),
524        (false, false) => Report::Vulnerabilities(ids),
525    }
526}
527
528/// `pip-audit`: its own closing sentence decides.
529fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
530    if out.contains("No known vulnerabilities found") {
531        return Report::Clean;
532    }
533    if let Some(line) = out
534        .lines()
535        .map(str::trim)
536        .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
537    {
538        return Report::Vulnerabilities(vec![line.to_string()]);
539    }
540    if exit_ok {
541        Report::Clean
542    } else {
543        Report::CouldNotCheck
544    }
545}
546
547/// The `site-packages` of the environment this project actually uses, if
548/// one is on disk.
549///
550/// `$VIRTUAL_ENV` first — an activated environment is the one whose imports
551/// are live — then the `.venv` uv and PEP 668 tooling create by convention.
552/// Layout differs by platform: `lib/python3.13/site-packages` everywhere
553/// except Windows, which uses `Lib/site-packages`, so the python-version
554/// directory is discovered rather than guessed.
555fn venv_site_packages(root: &str, source: Option<&std::path::Path>) -> Option<String> {
556    // A rehearsal snapshot installs no virtualenv; the working tree it was
557    // taken from (`source`) holds one, but it answers for THIS commit only
558    // when that tree is this commit with its Python manifests unmodified: a
559    // `.venv` synced to a newer HEAD would vouch for a tag it never held
560    // (ADR-0018).
561    let source_venv = source
562        .filter(|src| {
563            let answers = source_is_this_commit(src);
564            if !answers {
565                common::warn(
566                    "audit-python: the source worktree's virtualenv is not this commit's \
567                     (another HEAD, or modified Python manifests) — not auditing it",
568                );
569            }
570            answers
571        })
572        .map(|src| src.join(".venv"));
573    let candidates = std::env::var_os("VIRTUAL_ENV")
574        .map(std::path::PathBuf::from)
575        .into_iter()
576        .chain(std::iter::once(std::path::Path::new(root).join(".venv")))
577        .chain(source_venv);
578    for venv in candidates {
579        let windows = venv.join("Lib").join("site-packages");
580        if windows.is_dir() {
581            return Some(windows.to_string_lossy().into_owned());
582        }
583        let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
584            continue;
585        };
586        for e in entries.flatten() {
587            if !e.file_name().to_string_lossy().starts_with("python") {
588                continue;
589            }
590            let sp = e.path().join("site-packages");
591            if sp.is_dir() {
592                return Some(sp.to_string_lossy().into_owned());
593            }
594        }
595    }
596    None
597}
598
599/// Run one audit tool from the repo root and read its answer.
600fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
601    audited_in(settings, argv, std::path::Path::new(&common::repo_root()))
602}
603
604/// Run one audit tool from `dir` and read its answer.
605fn audited_in(
606    settings: &crate::config::Settings,
607    argv: &[String],
608    dir: &std::path::Path,
609) -> Option<(bool, String)> {
610    let mut cmd = std::process::Command::new(&argv[0]);
611    cmd.args(&argv[1..])
612        .current_dir(dir)
613        .stdin(std::process::Stdio::null());
614    common::strip_git_env(&mut cmd);
615    let (ran, out) = common::capture_within(settings, &mut cmd)?;
616    match ran {
617        common::Ran::Status(s) => Some((s.success(), out)),
618        common::Ran::TimedOut(budget) => {
619            common::say_timed_out(&argv[0], budget);
620            None
621        }
622    }
623}
624
625/// The tool's own reason for not answering: its last line that says
626/// `error`, else its last non-empty line, clipped. "Could not complete" with
627/// nothing after it was the whole message once, over a tree with 19 known
628/// vulnerabilities (amont#305) — the next one must be readable from the hook
629/// output alone.
630fn failure_line(out: &str) -> Option<String> {
631    let lines: Vec<&str> = out
632        .lines()
633        .map(str::trim)
634        .filter(|l| !l.is_empty())
635        .collect();
636    let line = lines
637        .iter()
638        .rev()
639        .find(|l| l.to_ascii_lowercase().contains("error"))
640        .or(lines.last())?;
641    let mut s: String = line.chars().take(200).collect();
642    if line.chars().count() > 200 {
643        s.push('…');
644    }
645    Some(s)
646}
647
648/// What one audit found across every directory it ran in.
649struct Merged {
650    report: Report,
651    /// The tools' reports, each under a header naming its directory (the
652    /// bare report when the only directory is the root).
653    full: String,
654    waivable: bool,
655}
656
657/// Run one audit in every directory holding `lockfile` and merge the
658/// answers — the shape `js()` has had since a root-only run left a nested
659/// npm project unaudited. Rust, Go and Python kept the root-only runner, and
660/// a repository whose `Cargo.lock` lived in `apps/ui/src-tauri` was reported
661/// "could not complete" over 19 known vulnerabilities (amont#305).
662///
663/// `argv_in(dir)` builds the command for one directory, or None to skip it
664/// (said by the caller). `refine(dir, report, out)` runs in that directory
665/// after the read — a release's shipped-only split, attribution. A finding
666/// from a subdirectory is labelled with it; the root's are not, so a
667/// repository with its lockfile at the root reads exactly as before. A
668/// directory the tool could not answer for is named with the tool's own
669/// reason, and keeps the merged result from reading clean or being waived.
670fn audit_each_dir(
671    settings: &crate::config::Settings,
672    tool: &str,
673    lockfile: &str,
674    argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
675    read: fn(bool, &str) -> Report,
676    mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
677) -> Option<Merged> {
678    let root = std::path::PathBuf::from(common::repo_root());
679    let dirs = lockfile_dirs(lockfile);
680    let only_root = dirs.len() == 1 && dirs[0].is_empty();
681    let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
682    let mut full = String::new();
683    for dir in &dirs {
684        let path = root.join(dir);
685        let label = if dir.is_empty() { "." } else { dir.as_str() };
686        let label_ids = |ids: Vec<String>| -> Vec<String> {
687            if dir.is_empty() {
688                ids
689            } else {
690                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
691            }
692        };
693        let Some(argv) = argv_in(&path) else {
694            unchecked.push(format!("{label} (nothing to audit there)"));
695            continue;
696        };
697        // A timeout is said by `audited_in` itself; it is not an answer.
698        let (exit_ok, out) = audited_in(settings, &argv, &path)?;
699        match refine(&path, read(exit_ok, &out), &out) {
700            Report::Vulnerabilities(ids) => {
701                vulns.extend(label_ids(ids));
702                if only_root {
703                    full.push_str(&out);
704                } else {
705                    full.push_str(&format!("── {tool} in {label}\n{out}\n"));
706                }
707            }
708            Report::Advisories(ids) => advisories.extend(label_ids(ids)),
709            Report::CouldNotCheck => unchecked.push(match failure_line(&out) {
710                Some(why) => format!("{label} ({why})"),
711                None => label.to_string(),
712            }),
713            Report::Clean => {}
714        }
715    }
716    if !unchecked.is_empty() {
717        common::warn(&format!(
718            "{tool}: the audit could not answer in {} — NOT checked there",
719            unchecked.join(", ")
720        ));
721    }
722    let report = if !vulns.is_empty() {
723        Report::Vulnerabilities(vulns)
724    } else if !unchecked.is_empty() {
725        Report::CouldNotCheck
726    } else if !advisories.is_empty() {
727        Report::Advisories(advisories)
728    } else {
729        Report::Clean
730    };
731    Some(Merged {
732        report,
733        full,
734        waivable: unchecked.is_empty(),
735    })
736}
737
738fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
739    let (settings, refs) = (ctx.settings, ctx.push.get());
740    if !has_lockfile("Cargo.lock") {
741        return Ran::Inert;
742    }
743    if common::which("cargo-audit").is_none() {
744        common::warn(
745            "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
746             the audit did NOT run",
747        );
748        return Ran::Unavailable;
749    }
750    let argv = vec![
751        common::program("cargo"),
752        "audit".into(),
753        "--color".into(),
754        "never".into(),
755    ];
756    let release = releasing(refs);
757    let Some(merged) = audit_each_dir(
758        settings,
759        "audit-rust",
760        "Cargo.lock",
761        |_| Some(argv.clone()),
762        read_cargo_audit,
763        |dir, mut report, out| {
764            if release {
765                if let Report::Vulnerabilities(ids) = report {
766                    let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
767                        cargo_tree_shipped(settings, dir, krate)
768                    });
769                    warn_dev_only("audit-rust", &dev_only);
770                    report = if shipped.is_empty() {
771                        Report::Clean
772                    } else {
773                        Report::Vulnerabilities(shipped)
774                    };
775                }
776            }
777            attribute(report, out, |krate| {
778                cargo_tree_inverse(settings, dir, krate)
779            })
780        },
781    ) else {
782        return Ran::Unavailable;
783    };
784    Ran::Concluded(Concluded {
785        tool: "audit-rust".to_string(),
786        report: merged.report,
787        full: merged.full,
788        waivable: merged.waivable,
789    })
790}
791
792/// `cargo tree -i <crate>` over the edges a RELEASE ships: normal and build
793/// dependencies (a dependency's build script runs on every machine that
794/// compiles it), for every target and every feature, so nothing a consumer
795/// could switch on is mistaken for dev-only. None if it could not run.
796fn cargo_tree_shipped(
797    settings: &crate::config::Settings,
798    dir: &std::path::Path,
799    spec: &str,
800) -> Option<String> {
801    let argv = vec![
802        common::program("cargo"),
803        "tree".into(),
804        "--invert".into(),
805        spec.into(),
806        "--edges".into(),
807        "normal,build".into(),
808        "--target".into(),
809        "all".into(),
810        "--all-features".into(),
811        "--color".into(),
812        "never".into(),
813    ];
814    // Unlike the message-only inverse tree, a failure here must not read as
815    // "nothing reaches it": an error prints no local crate either.
816    audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
817}
818
819/// Does a shipped-edges inverse tree say the crate is dev-only? Only on
820/// positive evidence: no local crate reaches it AND cargo said there is
821/// nothing to print. Anything else — an unreadable tree — ships.
822fn tree_says_dev_only(tree: &str) -> bool {
823    local_dependents(tree).is_empty() && tree.contains("nothing to print")
824}
825
826/// Split a release's advisory ids into those that ship and those only the
827/// dev tree carries. An id whose crate is unknown, or whose tree could not
828/// be read, ships: an unknown is not a pass.
829fn split_shipped_crates(
830    ids: Vec<String>,
831    out: &str,
832    shipped_tree: impl Fn(&str) -> Option<String>,
833) -> (Vec<String>, Vec<String>) {
834    let specs = ids_with_specs(out);
835    let mut verdicts: Vec<(String, bool)> = Vec::new();
836    let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
837    for id in ids {
838        let spec = specs
839            .iter()
840            .find(|(pid, spec)| *pid == id && spec.is_some())
841            .and_then(|(_, spec)| spec.clone());
842        let ships = match spec {
843            None => true,
844            // Cached by name@version: two locked versions of one crate are
845            // two answers, and one being dev-only says nothing of the other.
846            Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
847                Some((_, v)) => *v,
848                None => {
849                    let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
850                    verdicts.push((spec, v));
851                    v
852                }
853            },
854        };
855        if ships {
856            shipped.push(id);
857        } else {
858            dev_only.push(id);
859        }
860    }
861    (shipped, dev_only)
862}
863
864/// Each advisory id with the package its OWN block names: `crate@version`
865/// when cargo audit printed a `Version:` in that block, the bare crate name
866/// otherwise, None for an id outside any block.
867fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
868    let mut pairs = Vec::new();
869    let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
870    for line in out.lines().map(str::trim) {
871        if let Some(rest) = line.strip_prefix("Crate:") {
872            krate = rest.split_whitespace().next().map(str::to_string);
873            version = None;
874        } else if let Some(rest) = line.strip_prefix("Version:") {
875            version = rest.split_whitespace().next().map(str::to_string);
876        } else if let Some(rest) = line.strip_prefix("ID:") {
877            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
878                let spec = krate.take().map(|k| match version.take() {
879                    Some(v) => format!("{k}@{v}"),
880                    None => k,
881                });
882                pairs.push((id.to_string(), spec));
883            }
884        }
885    }
886    pairs
887}
888
889/// Name what a release does not ship and therefore does not refuse.
890fn warn_dev_only(tool: &str, dev_only: &[String]) {
891    if !dev_only.is_empty() {
892        common::warn(&format!(
893            "{tool}: only in development dependencies, which the release does not ship — not blocking: {}",
894            dev_only.join("; ")
895        ));
896    }
897}
898
899/// `cargo tree -i <crate>`, or None if it could not be run. Failure here is
900/// never fatal: attribution is an improvement to a message, and an advisory
901/// reported without it is still an advisory reported.
902fn cargo_tree_inverse(
903    settings: &crate::config::Settings,
904    dir: &std::path::Path,
905    krate: &str,
906) -> Option<String> {
907    let argv = vec![
908        common::program("cargo"),
909        "tree".into(),
910        "--invert".into(),
911        krate.into(),
912        "--edges".into(),
913        "normal".into(),
914        "--color".into(),
915        "never".into(),
916    ];
917    audited_in(settings, &argv, dir).map(|(_, out)| out)
918}
919
920/// Name the crate behind each advisory, and which of this workspace's crates
921/// reach it.
922///
923/// Deliberately spawns NOTHING on a clean report, which is every run that
924/// matters: the `cargo tree` calls happen once per distinct affected crate,
925/// only when there is already something to say. A hook on the push path does
926/// not pay for a message nobody will read.
927fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
928    match report {
929        Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
930        Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
931        // Clean and CouldNotCheck carry no ids, so there is nothing to
932        // attribute and — the part that matters — nothing to spawn.
933        other => other,
934    }
935}
936
937/// Each id, rewritten with its crate and what reaches it where both are
938/// known. One `cargo tree` per distinct crate, not per advisory: `lru`
939/// carried two advisories in the run that prompted this.
940fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
941    let pairs = ids_with_crates(out);
942    let mut seen: Vec<(String, Vec<String>)> = Vec::new();
943    ids.iter()
944        .map(|id| {
945            let krate = pairs
946                .iter()
947                .find(|(pid, k)| pid == id && k.is_some())
948                .and_then(|(_, k)| k.clone());
949            let Some(k) = krate else {
950                return id.clone();
951            };
952            if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
953                return describe(id, Some(&k), reaches);
954            }
955            let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
956            seen.push((k.clone(), reaches.clone()));
957            describe(id, Some(&k), &reaches)
958        })
959        .collect()
960}
961
962/// Does the repository carry `lockfile` anywhere in its index? An audit
963/// without a resolved tree audits a guess — and one asked about a
964/// repository in another language has nothing to audit at all. That is
965/// `Inert`, not "could not run": the dispatcher asks the same question
966/// from the registry's scope, and this is the answer for a check invoked
967/// by name.
968fn has_lockfile(lockfile: &str) -> bool {
969    crate::tracked_paths()
970        .iter()
971        .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
972}
973
974/// The directories holding a tracked `lockfile`, repo-relative ("" for the
975/// root), sorted. npm resolves a project from its own directory, so a
976/// repository whose packages live in subdirectories (`web/`, `mcp/`) has no
977/// lockfile at the root at all.
978fn lockfile_dirs(lockfile: &str) -> Vec<String> {
979    let mut dirs: Vec<String> = crate::tracked_paths()
980        .iter()
981        .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
982        .map(|p| {
983            p.rsplit_once('/')
984                .map(|(d, _)| d.to_string())
985                .unwrap_or_default()
986        })
987        .collect();
988    dirs.sort();
989    dirs.dedup();
990    dirs
991}
992
993/// One JS package manager `audit-js` knows how to ask: the lockfile that
994/// opts a directory in, the tool that reads it, and how to read its answer.
995struct JsAuditor {
996    lockfile: &'static str,
997    tool: &'static str,
998    read: fn(bool, &str) -> Report,
999    /// Extra arguments for a project in `dir`.
1000    args: fn(&str) -> Vec<String>,
1001    /// The flag that limits the audit to what the project ships — its
1002    /// production dependencies, without the dev tree.
1003    prod_only: &'static str,
1004}
1005
1006/// pnpm answers for the WORKSPACE it finds above a directory, not for the
1007/// directory: a standalone project with its own pnpm-lock.yaml inside a
1008/// workspace (a spike, an example) was reported with the workspace root's
1009/// findings, all of them, under its own name. `--ignore-workspace` makes it
1010/// read the lockfile it stands next to — except at a workspace's own root,
1011/// where the workspace IS the project and every member must be audited.
1012fn pnpm_args(dir: &str) -> Vec<String> {
1013    let manifest = if dir.is_empty() {
1014        "pnpm-workspace.yaml".to_string()
1015    } else {
1016        format!("{dir}/pnpm-workspace.yaml")
1017    };
1018    if crate::tracked_paths().contains(&manifest) {
1019        vec![]
1020    } else {
1021        vec!["--ignore-workspace".into()]
1022    }
1023}
1024
1025const JS_AUDITORS: [JsAuditor; 2] = [
1026    JsAuditor {
1027        lockfile: "package-lock.json",
1028        tool: "npm",
1029        read: read_npm_audit,
1030        args: |_| vec![],
1031        prod_only: "--omit=dev",
1032    },
1033    JsAuditor {
1034        lockfile: "pnpm-lock.yaml",
1035        tool: "pnpm",
1036        read: read_pnpm_audit,
1037        args: pnpm_args,
1038        prod_only: "--prod",
1039    },
1040];
1041
1042/// `npm audit` in every directory that tracks a `package-lock.json`, and
1043/// `pnpm audit` in every directory that tracks a `pnpm-lock.yaml`.
1044///
1045/// It used to run once at the repository root, where a repository whose
1046/// packages live in subdirectories has no lockfile: npm answered ENOLOCK,
1047/// the check said "could not complete", and a tree with 17 known
1048/// vulnerabilities (9 high) went unaudited release after release. Each
1049/// project is audited on its own; any finding counts, labelled with its
1050/// directory, and a project the tool could not answer for keeps the whole
1051/// result from reading clean.
1052///
1053/// And it only ever knew npm: a pnpm workspace has no `package-lock.json`,
1054/// so its whole tree — 28 vulnerable versions, two critical, in one
1055/// repository — was never audited and nothing said so. pnpm audits its own
1056/// lockfile, from the lockfile alone, the same way.
1057///
1058/// On a release, what blocks is what SHIPS: a finding is audited again with
1059/// the production dependencies only (`--omit=dev` / `--prod`), and one that
1060/// lives only in the dev tree — a build script's toolchain, a test runner —
1061/// is named but does not refuse the tag. Nobody who installs the package
1062/// installs it. A finding whose production re-audit cannot answer still
1063/// blocks: an unknown is not a pass.
1064fn js_run(ctx: &crate::registry::Ctx) -> Ran {
1065    let (settings, refs) = (ctx.settings, ctx.push.get());
1066    let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
1067        .iter()
1068        .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
1069        .collect();
1070    if projects.is_empty() {
1071        return Ran::Inert;
1072    }
1073    let root = std::path::PathBuf::from(common::repo_root());
1074    let release = releasing(refs);
1075    let mut found = Vec::new();
1076    let mut dev_only = Vec::new();
1077    let mut unchecked = Vec::new();
1078    let mut full = String::new();
1079    for (auditor, dir) in &projects {
1080        let label = if dir.is_empty() {
1081            ".".to_string()
1082        } else {
1083            dir.clone()
1084        };
1085        let mut argv = vec![common::program(auditor.tool), "audit".into()];
1086        argv.extend((auditor.args)(dir));
1087        let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
1088            common::warn(&format!(
1089                "audit-js: {} could not run in {label} — the audit did NOT run",
1090                auditor.tool
1091            ));
1092            return Ran::Unavailable;
1093        };
1094        match (auditor.read)(exit_ok, &out) {
1095            Report::Vulnerabilities(what) if release => {
1096                let mut prod = argv.clone();
1097                prod.push(auditor.prod_only.into());
1098                match audited_in(settings, &prod, &root.join(dir))
1099                    .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
1100                {
1101                    Some((Report::Clean | Report::Advisories(_), _)) => {
1102                        dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1103                    }
1104                    Some((Report::Vulnerabilities(shipped), pout)) => {
1105                        found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
1106                        full.push_str(&format!(
1107                            "── {} audit {} in {label}\n{pout}\n",
1108                            auditor.tool, auditor.prod_only
1109                        ));
1110                    }
1111                    Some((Report::CouldNotCheck, _)) | None => {
1112                        found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1113                        full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1114                    }
1115                }
1116            }
1117            Report::Vulnerabilities(what) => {
1118                found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1119                full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1120            }
1121            Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
1122            Report::Clean | Report::Advisories(_) => {}
1123        }
1124    }
1125    if !unchecked.is_empty() {
1126        common::warn(&format!(
1127            "audit-js: the audit could not answer in {} — those projects were NOT checked",
1128            unchecked.join(", ")
1129        ));
1130    }
1131    warn_dev_only("audit-js", &dev_only);
1132    let waivable = unchecked.is_empty();
1133    let report = if !found.is_empty() {
1134        Report::Vulnerabilities(found)
1135    } else if !unchecked.is_empty() {
1136        Report::CouldNotCheck
1137    } else {
1138        Report::Clean
1139    };
1140    Ran::Concluded(Concluded {
1141        tool: "audit-js".to_string(),
1142        report,
1143        full,
1144        waivable,
1145    })
1146}
1147
1148/// Go needs no production filter: modules have no dev-dependency set, and
1149/// `govulncheck ./...` without `-test` reports only vulnerabilities the
1150/// module's non-test code can reach — what ships, already.
1151fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1152    let settings = ctx.settings;
1153    if !has_lockfile("go.sum") {
1154        return Ran::Inert;
1155    }
1156    if common::which("govulncheck").is_none() {
1157        common::warn(
1158            "audit-go: govulncheck is not installed \
1159             (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1160        );
1161        return Ran::Unavailable;
1162    }
1163    let argv = vec![common::program("govulncheck"), "./...".into()];
1164    let Some(merged) = audit_each_dir(
1165        settings,
1166        "audit-go",
1167        "go.sum",
1168        |_| Some(argv.clone()),
1169        read_govulncheck,
1170        |_, report, _| report,
1171    ) else {
1172        return Ran::Unavailable;
1173    };
1174    Ran::Concluded(Concluded {
1175        tool: "audit-go".to_string(),
1176        report: merged.report,
1177        full: merged.full,
1178        waivable: merged.waivable,
1179    })
1180}
1181
1182fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1183    let (settings, refs) = (ctx.settings, ctx.push.get());
1184    if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1185        return Ran::Inert;
1186    }
1187    if common::which("pip-audit").is_none() {
1188        common::warn(
1189            "audit-python: pip-audit is not installed (pip install pip-audit) — \
1190             the audit did NOT run",
1191        );
1192        return Ran::Unavailable;
1193    }
1194    let root = common::repo_root();
1195    // A requirements.txt is the production list by convention, audited in
1196    // its own directory — wherever the repository keeps one (amont#305).
1197    if !lockfile_dirs("requirements.txt").is_empty() {
1198        let argv = vec![
1199            common::program("pip-audit"),
1200            "-r".into(),
1201            "requirements.txt".into(),
1202        ];
1203        let Some(merged) = audit_each_dir(
1204            settings,
1205            "audit-python",
1206            "requirements.txt",
1207            |_| Some(argv.clone()),
1208            read_pip_audit,
1209            |_, report, _| report,
1210        ) else {
1211            return Ran::Unavailable;
1212        };
1213        // A row whose advisory id is not one a waiver can name makes the
1214        // whole report unwaivable.
1215        let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1216        return Ran::Concluded(Concluded {
1217            tool: "audit-python".to_string(),
1218            report: merged.report,
1219            full: merged.full,
1220            waivable,
1221        });
1222    }
1223    let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1224        // A uv/PEP-621 project has no requirements.txt, and EXPORTING one
1225        // does not work either: `uv export` emits the workspace's own
1226        // members and any private-index dependency, and pip-audit resolves
1227        // a requirements file in a throwaway venv that can reach neither —
1228        // it dies on "No matching distribution found". Auditing the
1229        // INSTALLED tree resolves nothing, and is the truer question
1230        // anyway: these are the versions actually imported.
1231        vec![
1232            common::program("pip-audit"),
1233            "--path".into(),
1234            site_packages,
1235            // Workspace members are installed editable and are not on
1236            // PyPI; without this each one is a line of noise.
1237            "--skip-editable".into(),
1238        ]
1239    } else {
1240        common::warn(
1241            "audit-python: no requirements.txt, and no virtualenv to audit \
1242             (looked at $VIRTUAL_ENV and .venv) — the audit did NOT run",
1243        );
1244        return Ran::Unavailable;
1245    };
1246    let Some((exit_ok, out)) = audited(settings, &argv) else {
1247        return Ran::Unavailable;
1248    };
1249    let release = releasing(refs);
1250    let mut report = read_pip_audit(exit_ok, &out);
1251    // A requirements.txt is the production list by convention (dev pins
1252    // live beside it, in requirements-dev.txt). A virtualenv holds the dev
1253    // groups too, so on a release its findings are checked against what
1254    // `uv export --no-dev` says ships.
1255    let venv_mode = argv.iter().any(|a| a == "--path");
1256    // A row whose advisory id is not one a waiver can name (MAL-, a new
1257    // scheme) makes the whole report unwaivable, in every mode.
1258    let mut waivable = pip_rows_all_named(&out);
1259    if release && venv_mode && matches!(report, Report::Vulnerabilities(_)) {
1260        let rows = pip_vulnerable_rows(&out);
1261        if let (false, Some(prod)) = (rows.is_empty(), uv_production_names(settings)) {
1262            let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1263                .into_iter()
1264                .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1265                .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1266                    if ships {
1267                        s.push(row);
1268                    } else {
1269                        d.push(row);
1270                    }
1271                    (s, d)
1272                });
1273            warn_dev_only("audit-python", &dev_only);
1274            waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1275            report = if shipped.is_empty() {
1276                Report::Clean
1277            } else {
1278                Report::Vulnerabilities(shipped)
1279            };
1280        }
1281    }
1282    Ran::Concluded(Concluded {
1283        tool: "audit-python".to_string(),
1284        report,
1285        full: out,
1286        waivable,
1287    })
1288}
1289
1290/// Is `source`'s working tree exactly the commit checked out here, with its
1291/// Python manifests unmodified? Then its installed environment is this
1292/// commit's (as far as the hook in `source` would have known).
1293fn source_is_this_commit(source: &std::path::Path) -> bool {
1294    let src = source.to_string_lossy();
1295    let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1296    let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
1297    let unmodified = crate::git::stdout(&[
1298        "-C",
1299        &src,
1300        "status",
1301        "--porcelain",
1302        "--untracked-files=no",
1303        "--",
1304        "*pyproject.toml",
1305        "*uv.lock",
1306        "*requirements*.txt",
1307    ])
1308    .is_some_and(|out| out.trim().is_empty());
1309    here.is_some() && here == there && unmodified
1310}
1311
1312/// PEP 503 normalised: `Foo_Bar.baz` and `foo-bar-baz` are one package.
1313fn normalise(name: &str) -> String {
1314    name.to_ascii_lowercase()
1315        .split(['-', '_', '.'])
1316        .filter(|p| !p.is_empty())
1317        .collect::<Vec<_>>()
1318        .join("-")
1319}
1320
1321/// The packages pip-audit's table names, one row per advisory:
1322/// `Name Version ID Fix Versions`. Only rows whose third column is an
1323/// advisory id count, so the header, the rule and the summary never do.
1324fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
1325    let mut rows: Vec<(String, String)> = out
1326        .lines()
1327        .filter_map(|l| {
1328            let cols: Vec<&str> = l.split_whitespace().collect();
1329            let id = cols.get(2)?;
1330            ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
1331                .iter()
1332                .any(|p| id.starts_with(p))
1333                .then(|| (normalise(cols[0]), (*id).to_string()))
1334        })
1335        .collect();
1336    rows.sort();
1337    rows.dedup();
1338    rows
1339}
1340
1341/// Does every advisory row of pip-audit's table carry an id a waiver can
1342/// name? A row is `name version id …`: a version starting with a digit and
1343/// an id shaped `PREFIX-…`, whatever the prefix.
1344fn pip_rows_all_named(out: &str) -> bool {
1345    out.lines().all(|l| {
1346        let cols: Vec<&str> = l.split_whitespace().collect();
1347        let is_row = cols.len() >= 3
1348            && cols[1].starts_with(|c: char| c.is_ascii_digit())
1349            && cols[2].contains('-')
1350            && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
1351        !is_row || !advisory_ids(cols[2]).is_empty()
1352    })
1353}
1354
1355/// What a uv project ships: `uv export --no-dev` of its lock, names only.
1356/// None when there is no `uv.lock`, no `uv`, or the export fails — the
1357/// caller then keeps every finding, because an unknown is not a pass.
1358fn uv_production_names(
1359    settings: &crate::config::Settings,
1360) -> Option<std::collections::HashSet<String>> {
1361    if !has_lockfile("uv.lock") || common::which("uv").is_none() {
1362        return None;
1363    }
1364    let argv = vec![
1365        common::program("uv"),
1366        "export".into(),
1367        "--frozen".into(),
1368        "--no-dev".into(),
1369        // Optional extras ship: a consumer who asks for one installs it.
1370        "--all-extras".into(),
1371        "--no-hashes".into(),
1372        "--no-emit-workspace".into(),
1373        "--format".into(),
1374        "requirements-txt".into(),
1375    ];
1376    let (ok, out) = audited(settings, &argv)?;
1377    if !ok {
1378        return None;
1379    }
1380    Some(
1381        out.lines()
1382            .map(str::trim)
1383            .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
1384            .filter_map(|l| {
1385                l.split(|c: char| "=<>!~;[ ".contains(c))
1386                    .next()
1387                    .map(normalise)
1388            })
1389            .collect(),
1390    )
1391}
1392
1393/// The notes ref of audit records: local, never pushed, never a stamp.
1394pub const AUDIT_REF: &str = "amont-audit";
1395const AUDIT_FORMAT: &str = "amont-audit-v1";
1396/// How long a record answers for its lockfiles, in hours.
1397const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
1398/// A report that could not check anything answers for an hour only: an
1399/// offline push is never blocked, and the audit is tried again soon.
1400const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
1401
1402/// Is `check` one of the dependency audits?
1403pub fn is_audit(check: &str) -> bool {
1404    check.starts_with("pre-push-audit-")
1405}
1406
1407/// The files (by name) whose content an audit's branch-mode report depends
1408/// on. A release reads the manifests too (its dev-only split), so a release
1409/// record is keyed by the whole tree instead.
1410fn inputs_of(check: &str) -> &'static [&'static str] {
1411    match check {
1412        "pre-push-audit-rust" => &["Cargo.lock"],
1413        "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
1414        "pre-push-audit-go" => &["go.sum", "go.mod"],
1415        "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
1416        _ => &[],
1417    }
1418}
1419
1420/// The stakes a push's audit is judged and recorded under.
1421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1422enum AuditMode {
1423    /// A branch push: findings warn.
1424    Branch,
1425    /// A push carrying a `v*` tag: shipped vulnerabilities block.
1426    Release,
1427}
1428
1429impl AuditMode {
1430    fn of(refs: &[PushRef]) -> AuditMode {
1431        if releasing(refs) {
1432            AuditMode::Release
1433        } else {
1434            AuditMode::Branch
1435        }
1436    }
1437}
1438
1439/// What an audit concluded before the push's stakes were applied: what
1440/// `conclude_waivable` judges, and what a record keeps so a later push can
1441/// judge it again against that day's waivers and that push (ADR-0018).
1442#[derive(Debug, Clone, PartialEq, Eq)]
1443struct Concluded {
1444    tool: String,
1445    report: Report,
1446    full: String,
1447    waivable: bool,
1448}
1449
1450/// How one ecosystem's audit ended: with a report to judge, or before it had
1451/// one.
1452enum Ran {
1453    Concluded(Concluded),
1454    /// Nothing to audit here (no lockfile).
1455    Inert,
1456    /// It could not run: no tool, or a tool that would not start.
1457    Unavailable,
1458}
1459
1460/// A record waiting for the hook to decide it may be written: only where the
1461/// working tree is the keyed tip (the tools read the working tree).
1462#[derive(Debug, Clone)]
1463pub struct Pending {
1464    pub tip: String,
1465    material: String,
1466    body: String,
1467}
1468
1469/// One push's audit bookkeeping, owned by the hook and lent to each audit on
1470/// `Ctx`: the records the audits produced, and the reads both the refusal and
1471/// the replay ask for (each costs a git spawn while git holds the
1472/// connection open).
1473#[derive(Default)]
1474pub struct Ledger {
1475    pending: std::sync::Mutex<Vec<Pending>>,
1476    peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
1477    fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
1478}
1479
1480impl Ledger {
1481    /// The records this push's audits produced, handed to the hook.
1482    pub fn take_pending(&self) -> Vec<Pending> {
1483        std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
1484    }
1485
1486    /// `oid` peeled to its commit, asked of git once per push.
1487    fn peel(&self, oid: &str) -> Option<String> {
1488        if let Some(known) = self
1489            .peeled
1490            .lock()
1491            .unwrap_or_else(|e| e.into_inner())
1492            .get(oid)
1493        {
1494            return known.clone();
1495        }
1496        let commit =
1497            crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
1498        self.peeled
1499            .lock()
1500            .unwrap_or_else(|e| e.into_inner())
1501            .insert(oid.to_string(), commit.clone());
1502        commit
1503    }
1504
1505    /// The pushed commits: every non-deleting ref's tip, peeled to its commit.
1506    fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
1507        let mut commits: Vec<String> = refs
1508            .iter()
1509            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1510            .filter_map(|r| self.peel(&r.local_oid))
1511            .collect();
1512        commits.sort();
1513        commits.dedup();
1514        commits
1515    }
1516}
1517
1518/// Write `pending` as a note on the blob of its key text. A failure is named
1519/// for the caller to report: the next push then owes the audit again.
1520pub fn write_pending(pending: &Pending) -> Result<(), String> {
1521    // `stdout_piped` keeps git's trailing newline; a key with one names no
1522    // object, and `notes add` would refuse it.
1523    let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
1524        .map(|k| k.trim().to_string())
1525        .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
1526    let written = crate::git::succeeds(&[
1527        "notes",
1528        "--ref",
1529        AUDIT_REF,
1530        "add",
1531        "-f",
1532        "-m",
1533        &pending.body,
1534        &key,
1535    ]);
1536    if written {
1537        Ok(())
1538    } else {
1539        Err(format!("git refused to write the audit record {key}"))
1540    }
1541}
1542
1543/// The text a record is keyed by (the key is its blob's oid).
1544fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
1545    match mode {
1546        AuditMode::Release => {
1547            let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
1548            Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
1549        }
1550        AuditMode::Branch => {
1551            let names = inputs_of(check);
1552            let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
1553            let mut lines: Vec<String> = listing
1554                .lines()
1555                .filter_map(|entry| {
1556                    let (meta, path) = entry.split_once('\t')?;
1557                    let blob = meta.split_whitespace().nth(2)?;
1558                    let base = path.rsplit('/').next().unwrap_or(path);
1559                    names.contains(&base).then(|| format!("{path} {blob}"))
1560                })
1561                .collect();
1562            lines.sort();
1563            Some(format!(
1564                "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
1565                lines.join("\n")
1566            ))
1567        }
1568    }
1569}
1570
1571fn now_secs() -> i64 {
1572    std::time::SystemTime::now()
1573        .duration_since(std::time::UNIX_EPOCH)
1574        .map(|d| d.as_secs() as i64)
1575        .unwrap_or(0)
1576}
1577
1578fn class_of(report: &Report) -> &'static str {
1579    match report {
1580        Report::Clean => "clean",
1581        Report::Advisories(_) => "advisories",
1582        Report::Vulnerabilities(_) => "vulnerabilities",
1583        Report::CouldNotCheck => "unchecked",
1584    }
1585}
1586
1587fn render(concluded: &Concluded, at: i64) -> String {
1588    let items: &[String] = match &concluded.report {
1589        Report::Advisories(v) | Report::Vulnerabilities(v) => v,
1590        Report::Clean | Report::CouldNotCheck => &[],
1591    };
1592    let mut body = format!(
1593        "{AUDIT_FORMAT} {at} {} {} {}",
1594        class_of(&concluded.report),
1595        u8::from(concluded.waivable),
1596        concluded.tool
1597    );
1598    for item in items {
1599        body.push_str("\nitem ");
1600        body.push_str(item);
1601    }
1602    body.push_str("\n---\n");
1603    body.push_str(&concluded.full);
1604    body
1605}
1606
1607fn parse(body: &str) -> Option<(i64, Concluded)> {
1608    let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
1609    let mut fields = head.split_whitespace();
1610    if fields.next()? != AUDIT_FORMAT {
1611        return None;
1612    }
1613    let at: i64 = fields.next()?.parse().ok()?;
1614    let class = fields.next()?;
1615    let waivable = fields.next()? == "1";
1616    let tool = fields.next()?.to_string();
1617    let (items_part, full) = match rest.split_once("---\n") {
1618        Some((i, full)) => (i, full.to_string()),
1619        None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
1620    };
1621    let items: Vec<String> = items_part
1622        .lines()
1623        .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
1624        .collect();
1625    let report = match class {
1626        "clean" => Report::Clean,
1627        "advisories" => Report::Advisories(items),
1628        "vulnerabilities" => Report::Vulnerabilities(items),
1629        "unchecked" => Report::CouldNotCheck,
1630        _ => return None,
1631    };
1632    Some((
1633        at,
1634        Concluded {
1635            tool,
1636            report,
1637            full,
1638            waivable,
1639        },
1640    ))
1641}
1642
1643/// The fresh record of `check` for `commit` in this mode, if any.
1644fn fresh_record(
1645    settings: &crate::config::Settings,
1646    check: &str,
1647    mode: AuditMode,
1648    commit: &str,
1649) -> Option<Concluded> {
1650    let material = key_material(check, mode, commit)?;
1651    let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
1652        .trim()
1653        .to_string();
1654    let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
1655    let (at, concluded) = parse(&body)?;
1656    let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
1657        UNCHECKED_MAX_AGE_SECS
1658    } else {
1659        crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
1660    };
1661    let age = now_secs() - at;
1662    (0..=max_age).contains(&age).then_some(concluded)
1663}
1664
1665/// Does every commit `refs` pushes carry a fresh record of `check`, all the
1666/// same, in this push's mode? The one the push would replay, or None. Asked
1667/// by the refusal and again by the replay, so answered once per push:
1668/// nothing in one hook run writes a record before both have asked.
1669fn fresh_for_refs(
1670    settings: &crate::config::Settings,
1671    ledger: &Ledger,
1672    check: &str,
1673    refs: &[PushRef],
1674) -> Option<Concluded> {
1675    if !crate::gate_stamp::push_stamps_enabled(settings) {
1676        return None;
1677    }
1678    let memo_key = format!(
1679        "{check} {}",
1680        refs.iter()
1681            .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
1682            .collect::<Vec<_>>()
1683            .join(" ")
1684    );
1685    if let Some(known) = ledger
1686        .fresh
1687        .lock()
1688        .unwrap_or_else(|e| e.into_inner())
1689        .get(&memo_key)
1690    {
1691        return known.clone();
1692    }
1693    let mode = AuditMode::of(refs);
1694    let mut found: Option<Concluded> = None;
1695    for commit in ledger.pushed_commits(refs) {
1696        let Some(record) = fresh_record(settings, check, mode, &commit) else {
1697            found = None;
1698            break;
1699        };
1700        if found.as_ref().is_some_and(|prev| *prev != record) {
1701            found = None;
1702            break;
1703        }
1704        found = Some(record);
1705    }
1706    ledger
1707        .fresh
1708        .lock()
1709        .unwrap_or_else(|e| e.into_inner())
1710        .insert(memo_key, found.clone());
1711    found
1712}
1713
1714/// Is `check` owed by a push of `refs`: opted in, and with no fresh record?
1715pub fn owed(
1716    settings: &crate::config::Settings,
1717    ledger: &Ledger,
1718    check: &str,
1719    refs: &[PushRef],
1720) -> bool {
1721    !ledger.pushed_commits(refs).is_empty()
1722        && fresh_for_refs(settings, ledger, check, refs).is_none()
1723}
1724
1725/// Run an audit through its record: replay a fresh one, or run the tool and
1726/// keep what it concluded on the ledger (a tool that never got to a report
1727/// counts as "could not check").
1728fn recorded(
1729    check: &str,
1730    tool: &str,
1731    ctx: &crate::registry::Ctx,
1732    run: fn(&crate::registry::Ctx) -> Ran,
1733) -> Outcome {
1734    let (settings, refs) = (ctx.settings, ctx.push.get());
1735    let mode = AuditMode::of(refs);
1736    let releasing = mode == AuditMode::Release;
1737    if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
1738        common::ok(
1739            settings,
1740            &format!("{tool}: replaying the audit recorded for this push"),
1741        );
1742        return conclude_waivable(
1743            settings,
1744            &record.tool,
1745            record.report,
1746            releasing,
1747            &record.full,
1748            record.waivable,
1749        );
1750    }
1751    let (outcome, concluded) = match run(ctx) {
1752        Ran::Concluded(concluded) => (
1753            conclude_waivable(
1754                settings,
1755                &concluded.tool,
1756                concluded.report.clone(),
1757                releasing,
1758                &concluded.full,
1759                concluded.waivable,
1760            ),
1761            Some(concluded),
1762        ),
1763        Ran::Unavailable => (
1764            Outcome::Unavailable,
1765            Some(Concluded {
1766                tool: tool.to_string(),
1767                report: Report::CouldNotCheck,
1768                full: String::new(),
1769                waivable: false,
1770            }),
1771        ),
1772        Ran::Inert => (Outcome::Inert, None),
1773    };
1774    if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
1775        let body = render(&concluded, now_secs());
1776        let records: Vec<Pending> = ctx
1777            .audits
1778            .pushed_commits(refs)
1779            .into_iter()
1780            .filter_map(|commit| {
1781                key_material(check, mode, &commit).map(|material| Pending {
1782                    tip: commit,
1783                    material,
1784                    body: body.clone(),
1785                })
1786            })
1787            .collect();
1788        ctx.audits
1789            .pending
1790            .lock()
1791            .unwrap_or_else(|e| e.into_inner())
1792            .extend(records);
1793    }
1794    outcome
1795}
1796
1797pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
1798    recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
1799}
1800
1801pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
1802    recorded("pre-push-audit-js", "audit-js", ctx, js_run)
1803}
1804
1805pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
1806    recorded("pre-push-audit-go", "audit-go", ctx, go_run)
1807}
1808
1809pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
1810    recorded("pre-push-audit-python", "audit-python", ctx, python_run)
1811}
1812
1813#[cfg(test)]
1814mod tests {
1815    use super::*;
1816
1817    /// uv projects have no `requirements.txt`, so the venv is the only thing
1818    /// left to audit — and before this, `audit-python` looked for nothing
1819    /// else and reported "the audit did NOT run" forever. Six repositories
1820    /// in one fleet were in exactly that state, one of them carrying 53
1821    /// known vulnerabilities nobody had been told about.
1822    #[test]
1823    fn a_uv_project_is_audited_through_its_venv() {
1824        let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
1825        let _ = std::fs::remove_dir_all(&root);
1826
1827        // Nothing on disk: nothing to audit, and we say so rather than
1828        // inventing a target.
1829        std::fs::create_dir_all(&root).unwrap();
1830        assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
1831
1832        // The posix layout, with the python version DISCOVERED — hard-coding
1833        // `python3.13` would silently stop finding it after an upgrade.
1834        // Joined segment by segment, NOT as one "a/b/c" literal: on Windows
1835        // the literal keeps its forward slashes while the code under test
1836        // returns backslashes, and the test fails on a difference that is
1837        // only in the expectation.
1838        let sp = root
1839            .join(".venv")
1840            .join("lib")
1841            .join("python3.13")
1842            .join("site-packages");
1843        std::fs::create_dir_all(&sp).unwrap();
1844        assert_eq!(
1845            venv_site_packages(root.to_str().unwrap(), None),
1846            Some(sp.to_string_lossy().into_owned())
1847        );
1848
1849        // The Windows layout, which has no version directory at all.
1850        let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
1851        let _ = std::fs::remove_dir_all(&win);
1852        let wsp = win.join(".venv").join("Lib").join("site-packages");
1853        std::fs::create_dir_all(&wsp).unwrap();
1854        assert_eq!(
1855            venv_site_packages(win.to_str().unwrap(), None),
1856            Some(wsp.to_string_lossy().into_owned())
1857        );
1858
1859        let _ = std::fs::remove_dir_all(&root);
1860        let _ = std::fs::remove_dir_all(&win);
1861    }
1862
1863    fn tag(name: &str) -> PushRef {
1864        PushRef {
1865            local_ref: name.to_string(),
1866            local_oid: "a".repeat(40),
1867            remote_ref: name.to_string(),
1868            remote_oid: "0".repeat(40),
1869        }
1870    }
1871
1872    /// `v` + digit gates; a branch, a bare-word tag, or a tag merely
1873    /// starting with the letter v does not.
1874    #[test]
1875    fn pip_audit_rows_name_their_packages_normalised() {
1876        let out = "Name       Version ID                  Fix Versions\n\
1877                   ---------- ------- ------------------- ------------\n\
1878                   Pytest_Cov 4.0.0   GHSA-aaaa-bbbb-cccc 4.1.0\n\
1879                   requests   2.31.0  PYSEC-2023-74       2.31.1\n\
1880                   requests   2.31.0  CVE-2024-35195      2.32.0\n\
1881                   Found 3 known vulnerabilities in 2 packages\n";
1882        let names: Vec<String> = pip_vulnerable_rows(out)
1883            .into_iter()
1884            .map(|(n, _)| n)
1885            .collect();
1886        assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
1887        assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
1888    }
1889
1890    #[test]
1891    fn advisory_ids_are_found_wherever_they_sit() {
1892        let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
1893                    ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
1894        assert_eq!(
1895            advisory_ids(text),
1896            vec![
1897                "CVE-2024-35195",
1898                "GHSA-h3mg-xc3c-68pw",
1899                "GO-2024-2687",
1900                "OSV-2024-12",
1901                "PYSEC-2023-74",
1902                "RUSTSEC-2025-0001"
1903            ]
1904        );
1905    }
1906
1907    #[test]
1908    fn a_waiver_is_reasoned_dated_and_bounded() {
1909        let today = days_from_date("2026-10-05").unwrap();
1910        let w = Waivers::parse(
1911            "# id expires reason\n\
1912             GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
1913             GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
1914             GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
1915             GHSA-jjjj-kkkk-llll 2026-11-01\n\
1916             GHSA-mmmm-nnnn-oooo soon no date\n",
1917            today,
1918        );
1919        assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
1920        assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
1921        assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
1922        assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
1923        assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
1924        assert_eq!(w.problems().len(), 4);
1925        assert_eq!(days_from_date("1970-01-01"), Some(0));
1926        assert_eq!(days_from_date("2026-02-30"), None);
1927        assert!(days_from_date("2028-02-29").is_some());
1928        assert_eq!(days_from_date("2026-13-01"), None);
1929    }
1930
1931    #[test]
1932    fn two_locked_versions_are_two_answers() {
1933        let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
1934                   Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
1935        let ids = vec![
1936            "RUSTSEC-2025-0010".to_string(),
1937            "RUSTSEC-2025-0011".to_string(),
1938        ];
1939        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
1940            "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
1941            "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
1942            _ => None,
1943        });
1944        assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
1945        assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
1946    }
1947
1948    #[test]
1949    fn a_pip_row_without_a_nameable_id_is_unwaivable() {
1950        let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
1951        let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
1952        assert!(pip_rows_all_named(named));
1953        assert!(!pip_rows_all_named(unnamed));
1954    }
1955
1956    #[test]
1957    fn a_crate_ships_unless_its_tree_says_otherwise() {
1958        let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
1959                   Crate: app\nID: RUSTSEC-2025-0002\n\
1960                   Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
1961        let ids = vec![
1962            "RUSTSEC-2025-0001".to_string(),
1963            "RUSTSEC-2025-0002".to_string(),
1964            "RUSTSEC-2025-0003".to_string(),
1965            "RUSTSEC-2025-0004".to_string(),
1966        ];
1967        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
1968            // Asked by name@version when cargo audit gave the version.
1969            "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
1970            "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
1971            // A tree that says neither: not proof of dev-only.
1972            "odd" => Some("odd v1.0.0\n".into()),
1973            _ => None,
1974        });
1975        // 0003 has no crate, 0004's tree is unclear: unknowns ship.
1976        assert_eq!(
1977            shipped,
1978            vec![
1979                "RUSTSEC-2025-0002",
1980                "RUSTSEC-2025-0003",
1981                "RUSTSEC-2025-0004"
1982            ]
1983        );
1984        assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
1985    }
1986
1987    #[test]
1988    fn a_release_is_a_v_number_tag() {
1989        assert!(releasing(&[tag("refs/tags/v1.6.6")]));
1990        assert!(releasing(&[tag("refs/tags/v2")]));
1991        assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
1992        assert!(!releasing(&[tag("refs/tags/release")]));
1993        assert!(!releasing(&[tag("refs/heads/v1-styles")]));
1994        assert!(!releasing(&[tag("refs/heads/main")]));
1995        // A mixed push gates: the tag is in there.
1996        assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
1997    }
1998
1999    /// ci.yaml's lesson, pinned at the unit level: the ids decide, the exit
2000    /// code only classifies them.
2001    #[test]
2002    fn cargo_audit_ids_decide_not_the_exit_code() {
2003        assert_eq!(
2004            read_cargo_audit(true, "ok, 312 crates checked"),
2005            Report::Clean
2006        );
2007        assert_eq!(
2008            read_cargo_audit(false, "error: couldn't fetch advisory database"),
2009            Report::CouldNotCheck
2010        );
2011        let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
2012        assert_eq!(
2013            read_cargo_audit(true, warn),
2014            Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
2015        );
2016        let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
2017        assert_eq!(
2018            read_cargo_audit(false, vuln),
2019            Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
2020        );
2021        // A lookalike is not an id.
2022        assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
2023    }
2024
2025    /// The real report shape, trimmed from the run that prompted this: two
2026    /// advisories against ONE crate, and one against another.
2027    fn real_report() -> String {
2028        [
2029            "Crate:     paste",
2030            "Version:   1.0.15",
2031            "Warning:   unmaintained",
2032            "ID:        RUSTSEC-2024-0436",
2033            "URL:       https://rustsec.org/advisories/RUSTSEC-2024-0436",
2034            "",
2035            "Crate:     lru",
2036            "Version:   0.12.5",
2037            "Warning:   unsound",
2038            "ID:        RUSTSEC-2026-0253",
2039            "",
2040            "Crate:     lru",
2041            "Version:   0.12.5",
2042            "ID:        RUSTSEC-2026-0002",
2043            "",
2044            "warning: 3 allowed warnings found",
2045        ]
2046        .join("\n")
2047    }
2048
2049    #[test]
2050    fn an_advisory_is_paired_with_its_crate() {
2051        let pairs = ids_with_crates(&real_report());
2052        assert_eq!(
2053            pairs,
2054            vec![
2055                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
2056                ("RUSTSEC-2026-0253".into(), Some("lru".into())),
2057                ("RUSTSEC-2026-0002".into(), Some("lru".into())),
2058            ]
2059        );
2060    }
2061
2062    /// A `Crate:` binds to ONE id. An id printed loose reports no crate
2063    /// rather than inheriting whichever block happened to precede it.
2064    #[test]
2065    fn a_loose_id_borrows_no_crate() {
2066        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
2067        assert_eq!(
2068            ids_with_crates(out),
2069            vec![
2070                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
2071                ("RUSTSEC-2025-0001".into(), None),
2072            ]
2073        );
2074    }
2075
2076    /// Local crates carry a path; registry crates do not. That is the whole
2077    /// discriminator, and it has to work without knowing the member names.
2078    #[test]
2079    fn only_local_crates_are_named_as_reached() {
2080        let tree =
2081            "lru v0.12.5\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
2082        assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
2083        assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
2084    }
2085
2086    /// End to end on the real report, with the tree calls faked: each id
2087    /// names its crate and the workspace crate that reaches it, and `lru`'s
2088    /// two advisories cost ONE lookup.
2089    #[test]
2090    fn the_warning_names_the_crate_and_what_reaches_it() {
2091        let calls = std::cell::RefCell::new(Vec::new());
2092        let fake = |k: &str| {
2093            calls.borrow_mut().push(k.to_string());
2094            Some(format!(
2095                "{k} v1\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
2096            ))
2097        };
2098        let out = real_report();
2099        let got = attribute(read_cargo_audit(true, &out), &out, fake);
2100        assert_eq!(
2101            got,
2102            Report::Advisories(vec![
2103                "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
2104                "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
2105                "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
2106            ])
2107        );
2108        assert_eq!(
2109            calls.into_inner(),
2110            vec!["paste", "lru"],
2111            "one call per crate"
2112        );
2113    }
2114
2115    /// A lock-file-only crate — an optional dependency of a feature nobody
2116    /// enabled — is reported as such. `cargo audit` reads Cargo.lock, so this
2117    /// is a real and confusing case, and naming it is the point.
2118    #[test]
2119    fn a_crate_outside_the_build_graph_says_so() {
2120        let out = "Crate:     wezterm-input-types\nID:        RUSTSEC-2025-0001";
2121        let got = attribute(read_cargo_audit(true, out), out, |_| {
2122            Some("warning: nothing to print.".into())
2123        });
2124        assert_eq!(
2125            got,
2126            Report::Advisories(vec![
2127                "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
2128            ])
2129        );
2130    }
2131
2132    /// Attribution is a better message, never a gate. A clean report spawns
2133    /// nothing, and a `cargo tree` that cannot run still reports the id.
2134    #[test]
2135    fn attribution_never_changes_the_verdict() {
2136        let spawned = std::cell::Cell::new(false);
2137        let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
2138            spawned.set(true);
2139            None
2140        });
2141        assert_eq!(clean, Report::Clean);
2142        assert!(!spawned.get(), "a clean report must spawn nothing");
2143
2144        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436";
2145        let blind = attribute(read_cargo_audit(false, out), out, |_| None);
2146        assert_eq!(
2147            blind,
2148            Report::Vulnerabilities(vec![
2149                "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
2150            ])
2151        );
2152    }
2153
2154    #[test]
2155    fn npm_audit_summary_decides() {
2156        assert_eq!(
2157            read_npm_audit(true, "found 0 vulnerabilities\n"),
2158            Report::Clean
2159        );
2160        assert_eq!(
2161            read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
2162            Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
2163        );
2164        // npm 7+ dropped the verb: this is what every current npm prints,
2165        // and what read as "never answered" until the parser learned it.
2166        assert_eq!(
2167            read_npm_audit(
2168                false,
2169                "# npm audit report\n\nvite  6.0.0 - 6.1.5\nSeverity: high\n\n\
2170                 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n  npm audit fix\n"
2171            ),
2172            Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
2173        );
2174        assert_eq!(
2175            read_npm_audit(false, "1 vulnerability (1 high)\n"),
2176            Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
2177        );
2178        assert_eq!(
2179            read_npm_audit(true, "up to date, audited 100 packages\n"),
2180            Report::Clean
2181        );
2182        assert_eq!(
2183            read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
2184            Report::CouldNotCheck
2185        );
2186    }
2187
2188    #[test]
2189    fn pnpm_audit_summary_decides() {
2190        assert_eq!(
2191            read_pnpm_audit(true, "No known vulnerabilities found\n"),
2192            Report::Clean
2193        );
2194        // What pnpm prints after its table: the count, then the severities,
2195        // which the finding carries so the warning says how bad.
2196        assert_eq!(
2197            read_pnpm_audit(
2198                false,
2199                "│ More info │ https://github.com/advisories/GHSA-395f │\n\
2200                 └───────────┴──────────────────────────────────────────┘\n\
2201                 107 vulnerabilities found\n\
2202                 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
2203            ),
2204            Report::Vulnerabilities(vec![
2205                "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
2206            ])
2207        );
2208        assert_eq!(
2209            read_pnpm_audit(false, "1 vulnerabilities found\n"),
2210            Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
2211        );
2212        assert_eq!(
2213            read_pnpm_audit(
2214                false,
2215                " ERR_PNPM_AUDIT_BAD_RESPONSE  The audit endpoint responded with 503\n"
2216            ),
2217            Report::CouldNotCheck
2218        );
2219    }
2220
2221    /// The cargo-audit split, spoken in Go: ids decide, the exit code says
2222    /// whether the analysed code is actually affected.
2223    #[test]
2224    fn govulncheck_ids_decide_not_the_exit_code() {
2225        assert_eq!(
2226            read_govulncheck(true, "No vulnerabilities found.\n"),
2227            Report::Clean
2228        );
2229        assert_eq!(
2230            read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
2231            Report::CouldNotCheck
2232        );
2233        // Informational: the module is vulnerable, the analysed code never
2234        // calls it — exit 0, ids present.
2235        assert_eq!(
2236            read_govulncheck(
2237                true,
2238                "=== Informational ===\nVulnerability #1: GO-2023-1840\n  More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
2239            ),
2240            Report::Advisories(vec!["GO-2023-1840".into()])
2241        );
2242        assert_eq!(
2243            read_govulncheck(
2244                false,
2245                "Vulnerability #1: GO-2022-0969\n  Your code calls it.\nGO-2022-0969 again\n"
2246            ),
2247            Report::Vulnerabilities(vec!["GO-2022-0969".into()])
2248        );
2249        // A lookalike is not an id.
2250        assert_eq!(
2251            read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
2252            Report::Clean
2253        );
2254    }
2255
2256    #[test]
2257    fn pip_audit_sentence_decides() {
2258        assert_eq!(
2259            read_pip_audit(true, "No known vulnerabilities found\n"),
2260            Report::Clean
2261        );
2262        assert_eq!(
2263            read_pip_audit(
2264                false,
2265                "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
2266            ),
2267            Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
2268        );
2269        assert_eq!(
2270            read_pip_audit(false, "ERROR: could not resolve\n"),
2271            Report::CouldNotCheck
2272        );
2273    }
2274}