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.
1255fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1256    let settings = ctx.settings;
1257    if !has_lockfile("go.sum") {
1258        return Ran::Inert;
1259    }
1260    if common::which("govulncheck").is_none() {
1261        common::warn(
1262            "audit-go: govulncheck is not installed \
1263             (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1264        );
1265        return Ran::Unavailable;
1266    }
1267    let argv = vec![common::program("govulncheck"), "./...".into()];
1268    let merged = audit_each_dir(
1269        settings,
1270        "audit-go",
1271        "go.sum",
1272        |_| Some(argv.clone()),
1273        read_govulncheck,
1274        |_, report, _| report,
1275    );
1276    Ran::Concluded(Concluded {
1277        tool: "audit-go".to_string(),
1278        report: merged.report,
1279        full: merged.full,
1280        waivable: merged.waivable,
1281        complete: merged.complete,
1282    })
1283}
1284
1285fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1286    let (settings, refs) = (ctx.settings, ctx.push.get());
1287    if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1288        return Ran::Inert;
1289    }
1290    if common::which("pip-audit").is_none() {
1291        common::warn(
1292            "audit-python: pip-audit is not installed (pip install pip-audit) — \
1293             the audit did NOT run",
1294        );
1295        return Ran::Unavailable;
1296    }
1297    let root = common::repo_root();
1298    // A requirements.txt is the production list by convention, audited in
1299    // its own directory — wherever the repository keeps one (amont#305).
1300    if !lockfile_dirs("requirements.txt").is_empty() {
1301        let root_path = std::path::PathBuf::from(&root);
1302        let rel_of = |dir: &std::path::Path| {
1303            dir.strip_prefix(&root_path)
1304                .map(|p| p.to_string_lossy().into_owned())
1305                .unwrap_or_default()
1306        };
1307        let answer_in = |dir: &std::path::Path| {
1308            let pins = hashed_pins(dir);
1309            let names = pins.as_ref().map(HashedPins::names);
1310            let answer = match pins {
1311                Some(pins) if pins.marked => audit_marked_pins(settings, dir, &rel_of(dir), pins),
1312                hashed => {
1313                    let mut argv = vec![
1314                        common::program("pip-audit"),
1315                        "-r".into(),
1316                        "requirements.txt".into(),
1317                    ];
1318                    // A fully hashed file is a closed set: nothing to resolve,
1319                    // and resolving it on this host can fail on a pin with no
1320                    // wheel here (torch 2.14.0+cpu on Intel macOS, decisions f108).
1321                    if hashed.is_some() {
1322                        argv.extend(["--no-deps".into(), "--disable-pip".into()]);
1323                    }
1324                    answer_of(settings, &argv, dir, read_pip_audit)
1325                }
1326            };
1327            let DirAnswer::Read {
1328                report,
1329                out,
1330                full,
1331                gap,
1332            } = answer
1333            else {
1334                return answer;
1335            };
1336            let skipped = pip_skipped_names(&out);
1337            if skipped.is_empty() {
1338                return DirAnswer::Read {
1339                    report,
1340                    out,
1341                    full,
1342                    gap,
1343                };
1344            }
1345            let skipped_names: Vec<&str> = skipped.iter().map(String::as_str).collect();
1346            common::warn(&skipped_line(
1347                &requirements_prefix(&rel_of(dir)),
1348                &skipped_names,
1349            ));
1350            // Every pin skipped: nothing was audited, which is not clean.
1351            let all_skipped = names.is_some_and(|n| skipped.len() >= n);
1352            let report = if all_skipped && !matches!(report, Report::Vulnerabilities(_)) {
1353                Report::CouldNotCheck
1354            } else {
1355                report
1356            };
1357            DirAnswer::Read {
1358                report,
1359                out,
1360                full,
1361                gap,
1362            }
1363        };
1364        let merged = audit_each_dir_answered(
1365            "audit-python",
1366            "requirements.txt",
1367            answer_in,
1368            |_, report, _| report,
1369        );
1370        // A row whose advisory id is not one a waiver can name makes the
1371        // whole report unwaivable.
1372        let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1373        return Ran::Concluded(Concluded {
1374            tool: "audit-python".to_string(),
1375            report: merged.report,
1376            full: merged.full,
1377            waivable,
1378            complete: merged.complete,
1379        });
1380    }
1381    let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1382        // A uv/PEP-621 project has no requirements.txt, and EXPORTING one
1383        // does not work either: `uv export` emits the workspace's own
1384        // members and any private-index dependency, and pip-audit resolves
1385        // a requirements file in a throwaway venv that can reach neither —
1386        // it dies on "No matching distribution found". Auditing the
1387        // INSTALLED tree resolves nothing, and is the truer question
1388        // anyway: these are the versions actually imported.
1389        vec![
1390            common::program("pip-audit"),
1391            "--path".into(),
1392            site_packages,
1393            // Workspace members are installed editable and are not on
1394            // PyPI; without this each one is a line of noise.
1395            "--skip-editable".into(),
1396        ]
1397    } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1398        // No virtualenv: the lock says what would be installed.
1399        return python_lock_run(ctx);
1400    } else {
1401        common::warn(
1402            "audit-python: the audit did NOT run — found no requirements.txt,\n  \
1403             no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n  \
1404             Next: `uv sync`, or install uv so uv.lock can be audited.",
1405        );
1406        return Ran::Unavailable;
1407    };
1408    let Some((exit_ok, out)) = audited(settings, &argv) else {
1409        return Ran::Unavailable;
1410    };
1411    // A requirements.txt is the production list by convention (dev pins
1412    // live beside it, in requirements-dev.txt). A virtualenv or a lock holds
1413    // the dev groups too, so on a release its findings are checked against
1414    // what `uv export --no-dev` says ships — asked only when there are any.
1415    let report = read_pip_audit(exit_ok, &out);
1416    let production = if releasing(refs) && has_rows_to_split(&report, &out) {
1417        uv_production_names(settings, std::path::Path::new(&root))
1418    } else {
1419        None
1420    };
1421    let (report, waivable) = shipped_only(report, &out, production.as_ref());
1422    Ran::Concluded(Concluded {
1423        tool: "audit-python".to_string(),
1424        report,
1425        full: out,
1426        waivable,
1427        complete: true,
1428    })
1429}
1430
1431/// On a release, split pip-audit's findings into what ships and what only
1432/// the dev groups carry; the latter warn and do not block. `(report,
1433/// waivable)`: a row whose advisory id is not one a waiver can name (MAL-, a
1434/// new scheme) makes the whole report unwaivable. When the production names
1435/// are unknown (`None`) every finding is kept: an unknown is not a pass.
1436fn shipped_only(
1437    mut report: Report,
1438    out: &str,
1439    production: Option<&std::collections::HashSet<String>>,
1440) -> (Report, bool) {
1441    let mut waivable = pip_rows_all_named(out);
1442    if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1443        let rows = pip_vulnerable_rows(out);
1444        if !rows.is_empty() {
1445            let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1446                .into_iter()
1447                .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1448                .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1449                    if ships {
1450                        s.push(row);
1451                    } else {
1452                        d.push(row);
1453                    }
1454                    (s, d)
1455                });
1456            warn_dev_only("audit-python", &dev_only);
1457            waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1458            report = if shipped.is_empty() {
1459                Report::Clean
1460            } else {
1461                Report::Vulnerabilities(shipped)
1462            };
1463        }
1464    }
1465    (report, waivable)
1466}
1467
1468/// Would [`shipped_only`] split anything? Only a vulnerability report with
1469/// rows it can read; for every other report the production names change
1470/// nothing, so they are not worth a `uv export`.
1471fn has_rows_to_split(report: &Report, out: &str) -> bool {
1472    matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
1473}
1474
1475/// What one lock directory ships, asked of [`uv_production_names`] at most
1476/// once, and only on a release whose batch has findings to split.
1477enum Production {
1478    /// No release: never asked, every finding is kept.
1479    Never,
1480    /// A release, not asked yet: ask in this lock directory.
1481    Unasked(std::path::PathBuf),
1482    /// Asked; None when the export could not answer or time ran out.
1483    Asked(Option<std::collections::HashSet<String>>),
1484}
1485
1486impl Production {
1487    /// The production names, None when this is no release, the export
1488    /// cannot answer, or the budget is spent before it is asked (`say`
1489    /// warns once): every finding is then kept.
1490    fn names(
1491        &mut self,
1492        settings: &crate::config::Settings,
1493        budget: &Budget,
1494        say: &dyn Fn(&str),
1495    ) -> Option<&std::collections::HashSet<String>> {
1496        if let Production::Unasked(dir) = self {
1497            *self = Production::Asked(if budget.spent() {
1498                say(&format!(
1499                    "out of time before the dev-only split — every finding counts\n  {TIMEOUT_NEXT}"
1500                ));
1501                None
1502            } else {
1503                uv_production_names(settings, dir)
1504            });
1505        }
1506        match self {
1507            Production::Asked(names) => names.as_ref(),
1508            Production::Never | Production::Unasked(_) => None,
1509        }
1510    }
1511}
1512
1513/// The next step after the lock route ran out of time.
1514const TIMEOUT_NEXT: &str =
1515    "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";
1516
1517/// The next step after a scratch file could not be made, written or read.
1518const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";
1519
1520/// The next step after pip-audit could not answer, from its own reason: the
1521/// network when the reason names it, else pip-audit itself.
1522fn pip_audit_next(why: &str) -> &'static str {
1523    // holds-until: pip-audit's English error wording is the only signal; when
1524    // it reports an error class or a distinct exit code for the network,
1525    // decide on that instead of these words.
1526    let why = why.to_ascii_lowercase();
1527    let network = [
1528        "network",
1529        "connect",
1530        "timed out",
1531        "timeout",
1532        "resolve",
1533        "dns",
1534        "ssl",
1535        "certificate",
1536        "unreachable",
1537        "temporary failure",
1538    ]
1539    .iter()
1540    .any(|word| why.contains(word));
1541    if network {
1542        "Next: check the network, then push again"
1543    } else {
1544        "Next: `pip-audit --version` to check the install, then push again"
1545    }
1546}
1547
1548/// The only registry whose packages are looked up: ADR-0055 sends public
1549/// names to OSV and pip-audit asks PyPI, and nothing else may be sent.
1550const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1551
1552/// Columns a warning line may use.
1553const WARNING_COLUMNS: usize = 80;
1554
1555/// How many names a count in a warning spells out.
1556const NAMES_SHOWN: usize = 3;
1557
1558/// A directory only this process can enter, removed on every return and
1559/// panic. A signal leaves it behind, as `capture.rs` notes for its own.
1560struct PrivateDir {
1561    path: std::path::PathBuf,
1562}
1563
1564impl PrivateDir {
1565    /// A fresh directory under the temp dir, mode 0700, named unpredictably.
1566    fn create() -> std::io::Result<PrivateDir> {
1567        Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1568    }
1569
1570    /// `path` itself, created exclusively and not recursively: it fails when
1571    /// anything is already there, so nothing planted is ever written through.
1572    fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1573        #[cfg(unix)]
1574        let builder = {
1575            let mut unix_builder = std::fs::DirBuilder::new();
1576            std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1577            unix_builder
1578        };
1579        #[cfg(not(unix))]
1580        let builder = std::fs::DirBuilder::new();
1581        builder.create(&path)?;
1582        Ok(PrivateDir { path })
1583    }
1584
1585    fn path(&self) -> &std::path::Path {
1586        &self.path
1587    }
1588}
1589
1590impl Drop for PrivateDir {
1591    fn drop(&mut self) {
1592        let _ = std::fs::remove_dir_all(&self.path); // best effort: a leftover temp dir holds no secret, and a failure must not panic
1593    }
1594}
1595
1596/// One time budget for a run of several pip-audit calls: the whole lock
1597/// route, or one marked requirements file's batches.
1598struct Budget {
1599    started: std::time::Instant,
1600    /// None: `greengate.timeout 0` disables the ceiling.
1601    limit: Option<std::time::Duration>,
1602}
1603
1604impl Budget {
1605    fn new(settings: &crate::config::Settings) -> Budget {
1606        Budget {
1607            started: std::time::Instant::now(),
1608            limit: Some(common::check_timeout(settings))
1609                .filter(|secs| *secs > 0)
1610                .map(std::time::Duration::from_secs),
1611        }
1612    }
1613
1614    fn spent(&self) -> bool {
1615        self.limit
1616            .is_some_and(|limit| self.started.elapsed() >= limit)
1617    }
1618}
1619
1620/// Which `uv.lock` packages come from PyPI, by PEP 503 name.
1621#[derive(Debug, Default, PartialEq, Eq)]
1622struct LockSources {
1623    /// Every `[[package]]` block of the name has the PyPI registry.
1624    pypi: std::collections::BTreeSet<String>,
1625    /// Blocks with no name: counted, never classified.
1626    nameless: usize,
1627}
1628
1629/// `source = { registry = "<url>" }` naming PyPI, trailing slash or not.
1630fn is_pypi_source(source_field: &str) -> bool {
1631    source_field
1632        .split_once("registry = \"")
1633        .and_then(|(_, rest)| rest.split('"').next())
1634        .is_some_and(|url| url.trim_end_matches('/') == PYPI_REGISTRY)
1635}
1636
1637/// A std-only line scan of `uv.lock`'s `[[package]]` blocks (no TOML crate:
1638/// `scripts/check-no-deps.sh`). Only top-level `name` and `source` keys of a
1639/// block count; a name qualifies only when all its blocks come from PyPI.
1640fn scan_uv_lock(text: &str) -> LockSources {
1641    struct Block {
1642        name: Option<String>,
1643        pypi: bool,
1644    }
1645    let mut blocks: Vec<Block> = Vec::new();
1646    let mut top_level = false;
1647    for line in text.lines() {
1648        if line.starts_with('[') {
1649            top_level = line.trim() == "[[package]]";
1650            if top_level {
1651                blocks.push(Block {
1652                    name: None,
1653                    pypi: false,
1654                });
1655            }
1656            continue;
1657        }
1658        let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1659            continue;
1660        };
1661        if let Some(value) = line.strip_prefix("name = ") {
1662            if block.name.is_none() {
1663                block.name = value.split('"').nth(1).map(normalise);
1664            }
1665        } else if let Some(value) = line.strip_prefix("source = ") {
1666            block.pypi = is_pypi_source(value);
1667        }
1668    }
1669    let mut sources = LockSources::default();
1670    let mut rejected = std::collections::BTreeSet::new();
1671    for block in blocks {
1672        match block.name.filter(|n| !n.is_empty()) {
1673            None => sources.nameless += 1,
1674            Some(name) if block.pypi => {
1675                sources.pypi.insert(name);
1676            }
1677            Some(name) => {
1678                rejected.insert(name);
1679            }
1680        }
1681    }
1682    sources.pypi.retain(|name| !rejected.contains(name));
1683    sources
1684}
1685
1686/// What of an export may be sent to pip-audit.
1687#[derive(Debug, Default, PartialEq, Eq)]
1688struct ExportPins {
1689    /// Audit inputs: `name -> version`, one version per name in each batch,
1690    /// because pip-audit rejects conflicting pins in one requirements input.
1691    batches: Vec<std::collections::BTreeMap<String, String>>,
1692    /// Distinct (name, version) pairs across the batches.
1693    versions: usize,
1694    /// Exported names that are not PyPI's: never sent.
1695    skipped: std::collections::BTreeSet<String>,
1696    /// PyPI names whose line is not an exact `name==version` pin.
1697    unclassified: std::collections::BTreeSet<String>,
1698}
1699
1700/// `name==version` of one export line with its environment marker stripped,
1701/// so every platform and Python-version variant is audited whatever the host.
1702fn exact_pin(line: &str) -> Option<(String, String)> {
1703    let spec = line.split(';').next()?.trim();
1704    let (name, version) = spec.split_once("==")?;
1705    let name = name.split('[').next()?.trim();
1706    let version = version.trim();
1707    let name_ok = !name.is_empty()
1708        && name
1709            .chars()
1710            .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1711    let version_ok = !version.is_empty()
1712        && version
1713            .chars()
1714            .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1715    (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1716}
1717
1718fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1719    let mut pins = ExportPins::default();
1720    let mut pairs = std::collections::BTreeSet::new();
1721    for line in raw.lines().map(str::trim) {
1722        if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1723            continue;
1724        }
1725        let name = normalise(
1726            line.split(|c: char| "=<>!~;[ @".contains(c))
1727                .next()
1728                .unwrap_or_default(),
1729        );
1730        if name.is_empty() {
1731            continue;
1732        }
1733        if !pypi.contains(&name) {
1734            pins.skipped.insert(name);
1735            continue;
1736        }
1737        match exact_pin(line) {
1738            Some(pair) => {
1739                pairs.insert(pair);
1740            }
1741            None => {
1742                pins.unclassified.insert(name);
1743            }
1744        }
1745    }
1746    pins.versions = pairs.len();
1747    pins.batches = batches_of(pairs);
1748    pins
1749}
1750
1751/// `(name, version)` pairs split into pip-audit inputs, one version of a
1752/// name in each: pip-audit refuses two pins of one name in one run, even
1753/// across several `-r` files ("package jinja2 has duplicate requirements").
1754fn batches_of(
1755    pairs: std::collections::BTreeSet<(String, String)>,
1756) -> Vec<std::collections::BTreeMap<String, String>> {
1757    let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
1758    for (name, version) in pairs {
1759        match batches.iter().position(|batch| !batch.contains_key(&name)) {
1760            Some(index) => {
1761                batches[index].insert(name, version);
1762            }
1763            None => batches.push(std::collections::BTreeMap::from([(name, version)])),
1764        }
1765    }
1766    batches
1767}
1768
1769/// `requirements.txt` in the repository-relative directory `rel`.
1770fn requirements_path(rel: &str) -> String {
1771    if rel.is_empty() {
1772        "requirements.txt".to_string()
1773    } else {
1774        format!("{rel}/requirements.txt")
1775    }
1776}
1777
1778/// What a warning about `rel`'s requirements.txt starts with: nothing at
1779/// the root, so a root file reads as it always has.
1780fn requirements_prefix(rel: &str) -> String {
1781    if rel.is_empty() {
1782        String::new()
1783    } else {
1784        format!("{}: ", requirements_path(rel))
1785    }
1786}
1787
1788/// A hashed requirements.txt whose pins carry environment markers, audited
1789/// from its pins with the markers stripped, so every platform's pin is
1790/// audited whatever the host (decisions f118). pip-audit evaluates a marker
1791/// against the host and drops a pin it does not match without a word:
1792/// `jinja2==2.10 ; sys_platform == 'linux'` read clean on a Mac.
1793///
1794/// Each batch is a separate run (pip-audit refuses two pins of one name in
1795/// one run) and is read on its own: a clean batch's sentence would hide the
1796/// next one's finding. A gap keeps what the earlier batches found.
1797fn audit_marked_pins(
1798    settings: &crate::config::Settings,
1799    dir: &std::path::Path,
1800    rel: &str,
1801    pins: HashedPins,
1802) -> DirAnswer {
1803    let prefix = requirements_prefix(rel);
1804    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1805    let unchecked = |why: &str| DirAnswer::Read {
1806        report: Report::CouldNotCheck,
1807        out: String::new(),
1808        full: String::new(),
1809        gap: Some(why.to_string()),
1810    };
1811    let budget = Budget::new(settings);
1812    let private = match PrivateDir::create() {
1813        Ok(private) => private,
1814        Err(why) => {
1815            say(&format!(
1816                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
1817                why.kind()
1818            ));
1819            return unchecked("no private directory");
1820        }
1821    };
1822    // Whatever pip-audit prints, the temp path stays out of it.
1823    let canonical = std::fs::canonicalize(private.path()).ok();
1824    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
1825    let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
1826    let mut gap: Option<String> = None;
1827    let mut answered: Vec<&str> = Vec::new();
1828    let batches = batches_of(pins.pairs);
1829    for (index, batch) in batches.iter().enumerate() {
1830        if budget.spent() {
1831            say(&format!(
1832                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
1833            ));
1834            gap.get_or_insert_with(|| "out of time".to_string());
1835            break;
1836        }
1837        let file = private.path().join(format!("batch-{index}.txt"));
1838        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
1839        if let Err(why) = std::fs::write(&file, body) {
1840            say(&format!(
1841                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
1842                why.kind()
1843            ));
1844            gap.get_or_insert_with(|| "could not write a batch file".to_string());
1845            break;
1846        }
1847        let argv = vec![
1848            common::program("pip-audit"),
1849            "-r".into(),
1850            file.to_string_lossy().into_owned(),
1851            "--no-deps".into(),
1852            "--disable-pip".into(),
1853        ];
1854        // A timeout is said by `audited_in` itself.
1855        let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
1856            if answered.is_empty() && gap.is_none() {
1857                return DirAnswer::TimedOut;
1858            }
1859            // `audited_in` named the knob: the run's own or its silence budget.
1860            say("timed out; unaudited versions remain — NOT fully checked");
1861            gap.get_or_insert_with(|| "timed out".to_string());
1862            break;
1863        };
1864        let batch_out = scrub(&batch_out);
1865        match read_pip_audit(exit_ok, &batch_out) {
1866            Report::Vulnerabilities(found) => {
1867                vulnerabilities.extend(found);
1868                full.push_str(&batch_out);
1869                answered.extend(batch.keys().map(String::as_str));
1870            }
1871            // pip-audit has no advisory class: read_pip_audit never says it.
1872            Report::Clean | Report::Advisories(_) => {
1873                answered.extend(batch.keys().map(String::as_str));
1874            }
1875            Report::CouldNotCheck => {
1876                let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
1877                say(&format!(
1878                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
1879                    clip(&why, WARNING_COLUMNS - 2),
1880                    pip_audit_next(&why)
1881                ));
1882                gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
1883            }
1884        }
1885        out.push_str(&batch_out);
1886    }
1887    let skipped = pip_skipped_names(&out);
1888    let audited = answered
1889        .iter()
1890        .filter(|name| !skipped.iter().any(|s| s == *name))
1891        .count();
1892    if audited > 0 {
1893        common::ok(
1894            settings,
1895            &format!(
1896                "audit-python: audited {} ({}, {} skipped)",
1897                requirements_path(rel),
1898                plural(audited, "package version"),
1899                answered.len() - audited
1900            ),
1901        );
1902    }
1903    let report = if !vulnerabilities.is_empty() {
1904        Report::Vulnerabilities(vulnerabilities)
1905    } else if gap.is_some() {
1906        Report::CouldNotCheck
1907    } else {
1908        Report::Clean
1909    };
1910    DirAnswer::Read {
1911        report,
1912        out,
1913        full,
1914        gap,
1915    }
1916}
1917
1918/// The pins of a fully hashed requirements.txt.
1919#[derive(Debug, Default, PartialEq, Eq)]
1920struct HashedPins {
1921    /// Distinct `(name, version)` pairs, markers and extras stripped.
1922    pairs: std::collections::BTreeSet<(String, String)>,
1923    /// Some pin carries an environment marker.
1924    marked: bool,
1925}
1926
1927impl HashedPins {
1928    /// How many distinct names the pins carry.
1929    fn names(&self) -> usize {
1930        let names: std::collections::BTreeSet<&str> =
1931            self.pairs.iter().map(|(name, _)| name.as_str()).collect();
1932        names.len()
1933    }
1934}
1935
1936/// The pins of `dir/requirements.txt` when every requirement is an exact
1937/// `name==version` pin carrying a `--hash`, else None.
1938///
1939/// Hashes are pip-compile's signal (and pip's `--require-hashes` mode): every
1940/// dependency is listed, so there is nothing to resolve. A file of `==` pins
1941/// without hashes lists its top-level packages only (homelab's rag-api,
1942/// websearch) and must still resolve; so must any option line (`-r`, `-c`,
1943/// `-e`, an index URL), a URL or path requirement, and an empty file. A pin
1944/// may carry an environment marker (a universal compile writes them).
1945fn hashed_pins(dir: &std::path::Path) -> Option<HashedPins> {
1946    let text = std::fs::read_to_string(dir.join("requirements.txt")).ok()?;
1947    hashed_pins_in(&text)
1948}
1949
1950fn hashed_pins_in(text: &str) -> Option<HashedPins> {
1951    let mut logical = Vec::new();
1952    let mut current = String::new();
1953    for line in text.lines() {
1954        match line.strip_suffix('\\') {
1955            Some(head) => {
1956                current.push_str(head);
1957                current.push(' ');
1958            }
1959            None => {
1960                current.push_str(line);
1961                logical.push(std::mem::take(&mut current));
1962            }
1963        }
1964    }
1965    logical.push(current);
1966    let mut pins = HashedPins::default();
1967    for line in &logical {
1968        // pip reads `#` as a comment only at the start or after whitespace.
1969        let line = match line.find(" #") {
1970            Some(cut) => &line[..cut],
1971            None => line.as_str(),
1972        };
1973        let line = line.trim();
1974        if line.is_empty() || line.starts_with('#') {
1975            continue;
1976        }
1977        if line.starts_with('-') {
1978            return None;
1979        }
1980        let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
1981        let hashed = options
1982            .split_whitespace()
1983            .any(|option| option.starts_with("--hash"));
1984        if !hashed {
1985            return None;
1986        }
1987        pins.pairs.insert(exact_pin(spec)?);
1988        pins.marked |= spec.contains(';');
1989    }
1990    (!pins.pairs.is_empty()).then_some(pins)
1991}
1992
1993/// The names in pip-audit's `Name  Skip Reason` table: packages it could not
1994/// audit (not on PyPI, or a local version such as `2.14.0+cpu`).
1995fn pip_skipped_names(out: &str) -> Vec<String> {
1996    let mut lines = out.lines().map(str::trim);
1997    let mut names = Vec::new();
1998    while let Some(line) = lines.next() {
1999        if !(line.starts_with("Name") && line.contains("Skip Reason")) {
2000            continue;
2001        }
2002        let rows = lines
2003            .by_ref()
2004            .skip_while(|l| l.starts_with('-'))
2005            .take_while(|l| !l.is_empty());
2006        names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
2007    }
2008    names.sort();
2009    names.dedup();
2010    names
2011}
2012
2013fn plural(count: usize, noun: &str) -> String {
2014    if count == 1 {
2015        format!("{count} {noun}")
2016    } else {
2017        format!("{count} {noun}s")
2018    }
2019}
2020
2021/// "N private/non-PyPI package(s) skipped (a, b, c +K more)", with as many
2022/// names as keep the line within the columns, and always at least one: a
2023/// long directory prefix once left "(+1 more)" naming nothing (f108).
2024fn skipped_line(prefix: &str, names: &[&str]) -> String {
2025    let head = format!(
2026        "audit-python: {prefix}{} skipped",
2027        plural(names.len(), "private/non-PyPI package")
2028    );
2029    let fewest = names.len().min(1);
2030    for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
2031        let list: Vec<&str> = names.iter().take(shown).copied().collect();
2032        let more = names.len() - shown;
2033        let detail = match (list.is_empty(), more) {
2034            (true, 0) => String::new(),
2035            (true, _) => format!(" (+{more} more)"),
2036            (false, 0) => format!(" ({})", list.join(", ")),
2037            (false, _) => format!(" ({} +{more} more)", list.join(", ")),
2038        };
2039        let line = format!("{head}{detail}");
2040        if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
2041            return line;
2042        }
2043    }
2044    head
2045}
2046
2047/// `text` cut to `columns` characters.
2048fn clip(text: &str, columns: usize) -> String {
2049    text.chars().take(columns).collect()
2050}
2051
2052/// `text` with the private directory named `<tmp>`, in the form it was
2053/// created under and in its canonical form (macOS spells `/var` as
2054/// `/private/var`). The canonical one goes first: the plain one is a suffix
2055/// of it.
2056fn scrub_private(
2057    text: &str,
2058    private: &std::path::Path,
2059    canonical: Option<&std::path::Path>,
2060) -> String {
2061    let plain = private.to_string_lossy();
2062    let mut scrubbed = text.to_string();
2063    if let Some(canonical) = canonical.filter(|c| *c != private) {
2064        scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
2065    }
2066    scrubbed.replace(plain.as_ref(), "<tmp>")
2067}
2068
2069/// What auditing one `uv.lock` found.
2070struct LockDirAudit {
2071    vulnerabilities: Vec<String>,
2072    advisories: Vec<String>,
2073    full: String,
2074    /// False when any part of the lock went unchecked (export or batch
2075    /// failed, time ran out): never Clean, never waivable.
2076    complete: bool,
2077    waivable: bool,
2078}
2079
2080impl LockDirAudit {
2081    fn unchecked() -> LockDirAudit {
2082        LockDirAudit {
2083            vulnerabilities: Vec::new(),
2084            advisories: Vec::new(),
2085            full: String::new(),
2086            complete: false,
2087            waivable: false,
2088        }
2089    }
2090}
2091
2092/// `uv export` of the lock in `dir`, filtered to PyPI pins, audited by
2093/// pip-audit without resolving anything (`--no-deps --disable-pip`).
2094///
2095/// `production` splits each batch's findings by what the lock ships, asked
2096/// the first time a batch has findings.
2097fn audit_uv_lock(
2098    settings: &crate::config::Settings,
2099    mut production: Production,
2100    dir: &str,
2101    budget: &Budget,
2102) -> LockDirAudit {
2103    let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
2104    let lock_path = if dir.is_empty() {
2105        "uv.lock".to_string()
2106    } else {
2107        format!("{dir}/uv.lock")
2108    };
2109    let prefix = if dir.is_empty() {
2110        String::new()
2111    } else {
2112        format!("{lock_path}: ")
2113    };
2114    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2115    let private = match PrivateDir::create() {
2116        Ok(private) => private,
2117        Err(why) => {
2118            say(&format!(
2119                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
2120                why.kind()
2121            ));
2122            return LockDirAudit::unchecked();
2123        }
2124    };
2125    // Whatever a tool prints, the temp path stays out of it.
2126    let canonical = std::fs::canonicalize(private.path()).ok();
2127    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2128    let export = private.path().join("export.txt");
2129    if budget.spent() {
2130        say(&format!(
2131            "out of time before the export — the audit did NOT run\n  {TIMEOUT_NEXT}"
2132        ));
2133        return LockDirAudit::unchecked();
2134    }
2135    let argv = vec![
2136        common::program("uv"),
2137        "export".into(),
2138        "--frozen".into(),
2139        "--all-packages".into(),
2140        "--all-groups".into(),
2141        "--all-extras".into(),
2142        "--no-hashes".into(),
2143        "--no-emit-workspace".into(),
2144        "--format".into(),
2145        "requirements-txt".into(),
2146        "-o".into(),
2147        export.to_string_lossy().into_owned(),
2148    ];
2149    let exported = audited_in(settings, &argv, &dir_path);
2150    if !matches!(exported, Some((true, _))) {
2151        let why = exported
2152            .and_then(|(_, out)| failure_line(&scrub(&out)))
2153            .unwrap_or_else(|| "uv did not answer".to_string());
2154        let place = if dir.is_empty() {
2155            "at the repo root".to_string()
2156        } else {
2157            format!("in {dir}")
2158        };
2159        say(&format!(
2160            "uv export failed — the audit did NOT run\n  {}\n  Next: `uv export --frozen` {place}",
2161            clip(&why, WARNING_COLUMNS - 2)
2162        ));
2163        return LockDirAudit::unchecked();
2164    }
2165    let raw = std::fs::read_to_string(&export);
2166    // The raw export has served; only the filtered pins stay on disk.
2167    let _ = std::fs::remove_file(&export); // best effort: the guard removes the directory
2168    let raw = match raw {
2169        Ok(raw) => raw,
2170        Err(why) => {
2171            say(&format!(
2172                "could not read export.txt ({}) — the audit did NOT run\n  {TMPDIR_NEXT}",
2173                why.kind()
2174            ));
2175            return LockDirAudit::unchecked();
2176        }
2177    };
2178    let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
2179        Ok(lock) => lock,
2180        Err(why) => {
2181            say(&format!(
2182                "could not read uv.lock ({}) — the audit did NOT run\n  \
2183                 Next: check that {lock_path} is readable, then push again",
2184                why.kind()
2185            ));
2186            return LockDirAudit::unchecked();
2187        }
2188    };
2189    let sources = scan_uv_lock(&lock);
2190    let pins = filter_export(&raw, &sources.pypi);
2191    if !pins.skipped.is_empty() {
2192        let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
2193        common::warn(&skipped_line(&prefix, &names));
2194    }
2195    let unclassified = pins.unclassified.len() + sources.nameless;
2196    if unclassified > 0 {
2197        let source = if prefix.is_empty() {
2198            " from uv.lock"
2199        } else {
2200            ""
2201        };
2202        say(&format!(
2203            "{} could not be classified{source}; not audited\n  \
2204             Next: check that each [[package]] in {lock_path} has a name and source",
2205            plural(unclassified, "package")
2206        ));
2207    }
2208    if pins.batches.is_empty() {
2209        say(&format!(
2210            "no PyPI package to audit — the audit did NOT run\n  \
2211             Next: none if every package is private; else check {lock_path} sources"
2212        ));
2213        return LockDirAudit::unchecked();
2214    }
2215    let mut audit = LockDirAudit {
2216        vulnerabilities: Vec::new(),
2217        advisories: Vec::new(),
2218        full: String::new(),
2219        complete: true,
2220        waivable: true,
2221    };
2222    let mut audited = 0;
2223    for (index, batch) in pins.batches.iter().enumerate() {
2224        let file = private.path().join(format!("batch-{index}.txt"));
2225        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2226        if budget.spent() {
2227            say(&format!(
2228                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
2229            ));
2230            audit.complete = false;
2231            break;
2232        }
2233        if let Err(why) = std::fs::write(&file, body) {
2234            say(&format!(
2235                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
2236                why.kind()
2237            ));
2238            audit.complete = false;
2239            break;
2240        }
2241        let argv = vec![
2242            common::program("pip-audit"),
2243            "-r".into(),
2244            file.to_string_lossy().into_owned(),
2245            "--no-deps".into(),
2246            "--disable-pip".into(),
2247        ];
2248        let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
2249            audit.complete = false;
2250            break;
2251        };
2252        let out = scrub(&out);
2253        let report = read_pip_audit(exit_ok, &out);
2254        let names = if has_rows_to_split(&report, &out) {
2255            production.names(settings, budget, &say)
2256        } else {
2257            None
2258        };
2259        let (report, waivable) = shipped_only(report, &out, names);
2260        audit.waivable &= waivable;
2261        match report {
2262            Report::Vulnerabilities(found) => {
2263                audit.vulnerabilities.extend(found);
2264                audit.full.push_str(&out);
2265                audited += batch.len();
2266            }
2267            Report::Advisories(found) => {
2268                audit.advisories.extend(found);
2269                audited += batch.len();
2270            }
2271            Report::Clean => audited += batch.len(),
2272            Report::CouldNotCheck => {
2273                audit.complete = false;
2274                let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
2275                say(&format!(
2276                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
2277                    clip(&why, WARNING_COLUMNS - 2),
2278                    pip_audit_next(&why)
2279                ));
2280            }
2281        }
2282    }
2283    if !audit.complete {
2284        audit.waivable = false;
2285    }
2286    if audited > 0 {
2287        common::ok(
2288            settings,
2289            &format!(
2290                "audit-python: audited {lock_path} ({}, {} skipped)",
2291                plural(audited, "package version"),
2292                pins.skipped.len()
2293            ),
2294        );
2295    }
2296    audit
2297}
2298
2299/// The lock route: each tracked `uv.lock` audited from its own directory.
2300/// The result is the worst directory's: findings block as ever, and a
2301/// directory that went unchecked is never hidden by a clean one.
2302fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
2303    let (settings, refs) = (ctx.settings, ctx.push.get());
2304    let release = releasing(refs);
2305    let budget = Budget::new(settings);
2306    let root = std::path::PathBuf::from(common::repo_root());
2307    let dirs = lockfile_dirs("uv.lock");
2308    let only_root = dirs.len() == 1 && dirs[0].is_empty();
2309    let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
2310    let mut full = String::new();
2311    let (mut complete, mut waivable) = (true, true);
2312    for dir in &dirs {
2313        let production = if release {
2314            Production::Unasked(root.join(dir))
2315        } else {
2316            Production::Never
2317        };
2318        let audit = audit_uv_lock(settings, production, dir, &budget);
2319        let label = |ids: Vec<String>| -> Vec<String> {
2320            if dir.is_empty() {
2321                ids
2322            } else {
2323                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
2324            }
2325        };
2326        vulnerabilities.extend(label(audit.vulnerabilities));
2327        advisories.extend(label(audit.advisories));
2328        if !audit.full.is_empty() {
2329            if only_root {
2330                full.push_str(&audit.full);
2331            } else {
2332                full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
2333            }
2334        }
2335        complete &= audit.complete;
2336        waivable &= audit.waivable;
2337    }
2338    let report = if !vulnerabilities.is_empty() {
2339        Report::Vulnerabilities(vulnerabilities)
2340    } else if !complete {
2341        return Ran::Unavailable;
2342    } else if !advisories.is_empty() {
2343        Report::Advisories(advisories)
2344    } else {
2345        Report::Clean
2346    };
2347    Ran::Concluded(Concluded {
2348        tool: "audit-python".to_string(),
2349        report,
2350        full,
2351        waivable: waivable && complete,
2352        complete,
2353    })
2354}
2355
2356/// Is `source`'s working tree exactly the commit checked out here, with its
2357/// Python manifests unmodified? Then its installed environment is this
2358/// commit's (as far as the hook in `source` would have known).
2359fn source_is_this_commit(source: &std::path::Path) -> bool {
2360    let src = source.to_string_lossy();
2361    let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
2362    let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
2363    let unmodified = crate::git::stdout(&[
2364        "-C",
2365        &src,
2366        "status",
2367        "--porcelain",
2368        "--untracked-files=no",
2369        "--",
2370        "*pyproject.toml",
2371        "*uv.lock",
2372        "*requirements*.txt",
2373    ])
2374    .is_some_and(|out| out.trim().is_empty());
2375    here.is_some() && here == there && unmodified
2376}
2377
2378/// PEP 503 normalised: `Foo_Bar.baz` and `foo-bar-baz` are one package.
2379fn normalise(name: &str) -> String {
2380    name.to_ascii_lowercase()
2381        .split(['-', '_', '.'])
2382        .filter(|p| !p.is_empty())
2383        .collect::<Vec<_>>()
2384        .join("-")
2385}
2386
2387/// The packages pip-audit's table names, one row per advisory:
2388/// `Name Version ID Fix Versions`. Only rows whose third column is an
2389/// advisory id count, so the header, the rule and the summary never do.
2390fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
2391    let mut rows: Vec<(String, String)> = out
2392        .lines()
2393        .filter_map(|l| {
2394            let cols: Vec<&str> = l.split_whitespace().collect();
2395            let id = cols.get(2)?;
2396            ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
2397                .iter()
2398                .any(|p| id.starts_with(p))
2399                .then(|| (normalise(cols[0]), (*id).to_string()))
2400        })
2401        .collect();
2402    rows.sort();
2403    rows.dedup();
2404    rows
2405}
2406
2407/// Does every advisory row of pip-audit's table carry an id a waiver can
2408/// name? A row is `name version id …`: a version starting with a digit and
2409/// an id shaped `PREFIX-…`, whatever the prefix.
2410fn pip_rows_all_named(out: &str) -> bool {
2411    out.lines().all(|l| {
2412        let cols: Vec<&str> = l.split_whitespace().collect();
2413        let is_row = cols.len() >= 3
2414            && cols[1].starts_with(|c: char| c.is_ascii_digit())
2415            && cols[2].contains('-')
2416            && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
2417        !is_row || !advisory_ids(cols[2]).is_empty()
2418    })
2419}
2420
2421/// What a uv project ships: `uv export --no-dev` of its lock in `dir`, names
2422/// only. None when there is no `uv.lock`, no `uv`, or the export fails — the
2423/// caller then keeps every finding, because an unknown is not a pass.
2424fn uv_production_names(
2425    settings: &crate::config::Settings,
2426    dir: &std::path::Path,
2427) -> Option<std::collections::HashSet<String>> {
2428    if !has_lockfile("uv.lock") || common::which("uv").is_none() {
2429        return None;
2430    }
2431    let argv = vec![
2432        common::program("uv"),
2433        "export".into(),
2434        "--frozen".into(),
2435        // The same members the audit exported, so scope and classification
2436        // cover one workspace.
2437        "--all-packages".into(),
2438        "--no-dev".into(),
2439        "--no-default-groups".into(),
2440        // Optional extras ship: a consumer who asks for one installs it.
2441        "--all-extras".into(),
2442        "--no-hashes".into(),
2443        "--no-emit-workspace".into(),
2444        "--format".into(),
2445        "requirements-txt".into(),
2446    ];
2447    let (ok, out) = audited_in(settings, &argv, dir)?;
2448    if !ok {
2449        return None;
2450    }
2451    Some(
2452        out.lines()
2453            .map(str::trim)
2454            .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
2455            .filter_map(|l| {
2456                l.split(|c: char| "=<>!~;[ ".contains(c))
2457                    .next()
2458                    .map(normalise)
2459            })
2460            .collect(),
2461    )
2462}
2463
2464/// The notes ref of audit records: local, never pushed, never a stamp.
2465pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
2466const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
2467/// How long a record answers for its lockfiles, in hours.
2468const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
2469/// A report that could not check anything answers for an hour only: an
2470/// offline push is never blocked, and the audit is tried again soon.
2471const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
2472/// The greengate that writes a record, the header's last field. An
2473/// unchecked record answers only to the version that wrote it: the next one
2474/// may have a route that can check (f03).
2475const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");
2476
2477/// Is `check` one of the dependency audits?
2478pub fn is_audit(check: &str) -> bool {
2479    check.starts_with("pre-push-audit-")
2480}
2481
2482/// The files (by name) whose content an audit's branch-mode report depends
2483/// on. A release reads the manifests too (its dev-only split), so a release
2484/// record is keyed by the whole tree instead.
2485fn inputs_of(check: &str) -> &'static [&'static str] {
2486    match check {
2487        "pre-push-audit-rust" => &["Cargo.lock"],
2488        "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
2489        "pre-push-audit-go" => &["go.sum", "go.mod"],
2490        "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
2491        _ => &[],
2492    }
2493}
2494
2495/// The stakes a push's audit is judged and recorded under.
2496#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2497enum AuditMode {
2498    /// A branch push: findings warn.
2499    Branch,
2500    /// A push carrying a `v*` tag: shipped vulnerabilities block.
2501    Release,
2502}
2503
2504impl AuditMode {
2505    fn of(refs: &[PushRef]) -> AuditMode {
2506        if releasing(refs) {
2507            AuditMode::Release
2508        } else {
2509            AuditMode::Branch
2510        }
2511    }
2512}
2513
2514/// What an audit concluded before the push's stakes were applied: what
2515/// `conclude_waivable` judges, and what a record keeps so a later push can
2516/// judge it again against that day's waivers and that push (ADR-0018).
2517#[derive(Debug, Clone, PartialEq, Eq)]
2518struct Concluded {
2519    tool: String,
2520    report: Report,
2521    full: String,
2522    waivable: bool,
2523    /// False when part of the audit did not answer (a timeout, a batch that
2524    /// never ran): such a result is never recorded, so the next push audits
2525    /// again instead of replaying a gap for a day.
2526    complete: bool,
2527}
2528
2529/// How one ecosystem's audit ended: with a report to judge, or before it had
2530/// one.
2531enum Ran {
2532    Concluded(Concluded),
2533    /// Nothing to audit here (no lockfile).
2534    Inert,
2535    /// It could not run: no tool, or a tool that would not start.
2536    Unavailable,
2537}
2538
2539/// A record waiting for the hook to decide it may be written: only where the
2540/// working tree is the keyed tip (the tools read the working tree).
2541#[derive(Debug, Clone)]
2542pub struct Pending {
2543    pub tip: String,
2544    material: String,
2545    body: String,
2546}
2547
2548/// One push's audit bookkeeping, owned by the hook and lent to each audit on
2549/// `Ctx`: the records the audits produced, and the reads both the refusal and
2550/// the replay ask for (each costs a git spawn while git holds the
2551/// connection open).
2552#[derive(Default)]
2553pub struct Ledger {
2554    pending: std::sync::Mutex<Vec<Pending>>,
2555    peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
2556    fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
2557}
2558
2559impl Ledger {
2560    /// The records this push's audits produced, handed to the hook.
2561    pub fn take_pending(&self) -> Vec<Pending> {
2562        std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
2563    }
2564
2565    /// `oid` peeled to its commit, asked of git once per push.
2566    fn peel(&self, oid: &str) -> Option<String> {
2567        if let Some(known) = self
2568            .peeled
2569            .lock()
2570            .unwrap_or_else(|e| e.into_inner())
2571            .get(oid)
2572        {
2573            return known.clone();
2574        }
2575        let commit =
2576            crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
2577        self.peeled
2578            .lock()
2579            .unwrap_or_else(|e| e.into_inner())
2580            .insert(oid.to_string(), commit.clone());
2581        commit
2582    }
2583
2584    /// The pushed commits: every non-deleting ref's tip, peeled to its commit.
2585    fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
2586        let mut commits: Vec<String> = refs
2587            .iter()
2588            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
2589            .filter_map(|r| self.peel(&r.local_oid))
2590            .collect();
2591        commits.sort();
2592        commits.dedup();
2593        commits
2594    }
2595}
2596
2597/// Write `pending` as a note on the blob of its key text. A failure is named
2598/// for the caller to report: the next push then owes the audit again.
2599pub fn write_pending(pending: &Pending) -> Result<(), String> {
2600    // `stdout_piped` keeps git's trailing newline; a key with one names no
2601    // object, and `notes add` would refuse it.
2602    let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
2603        .map(|k| k.trim().to_string())
2604        .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
2605    let written = crate::git::succeeds(&[
2606        "notes",
2607        "--ref",
2608        AUDIT_REF,
2609        "add",
2610        "-f",
2611        "-m",
2612        &pending.body,
2613        &key,
2614    ]);
2615    if written {
2616        Ok(())
2617    } else {
2618        Err(format!("git refused to write the audit record {key}"))
2619    }
2620}
2621
2622/// The text a record is keyed by (the key is its blob's oid).
2623fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
2624    match mode {
2625        AuditMode::Release => {
2626            let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
2627            Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
2628        }
2629        AuditMode::Branch => {
2630            let names = inputs_of(check);
2631            let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
2632            let mut lines: Vec<String> = listing
2633                .lines()
2634                .filter_map(|entry| {
2635                    let (meta, path) = entry.split_once('\t')?;
2636                    let blob = meta.split_whitespace().nth(2)?;
2637                    let base = path.rsplit('/').next().unwrap_or(path);
2638                    names.contains(&base).then(|| format!("{path} {blob}"))
2639                })
2640                .collect();
2641            lines.sort();
2642            Some(format!(
2643                "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
2644                lines.join("\n")
2645            ))
2646        }
2647    }
2648}
2649
2650fn now_secs() -> i64 {
2651    std::time::SystemTime::now()
2652        .duration_since(std::time::UNIX_EPOCH)
2653        .map(|d| d.as_secs() as i64)
2654        .unwrap_or(0)
2655}
2656
2657fn class_of(report: &Report) -> &'static str {
2658    match report {
2659        Report::Clean => "clean",
2660        Report::Advisories(_) => "advisories",
2661        Report::Vulnerabilities(_) => "vulnerabilities",
2662        Report::CouldNotCheck => "unchecked",
2663    }
2664}
2665
2666fn render(concluded: &Concluded, at: i64) -> String {
2667    let items: &[String] = match &concluded.report {
2668        Report::Advisories(v) | Report::Vulnerabilities(v) => v,
2669        Report::Clean | Report::CouldNotCheck => &[],
2670    };
2671    let mut body = format!(
2672        "{AUDIT_FORMAT} {at} {} {} {} {WRITER_VERSION}",
2673        class_of(&concluded.report),
2674        u8::from(concluded.waivable),
2675        concluded.tool
2676    );
2677    for item in items {
2678        body.push_str("\nitem ");
2679        body.push_str(item);
2680    }
2681    body.push_str("\n---\n");
2682    body.push_str(&concluded.full);
2683    body
2684}
2685
2686/// A record's time, the greengate that wrote it (None in a record from before
2687/// the version field), and what it concluded.
2688fn parse(body: &str) -> Option<(i64, Option<String>, Concluded)> {
2689    let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
2690    let mut fields = head.split_whitespace();
2691    if fields.next()? != AUDIT_FORMAT {
2692        return None;
2693    }
2694    let at: i64 = fields.next()?.parse().ok()?;
2695    let class = fields.next()?;
2696    let waivable = fields.next()? == "1";
2697    let tool = fields.next()?.to_string();
2698    let writer = fields.next().map(str::to_string);
2699    let (items_part, full) = match rest.split_once("---\n") {
2700        Some((i, full)) => (i, full.to_string()),
2701        None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
2702    };
2703    let items: Vec<String> = items_part
2704        .lines()
2705        .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
2706        .collect();
2707    let report = match class {
2708        "clean" => Report::Clean,
2709        "advisories" => Report::Advisories(items),
2710        "vulnerabilities" => Report::Vulnerabilities(items),
2711        "unchecked" => Report::CouldNotCheck,
2712        _ => return None,
2713    };
2714    Some((
2715        at,
2716        writer,
2717        Concluded {
2718            tool,
2719            report,
2720            full,
2721            waivable,
2722            complete: true,
2723        },
2724    ))
2725}
2726
2727/// The fresh record of `check` for `commit` in this mode, if any.
2728fn fresh_record(
2729    settings: &crate::config::Settings,
2730    check: &str,
2731    mode: AuditMode,
2732    commit: &str,
2733) -> Option<Concluded> {
2734    let material = key_material(check, mode, commit)?;
2735    let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
2736        .trim()
2737        .to_string();
2738    let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
2739    let (at, writer, concluded) = parse(&body)?;
2740    let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
2741        if writer.as_deref() != Some(WRITER_VERSION) {
2742            return None;
2743        }
2744        UNCHECKED_MAX_AGE_SECS
2745    } else {
2746        crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
2747    };
2748    let age = now_secs() - at;
2749    (0..=max_age).contains(&age).then_some(concluded)
2750}
2751
2752/// Does every commit `refs` pushes carry a fresh record of `check`, all the
2753/// same, in this push's mode? The one the push would replay, or None. Asked
2754/// by the refusal and again by the replay, so answered once per push:
2755/// nothing in one hook run writes a record before both have asked.
2756fn fresh_for_refs(
2757    settings: &crate::config::Settings,
2758    ledger: &Ledger,
2759    check: &str,
2760    refs: &[PushRef],
2761) -> Option<Concluded> {
2762    if !crate::gate_stamp::push_stamps_enabled(settings) {
2763        return None;
2764    }
2765    let memo_key = format!(
2766        "{check} {}",
2767        refs.iter()
2768            .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
2769            .collect::<Vec<_>>()
2770            .join(" ")
2771    );
2772    if let Some(known) = ledger
2773        .fresh
2774        .lock()
2775        .unwrap_or_else(|e| e.into_inner())
2776        .get(&memo_key)
2777    {
2778        return known.clone();
2779    }
2780    let mode = AuditMode::of(refs);
2781    let mut found: Option<Concluded> = None;
2782    for commit in ledger.pushed_commits(refs) {
2783        let Some(record) = fresh_record(settings, check, mode, &commit) else {
2784            found = None;
2785            break;
2786        };
2787        if found.as_ref().is_some_and(|prev| *prev != record) {
2788            found = None;
2789            break;
2790        }
2791        found = Some(record);
2792    }
2793    ledger
2794        .fresh
2795        .lock()
2796        .unwrap_or_else(|e| e.into_inner())
2797        .insert(memo_key, found.clone());
2798    found
2799}
2800
2801/// Is `check` owed by a push of `refs`: opted in, and with no fresh record?
2802pub fn owed(
2803    settings: &crate::config::Settings,
2804    ledger: &Ledger,
2805    check: &str,
2806    refs: &[PushRef],
2807) -> bool {
2808    !ledger.pushed_commits(refs).is_empty()
2809        && fresh_for_refs(settings, ledger, check, refs).is_none()
2810}
2811
2812/// Run an audit through its record: replay a fresh one, or run the tool and
2813/// keep what it concluded on the ledger (a tool that never got to a report
2814/// counts as "could not check").
2815fn recorded(
2816    check: &str,
2817    tool: &str,
2818    ctx: &crate::registry::Ctx,
2819    run: fn(&crate::registry::Ctx) -> Ran,
2820) -> Outcome {
2821    let (settings, refs) = (ctx.settings, ctx.push.get());
2822    let mode = AuditMode::of(refs);
2823    let releasing = mode == AuditMode::Release;
2824    if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
2825        common::ok(
2826            settings,
2827            &format!("{tool}: replaying the audit recorded for this push"),
2828        );
2829        return conclude_waivable(
2830            settings,
2831            &record.tool,
2832            record.report,
2833            releasing,
2834            &record.full,
2835            record.waivable,
2836        );
2837    }
2838    let (outcome, concluded) = match run(ctx) {
2839        Ran::Concluded(concluded) => (
2840            conclude_waivable(
2841                settings,
2842                &concluded.tool,
2843                concluded.report.clone(),
2844                releasing,
2845                &concluded.full,
2846                concluded.waivable,
2847            ),
2848            Some(concluded),
2849        ),
2850        Ran::Unavailable => (
2851            Outcome::Unavailable,
2852            Some(Concluded {
2853                tool: tool.to_string(),
2854                report: Report::CouldNotCheck,
2855                full: String::new(),
2856                waivable: false,
2857                complete: true,
2858            }),
2859        ),
2860        Ran::Inert => (Outcome::Inert, None),
2861    };
2862    // A result with a gap is not recorded; an unchecked one is, for an hour.
2863    let concluded = concluded.filter(|concluded| {
2864        concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
2865    });
2866    if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
2867        let body = render(&concluded, now_secs());
2868        let records: Vec<Pending> = ctx
2869            .audits
2870            .pushed_commits(refs)
2871            .into_iter()
2872            .filter_map(|commit| {
2873                key_material(check, mode, &commit).map(|material| Pending {
2874                    tip: commit,
2875                    material,
2876                    body: body.clone(),
2877                })
2878            })
2879            .collect();
2880        ctx.audits
2881            .pending
2882            .lock()
2883            .unwrap_or_else(|e| e.into_inner())
2884            .extend(records);
2885    }
2886    outcome
2887}
2888
2889pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
2890    recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
2891}
2892
2893pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
2894    recorded("pre-push-audit-js", "audit-js", ctx, js_run)
2895}
2896
2897pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
2898    recorded("pre-push-audit-go", "audit-go", ctx, go_run)
2899}
2900
2901pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
2902    recorded("pre-push-audit-python", "audit-python", ctx, python_run)
2903}
2904
2905#[cfg(test)]
2906mod tests {
2907    use super::*;
2908
2909    /// uv projects have no `requirements.txt`, so the venv is the only thing
2910    /// left to audit — and before this, `audit-python` looked for nothing
2911    /// else and reported "the audit did NOT run" forever. Six repositories
2912    /// in one fleet were in exactly that state, one of them carrying 53
2913    /// known vulnerabilities nobody had been told about.
2914    #[test]
2915    fn a_uv_project_is_audited_through_its_venv() {
2916        let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
2917        let _ = std::fs::remove_dir_all(&root);
2918
2919        // Nothing on disk: nothing to audit, and we say so rather than
2920        // inventing a target.
2921        std::fs::create_dir_all(&root).unwrap();
2922        assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
2923
2924        // The posix layout, with the python version DISCOVERED — hard-coding
2925        // `python3.13` would silently stop finding it after an upgrade.
2926        // Joined segment by segment, NOT as one "a/b/c" literal: on Windows
2927        // the literal keeps its forward slashes while the code under test
2928        // returns backslashes, and the test fails on a difference that is
2929        // only in the expectation.
2930        let sp = root
2931            .join(".venv")
2932            .join("lib")
2933            .join("python3.13")
2934            .join("site-packages");
2935        std::fs::create_dir_all(&sp).unwrap();
2936        assert_eq!(
2937            venv_site_packages(root.to_str().unwrap(), None),
2938            Some(sp.to_string_lossy().into_owned())
2939        );
2940
2941        // The Windows layout, which has no version directory at all.
2942        let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
2943        let _ = std::fs::remove_dir_all(&win);
2944        let wsp = win.join(".venv").join("Lib").join("site-packages");
2945        std::fs::create_dir_all(&wsp).unwrap();
2946        assert_eq!(
2947            venv_site_packages(win.to_str().unwrap(), None),
2948            Some(wsp.to_string_lossy().into_owned())
2949        );
2950
2951        let _ = std::fs::remove_dir_all(&root);
2952        let _ = std::fs::remove_dir_all(&win);
2953    }
2954
2955    fn tag(name: &str) -> PushRef {
2956        PushRef {
2957            local_ref: name.to_string(),
2958            local_oid: "a".repeat(40),
2959            remote_ref: name.to_string(),
2960            remote_oid: "0".repeat(40),
2961        }
2962    }
2963
2964    /// `v` + digit gates; a branch, a bare-word tag, or a tag merely
2965    /// starting with the letter v does not.
2966    #[test]
2967    fn pip_audit_rows_name_their_packages_normalised() {
2968        let out = "Name       Version ID                  Fix Versions\n\
2969                   ---------- ------- ------------------- ------------\n\
2970                   Pytest_Cov 4.0.0   GHSA-aaaa-bbbb-cccc 4.1.0\n\
2971                   requests   2.31.0  PYSEC-2023-74       2.31.1\n\
2972                   requests   2.31.0  CVE-2024-35195      2.32.0\n\
2973                   Found 3 known vulnerabilities in 2 packages\n";
2974        let names: Vec<String> = pip_vulnerable_rows(out)
2975            .into_iter()
2976            .map(|(n, _)| n)
2977            .collect();
2978        assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
2979        assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
2980    }
2981
2982    #[test]
2983    fn advisory_ids_are_found_wherever_they_sit() {
2984        let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
2985                    ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
2986        assert_eq!(
2987            advisory_ids(text),
2988            vec![
2989                "CVE-2024-35195",
2990                "GHSA-h3mg-xc3c-68pw",
2991                "GO-2024-2687",
2992                "OSV-2024-12",
2993                "PYSEC-2023-74",
2994                "RUSTSEC-2025-0001"
2995            ]
2996        );
2997    }
2998
2999    #[test]
3000    fn a_waiver_is_reasoned_dated_and_bounded() {
3001        let today = days_from_date("2026-10-05").unwrap();
3002        let w = Waivers::parse(
3003            "# id expires reason\n\
3004             GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
3005             GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
3006             GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
3007             GHSA-jjjj-kkkk-llll 2026-11-01\n\
3008             GHSA-mmmm-nnnn-oooo soon no date\n",
3009            today,
3010        );
3011        assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
3012        assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
3013        assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
3014        assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
3015        assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
3016        assert_eq!(w.problems().len(), 4);
3017        assert_eq!(days_from_date("1970-01-01"), Some(0));
3018        assert_eq!(days_from_date("2026-02-30"), None);
3019        assert!(days_from_date("2028-02-29").is_some());
3020        assert_eq!(days_from_date("2026-13-01"), None);
3021    }
3022
3023    #[test]
3024    fn two_locked_versions_are_two_answers() {
3025        let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
3026                   Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
3027        let ids = vec![
3028            "RUSTSEC-2025-0010".to_string(),
3029            "RUSTSEC-2025-0011".to_string(),
3030        ];
3031        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3032            "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
3033            "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
3034            _ => None,
3035        });
3036        assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
3037        assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
3038    }
3039
3040    #[test]
3041    fn a_pip_row_without_a_nameable_id_is_unwaivable() {
3042        let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
3043        let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
3044        assert!(pip_rows_all_named(named));
3045        assert!(!pip_rows_all_named(unnamed));
3046    }
3047
3048    #[test]
3049    fn a_crate_ships_unless_its_tree_says_otherwise() {
3050        let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
3051                   Crate: app\nID: RUSTSEC-2025-0002\n\
3052                   Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
3053        let ids = vec![
3054            "RUSTSEC-2025-0001".to_string(),
3055            "RUSTSEC-2025-0002".to_string(),
3056            "RUSTSEC-2025-0003".to_string(),
3057            "RUSTSEC-2025-0004".to_string(),
3058        ];
3059        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3060            // Asked by name@version when cargo audit gave the version.
3061            "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
3062            "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
3063            // A tree that says neither: not proof of dev-only.
3064            "odd" => Some("odd v1.0.0\n".into()),
3065            _ => None,
3066        });
3067        // 0003 has no crate, 0004's tree is unclear: unknowns ship.
3068        assert_eq!(
3069            shipped,
3070            vec![
3071                "RUSTSEC-2025-0002",
3072                "RUSTSEC-2025-0003",
3073                "RUSTSEC-2025-0004"
3074            ]
3075        );
3076        assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
3077    }
3078
3079    #[test]
3080    fn a_release_is_a_v_number_tag() {
3081        assert!(releasing(&[tag("refs/tags/v1.6.6")]));
3082        assert!(releasing(&[tag("refs/tags/v2")]));
3083        assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
3084        assert!(!releasing(&[tag("refs/tags/release")]));
3085        assert!(!releasing(&[tag("refs/heads/v1-styles")]));
3086        assert!(!releasing(&[tag("refs/heads/main")]));
3087        // A mixed push gates: the tag is in there.
3088        assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
3089    }
3090
3091    /// ci.yaml's lesson, pinned at the unit level: the ids decide, the exit
3092    /// code only classifies them.
3093    #[test]
3094    fn cargo_audit_ids_decide_not_the_exit_code() {
3095        assert_eq!(
3096            read_cargo_audit(true, "ok, 312 crates checked"),
3097            Report::Clean
3098        );
3099        assert_eq!(
3100            read_cargo_audit(false, "error: couldn't fetch advisory database"),
3101            Report::CouldNotCheck
3102        );
3103        let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
3104        assert_eq!(
3105            read_cargo_audit(true, warn),
3106            Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
3107        );
3108        let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
3109        assert_eq!(
3110            read_cargo_audit(false, vuln),
3111            Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
3112        );
3113        // A lookalike is not an id.
3114        assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
3115    }
3116
3117    /// The real report shape, trimmed from the run that prompted this: two
3118    /// advisories against ONE crate, and one against another.
3119    fn real_report() -> String {
3120        [
3121            "Crate:     paste",
3122            "Version:   1.0.15",
3123            "Warning:   unmaintained",
3124            "ID:        RUSTSEC-2024-0436",
3125            "URL:       https://rustsec.org/advisories/RUSTSEC-2024-0436",
3126            "",
3127            "Crate:     lru",
3128            "Version:   0.12.5",
3129            "Warning:   unsound",
3130            "ID:        RUSTSEC-2026-0253",
3131            "",
3132            "Crate:     lru",
3133            "Version:   0.12.5",
3134            "ID:        RUSTSEC-2026-0002",
3135            "",
3136            "warning: 3 allowed warnings found",
3137        ]
3138        .join("\n")
3139    }
3140
3141    #[test]
3142    fn an_advisory_is_paired_with_its_crate() {
3143        let pairs = ids_with_crates(&real_report());
3144        assert_eq!(
3145            pairs,
3146            vec![
3147                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3148                ("RUSTSEC-2026-0253".into(), Some("lru".into())),
3149                ("RUSTSEC-2026-0002".into(), Some("lru".into())),
3150            ]
3151        );
3152    }
3153
3154    /// A `Crate:` binds to ONE id. An id printed loose reports no crate
3155    /// rather than inheriting whichever block happened to precede it.
3156    #[test]
3157    fn a_loose_id_borrows_no_crate() {
3158        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
3159        assert_eq!(
3160            ids_with_crates(out),
3161            vec![
3162                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3163                ("RUSTSEC-2025-0001".into(), None),
3164            ]
3165        );
3166    }
3167
3168    /// Local crates carry a path; registry crates do not. That is the whole
3169    /// discriminator, and it has to work without knowing the member names.
3170    #[test]
3171    fn only_local_crates_are_named_as_reached() {
3172        let tree =
3173            "lru v0.12.5\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
3174        assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
3175        assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
3176    }
3177
3178    /// End to end on the real report, with the tree calls faked: each id
3179    /// names its crate and the workspace crate that reaches it, and `lru`'s
3180    /// two advisories cost ONE lookup.
3181    #[test]
3182    fn the_warning_names_the_crate_and_what_reaches_it() {
3183        let calls = std::cell::RefCell::new(Vec::new());
3184        let fake = |k: &str| {
3185            calls.borrow_mut().push(k.to_string());
3186            Some(format!(
3187                "{k} v1\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
3188            ))
3189        };
3190        let out = real_report();
3191        let got = attribute(read_cargo_audit(true, &out), &out, fake);
3192        assert_eq!(
3193            got,
3194            Report::Advisories(vec![
3195                "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
3196                "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
3197                "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
3198            ])
3199        );
3200        assert_eq!(
3201            calls.into_inner(),
3202            vec!["paste", "lru"],
3203            "one call per crate"
3204        );
3205    }
3206
3207    /// A lock-file-only crate — an optional dependency of a feature nobody
3208    /// enabled — is reported as such. `cargo audit` reads Cargo.lock, so this
3209    /// is a real and confusing case, and naming it is the point.
3210    #[test]
3211    fn a_crate_outside_the_build_graph_says_so() {
3212        let out = "Crate:     wezterm-input-types\nID:        RUSTSEC-2025-0001";
3213        let got = attribute(read_cargo_audit(true, out), out, |_| {
3214            Some("warning: nothing to print.".into())
3215        });
3216        assert_eq!(
3217            got,
3218            Report::Advisories(vec![
3219                "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
3220            ])
3221        );
3222    }
3223
3224    /// Attribution is a better message, never a gate. A clean report spawns
3225    /// nothing, and a `cargo tree` that cannot run still reports the id.
3226    #[test]
3227    fn attribution_never_changes_the_verdict() {
3228        let spawned = std::cell::Cell::new(false);
3229        let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
3230            spawned.set(true);
3231            None
3232        });
3233        assert_eq!(clean, Report::Clean);
3234        assert!(!spawned.get(), "a clean report must spawn nothing");
3235
3236        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436";
3237        let blind = attribute(read_cargo_audit(false, out), out, |_| None);
3238        assert_eq!(
3239            blind,
3240            Report::Vulnerabilities(vec![
3241                "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
3242            ])
3243        );
3244    }
3245
3246    #[test]
3247    fn npm_audit_summary_decides() {
3248        assert_eq!(
3249            read_npm_audit(true, "found 0 vulnerabilities\n"),
3250            Report::Clean
3251        );
3252        assert_eq!(
3253            read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
3254            Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
3255        );
3256        // npm 7+ dropped the verb: this is what every current npm prints,
3257        // and what read as "never answered" until the parser learned it.
3258        assert_eq!(
3259            read_npm_audit(
3260                false,
3261                "# npm audit report\n\nvite  6.0.0 - 6.1.5\nSeverity: high\n\n\
3262                 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n  npm audit fix\n"
3263            ),
3264            Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
3265        );
3266        assert_eq!(
3267            read_npm_audit(false, "1 vulnerability (1 high)\n"),
3268            Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
3269        );
3270        assert_eq!(
3271            read_npm_audit(true, "up to date, audited 100 packages\n"),
3272            Report::Clean
3273        );
3274        assert_eq!(
3275            read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
3276            Report::CouldNotCheck
3277        );
3278    }
3279
3280    #[test]
3281    fn pnpm_audit_summary_decides() {
3282        assert_eq!(
3283            read_pnpm_audit(true, "No known vulnerabilities found\n"),
3284            Report::Clean
3285        );
3286        // What pnpm prints after its table: the count, then the severities,
3287        // which the finding carries so the warning says how bad.
3288        assert_eq!(
3289            read_pnpm_audit(
3290                false,
3291                "│ More info │ https://github.com/advisories/GHSA-395f │\n\
3292                 └───────────┴──────────────────────────────────────────┘\n\
3293                 107 vulnerabilities found\n\
3294                 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
3295            ),
3296            Report::Vulnerabilities(vec![
3297                "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
3298            ])
3299        );
3300        assert_eq!(
3301            read_pnpm_audit(false, "1 vulnerabilities found\n"),
3302            Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
3303        );
3304        assert_eq!(
3305            read_pnpm_audit(
3306                false,
3307                " ERR_PNPM_AUDIT_BAD_RESPONSE  The audit endpoint responded with 503\n"
3308            ),
3309            Report::CouldNotCheck
3310        );
3311    }
3312
3313    /// The cargo-audit split, spoken in Go: ids decide, the exit code says
3314    /// whether the analysed code is actually affected.
3315    #[test]
3316    fn govulncheck_ids_decide_not_the_exit_code() {
3317        assert_eq!(
3318            read_govulncheck(true, "No vulnerabilities found.\n"),
3319            Report::Clean
3320        );
3321        assert_eq!(
3322            read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
3323            Report::CouldNotCheck
3324        );
3325        // Informational: the module is vulnerable, the analysed code never
3326        // calls it — exit 0, ids present.
3327        assert_eq!(
3328            read_govulncheck(
3329                true,
3330                "=== Informational ===\nVulnerability #1: GO-2023-1840\n  More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
3331            ),
3332            Report::Advisories(vec!["GO-2023-1840".into()])
3333        );
3334        assert_eq!(
3335            read_govulncheck(
3336                false,
3337                "Vulnerability #1: GO-2022-0969\n  Your code calls it.\nGO-2022-0969 again\n"
3338            ),
3339            Report::Vulnerabilities(vec!["GO-2022-0969".into()])
3340        );
3341        // A lookalike is not an id.
3342        assert_eq!(
3343            read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
3344            Report::Clean
3345        );
3346    }
3347
3348    #[test]
3349    fn pip_audit_sentence_decides() {
3350        assert_eq!(
3351            read_pip_audit(true, "No known vulnerabilities found\n"),
3352            Report::Clean
3353        );
3354        assert_eq!(
3355            read_pip_audit(
3356                false,
3357                "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
3358            ),
3359            Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
3360        );
3361        assert_eq!(
3362            read_pip_audit(false, "ERROR: could not resolve\n"),
3363            Report::CouldNotCheck
3364        );
3365    }
3366
3367    fn lock_block(name: Option<&str>, source: &str) -> String {
3368        let mut block = String::from("[[package]]\n");
3369        if let Some(name) = name {
3370            block.push_str(&format!("name = \"{name}\"\n"));
3371        }
3372        block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
3373        block
3374    }
3375
3376    #[test]
3377    fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
3378        let pypi = "{ registry = \"https://pypi.org/simple\" }";
3379        let lock = [
3380            lock_block(Some("Requests"), pypi),
3381            lock_block(
3382                Some("slashed"),
3383                "{ registry = \"https://pypi.org/simple/\" }",
3384            ),
3385            lock_block(
3386                Some("mirror"),
3387                "{ registry = \"https://mirror.example/simple\" }",
3388            ),
3389            lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
3390            lock_block(Some("pathdep"), "{ path = \"../x\" }"),
3391            lock_block(Some("edit"), "{ editable = \".\" }"),
3392            lock_block(Some("virt"), "{ virtual = \".\" }"),
3393            lock_block(Some("twice"), pypi),
3394            lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
3395            lock_block(None, pypi),
3396            "[package.metadata]\nname = \"ignored\"\n".to_string(),
3397        ]
3398        .concat();
3399        let sources = scan_uv_lock(&lock);
3400        let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
3401        assert_eq!(admitted, ["requests", "slashed"]);
3402        assert_eq!(sources.nameless, 1);
3403    }
3404
3405    #[test]
3406    fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
3407        let pypi: std::collections::BTreeSet<String> =
3408            ["numpy", "idna", "requests"].map(String::from).into();
3409        let raw = "\
3410# generated
3411numpy==1.26.4 ; python_full_version < '3.12'
3412numpy==2.1.0 ; python_full_version >= '3.12'
3413numpy==2.1.0 ; sys_platform == 'win32'
3414idna==3.7
3415platform-kernel==0.1.0
3416requests @ https://example.com/r.whl
3417";
3418        let pins = filter_export(raw, &pypi);
3419        assert_eq!(pins.versions, 3);
3420        assert_eq!(pins.batches.len(), 2);
3421        assert_eq!(
3422            pins.batches[0].get("numpy").map(String::as_str),
3423            Some("1.26.4")
3424        );
3425        assert_eq!(
3426            pins.batches[1].get("numpy").map(String::as_str),
3427            Some("2.1.0")
3428        );
3429        assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
3430        assert!(pins.skipped.contains("platform-kernel"));
3431        assert!(pins.unclassified.contains("requests"));
3432    }
3433
3434    /// pip-compile's shape, as homelab's laya-decisions has it (f108).
3435    const HASHED: &str = "\
3436# This file was autogenerated by uv via the following command:
3437#    ./compile-requirements.sh
3438anyio==4.15.1 \\
3439    --hash=sha256:6152 \\
3440    --hash=sha256:9f28
3441    # via
3442    #   starlette
3443idna==3.7 \\
3444    --hash=sha256:aaaa
3445torch==2.14.0+cpu \\
3446    --hash=sha256:bbbb
3447    # via -r requirements.in
3448";
3449
3450    #[test]
3451    fn only_a_fully_hashed_file_skips_the_resolve() {
3452        let pins = hashed_pins_in(HASHED).expect("hashed");
3453        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
3454        // Top-level `==` pins without hashes: their dependencies are unlisted.
3455        assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
3456        let one_unhashed = format!("{HASHED}idna==3.7\n");
3457        assert_eq!(hashed_pins_in(&one_unhashed), None);
3458        let ranged = "requests>=2.0 \\\n    --hash=sha256:cccc\n";
3459        assert_eq!(hashed_pins_in(ranged), None);
3460        let included = format!("-r requirements-upload.txt\n{HASHED}");
3461        assert_eq!(hashed_pins_in(&included), None);
3462        let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
3463        assert_eq!(hashed_pins_in(&indexed), None);
3464        // A marked pin is still a closed set: it takes the batch route.
3465        let marked =
3466            format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n    --hash=sha256:dddd\n");
3467        assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
3468        assert_eq!(
3469            hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
3470            None
3471        );
3472        assert_eq!(hashed_pins_in("# fixture\n"), None);
3473        assert_eq!(hashed_pins_in(""), None);
3474    }
3475
3476    #[test]
3477    fn marked_pins_are_stripped_and_their_versions_batched_apart() {
3478        let text = "\
3479six==1.16.0 \\
3480    --hash=sha256:aaaa
3481numpy==1.26.4 ; python_version == '3.9' \\
3482    --hash=sha256:bbbb
3483numpy==2.1.0 ; python_version == '3.12' \\
3484    --hash=sha256:cccc
3485";
3486        let pins = hashed_pins_in(text).expect("hashed");
3487        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
3488        let batches = batches_of(pins.pairs);
3489        assert_eq!(batches.len(), 2);
3490        assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
3491        assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
3492        assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
3493    }
3494
3495    /// pip-audit 2.10.1's output on laya-decisions with `--no-deps
3496    /// --disable-pip`, cut to two rows.
3497    const SKIPPING: &str = "\
3498Found 2 known vulnerabilities in 1 package
3499Name      Version ID              Fix Versions
3500--------- ------- --------------- ------------
3501starlette 0.41.3  PYSEC-2026-1941 0.47.2
3502starlette 0.41.3  PYSEC-2026-1942 0.49.1
3503
3504Name  Skip Reason
3505----- -------------------------------------------------------------------------
3506torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
3507";
3508
3509    #[test]
3510    fn the_skip_table_names_its_packages_and_is_no_finding() {
3511        assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
3512        assert_eq!(
3513            pip_vulnerable_rows(SKIPPING),
3514            vec![
3515                ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
3516                ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
3517            ]
3518        );
3519        assert!(pip_rows_all_named(SKIPPING));
3520        let clean = "No known vulnerabilities found\nName  Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
3521        assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
3522        assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
3523    }
3524
3525    #[test]
3526    fn the_skipped_line_names_three_and_counts_the_rest() {
3527        let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
3528        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
3529        assert_eq!(
3530            skipped_line("", &refs),
3531            "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
3532        );
3533        assert_eq!(
3534            skipped_line("", &refs[..1]),
3535            "audit-python: 1 private/non-PyPI package skipped (a)"
3536        );
3537        let long = "services/laya-decisions/requirements.txt: ";
3538        assert_eq!(
3539            skipped_line(long, &["torch", "triton"]),
3540            format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
3541        );
3542    }
3543
3544    #[test]
3545    fn scrub_names_the_canonical_private_path_too() {
3546        let plain = std::path::Path::new("/var/folders/a/audit-1");
3547        let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
3548        assert_eq!(
3549            scrub_private(
3550                "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
3551                plain,
3552                canonical
3553            ),
3554            "x <tmp>/b and <tmp>/c"
3555        );
3556    }
3557
3558    #[test]
3559    fn production_names_are_never_asked_off_a_release_or_out_of_time() {
3560        let settings = crate::config::Settings::default();
3561        let spent = Budget {
3562            started: std::time::Instant::now(),
3563            limit: Some(std::time::Duration::ZERO),
3564        };
3565        let said = std::cell::RefCell::new(Vec::<String>::new());
3566        let say = |m: &str| said.borrow_mut().push(m.to_string());
3567        let dir = std::env::temp_dir();
3568
3569        let mut off = Production::Never;
3570        assert!(off.names(&settings, &spent, &say).is_none());
3571        assert!(matches!(off, Production::Never), "no release never asks");
3572        assert!(said.borrow().is_empty());
3573
3574        let mut late = Production::Unasked(dir.clone());
3575        assert!(late.names(&settings, &spent, &say).is_none());
3576        assert!(late.names(&settings, &spent, &say).is_none());
3577        assert!(
3578            matches!(late, Production::Asked(None)),
3579            "spent is remembered as unknown"
3580        );
3581
3582        // In time it asks, once: this checkout tracks no uv.lock, so the
3583        // answer is unknown and stays the answer.
3584        let fresh = Budget {
3585            started: std::time::Instant::now(),
3586            limit: None,
3587        };
3588        let mut asked = Production::Unasked(dir);
3589        assert!(asked.names(&settings, &fresh, &say).is_none());
3590        assert!(matches!(asked, Production::Asked(None)));
3591        let said = said.borrow();
3592        assert_eq!(said.len(), 1, "warned once: {said:?}");
3593        assert!(said[0].contains("every finding counts"), "{said:?}");
3594        assert!(said[0].contains("greengate.timeout"), "{said:?}");
3595    }
3596
3597    #[test]
3598    fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
3599        for why in [
3600            "ConnectionError: Max retries exceeded",
3601            "error: request timed out",
3602            "SSL: CERTIFICATE_VERIFY_FAILED",
3603            "Temporary failure in name resolution",
3604        ] {
3605            assert!(pip_audit_next(why).contains("the network"), "{why}");
3606        }
3607        for why in [
3608            "(no output)",
3609            "ModuleNotFoundError: No module named 'pip_audit'",
3610        ] {
3611            assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
3612        }
3613    }
3614
3615    #[test]
3616    fn only_readable_vulnerability_rows_need_the_split() {
3617        let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
3618        assert!(has_rows_to_split(
3619            &Report::Vulnerabilities(vec!["certifi".into()]),
3620            rows
3621        ));
3622        assert!(!has_rows_to_split(
3623            &Report::Vulnerabilities(vec!["x".into()]),
3624            "Found 1\n"
3625        ));
3626        assert!(!has_rows_to_split(&Report::Clean, rows));
3627        assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
3628    }
3629
3630    #[test]
3631    fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
3632        let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
3633        let guard = PrivateDir::create_at(path.clone()).unwrap();
3634        #[cfg(unix)]
3635        {
3636            use std::os::unix::fs::PermissionsExt;
3637            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
3638            assert_eq!(mode & 0o777, 0o700);
3639        }
3640        assert!(PrivateDir::create_at(path.clone()).is_err());
3641        assert!(path.is_dir(), "the refused attempt must leave it alone");
3642        drop(guard);
3643        assert!(!path.exists());
3644    }
3645}