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                         ({}) — not blocking this release: {}",
97                        waivers.file.unwrap_or(WAIVERS_FILE),
98                        ids.iter()
99                            .map(|id| waivers.describe(id))
100                            .collect::<Vec<_>>()
101                            .join("; ")
102                    ));
103                    return Outcome::Warned;
104                }
105                for line in full.lines() {
106                    crate::say!("{line}");
107                }
108                for note in waivers.problems() {
109                    common::warn(&format!("{tool}: {note}"));
110                }
111                common::fail(&format!(
112                    "{tool}: known vulnerabilities in the dependency tree — a v* tag \
113                     does not ship with these: {}{}",
114                    what.join(", "),
115                    if ids.is_empty() {
116                        " (no advisory id to match a waiver against)".to_string()
117                    } else {
118                        format!(
119                            " — not waived: {}",
120                            unwaived
121                                .iter()
122                                .map(|s| s.as_str())
123                                .collect::<Vec<_>>()
124                                .join(", ")
125                        )
126                    }
127                ));
128                Outcome::Failed
129            } else if all_waived {
130                common::warn(&format!(
131                    "{tool}: known vulnerabilities ({}) — covered by a reviewed waiver \
132                     ({}), so a v* tag push will pass while it holds: {}",
133                    what.join(", "),
134                    waivers.file.unwrap_or(WAIVERS_FILE),
135                    ids.iter()
136                        .map(|id| waivers.describe(id))
137                        .collect::<Vec<_>>()
138                        .join("; ")
139                ));
140                Outcome::Warned
141            } else {
142                common::warn(&format!(
143                    "{tool}: known vulnerabilities in the dependency tree ({}) — \
144                     this will BLOCK a v* tag push",
145                    what.join(", ")
146                ));
147                Outcome::Warned
148            }
149        }
150        Report::CouldNotCheck => {
151            common::warn(&format!(
152                "{tool} could not complete — the dependency tree was NOT checked. \
153                 This is not a clean result."
154            ));
155            Outcome::Unavailable
156        }
157    }
158}
159
160/// Where a repository records the advisories a release may ship anyway.
161const WAIVERS_FILE: &str = crate::names::AUDIT_WAIVERS;
162
163/// The same file before greengate 4.3, read when [`WAIVERS_FILE`] is absent
164/// until the census renames every repository's (`greengate migrate --tracked`).
165const OLD_WAIVERS_FILE: &str = crate::names::old::AUDIT_WAIVERS;
166
167/// How far ahead a waiver may run. A waiver is a decision to revisit, not
168/// an exemption: one dated further out is void, so nothing is waived for
169/// good by accident.
170const MAX_WAIVER_DAYS: i64 = 90;
171
172/// One line of the waiver file: `<advisory id> <expires YYYY-MM-DD> <reason>`.
173#[derive(Debug)]
174struct Waiver {
175    id: String,
176    expires: String,
177    reason: String,
178    valid: bool,
179}
180
181/// The repository's reviewed waivers, judged against today.
182///
183/// A waiver lets a RELEASE ship a known vulnerability nobody can fix yet —
184/// an advisory with no patched version, on a path the project cannot
185/// replace. It is committed (so it is reviewed like code), names its
186/// reason, and expires: past its date, or dated more than
187/// [`MAX_WAIVER_DAYS`] ahead, it waives nothing and the tag is refused
188/// again. Branch pushes never consult it — they never block.
189#[derive(Debug, Default)]
190struct Waivers {
191    entries: Vec<Waiver>,
192    problems: Vec<String>,
193    /// The file these were read from, for messages to quote; `None` when no
194    /// file was read.
195    file: Option<&'static str>,
196}
197
198impl Waivers {
199    fn load(root: &str, today: i64) -> Self {
200        let root = std::path::Path::new(root);
201        let read = |file: &'static str| (file, std::fs::read_to_string(root.join(file)));
202        let (mut file, mut got) = read(WAIVERS_FILE);
203        if matches!(&got, Err(e) if e.kind() == std::io::ErrorKind::NotFound) {
204            (file, got) = read(OLD_WAIVERS_FILE);
205        } else if root.join(OLD_WAIVERS_FILE).exists() {
206            common::warn(&format!(
207                "{OLD_WAIVERS_FILE} is ignored: {WAIVERS_FILE} exists — \
208                 delete the old file"
209            ));
210        }
211        match got {
212            Ok(text) => Self {
213                file: Some(file),
214                ..Self::parse(&text, today)
215            },
216            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
217            Err(e) => Self {
218                entries: Vec::new(),
219                problems: vec![format!(
220                    "{file} could not be read ({e}) — it waives nothing"
221                )],
222                file: Some(file),
223            },
224        }
225    }
226
227    fn parse(text: &str, today: i64) -> Self {
228        let mut w = Self::default();
229        for line in text.lines().map(str::trim) {
230            if line.is_empty() || line.starts_with('#') {
231                continue;
232            }
233            let mut parts = line.splitn(3, char::is_whitespace);
234            let id = parts.next().unwrap_or_default().to_string();
235            let expires = parts.next().unwrap_or_default().trim().to_string();
236            let reason = parts.next().unwrap_or_default().trim().to_string();
237            let valid = match days_from_date(&expires) {
238                None => {
239                    w.problems.push(format!(
240                        "waiver for {id} has no readable expiry date (YYYY-MM-DD) — it waives nothing"
241                    ));
242                    false
243                }
244                Some(_) if reason.is_empty() => {
245                    w.problems.push(format!(
246                        "waiver for {id} gives no reason — it waives nothing"
247                    ));
248                    false
249                }
250                Some(d) if d < today => {
251                    w.problems
252                        .push(format!("waiver for {id} expired on {expires}"));
253                    false
254                }
255                Some(d) if d - today > MAX_WAIVER_DAYS => {
256                    w.problems.push(format!(
257                        "waiver for {id} runs to {expires}, more than {MAX_WAIVER_DAYS} days \
258                         ahead — it waives nothing; date it sooner and revisit"
259                    ));
260                    false
261                }
262                Some(_) => true,
263            };
264            w.entries.push(Waiver {
265                id,
266                expires,
267                reason,
268                valid,
269            });
270        }
271        w
272    }
273
274    fn covers(&self, id: &str) -> bool {
275        self.entries.iter().any(|w| w.valid && w.id == id)
276    }
277
278    fn describe(&self, id: &str) -> String {
279        match self.entries.iter().find(|w| w.valid && w.id == id) {
280            Some(w) => format!("{id} until {} ({})", w.expires, w.reason),
281            None => id.to_string(),
282        }
283    }
284
285    fn problems(&self) -> &[String] {
286        &self.problems
287    }
288}
289
290/// Days since 1970-01-01 for a `YYYY-MM-DD` date (proleptic Gregorian).
291fn days_from_date(date: &str) -> Option<i64> {
292    let mut it = date.split('-');
293    let (y, m, d): (i64, i64, i64) = (
294        it.next()?.parse().ok()?,
295        it.next()?.parse().ok()?,
296        it.next()?.parse().ok()?,
297    );
298    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
299    let month_days = [
300        31,
301        if leap { 29 } else { 28 },
302        31,
303        30,
304        31,
305        30,
306        31,
307        31,
308        30,
309        31,
310        30,
311        31,
312    ];
313    if it.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > month_days[(m - 1) as usize] {
314        return None;
315    }
316    // Howard Hinnant's days_from_civil.
317    let y = if m <= 2 { y - 1 } else { y };
318    let era = if y >= 0 { y } else { y - 399 } / 400;
319    let yoe = y - era * 400;
320    let mp = (m + 9) % 12;
321    let doy = (153 * mp + 2) / 5 + d - 1;
322    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
323    Some(era * 146_097 + doe - 719_468)
324}
325
326/// Today, in days since the epoch (UTC).
327fn today() -> i64 {
328    std::time::SystemTime::now()
329        .duration_since(std::time::UNIX_EPOCH)
330        .map(|d| (d.as_secs() / 86_400) as i64)
331        .unwrap_or(0)
332}
333
334/// Every advisory id in `text`: GitHub (`GHSA-xxxx-xxxx-xxxx`), RustSec,
335/// Go, PyPA and CVE ids, wherever they sit (a URL, a table cell).
336fn advisory_ids(text: &str) -> Vec<String> {
337    let mut ids: Vec<String> = text
338        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
339        .filter(|w| {
340            let parts: Vec<&str> = w.split('-').collect();
341            match parts.as_slice() {
342                ["GHSA", a, b, c] => [a, b, c]
343                    .iter()
344                    .all(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphanumeric())),
345                ["RUSTSEC" | "GO" | "PYSEC" | "CVE" | "OSV", year, num] => {
346                    year.len() == 4
347                        && year.bytes().all(|b| b.is_ascii_digit())
348                        && !num.is_empty()
349                        && num.bytes().all(|b| b.is_ascii_digit())
350                }
351                _ => false,
352            }
353        })
354        .map(str::to_string)
355        .collect();
356    ids.sort();
357    ids.dedup();
358    ids
359}
360
361/// Is this word a RUSTSEC id? `RUSTSEC-` + 4 digits + `-` + 4 digits.
362fn is_advisory_id(w: &str) -> bool {
363    w.len() == 17
364        && w.starts_with("RUSTSEC-")
365        && w[8..12].bytes().all(|b| b.is_ascii_digit())
366        && w.as_bytes()[12] == b'-'
367        && w[13..17].bytes().all(|b| b.is_ascii_digit())
368}
369
370/// Pair each advisory with the crate it was raised against.
371///
372/// `cargo audit`'s terminal report is blocks — `Crate:` … `ID:` — and the
373/// id alone does not say which crate carries it, let alone which of YOUR
374/// crates depends on that. Answering "is this on the commit path or only in
375/// an opt-in tool?" meant running `cargo tree -i` by hand every time.
376///
377/// A `Crate:` binds to the next `ID:` and is then spent, so an id appearing
378/// outside a block — a summary line, a URL — reports no crate rather than
379/// inheriting the previous block's.
380fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
381    let mut pairs: Vec<(String, Option<String>)> = Vec::new();
382    let mut pending: Option<String> = None;
383    for line in out.lines() {
384        let t = line.trim();
385        if let Some(rest) = t.strip_prefix("Crate:") {
386            pending = rest.split_whitespace().next().map(str::to_string);
387            continue;
388        }
389        if let Some(rest) = t.strip_prefix("ID:") {
390            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
391                pairs.push((id.to_string(), pending.take()));
392                continue;
393            }
394        }
395        // Ids outside a block still count — the older summary-line shapes
396        // and anything cargo audit prints loose.
397        for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
398            pairs.push((w.to_string(), None));
399        }
400    }
401    pairs
402}
403
404/// Which of THIS workspace's crates reach `crate`, read from `cargo tree -i`.
405///
406/// Cargo prints a local package with its path in parentheses and a registry
407/// package without one, which is the only discriminator needed and works in
408/// any repository — the hook cannot know a given workspace's member names.
409///
410/// An empty result is an answer, not a failure: `cargo tree` prints
411/// "nothing to print" for a crate that is in `Cargo.lock` but not in the
412/// build graph. `cargo audit` reads the lock file, so an advisory can name a
413/// crate nothing compiles — an optional dependency of a feature nobody
414/// enabled. Saying so is more useful than naming no crate at all.
415fn local_dependents(tree_out: &str) -> Vec<String> {
416    let mut names: Vec<String> = tree_out
417        .lines()
418        .filter(|l| l.contains(" (/"))
419        .filter_map(|l| {
420            l.split_whitespace()
421                .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
422                .map(str::to_string)
423        })
424        .collect();
425    names.sort();
426    names.dedup();
427    names
428}
429
430/// One advisory, said in full: the id, the crate it is against, and which of
431/// this workspace's crates actually reach it.
432fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
433    match (krate, reaches.is_empty()) {
434        (None, _) => id.to_string(),
435        (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
436        (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
437    }
438}
439
440/// `cargo audit`, ci.yaml's rules verbatim: the RUSTSEC ids decide, the
441/// exit code only says which class they are.
442fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
443    let mut ids: Vec<String> = out
444        .split_whitespace()
445        .filter(|w| {
446            w.len() == 17
447                && w.starts_with("RUSTSEC-")
448                && w[8..12].bytes().all(|b| b.is_ascii_digit())
449                && w.as_bytes()[12] == b'-'
450                && w[13..17].bytes().all(|b| b.is_ascii_digit())
451        })
452        .map(|w| w.to_string())
453        .collect();
454    ids.sort();
455    ids.dedup();
456    match (ids.is_empty(), exit_ok) {
457        (true, true) => Report::Clean,
458        (true, false) => Report::CouldNotCheck,
459        (false, true) => Report::Advisories(ids),
460        (false, false) => Report::Vulnerabilities(ids),
461    }
462}
463
464/// `npm audit`: the summary line decides. A clean tree is `found 0
465/// vulnerabilities` on every npm. A finding is `found N vulnerabilities`
466/// on npm 6 and `N vulnerabilities (a moderate, b high)` — the verb dropped,
467/// `1 vulnerability` in the singular — on npm 7 and later, which is every
468/// npm shipped since 2020. No recognisable summary plus a refusal to exit
469/// clean is a tool that never answered.
470fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
471    let summary = out.lines().rev().map(str::trim).find(|l| {
472        l.contains("vulnerabilit")
473            && (l.starts_with("found ")
474                || l.split_whitespace()
475                    .next()
476                    .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
477    });
478    match summary {
479        Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
480        Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
481        None if exit_ok => Report::Clean,
482        None => Report::CouldNotCheck,
483    }
484}
485
486/// `pnpm audit`: the summary line decides. A clean tree is `No known
487/// vulnerabilities found`; a finding is `N vulnerabilities found` followed by
488/// `Severity: a low | b moderate | …`, which is carried along so the warning
489/// says how bad. No recognisable summary plus a refusal to exit clean is a
490/// tool that never answered (`ERR_PNPM_AUDIT_BAD_RESPONSE`, no network).
491fn read_pnpm_audit(exit_ok: bool, out: &str) -> Report {
492    let lines: Vec<&str> = out.lines().map(str::trim).collect();
493    if lines
494        .iter()
495        .any(|l| l.starts_with("No known vulnerabilities found"))
496    {
497        return Report::Clean;
498    }
499    let found = lines.iter().enumerate().rev().find(|(_, l)| {
500        let mut w = l.split_whitespace();
501        w.next()
502            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
503            && w.next().is_some_and(|v| v.starts_with("vulnerabilit"))
504            && w.next() == Some("found")
505    });
506    match found {
507        Some((_, l)) if l.starts_with("0 ") => Report::Clean,
508        Some((i, l)) => {
509            let severity = lines
510                .get(i + 1)
511                .and_then(|n| n.strip_prefix("Severity:"))
512                .map(str::trim);
513            Report::Vulnerabilities(vec![match severity {
514                Some(sev) => format!("{l} ({sev})"),
515                None => l.to_string(),
516            }])
517        }
518        None if exit_ok => Report::Clean,
519        None => Report::CouldNotCheck,
520    }
521}
522
523/// `govulncheck`: the GO- ids decide, the exit code classifies them — the
524/// same split cargo-audit taught. The tool exits non-zero only when the
525/// analysed CODE is affected; ids with a clean exit are the informational
526/// section (vulnerable modules whose functions are never called), which is
527/// advisory-grade. No ids plus a refusal to exit clean is a tool that never
528/// answered (no network, no vulnerability database).
529fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
530    let mut ids: Vec<String> = out
531        .split_whitespace()
532        .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
533        .filter(|w| {
534            w.len() >= 12
535                && w.starts_with("GO-")
536                && w[3..7].bytes().all(|b| b.is_ascii_digit())
537                && w.as_bytes()[7] == b'-'
538                && w[8..].bytes().all(|b| b.is_ascii_digit())
539        })
540        .map(|w| w.to_string())
541        .collect();
542    ids.sort();
543    ids.dedup();
544    match (ids.is_empty(), exit_ok) {
545        (true, true) => Report::Clean,
546        (true, false) => Report::CouldNotCheck,
547        (false, true) => Report::Advisories(ids),
548        (false, false) => Report::Vulnerabilities(ids),
549    }
550}
551
552/// `pip-audit`: its own closing sentence decides.
553fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
554    if out.contains("No known vulnerabilities found") {
555        return Report::Clean;
556    }
557    if let Some(line) = out
558        .lines()
559        .map(str::trim)
560        .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
561    {
562        return Report::Vulnerabilities(vec![line.to_string()]);
563    }
564    if exit_ok {
565        Report::Clean
566    } else {
567        Report::CouldNotCheck
568    }
569}
570
571/// The `site-packages` of the environment this project actually uses, if
572/// one is on disk.
573///
574/// `$VIRTUAL_ENV` first — an activated environment is the one whose imports
575/// are live — then the `.venv` uv and PEP 668 tooling create by convention.
576/// Layout differs by platform: `lib/python3.13/site-packages` everywhere
577/// except Windows, which uses `Lib/site-packages`, so the python-version
578/// directory is discovered rather than guessed.
579fn venv_site_packages(root: &str, source: Option<&std::path::Path>) -> Option<String> {
580    // A rehearsal snapshot installs no virtualenv; the working tree it was
581    // taken from (`source`) holds one, but it answers for THIS commit only
582    // when that tree is this commit with its Python manifests unmodified: a
583    // `.venv` synced to a newer HEAD would vouch for a tag it never held
584    // (ADR-0018).
585    let source_venv = source
586        .filter(|src| {
587            let answers = source_is_this_commit(src);
588            if !answers {
589                common::warn(
590                    "audit-python: the source worktree's virtualenv is not this commit's \
591                     (another HEAD, or modified Python manifests) — not auditing it",
592                );
593            }
594            answers
595        })
596        .map(|src| src.join(".venv"));
597    let candidates = std::env::var_os("VIRTUAL_ENV")
598        .map(std::path::PathBuf::from)
599        .into_iter()
600        .chain(std::iter::once(std::path::Path::new(root).join(".venv")))
601        .chain(source_venv);
602    for venv in candidates {
603        let windows = venv.join("Lib").join("site-packages");
604        if windows.is_dir() {
605            return Some(windows.to_string_lossy().into_owned());
606        }
607        let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
608            continue;
609        };
610        for e in entries.flatten() {
611            if !e.file_name().to_string_lossy().starts_with("python") {
612                continue;
613            }
614            let sp = e.path().join("site-packages");
615            if sp.is_dir() {
616                return Some(sp.to_string_lossy().into_owned());
617            }
618        }
619    }
620    None
621}
622
623/// Run one audit tool from the repo root and read its answer.
624fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
625    audited_in(settings, argv, std::path::Path::new(&common::repo_root()))
626}
627
628/// Run one audit tool from `dir` and read its answer.
629fn audited_in(
630    settings: &crate::config::Settings,
631    argv: &[String],
632    dir: &std::path::Path,
633) -> Option<(bool, String)> {
634    let mut cmd = std::process::Command::new(&argv[0]);
635    cmd.args(&argv[1..])
636        .current_dir(dir)
637        .stdin(std::process::Stdio::null());
638    common::strip_git_env(&mut cmd);
639    let (ran, out) = common::capture_within(settings, &mut cmd)?;
640    match ran {
641        common::Ran::Status(s) => Some((s.success(), out)),
642        common::Ran::TimedOut(budget) => {
643            common::say_timed_out(&argv[0], budget);
644            None
645        }
646    }
647}
648
649/// The tool's own reason for not answering: its last line that says
650/// `error`, else its last non-empty line, clipped. "Could not complete" with
651/// nothing after it was the whole message once, over a tree with 19 known
652/// vulnerabilities (amont#305) — the next one must be readable from the hook
653/// output alone.
654fn failure_line(out: &str) -> Option<String> {
655    let lines: Vec<&str> = out
656        .lines()
657        .map(str::trim)
658        .filter(|l| !l.is_empty())
659        .collect();
660    let line = lines
661        .iter()
662        .rev()
663        .find(|l| l.to_ascii_lowercase().contains("error"))
664        .or(lines.last())?;
665    let mut s: String = line.chars().take(200).collect();
666    if line.chars().count() > 200 {
667        s.push('…');
668    }
669    Some(s)
670}
671
672/// What one audit found across every directory it ran in.
673struct Merged {
674    report: Report,
675    /// The tools' reports, each under a header naming its directory (the
676    /// bare report when the only directory is the root).
677    full: String,
678    waivable: bool,
679    /// Every directory answered in full.
680    complete: bool,
681}
682
683/// Run one audit in every directory holding `lockfile` and merge the
684/// answers — the shape `js()` has had since a root-only run left a nested
685/// npm project unaudited. Rust, Go and Python kept the root-only runner, and
686/// a repository whose `Cargo.lock` lived in `apps/ui/src-tauri` was reported
687/// "could not complete" over 19 known vulnerabilities (amont#305).
688///
689/// `argv_in(dir)` builds the command for one directory, or None to skip it
690/// (said by the caller). `refine(dir, report, out)` runs in that directory
691/// after the read — a release's shipped-only split, attribution. A finding
692/// from a subdirectory is labelled with it; the root's are not, so a
693/// repository with its lockfile at the root reads exactly as before. A
694/// directory the tool could not answer for is named with the tool's own
695/// reason, and keeps the merged result from reading clean or being waived.
696fn audit_each_dir(
697    settings: &crate::config::Settings,
698    tool: &str,
699    lockfile: &str,
700    argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
701    read: fn(bool, &str) -> Report,
702    refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
703) -> Merged {
704    let answer_in = |path: &std::path::Path| match argv_in(path) {
705        None => DirAnswer::Nothing,
706        Some(argv) => answer_of(settings, &argv, path, read),
707    };
708    audit_each_dir_answered(tool, lockfile, answer_in, refine)
709}
710
711/// One tool run in `dir`, read by `read`.
712fn answer_of(
713    settings: &crate::config::Settings,
714    argv: &[String],
715    dir: &std::path::Path,
716    read: fn(bool, &str) -> Report,
717) -> DirAnswer {
718    match audited_in(settings, argv, dir) {
719        None => DirAnswer::TimedOut,
720        Some((exit_ok, out)) => DirAnswer::Read {
721            report: read(exit_ok, &out),
722            full: out.clone(),
723            out,
724            gap: None,
725        },
726    }
727}
728
729/// What one directory's audit answered.
730enum DirAnswer {
731    /// Nothing to audit there.
732    Nothing,
733    /// The tool ran out of time, said by `audited_in`: not an answer, and
734    /// the directory is named NOT checked.
735    TimedOut,
736    /// The tool's report. `out` is everything the tool printed, which
737    /// `refine` reads; `full` is the part kept as the report when it has
738    /// findings. `gap` names what went unchecked when only part of the
739    /// directory was audited: its findings still count, and the merged
740    /// result is then never clean nor waivable.
741    Read {
742        report: Report,
743        out: String,
744        full: String,
745        gap: Option<String>,
746    },
747}
748
749/// [`audit_each_dir`] with each directory's answer given by `answer_in`,
750/// for an audit that takes more than one tool run in a directory.
751fn audit_each_dir_answered(
752    tool: &str,
753    lockfile: &str,
754    mut answer_in: impl FnMut(&std::path::Path) -> DirAnswer,
755    mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
756) -> Merged {
757    let root = std::path::PathBuf::from(common::repo_root());
758    let dirs = lockfile_dirs(lockfile);
759    let only_root = dirs.len() == 1 && dirs[0].is_empty();
760    let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
761    let mut partial = Vec::new();
762    let mut full = String::new();
763    for dir in &dirs {
764        let path = root.join(dir);
765        let label = if dir.is_empty() { "." } else { dir.as_str() };
766        let label_ids = |ids: Vec<String>| -> Vec<String> {
767            if dir.is_empty() {
768                ids
769            } else {
770                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
771            }
772        };
773        let (report, out, dir_full, gap) = match answer_in(&path) {
774            DirAnswer::Nothing => {
775                unchecked.push(format!("{label} (nothing to audit there)"));
776                continue;
777            }
778            // A timeout is said by `audited_in` itself. The other
779            // directories still answer: their findings must not be lost.
780            DirAnswer::TimedOut => {
781                unchecked.push(format!("{label} (timed out)"));
782                continue;
783            }
784            DirAnswer::Read {
785                report,
786                out,
787                full,
788                gap,
789            } => (report, out, full, gap),
790        };
791        let report = refine(&path, report, &out);
792        if gap.is_some() && !matches!(report, Report::CouldNotCheck) {
793            partial.push(label.to_string());
794        }
795        match report {
796            Report::Vulnerabilities(ids) => {
797                vulns.extend(label_ids(ids));
798                if only_root {
799                    full.push_str(&dir_full);
800                } else {
801                    full.push_str(&format!("── {tool} in {label}\n{dir_full}\n"));
802                }
803            }
804            Report::Advisories(ids) => advisories.extend(label_ids(ids)),
805            Report::CouldNotCheck => unchecked.push(match gap.or_else(|| failure_line(&out)) {
806                Some(why) => format!("{label} ({why})"),
807                None => label.to_string(),
808            }),
809            Report::Clean => {}
810        }
811    }
812    if !unchecked.is_empty() {
813        common::warn(&format!(
814            "{tool}: the audit could not answer in {} — NOT checked there",
815            unchecked.join(", ")
816        ));
817    }
818    // Its own lines said why; this one says the directory is not clean.
819    if !partial.is_empty() {
820        common::warn(&format!(
821            "{tool}: NOT fully checked in {} (part of the audit did not answer)",
822            partial.join(", ")
823        ));
824    }
825    let report = if !vulns.is_empty() {
826        Report::Vulnerabilities(vulns)
827    } else if !unchecked.is_empty() || !partial.is_empty() {
828        Report::CouldNotCheck
829    } else if !advisories.is_empty() {
830        Report::Advisories(advisories)
831    } else {
832        Report::Clean
833    };
834    Merged {
835        report,
836        full,
837        waivable: unchecked.is_empty() && partial.is_empty(),
838        complete: unchecked.is_empty() && partial.is_empty(),
839    }
840}
841
842fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
843    let (settings, refs) = (ctx.settings, ctx.push.get());
844    if !has_lockfile("Cargo.lock") {
845        return Ran::Inert;
846    }
847    if common::which("cargo-audit").is_none() {
848        common::warn(
849            "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
850             the audit did NOT run",
851        );
852        return Ran::Unavailable;
853    }
854    let argv = vec![
855        common::program("cargo"),
856        "audit".into(),
857        "--color".into(),
858        "never".into(),
859    ];
860    let release = releasing(refs);
861    let merged = audit_each_dir(
862        settings,
863        "audit-rust",
864        "Cargo.lock",
865        |_| Some(argv.clone()),
866        read_cargo_audit,
867        |dir, mut report, out| {
868            if release {
869                if let Report::Vulnerabilities(ids) = report {
870                    let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
871                        cargo_tree_shipped(settings, dir, krate)
872                    });
873                    warn_dev_only("audit-rust", &dev_only);
874                    report = if shipped.is_empty() {
875                        Report::Clean
876                    } else {
877                        Report::Vulnerabilities(shipped)
878                    };
879                }
880            }
881            attribute(report, out, |krate| {
882                cargo_tree_inverse(settings, dir, krate)
883            })
884        },
885    );
886    Ran::Concluded(Concluded {
887        tool: "audit-rust".to_string(),
888        report: merged.report,
889        full: merged.full,
890        waivable: merged.waivable,
891        complete: merged.complete,
892    })
893}
894
895/// `cargo tree -i <crate>` over the edges a RELEASE ships: normal and build
896/// dependencies (a dependency's build script runs on every machine that
897/// compiles it), for every target and every feature, so nothing a consumer
898/// could switch on is mistaken for dev-only. None if it could not run.
899fn cargo_tree_shipped(
900    settings: &crate::config::Settings,
901    dir: &std::path::Path,
902    spec: &str,
903) -> Option<String> {
904    let argv = vec![
905        common::program("cargo"),
906        "tree".into(),
907        "--invert".into(),
908        spec.into(),
909        "--edges".into(),
910        "normal,build".into(),
911        "--target".into(),
912        "all".into(),
913        "--all-features".into(),
914        "--color".into(),
915        "never".into(),
916    ];
917    // Unlike the message-only inverse tree, a failure here must not read as
918    // "nothing reaches it": an error prints no local crate either.
919    audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
920}
921
922/// Does a shipped-edges inverse tree say the crate is dev-only? Only on
923/// positive evidence: no local crate reaches it AND cargo said there is
924/// nothing to print. Anything else — an unreadable tree — ships.
925fn tree_says_dev_only(tree: &str) -> bool {
926    local_dependents(tree).is_empty() && tree.contains("nothing to print")
927}
928
929/// Split a release's advisory ids into those that ship and those only the
930/// dev tree carries. An id whose crate is unknown, or whose tree could not
931/// be read, ships: an unknown is not a pass.
932fn split_shipped_crates(
933    ids: Vec<String>,
934    out: &str,
935    shipped_tree: impl Fn(&str) -> Option<String>,
936) -> (Vec<String>, Vec<String>) {
937    let specs = ids_with_specs(out);
938    let mut verdicts: Vec<(String, bool)> = Vec::new();
939    let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
940    for id in ids {
941        let spec = specs
942            .iter()
943            .find(|(pid, spec)| *pid == id && spec.is_some())
944            .and_then(|(_, spec)| spec.clone());
945        let ships = match spec {
946            None => true,
947            // Cached by name@version: two locked versions of one crate are
948            // two answers, and one being dev-only says nothing of the other.
949            Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
950                Some((_, v)) => *v,
951                None => {
952                    let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
953                    verdicts.push((spec, v));
954                    v
955                }
956            },
957        };
958        if ships {
959            shipped.push(id);
960        } else {
961            dev_only.push(id);
962        }
963    }
964    (shipped, dev_only)
965}
966
967/// Each advisory id with the package its OWN block names: `crate@version`
968/// when cargo audit printed a `Version:` in that block, the bare crate name
969/// otherwise, None for an id outside any block.
970fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
971    let mut pairs = Vec::new();
972    let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
973    for line in out.lines().map(str::trim) {
974        if let Some(rest) = line.strip_prefix("Crate:") {
975            krate = rest.split_whitespace().next().map(str::to_string);
976            version = None;
977        } else if let Some(rest) = line.strip_prefix("Version:") {
978            version = rest.split_whitespace().next().map(str::to_string);
979        } else if let Some(rest) = line.strip_prefix("ID:") {
980            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
981                let spec = krate.take().map(|k| match version.take() {
982                    Some(v) => format!("{k}@{v}"),
983                    None => k,
984                });
985                pairs.push((id.to_string(), spec));
986            }
987        }
988    }
989    pairs
990}
991
992/// Name what a release does not ship and therefore does not refuse.
993fn warn_dev_only(tool: &str, dev_only: &[String]) {
994    if !dev_only.is_empty() {
995        common::warn(&format!(
996            "{tool}: dev-only, only in development dependencies, which the release does not ship — not blocking: {}",
997            dev_only.join("; ")
998        ));
999    }
1000}
1001
1002/// `cargo tree -i <crate>`, or None if it could not be run. Failure here is
1003/// never fatal: attribution is an improvement to a message, and an advisory
1004/// reported without it is still an advisory reported.
1005fn cargo_tree_inverse(
1006    settings: &crate::config::Settings,
1007    dir: &std::path::Path,
1008    krate: &str,
1009) -> Option<String> {
1010    let argv = vec![
1011        common::program("cargo"),
1012        "tree".into(),
1013        "--invert".into(),
1014        krate.into(),
1015        "--edges".into(),
1016        "normal".into(),
1017        "--color".into(),
1018        "never".into(),
1019    ];
1020    audited_in(settings, &argv, dir).map(|(_, out)| out)
1021}
1022
1023/// Name the crate behind each advisory, and which of this workspace's crates
1024/// reach it.
1025///
1026/// Deliberately spawns NOTHING on a clean report, which is every run that
1027/// matters: the `cargo tree` calls happen once per distinct affected crate,
1028/// only when there is already something to say. A hook on the push path does
1029/// not pay for a message nobody will read.
1030fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
1031    match report {
1032        Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
1033        Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
1034        // Clean and CouldNotCheck carry no ids, so there is nothing to
1035        // attribute and — the part that matters — nothing to spawn.
1036        other => other,
1037    }
1038}
1039
1040/// Each id, rewritten with its crate and what reaches it where both are
1041/// known. One `cargo tree` per distinct crate, not per advisory: `lru`
1042/// carried two advisories in the run that prompted this.
1043fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
1044    let pairs = ids_with_crates(out);
1045    let mut seen: Vec<(String, Vec<String>)> = Vec::new();
1046    ids.iter()
1047        .map(|id| {
1048            let krate = pairs
1049                .iter()
1050                .find(|(pid, k)| pid == id && k.is_some())
1051                .and_then(|(_, k)| k.clone());
1052            let Some(k) = krate else {
1053                return id.clone();
1054            };
1055            if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
1056                return describe(id, Some(&k), reaches);
1057            }
1058            let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
1059            seen.push((k.clone(), reaches.clone()));
1060            describe(id, Some(&k), &reaches)
1061        })
1062        .collect()
1063}
1064
1065/// Does the repository carry `lockfile` anywhere in its index? An audit
1066/// without a resolved tree audits a guess — and one asked about a
1067/// repository in another language has nothing to audit at all. That is
1068/// `Inert`, not "could not run": the dispatcher asks the same question
1069/// from the registry's scope, and this is the answer for a check invoked
1070/// by name.
1071fn has_lockfile(lockfile: &str) -> bool {
1072    crate::tracked_paths()
1073        .iter()
1074        .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1075}
1076
1077/// The directories holding a tracked `lockfile`, repo-relative ("" for the
1078/// root), sorted. npm resolves a project from its own directory, so a
1079/// repository whose packages live in subdirectories (`web/`, `mcp/`) has no
1080/// lockfile at the root at all.
1081fn lockfile_dirs(lockfile: &str) -> Vec<String> {
1082    let mut dirs: Vec<String> = crate::tracked_paths()
1083        .iter()
1084        .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1085        .map(|p| {
1086            p.rsplit_once('/')
1087                .map(|(d, _)| d.to_string())
1088                .unwrap_or_default()
1089        })
1090        .collect();
1091    dirs.sort();
1092    dirs.dedup();
1093    dirs
1094}
1095
1096/// One JS package manager `audit-js` knows how to ask: the lockfile that
1097/// opts a directory in, the tool that reads it, and how to read its answer.
1098struct JsAuditor {
1099    lockfile: &'static str,
1100    tool: &'static str,
1101    read: fn(bool, &str) -> Report,
1102    /// Extra arguments for a project in `dir`.
1103    args: fn(&str) -> Vec<String>,
1104    /// The flag that limits the audit to what the project ships — its
1105    /// production dependencies, without the dev tree.
1106    prod_only: &'static str,
1107}
1108
1109/// pnpm answers for the WORKSPACE it finds above a directory, not for the
1110/// directory: a standalone project with its own pnpm-lock.yaml inside a
1111/// workspace (a spike, an example) was reported with the workspace root's
1112/// findings, all of them, under its own name. `--ignore-workspace` makes it
1113/// read the lockfile it stands next to — except at a workspace's own root,
1114/// where the workspace IS the project and every member must be audited.
1115fn pnpm_args(dir: &str) -> Vec<String> {
1116    let manifest = if dir.is_empty() {
1117        "pnpm-workspace.yaml".to_string()
1118    } else {
1119        format!("{dir}/pnpm-workspace.yaml")
1120    };
1121    if crate::tracked_paths().contains(&manifest) {
1122        vec![]
1123    } else {
1124        vec!["--ignore-workspace".into()]
1125    }
1126}
1127
1128const JS_AUDITORS: [JsAuditor; 2] = [
1129    JsAuditor {
1130        lockfile: "package-lock.json",
1131        tool: "npm",
1132        read: read_npm_audit,
1133        args: |_| vec![],
1134        prod_only: "--omit=dev",
1135    },
1136    JsAuditor {
1137        lockfile: "pnpm-lock.yaml",
1138        tool: "pnpm",
1139        read: read_pnpm_audit,
1140        args: pnpm_args,
1141        prod_only: "--prod",
1142    },
1143];
1144
1145/// `npm audit` in every directory that tracks a `package-lock.json`, and
1146/// `pnpm audit` in every directory that tracks a `pnpm-lock.yaml`.
1147///
1148/// It used to run once at the repository root, where a repository whose
1149/// packages live in subdirectories has no lockfile: npm answered ENOLOCK,
1150/// the check said "could not complete", and a tree with 17 known
1151/// vulnerabilities (9 high) went unaudited release after release. Each
1152/// project is audited on its own; any finding counts, labelled with its
1153/// directory, and a project the tool could not answer for keeps the whole
1154/// result from reading clean.
1155///
1156/// And it only ever knew npm: a pnpm workspace has no `package-lock.json`,
1157/// so its whole tree — 28 vulnerable versions, two critical, in one
1158/// repository — was never audited and nothing said so. pnpm audits its own
1159/// lockfile, from the lockfile alone, the same way.
1160///
1161/// On a release, what blocks is what SHIPS: a finding is audited again with
1162/// the production dependencies only (`--omit=dev` / `--prod`), and one that
1163/// lives only in the dev tree — a build script's toolchain, a test runner —
1164/// is named but does not refuse the tag. Nobody who installs the package
1165/// installs it. A finding whose production re-audit cannot answer still
1166/// blocks: an unknown is not a pass.
1167fn js_run(ctx: &crate::registry::Ctx) -> Ran {
1168    let (settings, refs) = (ctx.settings, ctx.push.get());
1169    let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
1170        .iter()
1171        .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
1172        .collect();
1173    if projects.is_empty() {
1174        return Ran::Inert;
1175    }
1176    let root = std::path::PathBuf::from(common::repo_root());
1177    let release = releasing(refs);
1178    let mut found = Vec::new();
1179    let mut dev_only = Vec::new();
1180    let mut unchecked = Vec::new();
1181    let mut full = String::new();
1182    for (auditor, dir) in &projects {
1183        let label = if dir.is_empty() {
1184            ".".to_string()
1185        } else {
1186            dir.clone()
1187        };
1188        let mut argv = vec![common::program(auditor.tool), "audit".into()];
1189        argv.extend((auditor.args)(dir));
1190        let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
1191            common::warn(&format!(
1192                "audit-js: {} could not run in {label} — the audit did NOT run",
1193                auditor.tool
1194            ));
1195            return Ran::Unavailable;
1196        };
1197        match (auditor.read)(exit_ok, &out) {
1198            Report::Vulnerabilities(what) if release => {
1199                let mut prod = argv.clone();
1200                prod.push(auditor.prod_only.into());
1201                match audited_in(settings, &prod, &root.join(dir))
1202                    .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
1203                {
1204                    Some((Report::Clean | Report::Advisories(_), _)) => {
1205                        dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1206                    }
1207                    Some((Report::Vulnerabilities(shipped), pout)) => {
1208                        found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
1209                        full.push_str(&format!(
1210                            "── {} audit {} in {label}\n{pout}\n",
1211                            auditor.tool, auditor.prod_only
1212                        ));
1213                    }
1214                    Some((Report::CouldNotCheck, _)) | None => {
1215                        found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1216                        full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1217                    }
1218                }
1219            }
1220            Report::Vulnerabilities(what) => {
1221                found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1222                full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1223            }
1224            Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
1225            Report::Clean | Report::Advisories(_) => {}
1226        }
1227    }
1228    if !unchecked.is_empty() {
1229        common::warn(&format!(
1230            "audit-js: the audit could not answer in {} — those projects were NOT checked",
1231            unchecked.join(", ")
1232        ));
1233    }
1234    warn_dev_only("audit-js", &dev_only);
1235    let waivable = unchecked.is_empty();
1236    let report = if !found.is_empty() {
1237        Report::Vulnerabilities(found)
1238    } else if !unchecked.is_empty() {
1239        Report::CouldNotCheck
1240    } else {
1241        Report::Clean
1242    };
1243    Ran::Concluded(Concluded {
1244        tool: "audit-js".to_string(),
1245        report,
1246        full,
1247        waivable,
1248        complete: true,
1249    })
1250}
1251
1252/// Go needs no production filter: modules have no dev-dependency set, and
1253/// `govulncheck ./...` without `-test` reports only vulnerabilities the
1254/// module's non-test code can reach — what ships, already.
1255///
1256/// A tools module (a `go.mod` with a `tool` directive and no package) has
1257/// nothing `./...` matches, and govulncheck answers "no packages matched";
1258/// its tools are audited through the `tool` pattern instead.
1259fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1260    let settings = ctx.settings;
1261    if !has_lockfile("go.sum") {
1262        return Ran::Inert;
1263    }
1264    if common::which("govulncheck").is_none() {
1265        common::warn(
1266            "audit-go: govulncheck is not installed \
1267             (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1268        );
1269        return Ran::Unavailable;
1270    }
1271    // Which directories are tools modules, worked out once, in `argv_in`,
1272    // and read back in `refine`.
1273    let tool_dirs = std::cell::RefCell::new(std::collections::HashSet::new());
1274    let argv_in = |dir: &std::path::Path| {
1275        let tools_only =
1276            !super::go_tools::has_go_package(dir) && super::go_tools::declares_tool(dir);
1277        if tools_only {
1278            tool_dirs.borrow_mut().insert(dir.to_path_buf());
1279        }
1280        let pattern = if tools_only { "tool" } else { "./..." };
1281        Some(vec![common::program("govulncheck"), pattern.into()])
1282    };
1283    // Tools do not ship: their findings warn and never block, on a branch or
1284    // a `v*` tag (ADR-0055, dev-only findings warn).
1285    let root = std::path::PathBuf::from(common::repo_root());
1286    let mut in_tools = Vec::new();
1287    let refine = |dir: &std::path::Path, report: Report, _: &str| match report {
1288        Report::Vulnerabilities(ids) if tool_dirs.borrow().contains(dir) => {
1289            let label = dir
1290                .strip_prefix(&root)
1291                .ok()
1292                .map(|d| d.display().to_string())
1293                .filter(|d| !d.is_empty())
1294                .unwrap_or_else(|| ".".into());
1295            in_tools.push(format!("{label} (govulncheck tool): {}", ids.join(", ")));
1296            Report::Clean
1297        }
1298        other => other,
1299    };
1300    let merged = audit_each_dir(
1301        settings,
1302        "audit-go",
1303        "go.sum",
1304        argv_in,
1305        read_govulncheck,
1306        refine,
1307    );
1308    if !in_tools.is_empty() {
1309        common::warn(&format!(
1310            "audit-go: in a tools module, whose tools the release does not ship — not blocking: {}",
1311            in_tools.join("; ")
1312        ));
1313    }
1314    Ran::Concluded(Concluded {
1315        tool: "audit-go".to_string(),
1316        report: merged.report,
1317        full: merged.full,
1318        waivable: merged.waivable,
1319        complete: merged.complete,
1320    })
1321}
1322
1323fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1324    let (settings, refs) = (ctx.settings, ctx.push.get());
1325    if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1326        return Ran::Inert;
1327    }
1328    if common::which("pip-audit").is_none() {
1329        common::warn(
1330            "audit-python: pip-audit is not installed (pip install pip-audit) — \
1331             the audit did NOT run",
1332        );
1333        return Ran::Unavailable;
1334    }
1335    let root = common::repo_root();
1336    // A requirements.txt is the production list by convention, audited in
1337    // its own directory — wherever the repository keeps one (amont#305).
1338    if !lockfile_dirs("requirements.txt").is_empty() {
1339        let root_path = std::path::PathBuf::from(&root);
1340        let rel_of = |dir: &std::path::Path| {
1341            dir.strip_prefix(&root_path)
1342                .map(|p| p.to_string_lossy().into_owned())
1343                .unwrap_or_default()
1344        };
1345        let answer_in = |dir: &std::path::Path| {
1346            let pins = hashed_pins(dir);
1347            let names = pins.as_ref().map(HashedPins::names);
1348            let answer = match pins {
1349                Some(pins) if pins.marked => audit_marked_pins(settings, dir, &rel_of(dir), pins),
1350                hashed => {
1351                    let mut argv = vec![
1352                        common::program("pip-audit"),
1353                        "-r".into(),
1354                        "requirements.txt".into(),
1355                    ];
1356                    // A fully hashed file is a closed set: nothing to resolve,
1357                    // and resolving it on this host can fail on a pin with no
1358                    // wheel here (torch 2.14.0+cpu on Intel macOS, decisions f108).
1359                    if hashed.is_some() {
1360                        argv.extend(["--no-deps".into(), "--disable-pip".into()]);
1361                    }
1362                    answer_of(settings, &argv, dir, read_pip_audit)
1363                }
1364            };
1365            let DirAnswer::Read {
1366                report,
1367                out,
1368                full,
1369                gap,
1370            } = answer
1371            else {
1372                return answer;
1373            };
1374            let skipped = pip_skipped_names(&out);
1375            if skipped.is_empty() {
1376                return DirAnswer::Read {
1377                    report,
1378                    out,
1379                    full,
1380                    gap,
1381                };
1382            }
1383            let skipped_names: Vec<&str> = skipped.iter().map(String::as_str).collect();
1384            common::warn(&skipped_line(
1385                &requirements_prefix(&rel_of(dir)),
1386                &skipped_names,
1387            ));
1388            // Every pin skipped: nothing was audited, which is not clean.
1389            let all_skipped = names.is_some_and(|n| skipped.len() >= n);
1390            let report = if all_skipped && !matches!(report, Report::Vulnerabilities(_)) {
1391                Report::CouldNotCheck
1392            } else {
1393                report
1394            };
1395            DirAnswer::Read {
1396                report,
1397                out,
1398                full,
1399                gap,
1400            }
1401        };
1402        let merged = audit_each_dir_answered(
1403            "audit-python",
1404            "requirements.txt",
1405            answer_in,
1406            |_, report, _| report,
1407        );
1408        // A row whose advisory id is not one a waiver can name makes the
1409        // whole report unwaivable.
1410        let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1411        return Ran::Concluded(Concluded {
1412            tool: "audit-python".to_string(),
1413            report: merged.report,
1414            full: merged.full,
1415            waivable,
1416            complete: merged.complete,
1417        });
1418    }
1419    let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1420        // A uv/PEP-621 project has no requirements.txt, and EXPORTING one
1421        // does not work either: `uv export` emits the workspace's own
1422        // members and any private-index dependency, and pip-audit resolves
1423        // a requirements file in a throwaway venv that can reach neither —
1424        // it dies on "No matching distribution found". Auditing the
1425        // INSTALLED tree resolves nothing, and is the truer question
1426        // anyway: these are the versions actually imported.
1427        vec![
1428            common::program("pip-audit"),
1429            "--path".into(),
1430            site_packages,
1431            // Workspace members are installed editable and are not on
1432            // PyPI; without this each one is a line of noise.
1433            "--skip-editable".into(),
1434        ]
1435    } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1436        // No virtualenv: the lock says what would be installed.
1437        return python_lock_run(ctx);
1438    } else {
1439        common::warn(
1440            "audit-python: the audit did NOT run — found no requirements.txt,\n  \
1441             no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n  \
1442             Next: `uv sync`, or install uv so uv.lock can be audited.",
1443        );
1444        return Ran::Unavailable;
1445    };
1446    let Some((exit_ok, out)) = audited(settings, &argv) else {
1447        return Ran::Unavailable;
1448    };
1449    // A requirements.txt is the production list by convention (dev pins
1450    // live beside it, in requirements-dev.txt). A virtualenv or a lock holds
1451    // the dev groups too, so on a release its findings are checked against
1452    // what `uv export --no-dev` says ships — asked only when there are any.
1453    let report = read_pip_audit(exit_ok, &out);
1454    let production = if releasing(refs) && has_rows_to_split(&report, &out) {
1455        uv_production_names(settings, std::path::Path::new(&root))
1456    } else {
1457        None
1458    };
1459    let (report, waivable) = shipped_only(report, &out, production.as_ref());
1460    Ran::Concluded(Concluded {
1461        tool: "audit-python".to_string(),
1462        report,
1463        full: out,
1464        waivable,
1465        complete: true,
1466    })
1467}
1468
1469/// On a release, split pip-audit's findings into what ships and what only
1470/// the dev groups carry; the latter warn and do not block. `(report,
1471/// waivable)`: a row whose advisory id is not one a waiver can name (MAL-, a
1472/// new scheme) makes the whole report unwaivable. When the production names
1473/// are unknown (`None`) every finding is kept: an unknown is not a pass.
1474fn shipped_only(
1475    mut report: Report,
1476    out: &str,
1477    production: Option<&std::collections::HashSet<String>>,
1478) -> (Report, bool) {
1479    let mut waivable = pip_rows_all_named(out);
1480    if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1481        let rows = pip_vulnerable_rows(out);
1482        if !rows.is_empty() {
1483            let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1484                .into_iter()
1485                .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1486                .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1487                    if ships {
1488                        s.push(row);
1489                    } else {
1490                        d.push(row);
1491                    }
1492                    (s, d)
1493                });
1494            warn_dev_only("audit-python", &dev_only);
1495            waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1496            report = if shipped.is_empty() {
1497                Report::Clean
1498            } else {
1499                Report::Vulnerabilities(shipped)
1500            };
1501        }
1502    }
1503    (report, waivable)
1504}
1505
1506/// Would [`shipped_only`] split anything? Only a vulnerability report with
1507/// rows it can read; for every other report the production names change
1508/// nothing, so they are not worth a `uv export`.
1509fn has_rows_to_split(report: &Report, out: &str) -> bool {
1510    matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
1511}
1512
1513/// What one lock directory ships, asked of [`uv_production_names`] at most
1514/// once, and only on a release whose batch has findings to split.
1515enum Production {
1516    /// No release: never asked, every finding is kept.
1517    Never,
1518    /// A release, not asked yet: ask in this lock directory.
1519    Unasked(std::path::PathBuf),
1520    /// Asked; None when the export could not answer or time ran out.
1521    Asked(Option<std::collections::HashSet<String>>),
1522}
1523
1524impl Production {
1525    /// The production names, None when this is no release, the export
1526    /// cannot answer, or the budget is spent before it is asked (`say`
1527    /// warns once): every finding is then kept.
1528    fn names(
1529        &mut self,
1530        settings: &crate::config::Settings,
1531        budget: &Budget,
1532        say: &dyn Fn(&str),
1533    ) -> Option<&std::collections::HashSet<String>> {
1534        if let Production::Unasked(dir) = self {
1535            *self = Production::Asked(if budget.spent() {
1536                say(&format!(
1537                    "out of time before the dev-only split — every finding counts\n  {TIMEOUT_NEXT}"
1538                ));
1539                None
1540            } else {
1541                uv_production_names(settings, dir)
1542            });
1543        }
1544        match self {
1545            Production::Asked(names) => names.as_ref(),
1546            Production::Never | Production::Unasked(_) => None,
1547        }
1548    }
1549}
1550
1551/// The next step after the lock route ran out of time.
1552const TIMEOUT_NEXT: &str =
1553    "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";
1554
1555/// The next step after a scratch file could not be made, written or read.
1556const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";
1557
1558/// The next step after pip-audit could not answer, from its own reason: the
1559/// network when the reason names it, else pip-audit itself.
1560fn pip_audit_next(why: &str) -> &'static str {
1561    // holds-until: pip-audit's English error wording is the only signal; when
1562    // it reports an error class or a distinct exit code for the network,
1563    // decide on that instead of these words.
1564    let why = why.to_ascii_lowercase();
1565    let network = [
1566        "network",
1567        "connect",
1568        "timed out",
1569        "timeout",
1570        "resolve",
1571        "dns",
1572        "ssl",
1573        "certificate",
1574        "unreachable",
1575        "temporary failure",
1576    ]
1577    .iter()
1578    .any(|word| why.contains(word));
1579    if network {
1580        "Next: check the network, then push again"
1581    } else {
1582        "Next: `pip-audit --version` to check the install, then push again"
1583    }
1584}
1585
1586/// The only registry whose packages are looked up: ADR-0055 sends public
1587/// names to OSV and pip-audit asks PyPI, and nothing else may be sent.
1588const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1589
1590/// Columns a warning line may use.
1591const WARNING_COLUMNS: usize = 80;
1592
1593/// How many names a count in a warning spells out.
1594const NAMES_SHOWN: usize = 3;
1595
1596/// A directory only this process can enter, removed on every return and
1597/// panic. A signal leaves it behind, as `capture.rs` notes for its own.
1598struct PrivateDir {
1599    path: std::path::PathBuf,
1600}
1601
1602impl PrivateDir {
1603    /// A fresh directory under the temp dir, mode 0700, named unpredictably.
1604    fn create() -> std::io::Result<PrivateDir> {
1605        Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1606    }
1607
1608    /// `path` itself, created exclusively and not recursively: it fails when
1609    /// anything is already there, so nothing planted is ever written through.
1610    fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1611        #[cfg(unix)]
1612        let builder = {
1613            let mut unix_builder = std::fs::DirBuilder::new();
1614            std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1615            unix_builder
1616        };
1617        #[cfg(not(unix))]
1618        let builder = std::fs::DirBuilder::new();
1619        builder.create(&path)?;
1620        Ok(PrivateDir { path })
1621    }
1622
1623    fn path(&self) -> &std::path::Path {
1624        &self.path
1625    }
1626}
1627
1628impl Drop for PrivateDir {
1629    fn drop(&mut self) {
1630        let _ = std::fs::remove_dir_all(&self.path); // best effort: a leftover temp dir holds no secret, and a failure must not panic
1631    }
1632}
1633
1634/// One time budget for a run of several pip-audit calls: the whole lock
1635/// route, or one marked requirements file's batches.
1636struct Budget {
1637    started: std::time::Instant,
1638    /// None: `greengate.timeout 0` disables the ceiling.
1639    limit: Option<std::time::Duration>,
1640}
1641
1642impl Budget {
1643    fn new(settings: &crate::config::Settings) -> Budget {
1644        Budget {
1645            started: std::time::Instant::now(),
1646            limit: Some(common::check_timeout(settings))
1647                .filter(|secs| *secs > 0)
1648                .map(std::time::Duration::from_secs),
1649        }
1650    }
1651
1652    fn spent(&self) -> bool {
1653        self.limit
1654            .is_some_and(|limit| self.started.elapsed() >= limit)
1655    }
1656}
1657
1658/// Which `uv.lock` packages come from PyPI, by PEP 503 name.
1659#[derive(Debug, Default, PartialEq, Eq)]
1660struct LockSources {
1661    /// Every `[[package]]` block of the name has the PyPI registry.
1662    pypi: std::collections::BTreeSet<String>,
1663    /// Blocks with no name: counted, never classified.
1664    nameless: usize,
1665}
1666
1667/// `source = { registry = "<url>" }` naming PyPI, trailing slash or not.
1668fn is_pypi_source(source_field: &str) -> bool {
1669    source_field
1670        .split_once("registry = \"")
1671        .and_then(|(_, rest)| rest.split('"').next())
1672        .is_some_and(|url| url.trim_end_matches('/') == PYPI_REGISTRY)
1673}
1674
1675/// A std-only line scan of `uv.lock`'s `[[package]]` blocks (no TOML crate:
1676/// `scripts/check-no-deps.sh`). Only top-level `name` and `source` keys of a
1677/// block count; a name qualifies only when all its blocks come from PyPI.
1678fn scan_uv_lock(text: &str) -> LockSources {
1679    struct Block {
1680        name: Option<String>,
1681        pypi: bool,
1682    }
1683    let mut blocks: Vec<Block> = Vec::new();
1684    let mut top_level = false;
1685    for line in text.lines() {
1686        if line.starts_with('[') {
1687            top_level = line.trim() == "[[package]]";
1688            if top_level {
1689                blocks.push(Block {
1690                    name: None,
1691                    pypi: false,
1692                });
1693            }
1694            continue;
1695        }
1696        let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1697            continue;
1698        };
1699        if let Some(value) = line.strip_prefix("name = ") {
1700            if block.name.is_none() {
1701                block.name = value.split('"').nth(1).map(normalise);
1702            }
1703        } else if let Some(value) = line.strip_prefix("source = ") {
1704            block.pypi = is_pypi_source(value);
1705        }
1706    }
1707    let mut sources = LockSources::default();
1708    let mut rejected = std::collections::BTreeSet::new();
1709    for block in blocks {
1710        match block.name.filter(|n| !n.is_empty()) {
1711            None => sources.nameless += 1,
1712            Some(name) if block.pypi => {
1713                sources.pypi.insert(name);
1714            }
1715            Some(name) => {
1716                rejected.insert(name);
1717            }
1718        }
1719    }
1720    sources.pypi.retain(|name| !rejected.contains(name));
1721    sources
1722}
1723
1724/// What of an export may be sent to pip-audit.
1725#[derive(Debug, Default, PartialEq, Eq)]
1726struct ExportPins {
1727    /// Audit inputs: `name -> version`, one version per name in each batch,
1728    /// because pip-audit rejects conflicting pins in one requirements input.
1729    batches: Vec<std::collections::BTreeMap<String, String>>,
1730    /// Distinct (name, version) pairs across the batches.
1731    versions: usize,
1732    /// Exported names that are not PyPI's: never sent.
1733    skipped: std::collections::BTreeSet<String>,
1734    /// PyPI names whose line is not an exact `name==version` pin.
1735    unclassified: std::collections::BTreeSet<String>,
1736}
1737
1738/// `name==version` of one export line with its environment marker stripped,
1739/// so every platform and Python-version variant is audited whatever the host.
1740fn exact_pin(line: &str) -> Option<(String, String)> {
1741    let spec = line.split(';').next()?.trim();
1742    let (name, version) = spec.split_once("==")?;
1743    let name = name.split('[').next()?.trim();
1744    let version = version.trim();
1745    let name_ok = !name.is_empty()
1746        && name
1747            .chars()
1748            .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1749    let version_ok = !version.is_empty()
1750        && version
1751            .chars()
1752            .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1753    (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1754}
1755
1756fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1757    let mut pins = ExportPins::default();
1758    let mut pairs = std::collections::BTreeSet::new();
1759    for line in raw.lines().map(str::trim) {
1760        if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1761            continue;
1762        }
1763        let name = normalise(
1764            line.split(|c: char| "=<>!~;[ @".contains(c))
1765                .next()
1766                .unwrap_or_default(),
1767        );
1768        if name.is_empty() {
1769            continue;
1770        }
1771        if !pypi.contains(&name) {
1772            pins.skipped.insert(name);
1773            continue;
1774        }
1775        match exact_pin(line) {
1776            Some(pair) => {
1777                pairs.insert(pair);
1778            }
1779            None => {
1780                pins.unclassified.insert(name);
1781            }
1782        }
1783    }
1784    pins.versions = pairs.len();
1785    pins.batches = batches_of(pairs);
1786    pins
1787}
1788
1789/// `(name, version)` pairs split into pip-audit inputs, one version of a
1790/// name in each: pip-audit refuses two pins of one name in one run, even
1791/// across several `-r` files ("package jinja2 has duplicate requirements").
1792fn batches_of(
1793    pairs: std::collections::BTreeSet<(String, String)>,
1794) -> Vec<std::collections::BTreeMap<String, String>> {
1795    let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
1796    for (name, version) in pairs {
1797        match batches.iter().position(|batch| !batch.contains_key(&name)) {
1798            Some(index) => {
1799                batches[index].insert(name, version);
1800            }
1801            None => batches.push(std::collections::BTreeMap::from([(name, version)])),
1802        }
1803    }
1804    batches
1805}
1806
1807/// `requirements.txt` in the repository-relative directory `rel`.
1808fn requirements_path(rel: &str) -> String {
1809    if rel.is_empty() {
1810        "requirements.txt".to_string()
1811    } else {
1812        format!("{rel}/requirements.txt")
1813    }
1814}
1815
1816/// What a warning about `rel`'s requirements.txt starts with: nothing at
1817/// the root, so a root file reads as it always has.
1818fn requirements_prefix(rel: &str) -> String {
1819    if rel.is_empty() {
1820        String::new()
1821    } else {
1822        format!("{}: ", requirements_path(rel))
1823    }
1824}
1825
1826/// A hashed requirements.txt whose pins carry environment markers, audited
1827/// from its pins with the markers stripped, so every platform's pin is
1828/// audited whatever the host (decisions f118). pip-audit evaluates a marker
1829/// against the host and drops a pin it does not match without a word:
1830/// `jinja2==2.10 ; sys_platform == 'linux'` read clean on a Mac.
1831///
1832/// Each batch is a separate run (pip-audit refuses two pins of one name in
1833/// one run) and is read on its own: a clean batch's sentence would hide the
1834/// next one's finding. A gap keeps what the earlier batches found.
1835fn audit_marked_pins(
1836    settings: &crate::config::Settings,
1837    dir: &std::path::Path,
1838    rel: &str,
1839    pins: HashedPins,
1840) -> DirAnswer {
1841    let prefix = requirements_prefix(rel);
1842    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1843    let unchecked = |why: &str| DirAnswer::Read {
1844        report: Report::CouldNotCheck,
1845        out: String::new(),
1846        full: String::new(),
1847        gap: Some(why.to_string()),
1848    };
1849    let budget = Budget::new(settings);
1850    let private = match PrivateDir::create() {
1851        Ok(private) => private,
1852        Err(why) => {
1853            say(&format!(
1854                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
1855                why.kind()
1856            ));
1857            return unchecked("no private directory");
1858        }
1859    };
1860    // Whatever pip-audit prints, the temp path stays out of it.
1861    let canonical = std::fs::canonicalize(private.path()).ok();
1862    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
1863    let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
1864    let mut gap: Option<String> = None;
1865    let mut answered: Vec<&str> = Vec::new();
1866    let batches = batches_of(pins.pairs);
1867    for (index, batch) in batches.iter().enumerate() {
1868        if budget.spent() {
1869            say(&format!(
1870                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
1871            ));
1872            gap.get_or_insert_with(|| "out of time".to_string());
1873            break;
1874        }
1875        let file = private.path().join(format!("batch-{index}.txt"));
1876        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
1877        if let Err(why) = std::fs::write(&file, body) {
1878            say(&format!(
1879                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
1880                why.kind()
1881            ));
1882            gap.get_or_insert_with(|| "could not write a batch file".to_string());
1883            break;
1884        }
1885        let argv = vec![
1886            common::program("pip-audit"),
1887            "-r".into(),
1888            file.to_string_lossy().into_owned(),
1889            "--no-deps".into(),
1890            "--disable-pip".into(),
1891        ];
1892        // A timeout is said by `audited_in` itself.
1893        let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
1894            if answered.is_empty() && gap.is_none() {
1895                return DirAnswer::TimedOut;
1896            }
1897            // `audited_in` named the knob: the run's own or its silence budget.
1898            say("timed out; unaudited versions remain — NOT fully checked");
1899            gap.get_or_insert_with(|| "timed out".to_string());
1900            break;
1901        };
1902        let batch_out = scrub(&batch_out);
1903        match read_pip_audit(exit_ok, &batch_out) {
1904            Report::Vulnerabilities(found) => {
1905                vulnerabilities.extend(found);
1906                full.push_str(&batch_out);
1907                answered.extend(batch.keys().map(String::as_str));
1908            }
1909            // pip-audit has no advisory class: read_pip_audit never says it.
1910            Report::Clean | Report::Advisories(_) => {
1911                answered.extend(batch.keys().map(String::as_str));
1912            }
1913            Report::CouldNotCheck => {
1914                let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
1915                say(&format!(
1916                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
1917                    clip(&why, WARNING_COLUMNS - 2),
1918                    pip_audit_next(&why)
1919                ));
1920                gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
1921            }
1922        }
1923        out.push_str(&batch_out);
1924    }
1925    let skipped = pip_skipped_names(&out);
1926    let audited = answered
1927        .iter()
1928        .filter(|name| !skipped.iter().any(|s| s == *name))
1929        .count();
1930    if audited > 0 {
1931        common::ok(
1932            settings,
1933            &format!(
1934                "audit-python: audited {} ({}, {} skipped)",
1935                requirements_path(rel),
1936                plural(audited, "package version"),
1937                answered.len() - audited
1938            ),
1939        );
1940    }
1941    let report = if !vulnerabilities.is_empty() {
1942        Report::Vulnerabilities(vulnerabilities)
1943    } else if gap.is_some() {
1944        Report::CouldNotCheck
1945    } else {
1946        Report::Clean
1947    };
1948    DirAnswer::Read {
1949        report,
1950        out,
1951        full,
1952        gap,
1953    }
1954}
1955
1956/// The pins of a fully hashed requirements.txt.
1957#[derive(Debug, Default, PartialEq, Eq)]
1958struct HashedPins {
1959    /// Distinct `(name, version)` pairs, markers and extras stripped.
1960    pairs: std::collections::BTreeSet<(String, String)>,
1961    /// Some pin carries an environment marker.
1962    marked: bool,
1963}
1964
1965impl HashedPins {
1966    /// How many distinct names the pins carry.
1967    fn names(&self) -> usize {
1968        let names: std::collections::BTreeSet<&str> =
1969            self.pairs.iter().map(|(name, _)| name.as_str()).collect();
1970        names.len()
1971    }
1972}
1973
1974/// The pins of `dir/requirements.txt` when every requirement is an exact
1975/// `name==version` pin carrying a `--hash`, else None.
1976///
1977/// Hashes are pip-compile's signal (and pip's `--require-hashes` mode): every
1978/// dependency is listed, so there is nothing to resolve. A file of `==` pins
1979/// without hashes lists its top-level packages only (homelab's rag-api,
1980/// websearch) and must still resolve; so must any option line (`-r`, `-c`,
1981/// `-e`, an index URL), a URL or path requirement, and an empty file. A pin
1982/// may carry an environment marker (a universal compile writes them).
1983fn hashed_pins(dir: &std::path::Path) -> Option<HashedPins> {
1984    let text = std::fs::read_to_string(dir.join("requirements.txt")).ok()?;
1985    hashed_pins_in(&text)
1986}
1987
1988fn hashed_pins_in(text: &str) -> Option<HashedPins> {
1989    let mut logical = Vec::new();
1990    let mut current = String::new();
1991    for line in text.lines() {
1992        match line.strip_suffix('\\') {
1993            Some(head) => {
1994                current.push_str(head);
1995                current.push(' ');
1996            }
1997            None => {
1998                current.push_str(line);
1999                logical.push(std::mem::take(&mut current));
2000            }
2001        }
2002    }
2003    logical.push(current);
2004    let mut pins = HashedPins::default();
2005    for line in &logical {
2006        // pip reads `#` as a comment only at the start or after whitespace.
2007        let line = match line.find(" #") {
2008            Some(cut) => &line[..cut],
2009            None => line.as_str(),
2010        };
2011        let line = line.trim();
2012        if line.is_empty() || line.starts_with('#') {
2013            continue;
2014        }
2015        if line.starts_with('-') {
2016            return None;
2017        }
2018        let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
2019        let hashed = options
2020            .split_whitespace()
2021            .any(|option| option.starts_with("--hash"));
2022        if !hashed {
2023            return None;
2024        }
2025        pins.pairs.insert(exact_pin(spec)?);
2026        pins.marked |= spec.contains(';');
2027    }
2028    (!pins.pairs.is_empty()).then_some(pins)
2029}
2030
2031/// The names in pip-audit's `Name  Skip Reason` table: packages it could not
2032/// audit (not on PyPI, or a local version such as `2.14.0+cpu`).
2033fn pip_skipped_names(out: &str) -> Vec<String> {
2034    let mut lines = out.lines().map(str::trim);
2035    let mut names = Vec::new();
2036    while let Some(line) = lines.next() {
2037        if !(line.starts_with("Name") && line.contains("Skip Reason")) {
2038            continue;
2039        }
2040        let rows = lines
2041            .by_ref()
2042            .skip_while(|l| l.starts_with('-'))
2043            .take_while(|l| !l.is_empty());
2044        names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
2045    }
2046    names.sort();
2047    names.dedup();
2048    names
2049}
2050
2051fn plural(count: usize, noun: &str) -> String {
2052    if count == 1 {
2053        format!("{count} {noun}")
2054    } else {
2055        format!("{count} {noun}s")
2056    }
2057}
2058
2059/// "N private/non-PyPI package(s) skipped (a, b, c +K more)", with as many
2060/// names as keep the line within the columns, and always at least one: a
2061/// long directory prefix once left "(+1 more)" naming nothing (f108).
2062fn skipped_line(prefix: &str, names: &[&str]) -> String {
2063    let head = format!(
2064        "audit-python: {prefix}{} skipped",
2065        plural(names.len(), "private/non-PyPI package")
2066    );
2067    let fewest = names.len().min(1);
2068    for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
2069        let list: Vec<&str> = names.iter().take(shown).copied().collect();
2070        let more = names.len() - shown;
2071        let detail = match (list.is_empty(), more) {
2072            (true, 0) => String::new(),
2073            (true, _) => format!(" (+{more} more)"),
2074            (false, 0) => format!(" ({})", list.join(", ")),
2075            (false, _) => format!(" ({} +{more} more)", list.join(", ")),
2076        };
2077        let line = format!("{head}{detail}");
2078        if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
2079            return line;
2080        }
2081    }
2082    head
2083}
2084
2085/// `text` cut to `columns` characters.
2086fn clip(text: &str, columns: usize) -> String {
2087    text.chars().take(columns).collect()
2088}
2089
2090/// `text` with the private directory named `<tmp>`, in the form it was
2091/// created under and in its canonical form (macOS spells `/var` as
2092/// `/private/var`). The canonical one goes first: the plain one is a suffix
2093/// of it.
2094fn scrub_private(
2095    text: &str,
2096    private: &std::path::Path,
2097    canonical: Option<&std::path::Path>,
2098) -> String {
2099    let plain = private.to_string_lossy();
2100    let mut scrubbed = text.to_string();
2101    if let Some(canonical) = canonical.filter(|c| *c != private) {
2102        scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
2103    }
2104    scrubbed.replace(plain.as_ref(), "<tmp>")
2105}
2106
2107/// What auditing one `uv.lock` found.
2108struct LockDirAudit {
2109    vulnerabilities: Vec<String>,
2110    advisories: Vec<String>,
2111    full: String,
2112    /// False when any part of the lock went unchecked (export or batch
2113    /// failed, time ran out): never Clean, never waivable.
2114    complete: bool,
2115    waivable: bool,
2116}
2117
2118impl LockDirAudit {
2119    fn unchecked() -> LockDirAudit {
2120        LockDirAudit {
2121            vulnerabilities: Vec::new(),
2122            advisories: Vec::new(),
2123            full: String::new(),
2124            complete: false,
2125            waivable: false,
2126        }
2127    }
2128}
2129
2130/// `uv export` of the lock in `dir`, filtered to PyPI pins, audited by
2131/// pip-audit without resolving anything (`--no-deps --disable-pip`).
2132///
2133/// `production` splits each batch's findings by what the lock ships, asked
2134/// the first time a batch has findings.
2135fn audit_uv_lock(
2136    settings: &crate::config::Settings,
2137    mut production: Production,
2138    dir: &str,
2139    budget: &Budget,
2140) -> LockDirAudit {
2141    let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
2142    let lock_path = if dir.is_empty() {
2143        "uv.lock".to_string()
2144    } else {
2145        format!("{dir}/uv.lock")
2146    };
2147    let prefix = if dir.is_empty() {
2148        String::new()
2149    } else {
2150        format!("{lock_path}: ")
2151    };
2152    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2153    let private = match PrivateDir::create() {
2154        Ok(private) => private,
2155        Err(why) => {
2156            say(&format!(
2157                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
2158                why.kind()
2159            ));
2160            return LockDirAudit::unchecked();
2161        }
2162    };
2163    // Whatever a tool prints, the temp path stays out of it.
2164    let canonical = std::fs::canonicalize(private.path()).ok();
2165    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2166    let export = private.path().join("export.txt");
2167    if budget.spent() {
2168        say(&format!(
2169            "out of time before the export — the audit did NOT run\n  {TIMEOUT_NEXT}"
2170        ));
2171        return LockDirAudit::unchecked();
2172    }
2173    let argv = vec![
2174        common::program("uv"),
2175        "export".into(),
2176        "--frozen".into(),
2177        "--all-packages".into(),
2178        "--all-groups".into(),
2179        "--all-extras".into(),
2180        "--no-hashes".into(),
2181        "--no-emit-workspace".into(),
2182        "--format".into(),
2183        "requirements-txt".into(),
2184        "-o".into(),
2185        export.to_string_lossy().into_owned(),
2186    ];
2187    let exported = audited_in(settings, &argv, &dir_path);
2188    if !matches!(exported, Some((true, _))) {
2189        let why = exported
2190            .and_then(|(_, out)| failure_line(&scrub(&out)))
2191            .unwrap_or_else(|| "uv did not answer".to_string());
2192        let place = if dir.is_empty() {
2193            "at the repo root".to_string()
2194        } else {
2195            format!("in {dir}")
2196        };
2197        say(&format!(
2198            "uv export failed — the audit did NOT run\n  {}\n  Next: `uv export --frozen` {place}",
2199            clip(&why, WARNING_COLUMNS - 2)
2200        ));
2201        return LockDirAudit::unchecked();
2202    }
2203    let raw = std::fs::read_to_string(&export);
2204    // The raw export has served; only the filtered pins stay on disk.
2205    let _ = std::fs::remove_file(&export); // best effort: the guard removes the directory
2206    let raw = match raw {
2207        Ok(raw) => raw,
2208        Err(why) => {
2209            say(&format!(
2210                "could not read export.txt ({}) — the audit did NOT run\n  {TMPDIR_NEXT}",
2211                why.kind()
2212            ));
2213            return LockDirAudit::unchecked();
2214        }
2215    };
2216    let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
2217        Ok(lock) => lock,
2218        Err(why) => {
2219            say(&format!(
2220                "could not read uv.lock ({}) — the audit did NOT run\n  \
2221                 Next: check that {lock_path} is readable, then push again",
2222                why.kind()
2223            ));
2224            return LockDirAudit::unchecked();
2225        }
2226    };
2227    let sources = scan_uv_lock(&lock);
2228    let pins = filter_export(&raw, &sources.pypi);
2229    if !pins.skipped.is_empty() {
2230        let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
2231        common::warn(&skipped_line(&prefix, &names));
2232    }
2233    let unclassified = pins.unclassified.len() + sources.nameless;
2234    if unclassified > 0 {
2235        let source = if prefix.is_empty() {
2236            " from uv.lock"
2237        } else {
2238            ""
2239        };
2240        say(&format!(
2241            "{} could not be classified{source}; not audited\n  \
2242             Next: check that each [[package]] in {lock_path} has a name and source",
2243            plural(unclassified, "package")
2244        ));
2245    }
2246    if pins.batches.is_empty() {
2247        say(&format!(
2248            "no PyPI package to audit — the audit did NOT run\n  \
2249             Next: none if every package is private; else check {lock_path} sources"
2250        ));
2251        return LockDirAudit::unchecked();
2252    }
2253    let mut audit = LockDirAudit {
2254        vulnerabilities: Vec::new(),
2255        advisories: Vec::new(),
2256        full: String::new(),
2257        complete: true,
2258        waivable: true,
2259    };
2260    let mut audited = 0;
2261    for (index, batch) in pins.batches.iter().enumerate() {
2262        let file = private.path().join(format!("batch-{index}.txt"));
2263        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2264        if budget.spent() {
2265            say(&format!(
2266                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
2267            ));
2268            audit.complete = false;
2269            break;
2270        }
2271        if let Err(why) = std::fs::write(&file, body) {
2272            say(&format!(
2273                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
2274                why.kind()
2275            ));
2276            audit.complete = false;
2277            break;
2278        }
2279        let argv = vec![
2280            common::program("pip-audit"),
2281            "-r".into(),
2282            file.to_string_lossy().into_owned(),
2283            "--no-deps".into(),
2284            "--disable-pip".into(),
2285        ];
2286        let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
2287            audit.complete = false;
2288            break;
2289        };
2290        let out = scrub(&out);
2291        let report = read_pip_audit(exit_ok, &out);
2292        let names = if has_rows_to_split(&report, &out) {
2293            production.names(settings, budget, &say)
2294        } else {
2295            None
2296        };
2297        let (report, waivable) = shipped_only(report, &out, names);
2298        audit.waivable &= waivable;
2299        match report {
2300            Report::Vulnerabilities(found) => {
2301                audit.vulnerabilities.extend(found);
2302                audit.full.push_str(&out);
2303                audited += batch.len();
2304            }
2305            Report::Advisories(found) => {
2306                audit.advisories.extend(found);
2307                audited += batch.len();
2308            }
2309            Report::Clean => audited += batch.len(),
2310            Report::CouldNotCheck => {
2311                audit.complete = false;
2312                let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
2313                say(&format!(
2314                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
2315                    clip(&why, WARNING_COLUMNS - 2),
2316                    pip_audit_next(&why)
2317                ));
2318            }
2319        }
2320    }
2321    if !audit.complete {
2322        audit.waivable = false;
2323    }
2324    if audited > 0 {
2325        common::ok(
2326            settings,
2327            &format!(
2328                "audit-python: audited {lock_path} ({}, {} skipped)",
2329                plural(audited, "package version"),
2330                pins.skipped.len()
2331            ),
2332        );
2333    }
2334    audit
2335}
2336
2337/// The lock route: each tracked `uv.lock` audited from its own directory.
2338/// The result is the worst directory's: findings block as ever, and a
2339/// directory that went unchecked is never hidden by a clean one.
2340fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
2341    let (settings, refs) = (ctx.settings, ctx.push.get());
2342    let release = releasing(refs);
2343    let budget = Budget::new(settings);
2344    let root = std::path::PathBuf::from(common::repo_root());
2345    let dirs = lockfile_dirs("uv.lock");
2346    let only_root = dirs.len() == 1 && dirs[0].is_empty();
2347    let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
2348    let mut full = String::new();
2349    let (mut complete, mut waivable) = (true, true);
2350    for dir in &dirs {
2351        let production = if release {
2352            Production::Unasked(root.join(dir))
2353        } else {
2354            Production::Never
2355        };
2356        let audit = audit_uv_lock(settings, production, dir, &budget);
2357        let label = |ids: Vec<String>| -> Vec<String> {
2358            if dir.is_empty() {
2359                ids
2360            } else {
2361                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
2362            }
2363        };
2364        vulnerabilities.extend(label(audit.vulnerabilities));
2365        advisories.extend(label(audit.advisories));
2366        if !audit.full.is_empty() {
2367            if only_root {
2368                full.push_str(&audit.full);
2369            } else {
2370                full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
2371            }
2372        }
2373        complete &= audit.complete;
2374        waivable &= audit.waivable;
2375    }
2376    let report = if !vulnerabilities.is_empty() {
2377        Report::Vulnerabilities(vulnerabilities)
2378    } else if !complete {
2379        return Ran::Unavailable;
2380    } else if !advisories.is_empty() {
2381        Report::Advisories(advisories)
2382    } else {
2383        Report::Clean
2384    };
2385    Ran::Concluded(Concluded {
2386        tool: "audit-python".to_string(),
2387        report,
2388        full,
2389        waivable: waivable && complete,
2390        complete,
2391    })
2392}
2393
2394/// Is `source`'s working tree exactly the commit checked out here, with its
2395/// Python manifests unmodified? Then its installed environment is this
2396/// commit's (as far as the hook in `source` would have known).
2397fn source_is_this_commit(source: &std::path::Path) -> bool {
2398    let src = source.to_string_lossy();
2399    let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
2400    let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
2401    let unmodified = crate::git::stdout(&[
2402        "-C",
2403        &src,
2404        "status",
2405        "--porcelain",
2406        "--untracked-files=no",
2407        "--",
2408        "*pyproject.toml",
2409        "*uv.lock",
2410        "*requirements*.txt",
2411    ])
2412    .is_some_and(|out| out.trim().is_empty());
2413    here.is_some() && here == there && unmodified
2414}
2415
2416/// PEP 503 normalised: `Foo_Bar.baz` and `foo-bar-baz` are one package.
2417fn normalise(name: &str) -> String {
2418    name.to_ascii_lowercase()
2419        .split(['-', '_', '.'])
2420        .filter(|p| !p.is_empty())
2421        .collect::<Vec<_>>()
2422        .join("-")
2423}
2424
2425/// The packages pip-audit's table names, one row per advisory:
2426/// `Name Version ID Fix Versions`. Only rows whose third column is an
2427/// advisory id count, so the header, the rule and the summary never do.
2428fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
2429    let mut rows: Vec<(String, String)> = out
2430        .lines()
2431        .filter_map(|l| {
2432            let cols: Vec<&str> = l.split_whitespace().collect();
2433            let id = cols.get(2)?;
2434            ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
2435                .iter()
2436                .any(|p| id.starts_with(p))
2437                .then(|| (normalise(cols[0]), (*id).to_string()))
2438        })
2439        .collect();
2440    rows.sort();
2441    rows.dedup();
2442    rows
2443}
2444
2445/// Does every advisory row of pip-audit's table carry an id a waiver can
2446/// name? A row is `name version id …`: a version starting with a digit and
2447/// an id shaped `PREFIX-…`, whatever the prefix.
2448fn pip_rows_all_named(out: &str) -> bool {
2449    out.lines().all(|l| {
2450        let cols: Vec<&str> = l.split_whitespace().collect();
2451        let is_row = cols.len() >= 3
2452            && cols[1].starts_with(|c: char| c.is_ascii_digit())
2453            && cols[2].contains('-')
2454            && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
2455        !is_row || !advisory_ids(cols[2]).is_empty()
2456    })
2457}
2458
2459/// What a uv project ships: `uv export --no-dev` of its lock in `dir`, names
2460/// only. None when there is no `uv.lock`, no `uv`, or the export fails — the
2461/// caller then keeps every finding, because an unknown is not a pass.
2462fn uv_production_names(
2463    settings: &crate::config::Settings,
2464    dir: &std::path::Path,
2465) -> Option<std::collections::HashSet<String>> {
2466    if !has_lockfile("uv.lock") || common::which("uv").is_none() {
2467        return None;
2468    }
2469    let argv = vec![
2470        common::program("uv"),
2471        "export".into(),
2472        "--frozen".into(),
2473        // The same members the audit exported, so scope and classification
2474        // cover one workspace.
2475        "--all-packages".into(),
2476        "--no-dev".into(),
2477        "--no-default-groups".into(),
2478        // Optional extras ship: a consumer who asks for one installs it.
2479        "--all-extras".into(),
2480        "--no-hashes".into(),
2481        "--no-emit-workspace".into(),
2482        "--format".into(),
2483        "requirements-txt".into(),
2484    ];
2485    let (ok, out) = audited_in(settings, &argv, dir)?;
2486    if !ok {
2487        return None;
2488    }
2489    Some(
2490        out.lines()
2491            .map(str::trim)
2492            .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
2493            .filter_map(|l| {
2494                l.split(|c: char| "=<>!~;[ ".contains(c))
2495                    .next()
2496                    .map(normalise)
2497            })
2498            .collect(),
2499    )
2500}
2501
2502/// The notes ref of audit records: local, never pushed, never a stamp.
2503pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
2504const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
2505/// How long a record answers for its lockfiles, in hours.
2506const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
2507/// A report that could not check anything answers for an hour only: an
2508/// offline push is never blocked, and the audit is tried again soon.
2509const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
2510/// The greengate that writes a record, the header's last field. An
2511/// unchecked record answers only to the version that wrote it: the next one
2512/// may have a route that can check (f03).
2513const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");
2514
2515/// Is `check` one of the dependency audits?
2516pub fn is_audit(check: &str) -> bool {
2517    check.starts_with("pre-push-audit-")
2518}
2519
2520/// The files (by name) whose content an audit's branch-mode report depends
2521/// on. A release reads the manifests too (its dev-only split), so a release
2522/// record is keyed by the whole tree instead.
2523fn inputs_of(check: &str) -> &'static [&'static str] {
2524    match check {
2525        "pre-push-audit-rust" => &["Cargo.lock"],
2526        "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
2527        "pre-push-audit-go" => &["go.sum", "go.mod"],
2528        "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
2529        _ => &[],
2530    }
2531}
2532
2533/// The stakes a push's audit is judged and recorded under.
2534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2535enum AuditMode {
2536    /// A branch push: findings warn.
2537    Branch,
2538    /// A push carrying a `v*` tag: shipped vulnerabilities block.
2539    Release,
2540}
2541
2542impl AuditMode {
2543    fn of(refs: &[PushRef]) -> AuditMode {
2544        if releasing(refs) {
2545            AuditMode::Release
2546        } else {
2547            AuditMode::Branch
2548        }
2549    }
2550}
2551
2552/// What an audit concluded before the push's stakes were applied: what
2553/// `conclude_waivable` judges, and what a record keeps so a later push can
2554/// judge it again against that day's waivers and that push (ADR-0018).
2555#[derive(Debug, Clone, PartialEq, Eq)]
2556struct Concluded {
2557    tool: String,
2558    report: Report,
2559    full: String,
2560    waivable: bool,
2561    /// False when part of the audit did not answer (a timeout, a batch that
2562    /// never ran): such a result is never recorded, so the next push audits
2563    /// again instead of replaying a gap for a day.
2564    complete: bool,
2565}
2566
2567/// How one ecosystem's audit ended: with a report to judge, or before it had
2568/// one.
2569enum Ran {
2570    Concluded(Concluded),
2571    /// Nothing to audit here (no lockfile).
2572    Inert,
2573    /// It could not run: no tool, or a tool that would not start.
2574    Unavailable,
2575}
2576
2577/// A record waiting for the hook to decide it may be written: only where the
2578/// working tree is the keyed tip (the tools read the working tree).
2579#[derive(Debug, Clone)]
2580pub struct Pending {
2581    pub tip: String,
2582    material: String,
2583    body: String,
2584}
2585
2586/// One push's audit bookkeeping, owned by the hook and lent to each audit on
2587/// `Ctx`: the records the audits produced, and the reads both the refusal and
2588/// the replay ask for (each costs a git spawn while git holds the
2589/// connection open).
2590#[derive(Default)]
2591pub struct Ledger {
2592    pending: std::sync::Mutex<Vec<Pending>>,
2593    peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
2594    fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
2595}
2596
2597impl Ledger {
2598    /// The records this push's audits produced, handed to the hook.
2599    pub fn take_pending(&self) -> Vec<Pending> {
2600        std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
2601    }
2602
2603    /// `oid` peeled to its commit, asked of git once per push.
2604    fn peel(&self, oid: &str) -> Option<String> {
2605        if let Some(known) = self
2606            .peeled
2607            .lock()
2608            .unwrap_or_else(|e| e.into_inner())
2609            .get(oid)
2610        {
2611            return known.clone();
2612        }
2613        let commit =
2614            crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
2615        self.peeled
2616            .lock()
2617            .unwrap_or_else(|e| e.into_inner())
2618            .insert(oid.to_string(), commit.clone());
2619        commit
2620    }
2621
2622    /// The pushed commits: every non-deleting ref's tip, peeled to its commit.
2623    fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
2624        let mut commits: Vec<String> = refs
2625            .iter()
2626            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
2627            .filter_map(|r| self.peel(&r.local_oid))
2628            .collect();
2629        commits.sort();
2630        commits.dedup();
2631        commits
2632    }
2633}
2634
2635/// Write `pending` as a note on the blob of its key text. A failure is named
2636/// for the caller to report: the next push then owes the audit again.
2637pub fn write_pending(pending: &Pending) -> Result<(), String> {
2638    // `stdout_piped` keeps git's trailing newline; a key with one names no
2639    // object, and `notes add` would refuse it.
2640    let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
2641        .map(|k| k.trim().to_string())
2642        .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
2643    let written = crate::git::succeeds(&[
2644        "notes",
2645        "--ref",
2646        AUDIT_REF,
2647        "add",
2648        "-f",
2649        "-m",
2650        &pending.body,
2651        &key,
2652    ]);
2653    if written {
2654        Ok(())
2655    } else {
2656        Err(format!("git refused to write the audit record {key}"))
2657    }
2658}
2659
2660/// The text a record is keyed by (the key is its blob's oid).
2661fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
2662    match mode {
2663        AuditMode::Release => {
2664            let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
2665            Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
2666        }
2667        AuditMode::Branch => {
2668            let names = inputs_of(check);
2669            let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
2670            let mut lines: Vec<String> = listing
2671                .lines()
2672                .filter_map(|entry| {
2673                    let (meta, path) = entry.split_once('\t')?;
2674                    let blob = meta.split_whitespace().nth(2)?;
2675                    let base = path.rsplit('/').next().unwrap_or(path);
2676                    names.contains(&base).then(|| format!("{path} {blob}"))
2677                })
2678                .collect();
2679            lines.sort();
2680            Some(format!(
2681                "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
2682                lines.join("\n")
2683            ))
2684        }
2685    }
2686}
2687
2688fn now_secs() -> i64 {
2689    std::time::SystemTime::now()
2690        .duration_since(std::time::UNIX_EPOCH)
2691        .map(|d| d.as_secs() as i64)
2692        .unwrap_or(0)
2693}
2694
2695fn class_of(report: &Report) -> &'static str {
2696    match report {
2697        Report::Clean => "clean",
2698        Report::Advisories(_) => "advisories",
2699        Report::Vulnerabilities(_) => "vulnerabilities",
2700        Report::CouldNotCheck => "unchecked",
2701    }
2702}
2703
2704fn render(concluded: &Concluded, at: i64) -> String {
2705    let items: &[String] = match &concluded.report {
2706        Report::Advisories(v) | Report::Vulnerabilities(v) => v,
2707        Report::Clean | Report::CouldNotCheck => &[],
2708    };
2709    let mut body = format!(
2710        "{AUDIT_FORMAT} {at} {} {} {} {WRITER_VERSION}",
2711        class_of(&concluded.report),
2712        u8::from(concluded.waivable),
2713        concluded.tool
2714    );
2715    for item in items {
2716        body.push_str("\nitem ");
2717        body.push_str(item);
2718    }
2719    body.push_str("\n---\n");
2720    body.push_str(&concluded.full);
2721    body
2722}
2723
2724/// A record's time, the greengate that wrote it (None in a record from before
2725/// the version field), and what it concluded.
2726fn parse(body: &str) -> Option<(i64, Option<String>, Concluded)> {
2727    let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
2728    let mut fields = head.split_whitespace();
2729    if fields.next()? != AUDIT_FORMAT {
2730        return None;
2731    }
2732    let at: i64 = fields.next()?.parse().ok()?;
2733    let class = fields.next()?;
2734    let waivable = fields.next()? == "1";
2735    let tool = fields.next()?.to_string();
2736    let writer = fields.next().map(str::to_string);
2737    let (items_part, full) = match rest.split_once("---\n") {
2738        Some((i, full)) => (i, full.to_string()),
2739        None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
2740    };
2741    let items: Vec<String> = items_part
2742        .lines()
2743        .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
2744        .collect();
2745    let report = match class {
2746        "clean" => Report::Clean,
2747        "advisories" => Report::Advisories(items),
2748        "vulnerabilities" => Report::Vulnerabilities(items),
2749        "unchecked" => Report::CouldNotCheck,
2750        _ => return None,
2751    };
2752    Some((
2753        at,
2754        writer,
2755        Concluded {
2756            tool,
2757            report,
2758            full,
2759            waivable,
2760            complete: true,
2761        },
2762    ))
2763}
2764
2765/// The fresh record of `check` for `commit` in this mode, if any.
2766fn fresh_record(
2767    settings: &crate::config::Settings,
2768    check: &str,
2769    mode: AuditMode,
2770    commit: &str,
2771) -> Option<Concluded> {
2772    let material = key_material(check, mode, commit)?;
2773    let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
2774        .trim()
2775        .to_string();
2776    let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
2777    let (at, writer, concluded) = parse(&body)?;
2778    let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
2779        if writer.as_deref() != Some(WRITER_VERSION) {
2780            return None;
2781        }
2782        UNCHECKED_MAX_AGE_SECS
2783    } else {
2784        crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
2785    };
2786    let age = now_secs() - at;
2787    (0..=max_age).contains(&age).then_some(concluded)
2788}
2789
2790/// Does every commit `refs` pushes carry a fresh record of `check`, all the
2791/// same, in this push's mode? The one the push would replay, or None. Asked
2792/// by the refusal and again by the replay, so answered once per push:
2793/// nothing in one hook run writes a record before both have asked.
2794fn fresh_for_refs(
2795    settings: &crate::config::Settings,
2796    ledger: &Ledger,
2797    check: &str,
2798    refs: &[PushRef],
2799) -> Option<Concluded> {
2800    if !crate::gate_stamp::push_stamps_enabled(settings) {
2801        return None;
2802    }
2803    let memo_key = format!(
2804        "{check} {}",
2805        refs.iter()
2806            .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
2807            .collect::<Vec<_>>()
2808            .join(" ")
2809    );
2810    if let Some(known) = ledger
2811        .fresh
2812        .lock()
2813        .unwrap_or_else(|e| e.into_inner())
2814        .get(&memo_key)
2815    {
2816        return known.clone();
2817    }
2818    let mode = AuditMode::of(refs);
2819    let mut found: Option<Concluded> = None;
2820    for commit in ledger.pushed_commits(refs) {
2821        let Some(record) = fresh_record(settings, check, mode, &commit) else {
2822            found = None;
2823            break;
2824        };
2825        if found.as_ref().is_some_and(|prev| *prev != record) {
2826            found = None;
2827            break;
2828        }
2829        found = Some(record);
2830    }
2831    ledger
2832        .fresh
2833        .lock()
2834        .unwrap_or_else(|e| e.into_inner())
2835        .insert(memo_key, found.clone());
2836    found
2837}
2838
2839/// Is `check` owed by a push of `refs`: opted in, and with no fresh record?
2840pub fn owed(
2841    settings: &crate::config::Settings,
2842    ledger: &Ledger,
2843    check: &str,
2844    refs: &[PushRef],
2845) -> bool {
2846    !ledger.pushed_commits(refs).is_empty()
2847        && fresh_for_refs(settings, ledger, check, refs).is_none()
2848}
2849
2850/// Run an audit through its record: replay a fresh one, or run the tool and
2851/// keep what it concluded on the ledger (a tool that never got to a report
2852/// counts as "could not check").
2853fn recorded(
2854    check: &str,
2855    tool: &str,
2856    ctx: &crate::registry::Ctx,
2857    run: fn(&crate::registry::Ctx) -> Ran,
2858) -> Outcome {
2859    let (settings, refs) = (ctx.settings, ctx.push.get());
2860    let mode = AuditMode::of(refs);
2861    let releasing = mode == AuditMode::Release;
2862    if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
2863        common::ok(
2864            settings,
2865            &format!("{tool}: replaying the audit recorded for this push"),
2866        );
2867        return conclude_waivable(
2868            settings,
2869            &record.tool,
2870            record.report,
2871            releasing,
2872            &record.full,
2873            record.waivable,
2874        );
2875    }
2876    let (outcome, concluded) = match run(ctx) {
2877        Ran::Concluded(concluded) => (
2878            conclude_waivable(
2879                settings,
2880                &concluded.tool,
2881                concluded.report.clone(),
2882                releasing,
2883                &concluded.full,
2884                concluded.waivable,
2885            ),
2886            Some(concluded),
2887        ),
2888        Ran::Unavailable => (
2889            Outcome::Unavailable,
2890            Some(Concluded {
2891                tool: tool.to_string(),
2892                report: Report::CouldNotCheck,
2893                full: String::new(),
2894                waivable: false,
2895                complete: true,
2896            }),
2897        ),
2898        Ran::Inert => (Outcome::Inert, None),
2899    };
2900    // A result with a gap is not recorded; an unchecked one is, for an hour.
2901    let concluded = concluded.filter(|concluded| {
2902        concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
2903    });
2904    if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
2905        let body = render(&concluded, now_secs());
2906        let records: Vec<Pending> = ctx
2907            .audits
2908            .pushed_commits(refs)
2909            .into_iter()
2910            .filter_map(|commit| {
2911                key_material(check, mode, &commit).map(|material| Pending {
2912                    tip: commit,
2913                    material,
2914                    body: body.clone(),
2915                })
2916            })
2917            .collect();
2918        ctx.audits
2919            .pending
2920            .lock()
2921            .unwrap_or_else(|e| e.into_inner())
2922            .extend(records);
2923    }
2924    outcome
2925}
2926
2927pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
2928    recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
2929}
2930
2931pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
2932    recorded("pre-push-audit-js", "audit-js", ctx, js_run)
2933}
2934
2935pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
2936    recorded("pre-push-audit-go", "audit-go", ctx, go_run)
2937}
2938
2939pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
2940    recorded("pre-push-audit-python", "audit-python", ctx, python_run)
2941}
2942
2943#[cfg(test)]
2944mod tests {
2945    use super::*;
2946
2947    /// uv projects have no `requirements.txt`, so the venv is the only thing
2948    /// left to audit — and before this, `audit-python` looked for nothing
2949    /// else and reported "the audit did NOT run" forever. Six repositories
2950    /// in one fleet were in exactly that state, one of them carrying 53
2951    /// known vulnerabilities nobody had been told about.
2952    #[test]
2953    fn a_uv_project_is_audited_through_its_venv() {
2954        let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
2955        let _ = std::fs::remove_dir_all(&root);
2956
2957        // Nothing on disk: nothing to audit, and we say so rather than
2958        // inventing a target.
2959        std::fs::create_dir_all(&root).unwrap();
2960        assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
2961
2962        // The posix layout, with the python version DISCOVERED — hard-coding
2963        // `python3.13` would silently stop finding it after an upgrade.
2964        // Joined segment by segment, NOT as one "a/b/c" literal: on Windows
2965        // the literal keeps its forward slashes while the code under test
2966        // returns backslashes, and the test fails on a difference that is
2967        // only in the expectation.
2968        let sp = root
2969            .join(".venv")
2970            .join("lib")
2971            .join("python3.13")
2972            .join("site-packages");
2973        std::fs::create_dir_all(&sp).unwrap();
2974        assert_eq!(
2975            venv_site_packages(root.to_str().unwrap(), None),
2976            Some(sp.to_string_lossy().into_owned())
2977        );
2978
2979        // The Windows layout, which has no version directory at all.
2980        let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
2981        let _ = std::fs::remove_dir_all(&win);
2982        let wsp = win.join(".venv").join("Lib").join("site-packages");
2983        std::fs::create_dir_all(&wsp).unwrap();
2984        assert_eq!(
2985            venv_site_packages(win.to_str().unwrap(), None),
2986            Some(wsp.to_string_lossy().into_owned())
2987        );
2988
2989        let _ = std::fs::remove_dir_all(&root);
2990        let _ = std::fs::remove_dir_all(&win);
2991    }
2992
2993    fn tag(name: &str) -> PushRef {
2994        PushRef {
2995            local_ref: name.to_string(),
2996            local_oid: "a".repeat(40),
2997            remote_ref: name.to_string(),
2998            remote_oid: "0".repeat(40),
2999        }
3000    }
3001
3002    /// `v` + digit gates; a branch, a bare-word tag, or a tag merely
3003    /// starting with the letter v does not.
3004    #[test]
3005    fn pip_audit_rows_name_their_packages_normalised() {
3006        let out = "Name       Version ID                  Fix Versions\n\
3007                   ---------- ------- ------------------- ------------\n\
3008                   Pytest_Cov 4.0.0   GHSA-aaaa-bbbb-cccc 4.1.0\n\
3009                   requests   2.31.0  PYSEC-2023-74       2.31.1\n\
3010                   requests   2.31.0  CVE-2024-35195      2.32.0\n\
3011                   Found 3 known vulnerabilities in 2 packages\n";
3012        let names: Vec<String> = pip_vulnerable_rows(out)
3013            .into_iter()
3014            .map(|(n, _)| n)
3015            .collect();
3016        assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
3017        assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
3018    }
3019
3020    #[test]
3021    fn advisory_ids_are_found_wherever_they_sit() {
3022        let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
3023                    ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
3024        assert_eq!(
3025            advisory_ids(text),
3026            vec![
3027                "CVE-2024-35195",
3028                "GHSA-h3mg-xc3c-68pw",
3029                "GO-2024-2687",
3030                "OSV-2024-12",
3031                "PYSEC-2023-74",
3032                "RUSTSEC-2025-0001"
3033            ]
3034        );
3035    }
3036
3037    #[test]
3038    fn a_waiver_is_reasoned_dated_and_bounded() {
3039        let today = days_from_date("2026-10-05").unwrap();
3040        let w = Waivers::parse(
3041            "# id expires reason\n\
3042             GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
3043             GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
3044             GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
3045             GHSA-jjjj-kkkk-llll 2026-11-01\n\
3046             GHSA-mmmm-nnnn-oooo soon no date\n",
3047            today,
3048        );
3049        assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
3050        assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
3051        assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
3052        assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
3053        assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
3054        assert_eq!(w.problems().len(), 4);
3055        assert_eq!(days_from_date("1970-01-01"), Some(0));
3056        assert_eq!(days_from_date("2026-02-30"), None);
3057        assert!(days_from_date("2028-02-29").is_some());
3058        assert_eq!(days_from_date("2026-13-01"), None);
3059    }
3060
3061    #[test]
3062    fn two_locked_versions_are_two_answers() {
3063        let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
3064                   Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
3065        let ids = vec![
3066            "RUSTSEC-2025-0010".to_string(),
3067            "RUSTSEC-2025-0011".to_string(),
3068        ];
3069        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3070            "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
3071            "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
3072            _ => None,
3073        });
3074        assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
3075        assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
3076    }
3077
3078    #[test]
3079    fn a_pip_row_without_a_nameable_id_is_unwaivable() {
3080        let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
3081        let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
3082        assert!(pip_rows_all_named(named));
3083        assert!(!pip_rows_all_named(unnamed));
3084    }
3085
3086    #[test]
3087    fn a_crate_ships_unless_its_tree_says_otherwise() {
3088        let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
3089                   Crate: app\nID: RUSTSEC-2025-0002\n\
3090                   Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
3091        let ids = vec![
3092            "RUSTSEC-2025-0001".to_string(),
3093            "RUSTSEC-2025-0002".to_string(),
3094            "RUSTSEC-2025-0003".to_string(),
3095            "RUSTSEC-2025-0004".to_string(),
3096        ];
3097        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3098            // Asked by name@version when cargo audit gave the version.
3099            "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
3100            "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
3101            // A tree that says neither: not proof of dev-only.
3102            "odd" => Some("odd v1.0.0\n".into()),
3103            _ => None,
3104        });
3105        // 0003 has no crate, 0004's tree is unclear: unknowns ship.
3106        assert_eq!(
3107            shipped,
3108            vec![
3109                "RUSTSEC-2025-0002",
3110                "RUSTSEC-2025-0003",
3111                "RUSTSEC-2025-0004"
3112            ]
3113        );
3114        assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
3115    }
3116
3117    #[test]
3118    fn a_release_is_a_v_number_tag() {
3119        assert!(releasing(&[tag("refs/tags/v1.6.6")]));
3120        assert!(releasing(&[tag("refs/tags/v2")]));
3121        assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
3122        assert!(!releasing(&[tag("refs/tags/release")]));
3123        assert!(!releasing(&[tag("refs/heads/v1-styles")]));
3124        assert!(!releasing(&[tag("refs/heads/main")]));
3125        // A mixed push gates: the tag is in there.
3126        assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
3127    }
3128
3129    /// ci.yaml's lesson, pinned at the unit level: the ids decide, the exit
3130    /// code only classifies them.
3131    #[test]
3132    fn cargo_audit_ids_decide_not_the_exit_code() {
3133        assert_eq!(
3134            read_cargo_audit(true, "ok, 312 crates checked"),
3135            Report::Clean
3136        );
3137        assert_eq!(
3138            read_cargo_audit(false, "error: couldn't fetch advisory database"),
3139            Report::CouldNotCheck
3140        );
3141        let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
3142        assert_eq!(
3143            read_cargo_audit(true, warn),
3144            Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
3145        );
3146        let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
3147        assert_eq!(
3148            read_cargo_audit(false, vuln),
3149            Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
3150        );
3151        // A lookalike is not an id.
3152        assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
3153    }
3154
3155    /// The real report shape, trimmed from the run that prompted this: two
3156    /// advisories against ONE crate, and one against another.
3157    fn real_report() -> String {
3158        [
3159            "Crate:     paste",
3160            "Version:   1.0.15",
3161            "Warning:   unmaintained",
3162            "ID:        RUSTSEC-2024-0436",
3163            "URL:       https://rustsec.org/advisories/RUSTSEC-2024-0436",
3164            "",
3165            "Crate:     lru",
3166            "Version:   0.12.5",
3167            "Warning:   unsound",
3168            "ID:        RUSTSEC-2026-0253",
3169            "",
3170            "Crate:     lru",
3171            "Version:   0.12.5",
3172            "ID:        RUSTSEC-2026-0002",
3173            "",
3174            "warning: 3 allowed warnings found",
3175        ]
3176        .join("\n")
3177    }
3178
3179    #[test]
3180    fn an_advisory_is_paired_with_its_crate() {
3181        let pairs = ids_with_crates(&real_report());
3182        assert_eq!(
3183            pairs,
3184            vec![
3185                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3186                ("RUSTSEC-2026-0253".into(), Some("lru".into())),
3187                ("RUSTSEC-2026-0002".into(), Some("lru".into())),
3188            ]
3189        );
3190    }
3191
3192    /// A `Crate:` binds to ONE id. An id printed loose reports no crate
3193    /// rather than inheriting whichever block happened to precede it.
3194    #[test]
3195    fn a_loose_id_borrows_no_crate() {
3196        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
3197        assert_eq!(
3198            ids_with_crates(out),
3199            vec![
3200                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3201                ("RUSTSEC-2025-0001".into(), None),
3202            ]
3203        );
3204    }
3205
3206    /// Local crates carry a path; registry crates do not. That is the whole
3207    /// discriminator, and it has to work without knowing the member names.
3208    #[test]
3209    fn only_local_crates_are_named_as_reached() {
3210        let tree =
3211            "lru v0.12.5\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
3212        assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
3213        assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
3214    }
3215
3216    /// End to end on the real report, with the tree calls faked: each id
3217    /// names its crate and the workspace crate that reaches it, and `lru`'s
3218    /// two advisories cost ONE lookup.
3219    #[test]
3220    fn the_warning_names_the_crate_and_what_reaches_it() {
3221        let calls = std::cell::RefCell::new(Vec::new());
3222        let fake = |k: &str| {
3223            calls.borrow_mut().push(k.to_string());
3224            Some(format!(
3225                "{k} v1\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
3226            ))
3227        };
3228        let out = real_report();
3229        let got = attribute(read_cargo_audit(true, &out), &out, fake);
3230        assert_eq!(
3231            got,
3232            Report::Advisories(vec![
3233                "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
3234                "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
3235                "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
3236            ])
3237        );
3238        assert_eq!(
3239            calls.into_inner(),
3240            vec!["paste", "lru"],
3241            "one call per crate"
3242        );
3243    }
3244
3245    /// A lock-file-only crate — an optional dependency of a feature nobody
3246    /// enabled — is reported as such. `cargo audit` reads Cargo.lock, so this
3247    /// is a real and confusing case, and naming it is the point.
3248    #[test]
3249    fn a_crate_outside_the_build_graph_says_so() {
3250        let out = "Crate:     wezterm-input-types\nID:        RUSTSEC-2025-0001";
3251        let got = attribute(read_cargo_audit(true, out), out, |_| {
3252            Some("warning: nothing to print.".into())
3253        });
3254        assert_eq!(
3255            got,
3256            Report::Advisories(vec![
3257                "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
3258            ])
3259        );
3260    }
3261
3262    /// Attribution is a better message, never a gate. A clean report spawns
3263    /// nothing, and a `cargo tree` that cannot run still reports the id.
3264    #[test]
3265    fn attribution_never_changes_the_verdict() {
3266        let spawned = std::cell::Cell::new(false);
3267        let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
3268            spawned.set(true);
3269            None
3270        });
3271        assert_eq!(clean, Report::Clean);
3272        assert!(!spawned.get(), "a clean report must spawn nothing");
3273
3274        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436";
3275        let blind = attribute(read_cargo_audit(false, out), out, |_| None);
3276        assert_eq!(
3277            blind,
3278            Report::Vulnerabilities(vec![
3279                "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
3280            ])
3281        );
3282    }
3283
3284    #[test]
3285    fn npm_audit_summary_decides() {
3286        assert_eq!(
3287            read_npm_audit(true, "found 0 vulnerabilities\n"),
3288            Report::Clean
3289        );
3290        assert_eq!(
3291            read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
3292            Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
3293        );
3294        // npm 7+ dropped the verb: this is what every current npm prints,
3295        // and what read as "never answered" until the parser learned it.
3296        assert_eq!(
3297            read_npm_audit(
3298                false,
3299                "# npm audit report\n\nvite  6.0.0 - 6.1.5\nSeverity: high\n\n\
3300                 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n  npm audit fix\n"
3301            ),
3302            Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
3303        );
3304        assert_eq!(
3305            read_npm_audit(false, "1 vulnerability (1 high)\n"),
3306            Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
3307        );
3308        assert_eq!(
3309            read_npm_audit(true, "up to date, audited 100 packages\n"),
3310            Report::Clean
3311        );
3312        assert_eq!(
3313            read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
3314            Report::CouldNotCheck
3315        );
3316    }
3317
3318    #[test]
3319    fn pnpm_audit_summary_decides() {
3320        assert_eq!(
3321            read_pnpm_audit(true, "No known vulnerabilities found\n"),
3322            Report::Clean
3323        );
3324        // What pnpm prints after its table: the count, then the severities,
3325        // which the finding carries so the warning says how bad.
3326        assert_eq!(
3327            read_pnpm_audit(
3328                false,
3329                "│ More info │ https://github.com/advisories/GHSA-395f │\n\
3330                 └───────────┴──────────────────────────────────────────┘\n\
3331                 107 vulnerabilities found\n\
3332                 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
3333            ),
3334            Report::Vulnerabilities(vec![
3335                "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
3336            ])
3337        );
3338        assert_eq!(
3339            read_pnpm_audit(false, "1 vulnerabilities found\n"),
3340            Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
3341        );
3342        assert_eq!(
3343            read_pnpm_audit(
3344                false,
3345                " ERR_PNPM_AUDIT_BAD_RESPONSE  The audit endpoint responded with 503\n"
3346            ),
3347            Report::CouldNotCheck
3348        );
3349    }
3350
3351    /// The cargo-audit split, spoken in Go: ids decide, the exit code says
3352    /// whether the analysed code is actually affected.
3353    #[test]
3354    fn govulncheck_ids_decide_not_the_exit_code() {
3355        assert_eq!(
3356            read_govulncheck(true, "No vulnerabilities found.\n"),
3357            Report::Clean
3358        );
3359        assert_eq!(
3360            read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
3361            Report::CouldNotCheck
3362        );
3363        // Informational: the module is vulnerable, the analysed code never
3364        // calls it — exit 0, ids present.
3365        assert_eq!(
3366            read_govulncheck(
3367                true,
3368                "=== Informational ===\nVulnerability #1: GO-2023-1840\n  More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
3369            ),
3370            Report::Advisories(vec!["GO-2023-1840".into()])
3371        );
3372        assert_eq!(
3373            read_govulncheck(
3374                false,
3375                "Vulnerability #1: GO-2022-0969\n  Your code calls it.\nGO-2022-0969 again\n"
3376            ),
3377            Report::Vulnerabilities(vec!["GO-2022-0969".into()])
3378        );
3379        // A lookalike is not an id.
3380        assert_eq!(
3381            read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
3382            Report::Clean
3383        );
3384    }
3385
3386    #[test]
3387    fn pip_audit_sentence_decides() {
3388        assert_eq!(
3389            read_pip_audit(true, "No known vulnerabilities found\n"),
3390            Report::Clean
3391        );
3392        assert_eq!(
3393            read_pip_audit(
3394                false,
3395                "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
3396            ),
3397            Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
3398        );
3399        assert_eq!(
3400            read_pip_audit(false, "ERROR: could not resolve\n"),
3401            Report::CouldNotCheck
3402        );
3403    }
3404
3405    fn lock_block(name: Option<&str>, source: &str) -> String {
3406        let mut block = String::from("[[package]]\n");
3407        if let Some(name) = name {
3408            block.push_str(&format!("name = \"{name}\"\n"));
3409        }
3410        block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
3411        block
3412    }
3413
3414    #[test]
3415    fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
3416        let pypi = "{ registry = \"https://pypi.org/simple\" }";
3417        let lock = [
3418            lock_block(Some("Requests"), pypi),
3419            lock_block(
3420                Some("slashed"),
3421                "{ registry = \"https://pypi.org/simple/\" }",
3422            ),
3423            lock_block(
3424                Some("mirror"),
3425                "{ registry = \"https://mirror.example/simple\" }",
3426            ),
3427            lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
3428            lock_block(Some("pathdep"), "{ path = \"../x\" }"),
3429            lock_block(Some("edit"), "{ editable = \".\" }"),
3430            lock_block(Some("virt"), "{ virtual = \".\" }"),
3431            lock_block(Some("twice"), pypi),
3432            lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
3433            lock_block(None, pypi),
3434            "[package.metadata]\nname = \"ignored\"\n".to_string(),
3435        ]
3436        .concat();
3437        let sources = scan_uv_lock(&lock);
3438        let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
3439        assert_eq!(admitted, ["requests", "slashed"]);
3440        assert_eq!(sources.nameless, 1);
3441    }
3442
3443    #[test]
3444    fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
3445        let pypi: std::collections::BTreeSet<String> =
3446            ["numpy", "idna", "requests"].map(String::from).into();
3447        let raw = "\
3448# generated
3449numpy==1.26.4 ; python_full_version < '3.12'
3450numpy==2.1.0 ; python_full_version >= '3.12'
3451numpy==2.1.0 ; sys_platform == 'win32'
3452idna==3.7
3453platform-kernel==0.1.0
3454requests @ https://example.com/r.whl
3455";
3456        let pins = filter_export(raw, &pypi);
3457        assert_eq!(pins.versions, 3);
3458        assert_eq!(pins.batches.len(), 2);
3459        assert_eq!(
3460            pins.batches[0].get("numpy").map(String::as_str),
3461            Some("1.26.4")
3462        );
3463        assert_eq!(
3464            pins.batches[1].get("numpy").map(String::as_str),
3465            Some("2.1.0")
3466        );
3467        assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
3468        assert!(pins.skipped.contains("platform-kernel"));
3469        assert!(pins.unclassified.contains("requests"));
3470    }
3471
3472    /// pip-compile's shape, as homelab's laya-decisions has it (f108).
3473    const HASHED: &str = "\
3474# This file was autogenerated by uv via the following command:
3475#    ./compile-requirements.sh
3476anyio==4.15.1 \\
3477    --hash=sha256:6152 \\
3478    --hash=sha256:9f28
3479    # via
3480    #   starlette
3481idna==3.7 \\
3482    --hash=sha256:aaaa
3483torch==2.14.0+cpu \\
3484    --hash=sha256:bbbb
3485    # via -r requirements.in
3486";
3487
3488    #[test]
3489    fn only_a_fully_hashed_file_skips_the_resolve() {
3490        let pins = hashed_pins_in(HASHED).expect("hashed");
3491        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
3492        // Top-level `==` pins without hashes: their dependencies are unlisted.
3493        assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
3494        let one_unhashed = format!("{HASHED}idna==3.7\n");
3495        assert_eq!(hashed_pins_in(&one_unhashed), None);
3496        let ranged = "requests>=2.0 \\\n    --hash=sha256:cccc\n";
3497        assert_eq!(hashed_pins_in(ranged), None);
3498        let included = format!("-r requirements-upload.txt\n{HASHED}");
3499        assert_eq!(hashed_pins_in(&included), None);
3500        let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
3501        assert_eq!(hashed_pins_in(&indexed), None);
3502        // A marked pin is still a closed set: it takes the batch route.
3503        let marked =
3504            format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n    --hash=sha256:dddd\n");
3505        assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
3506        assert_eq!(
3507            hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
3508            None
3509        );
3510        assert_eq!(hashed_pins_in("# fixture\n"), None);
3511        assert_eq!(hashed_pins_in(""), None);
3512    }
3513
3514    #[test]
3515    fn marked_pins_are_stripped_and_their_versions_batched_apart() {
3516        let text = "\
3517six==1.16.0 \\
3518    --hash=sha256:aaaa
3519numpy==1.26.4 ; python_version == '3.9' \\
3520    --hash=sha256:bbbb
3521numpy==2.1.0 ; python_version == '3.12' \\
3522    --hash=sha256:cccc
3523";
3524        let pins = hashed_pins_in(text).expect("hashed");
3525        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
3526        let batches = batches_of(pins.pairs);
3527        assert_eq!(batches.len(), 2);
3528        assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
3529        assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
3530        assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
3531    }
3532
3533    /// pip-audit 2.10.1's output on laya-decisions with `--no-deps
3534    /// --disable-pip`, cut to two rows.
3535    const SKIPPING: &str = "\
3536Found 2 known vulnerabilities in 1 package
3537Name      Version ID              Fix Versions
3538--------- ------- --------------- ------------
3539starlette 0.41.3  PYSEC-2026-1941 0.47.2
3540starlette 0.41.3  PYSEC-2026-1942 0.49.1
3541
3542Name  Skip Reason
3543----- -------------------------------------------------------------------------
3544torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
3545";
3546
3547    #[test]
3548    fn the_skip_table_names_its_packages_and_is_no_finding() {
3549        assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
3550        assert_eq!(
3551            pip_vulnerable_rows(SKIPPING),
3552            vec![
3553                ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
3554                ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
3555            ]
3556        );
3557        assert!(pip_rows_all_named(SKIPPING));
3558        let clean = "No known vulnerabilities found\nName  Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
3559        assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
3560        assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
3561    }
3562
3563    #[test]
3564    fn the_skipped_line_names_three_and_counts_the_rest() {
3565        let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
3566        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
3567        assert_eq!(
3568            skipped_line("", &refs),
3569            "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
3570        );
3571        assert_eq!(
3572            skipped_line("", &refs[..1]),
3573            "audit-python: 1 private/non-PyPI package skipped (a)"
3574        );
3575        let long = "services/laya-decisions/requirements.txt: ";
3576        assert_eq!(
3577            skipped_line(long, &["torch", "triton"]),
3578            format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
3579        );
3580    }
3581
3582    #[test]
3583    fn scrub_names_the_canonical_private_path_too() {
3584        let plain = std::path::Path::new("/var/folders/a/audit-1");
3585        let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
3586        assert_eq!(
3587            scrub_private(
3588                "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
3589                plain,
3590                canonical
3591            ),
3592            "x <tmp>/b and <tmp>/c"
3593        );
3594    }
3595
3596    #[test]
3597    fn production_names_are_never_asked_off_a_release_or_out_of_time() {
3598        let settings = crate::config::Settings::default();
3599        let spent = Budget {
3600            started: std::time::Instant::now(),
3601            limit: Some(std::time::Duration::ZERO),
3602        };
3603        let said = std::cell::RefCell::new(Vec::<String>::new());
3604        let say = |m: &str| said.borrow_mut().push(m.to_string());
3605        let dir = std::env::temp_dir();
3606
3607        let mut off = Production::Never;
3608        assert!(off.names(&settings, &spent, &say).is_none());
3609        assert!(matches!(off, Production::Never), "no release never asks");
3610        assert!(said.borrow().is_empty());
3611
3612        let mut late = Production::Unasked(dir.clone());
3613        assert!(late.names(&settings, &spent, &say).is_none());
3614        assert!(late.names(&settings, &spent, &say).is_none());
3615        assert!(
3616            matches!(late, Production::Asked(None)),
3617            "spent is remembered as unknown"
3618        );
3619
3620        // In time it asks, once: this checkout tracks no uv.lock, so the
3621        // answer is unknown and stays the answer.
3622        let fresh = Budget {
3623            started: std::time::Instant::now(),
3624            limit: None,
3625        };
3626        let mut asked = Production::Unasked(dir);
3627        assert!(asked.names(&settings, &fresh, &say).is_none());
3628        assert!(matches!(asked, Production::Asked(None)));
3629        let said = said.borrow();
3630        assert_eq!(said.len(), 1, "warned once: {said:?}");
3631        assert!(said[0].contains("every finding counts"), "{said:?}");
3632        assert!(said[0].contains("greengate.timeout"), "{said:?}");
3633    }
3634
3635    #[test]
3636    fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
3637        for why in [
3638            "ConnectionError: Max retries exceeded",
3639            "error: request timed out",
3640            "SSL: CERTIFICATE_VERIFY_FAILED",
3641            "Temporary failure in name resolution",
3642        ] {
3643            assert!(pip_audit_next(why).contains("the network"), "{why}");
3644        }
3645        for why in [
3646            "(no output)",
3647            "ModuleNotFoundError: No module named 'pip_audit'",
3648        ] {
3649            assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
3650        }
3651    }
3652
3653    #[test]
3654    fn only_readable_vulnerability_rows_need_the_split() {
3655        let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
3656        assert!(has_rows_to_split(
3657            &Report::Vulnerabilities(vec!["certifi".into()]),
3658            rows
3659        ));
3660        assert!(!has_rows_to_split(
3661            &Report::Vulnerabilities(vec!["x".into()]),
3662            "Found 1\n"
3663        ));
3664        assert!(!has_rows_to_split(&Report::Clean, rows));
3665        assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
3666    }
3667
3668    #[test]
3669    fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
3670        let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
3671        let guard = PrivateDir::create_at(path.clone()).unwrap();
3672        #[cfg(unix)]
3673        {
3674            use std::os::unix::fs::PermissionsExt;
3675            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
3676            assert_eq!(mode & 0o777, 0o700);
3677        }
3678        assert!(PrivateDir::create_at(path.clone()).is_err());
3679        assert!(path.is_dir(), "the refused attempt must leave it alone");
3680        drop(guard);
3681        assert!(!path.exists());
3682    }
3683}