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                // audit-js splits on a branch too, and govulncheck reports
148                // only what ships: only these two judge the whole tree here.
149                if matches!(tool, "audit-rust" | "audit-python") {
150                    common::warn(&format!(
151                        "{tool}: this list is the whole tree; a tag judges only what ships"
152                    ));
153                }
154                Outcome::Warned
155            }
156        }
157        Report::CouldNotCheck => {
158            common::warn(&format!(
159                "{tool} could not complete — the dependency tree was NOT checked. \
160                 This is not a clean result."
161            ));
162            Outcome::Unavailable
163        }
164    }
165}
166
167/// Where a repository records the advisories a release may ship anyway.
168const WAIVERS_FILE: &str = crate::names::AUDIT_WAIVERS;
169
170/// The same file before greengate 4.3, read when [`WAIVERS_FILE`] is absent
171/// until the census renames every repository's (`greengate migrate --tracked`).
172const OLD_WAIVERS_FILE: &str = crate::names::old::AUDIT_WAIVERS;
173
174/// How far ahead a waiver may run. A waiver is a decision to revisit, not
175/// an exemption: one dated further out is void, so nothing is waived for
176/// good by accident.
177const MAX_WAIVER_DAYS: i64 = 90;
178
179/// One line of the waiver file: `<advisory id> <expires YYYY-MM-DD> <reason>`.
180#[derive(Debug)]
181struct Waiver {
182    id: String,
183    expires: String,
184    reason: String,
185    valid: bool,
186}
187
188/// The repository's reviewed waivers, judged against today.
189///
190/// A waiver lets a RELEASE ship a known vulnerability nobody can fix yet —
191/// an advisory with no patched version, on a path the project cannot
192/// replace. It is committed (so it is reviewed like code), names its
193/// reason, and expires: past its date, or dated more than
194/// [`MAX_WAIVER_DAYS`] ahead, it waives nothing and the tag is refused
195/// again. Branch pushes never consult it — they never block.
196#[derive(Debug, Default)]
197struct Waivers {
198    entries: Vec<Waiver>,
199    problems: Vec<String>,
200    /// The file these were read from, for messages to quote; `None` when no
201    /// file was read.
202    file: Option<&'static str>,
203}
204
205impl Waivers {
206    fn load(root: &str, today: i64) -> Self {
207        let root = std::path::Path::new(root);
208        let read = |file: &'static str| (file, std::fs::read_to_string(root.join(file)));
209        let (mut file, mut got) = read(WAIVERS_FILE);
210        if matches!(&got, Err(e) if e.kind() == std::io::ErrorKind::NotFound) {
211            (file, got) = read(OLD_WAIVERS_FILE);
212        } else if root.join(OLD_WAIVERS_FILE).exists() {
213            common::warn(&format!(
214                "{OLD_WAIVERS_FILE} is ignored: {WAIVERS_FILE} exists — \
215                 delete the old file"
216            ));
217        }
218        match got {
219            Ok(text) => Self {
220                file: Some(file),
221                ..Self::parse(&text, today)
222            },
223            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
224            Err(e) => Self {
225                entries: Vec::new(),
226                problems: vec![format!(
227                    "{file} could not be read ({e}) — it waives nothing"
228                )],
229                file: Some(file),
230            },
231        }
232    }
233
234    fn parse(text: &str, today: i64) -> Self {
235        let mut w = Self::default();
236        for line in text.lines().map(str::trim) {
237            if line.is_empty() || line.starts_with('#') {
238                continue;
239            }
240            let mut parts = line.splitn(3, char::is_whitespace);
241            let id = parts.next().unwrap_or_default().to_string();
242            let expires = parts.next().unwrap_or_default().trim().to_string();
243            let reason = parts.next().unwrap_or_default().trim().to_string();
244            let valid = match days_from_date(&expires) {
245                None => {
246                    w.problems.push(format!(
247                        "waiver for {id} has no readable expiry date (YYYY-MM-DD) — it waives nothing"
248                    ));
249                    false
250                }
251                Some(_) if reason.is_empty() => {
252                    w.problems.push(format!(
253                        "waiver for {id} gives no reason — it waives nothing"
254                    ));
255                    false
256                }
257                Some(d) if d < today => {
258                    w.problems
259                        .push(format!("waiver for {id} expired on {expires}"));
260                    false
261                }
262                Some(d) if d - today > MAX_WAIVER_DAYS => {
263                    w.problems.push(format!(
264                        "waiver for {id} runs to {expires}, more than {MAX_WAIVER_DAYS} days \
265                         ahead — it waives nothing; date it sooner and revisit"
266                    ));
267                    false
268                }
269                Some(_) => true,
270            };
271            w.entries.push(Waiver {
272                id,
273                expires,
274                reason,
275                valid,
276            });
277        }
278        w
279    }
280
281    fn covers(&self, id: &str) -> bool {
282        self.entries.iter().any(|w| w.valid && w.id == id)
283    }
284
285    fn describe(&self, id: &str) -> String {
286        match self.entries.iter().find(|w| w.valid && w.id == id) {
287            Some(w) => format!("{id} until {} ({})", w.expires, w.reason),
288            None => id.to_string(),
289        }
290    }
291
292    fn problems(&self) -> &[String] {
293        &self.problems
294    }
295}
296
297/// Days since 1970-01-01 for a `YYYY-MM-DD` date (proleptic Gregorian).
298fn days_from_date(date: &str) -> Option<i64> {
299    let mut it = date.split('-');
300    let (y, m, d): (i64, i64, i64) = (
301        it.next()?.parse().ok()?,
302        it.next()?.parse().ok()?,
303        it.next()?.parse().ok()?,
304    );
305    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
306    let month_days = [
307        31,
308        if leap { 29 } else { 28 },
309        31,
310        30,
311        31,
312        30,
313        31,
314        31,
315        30,
316        31,
317        30,
318        31,
319    ];
320    if it.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > month_days[(m - 1) as usize] {
321        return None;
322    }
323    // Howard Hinnant's days_from_civil.
324    let y = if m <= 2 { y - 1 } else { y };
325    let era = if y >= 0 { y } else { y - 399 } / 400;
326    let yoe = y - era * 400;
327    let mp = (m + 9) % 12;
328    let doy = (153 * mp + 2) / 5 + d - 1;
329    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
330    Some(era * 146_097 + doe - 719_468)
331}
332
333/// Today, in days since the epoch (UTC).
334fn today() -> i64 {
335    std::time::SystemTime::now()
336        .duration_since(std::time::UNIX_EPOCH)
337        .map(|d| (d.as_secs() / 86_400) as i64)
338        .unwrap_or(0)
339}
340
341/// Every advisory id in `text`: GitHub (`GHSA-xxxx-xxxx-xxxx`), RustSec,
342/// Go, PyPA and CVE ids, wherever they sit (a URL, a table cell).
343fn advisory_ids(text: &str) -> Vec<String> {
344    let mut ids: Vec<String> = text
345        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
346        .filter(|w| {
347            let parts: Vec<&str> = w.split('-').collect();
348            match parts.as_slice() {
349                ["GHSA", a, b, c] => [a, b, c]
350                    .iter()
351                    .all(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphanumeric())),
352                ["RUSTSEC" | "GO" | "PYSEC" | "CVE" | "OSV", year, num] => {
353                    year.len() == 4
354                        && year.bytes().all(|b| b.is_ascii_digit())
355                        && !num.is_empty()
356                        && num.bytes().all(|b| b.is_ascii_digit())
357                }
358                _ => false,
359            }
360        })
361        .map(str::to_string)
362        .collect();
363    ids.sort();
364    ids.dedup();
365    ids
366}
367
368/// Is this word a RUSTSEC id? `RUSTSEC-` + 4 digits + `-` + 4 digits.
369fn is_advisory_id(w: &str) -> bool {
370    w.len() == 17
371        && w.starts_with("RUSTSEC-")
372        && w[8..12].bytes().all(|b| b.is_ascii_digit())
373        && w.as_bytes()[12] == b'-'
374        && w[13..17].bytes().all(|b| b.is_ascii_digit())
375}
376
377/// Pair each advisory with the crate it was raised against.
378///
379/// `cargo audit`'s terminal report is blocks — `Crate:` … `ID:` — and the
380/// id alone does not say which crate carries it, let alone which of YOUR
381/// crates depends on that. Answering "is this on the commit path or only in
382/// an opt-in tool?" meant running `cargo tree -i` by hand every time.
383///
384/// A `Crate:` binds to the next `ID:` and is then spent, so an id appearing
385/// outside a block — a summary line, a URL — reports no crate rather than
386/// inheriting the previous block's.
387fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
388    let mut pairs: Vec<(String, Option<String>)> = Vec::new();
389    let mut pending: Option<String> = None;
390    for line in out.lines() {
391        let t = line.trim();
392        if let Some(rest) = t.strip_prefix("Crate:") {
393            pending = rest.split_whitespace().next().map(str::to_string);
394            continue;
395        }
396        if let Some(rest) = t.strip_prefix("ID:") {
397            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
398                pairs.push((id.to_string(), pending.take()));
399                continue;
400            }
401        }
402        // Ids outside a block still count — the older summary-line shapes
403        // and anything cargo audit prints loose.
404        for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
405            pairs.push((w.to_string(), None));
406        }
407    }
408    pairs
409}
410
411/// Which of THIS workspace's crates reach `crate`, read from `cargo tree -i`.
412///
413/// Cargo prints a local package with its path in parentheses and a registry
414/// package without one, which is the only discriminator needed and works in
415/// any repository — the hook cannot know a given workspace's member names.
416///
417/// An empty result is an answer, not a failure: `cargo tree` prints
418/// "nothing to print" for a crate that is in `Cargo.lock` but not in the
419/// build graph. `cargo audit` reads the lock file, so an advisory can name a
420/// crate nothing compiles — an optional dependency of a feature nobody
421/// enabled. Saying so is more useful than naming no crate at all.
422fn local_dependents(tree_out: &str) -> Vec<String> {
423    let mut names: Vec<String> = tree_out
424        .lines()
425        .filter(|l| l.contains(" (/"))
426        .filter_map(|l| {
427            l.split_whitespace()
428                .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
429                .map(str::to_string)
430        })
431        .collect();
432    names.sort();
433    names.dedup();
434    names
435}
436
437/// One advisory, said in full: the id, the crate it is against, and which of
438/// this workspace's crates actually reach it.
439fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
440    match (krate, reaches.is_empty()) {
441        (None, _) => id.to_string(),
442        (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
443        (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
444    }
445}
446
447/// `cargo audit`, ci.yaml's rules verbatim: the RUSTSEC ids decide, the
448/// exit code only says which class they are.
449fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
450    let mut ids: Vec<String> = out
451        .split_whitespace()
452        .filter(|w| {
453            w.len() == 17
454                && w.starts_with("RUSTSEC-")
455                && w[8..12].bytes().all(|b| b.is_ascii_digit())
456                && w.as_bytes()[12] == b'-'
457                && w[13..17].bytes().all(|b| b.is_ascii_digit())
458        })
459        .map(|w| w.to_string())
460        .collect();
461    ids.sort();
462    ids.dedup();
463    match (ids.is_empty(), exit_ok) {
464        (true, true) => Report::Clean,
465        (true, false) => Report::CouldNotCheck,
466        (false, true) => Report::Advisories(ids),
467        (false, false) => Report::Vulnerabilities(ids),
468    }
469}
470
471/// `npm audit`: the summary line decides. A clean tree is `found 0
472/// vulnerabilities` on every npm. A finding is `found N vulnerabilities`
473/// on npm 6 and `N vulnerabilities (a moderate, b high)` — the verb dropped,
474/// `1 vulnerability` in the singular — on npm 7 and later, which is every
475/// npm shipped since 2020. No recognisable summary plus a refusal to exit
476/// clean is a tool that never answered.
477fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
478    let summary = out.lines().rev().map(str::trim).find(|l| {
479        l.contains("vulnerabilit")
480            && (l.starts_with("found ")
481                || l.split_whitespace()
482                    .next()
483                    .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
484    });
485    match summary {
486        Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
487        Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
488        None if exit_ok => Report::Clean,
489        None => Report::CouldNotCheck,
490    }
491}
492
493/// `pnpm audit`: the summary line decides. A clean tree is `No known
494/// vulnerabilities found`; a finding is `N vulnerabilities found` followed by
495/// `Severity: a low | b moderate | …`, which is carried along so the warning
496/// says how bad. No recognisable summary plus a refusal to exit clean is a
497/// tool that never answered (`ERR_PNPM_AUDIT_BAD_RESPONSE`, no network).
498fn read_pnpm_audit(exit_ok: bool, out: &str) -> Report {
499    let lines: Vec<&str> = out.lines().map(str::trim).collect();
500    if lines
501        .iter()
502        .any(|l| l.starts_with("No known vulnerabilities found"))
503    {
504        return Report::Clean;
505    }
506    let found = lines.iter().enumerate().rev().find(|(_, l)| {
507        let mut w = l.split_whitespace();
508        w.next()
509            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
510            && w.next().is_some_and(|v| v.starts_with("vulnerabilit"))
511            && w.next() == Some("found")
512    });
513    match found {
514        Some((_, l)) if l.starts_with("0 ") => Report::Clean,
515        Some((i, l)) => {
516            let severity = lines
517                .get(i + 1)
518                .and_then(|n| n.strip_prefix("Severity:"))
519                .map(str::trim);
520            Report::Vulnerabilities(vec![match severity {
521                Some(sev) => format!("{l} ({sev})"),
522                None => l.to_string(),
523            }])
524        }
525        None if exit_ok => Report::Clean,
526        None => Report::CouldNotCheck,
527    }
528}
529
530/// `govulncheck`: the GO- ids decide, the exit code classifies them — the
531/// same split cargo-audit taught. The tool exits non-zero only when the
532/// analysed CODE is affected; ids with a clean exit are the informational
533/// section (vulnerable modules whose functions are never called), which is
534/// advisory-grade. No ids plus a refusal to exit clean is a tool that never
535/// answered (no network, no vulnerability database).
536fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
537    let mut ids: Vec<String> = out
538        .split_whitespace()
539        .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
540        .filter(|w| {
541            w.len() >= 12
542                && w.starts_with("GO-")
543                && w[3..7].bytes().all(|b| b.is_ascii_digit())
544                && w.as_bytes()[7] == b'-'
545                && w[8..].bytes().all(|b| b.is_ascii_digit())
546        })
547        .map(|w| w.to_string())
548        .collect();
549    ids.sort();
550    ids.dedup();
551    match (ids.is_empty(), exit_ok) {
552        (true, true) => Report::Clean,
553        (true, false) => Report::CouldNotCheck,
554        (false, true) => Report::Advisories(ids),
555        (false, false) => Report::Vulnerabilities(ids),
556    }
557}
558
559/// `pip-audit`: its own closing sentence decides.
560fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
561    if out.contains("No known vulnerabilities found") {
562        return Report::Clean;
563    }
564    if let Some(line) = out
565        .lines()
566        .map(str::trim)
567        .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
568    {
569        return Report::Vulnerabilities(vec![line.to_string()]);
570    }
571    if exit_ok {
572        Report::Clean
573    } else {
574        Report::CouldNotCheck
575    }
576}
577
578/// The `site-packages` of the environment this project actually uses, if
579/// one is on disk.
580///
581/// `$VIRTUAL_ENV` first — an activated environment is the one whose imports
582/// are live — then the `.venv` uv and PEP 668 tooling create by convention.
583/// Layout differs by platform: `lib/python3.13/site-packages` everywhere
584/// except Windows, which uses `Lib/site-packages`, so the python-version
585/// directory is discovered rather than guessed.
586fn venv_site_packages(root: &str, source: Option<&std::path::Path>) -> Option<String> {
587    // A rehearsal snapshot installs no virtualenv; the working tree it was
588    // taken from (`source`) holds one, but it answers for THIS commit only
589    // when that tree is this commit with its Python manifests unmodified: a
590    // `.venv` synced to a newer HEAD would vouch for a tag it never held
591    // (ADR-0018).
592    let source_venv = source
593        .filter(|src| {
594            let answers = source_is_this_commit(src);
595            if !answers {
596                common::warn(
597                    "audit-python: the source worktree's virtualenv is not this commit's \
598                     (another HEAD, or modified Python manifests) — not auditing it",
599                );
600            }
601            answers
602        })
603        .map(|src| src.join(".venv"));
604    let candidates = std::env::var_os("VIRTUAL_ENV")
605        .map(std::path::PathBuf::from)
606        .into_iter()
607        .chain(std::iter::once(std::path::Path::new(root).join(".venv")))
608        .chain(source_venv);
609    for venv in candidates {
610        let windows = venv.join("Lib").join("site-packages");
611        if windows.is_dir() {
612            return Some(windows.to_string_lossy().into_owned());
613        }
614        let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
615            continue;
616        };
617        for e in entries.flatten() {
618            if !e.file_name().to_string_lossy().starts_with("python") {
619                continue;
620            }
621            let sp = e.path().join("site-packages");
622            if sp.is_dir() {
623                return Some(sp.to_string_lossy().into_owned());
624            }
625        }
626    }
627    None
628}
629
630/// Run one audit tool from the repo root and read its answer.
631fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
632    audited_in(settings, argv, std::path::Path::new(&common::repo_root()))
633}
634
635/// Run one audit tool from `dir` and read its answer.
636fn audited_in(
637    settings: &crate::config::Settings,
638    argv: &[String],
639    dir: &std::path::Path,
640) -> Option<(bool, String)> {
641    let mut cmd = std::process::Command::new(&argv[0]);
642    cmd.args(&argv[1..])
643        .current_dir(dir)
644        .stdin(std::process::Stdio::null());
645    common::strip_git_env(&mut cmd);
646    let (ran, out) = common::capture_within(settings, &mut cmd)?;
647    match ran {
648        common::Ran::Status(s) => Some((s.success(), out)),
649        common::Ran::TimedOut(budget) => {
650            common::say_timed_out(&argv[0], budget);
651            None
652        }
653    }
654}
655
656/// The tool's own reason for not answering: its last line that says
657/// `error`, else its last non-empty line, clipped. "Could not complete" with
658/// nothing after it was the whole message once, over a tree with 19 known
659/// vulnerabilities (amont#305) — the next one must be readable from the hook
660/// output alone.
661fn failure_line(out: &str) -> Option<String> {
662    let lines: Vec<&str> = out
663        .lines()
664        .map(str::trim)
665        .filter(|l| !l.is_empty())
666        .collect();
667    let line = lines
668        .iter()
669        .rev()
670        .find(|l| l.to_ascii_lowercase().contains("error"))
671        .or(lines.last())?;
672    let mut s: String = line.chars().take(200).collect();
673    if line.chars().count() > 200 {
674        s.push('…');
675    }
676    Some(s)
677}
678
679/// What one audit found across every directory it ran in.
680struct Merged {
681    report: Report,
682    /// The tools' reports, each under a header naming its directory (the
683    /// bare report when the only directory is the root).
684    full: String,
685    waivable: bool,
686    /// Every directory answered in full.
687    complete: bool,
688}
689
690/// Run one audit in every directory holding `lockfile` and merge the
691/// answers — the shape `js()` has had since a root-only run left a nested
692/// npm project unaudited. Rust, Go and Python kept the root-only runner, and
693/// a repository whose `Cargo.lock` lived in `apps/ui/src-tauri` was reported
694/// "could not complete" over 19 known vulnerabilities (amont#305).
695///
696/// `argv_in(dir)` builds the command for one directory, or None to skip it
697/// (said by the caller). `refine(dir, report, out)` runs in that directory
698/// after the read — a release's shipped-only split, attribution. A finding
699/// from a subdirectory is labelled with it; the root's are not, so a
700/// repository with its lockfile at the root reads exactly as before. A
701/// directory the tool could not answer for is named with the tool's own
702/// reason, and keeps the merged result from reading clean or being waived.
703fn audit_each_dir(
704    settings: &crate::config::Settings,
705    tool: &str,
706    lockfile: &str,
707    argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
708    read: fn(bool, &str) -> Report,
709    refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
710) -> Merged {
711    let answer_in = |path: &std::path::Path| match argv_in(path) {
712        None => DirAnswer::Nothing,
713        Some(argv) => answer_of(settings, &argv, path, read),
714    };
715    audit_each_dir_answered(tool, lockfile, answer_in, refine)
716}
717
718/// One tool run in `dir`, read by `read`.
719fn answer_of(
720    settings: &crate::config::Settings,
721    argv: &[String],
722    dir: &std::path::Path,
723    read: fn(bool, &str) -> Report,
724) -> DirAnswer {
725    match audited_in(settings, argv, dir) {
726        None => DirAnswer::TimedOut,
727        Some((exit_ok, out)) => DirAnswer::Read {
728            report: read(exit_ok, &out),
729            full: out.clone(),
730            out,
731            gap: None,
732        },
733    }
734}
735
736/// What one directory's audit answered.
737enum DirAnswer {
738    /// Nothing to audit there.
739    Nothing,
740    /// The tool ran out of time, said by `audited_in`: not an answer, and
741    /// the directory is named NOT checked.
742    TimedOut,
743    /// The tool's report. `out` is everything the tool printed, which
744    /// `refine` reads; `full` is the part kept as the report when it has
745    /// findings. `gap` names what went unchecked when only part of the
746    /// directory was audited: its findings still count, and the merged
747    /// result is then never clean nor waivable.
748    Read {
749        report: Report,
750        out: String,
751        full: String,
752        gap: Option<String>,
753    },
754}
755
756/// [`audit_each_dir`] with each directory's answer given by `answer_in`,
757/// for an audit that takes more than one tool run in a directory.
758fn audit_each_dir_answered(
759    tool: &str,
760    lockfile: &str,
761    mut answer_in: impl FnMut(&std::path::Path) -> DirAnswer,
762    mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
763) -> Merged {
764    let root = std::path::PathBuf::from(common::repo_root());
765    let dirs = lockfile_dirs(lockfile);
766    let only_root = dirs.len() == 1 && dirs[0].is_empty();
767    let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
768    let mut partial = Vec::new();
769    let mut full = String::new();
770    for dir in &dirs {
771        let path = root.join(dir);
772        let label = if dir.is_empty() { "." } else { dir.as_str() };
773        let label_ids = |ids: Vec<String>| -> Vec<String> {
774            if dir.is_empty() {
775                ids
776            } else {
777                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
778            }
779        };
780        let (report, out, dir_full, gap) = match answer_in(&path) {
781            DirAnswer::Nothing => {
782                unchecked.push(format!("{label} (nothing to audit there)"));
783                continue;
784            }
785            // A timeout is said by `audited_in` itself. The other
786            // directories still answer: their findings must not be lost.
787            DirAnswer::TimedOut => {
788                unchecked.push(format!("{label} (timed out)"));
789                continue;
790            }
791            DirAnswer::Read {
792                report,
793                out,
794                full,
795                gap,
796            } => (report, out, full, gap),
797        };
798        let report = refine(&path, report, &out);
799        if gap.is_some() && !matches!(report, Report::CouldNotCheck) {
800            partial.push(label.to_string());
801        }
802        match report {
803            Report::Vulnerabilities(ids) => {
804                vulns.extend(label_ids(ids));
805                if only_root {
806                    full.push_str(&dir_full);
807                } else {
808                    full.push_str(&format!("── {tool} in {label}\n{dir_full}\n"));
809                }
810            }
811            Report::Advisories(ids) => advisories.extend(label_ids(ids)),
812            Report::CouldNotCheck => unchecked.push(match gap.or_else(|| failure_line(&out)) {
813                Some(why) => format!("{label} ({why})"),
814                None => label.to_string(),
815            }),
816            Report::Clean => {}
817        }
818    }
819    if !unchecked.is_empty() {
820        common::warn(&format!(
821            "{tool}: the audit could not answer in {} — NOT checked there",
822            unchecked.join(", ")
823        ));
824    }
825    // Its own lines said why; this one says the directory is not clean.
826    if !partial.is_empty() {
827        common::warn(&format!(
828            "{tool}: NOT fully checked in {} (part of the audit did not answer)",
829            partial.join(", ")
830        ));
831    }
832    let report = if !vulns.is_empty() {
833        Report::Vulnerabilities(vulns)
834    } else if !unchecked.is_empty() || !partial.is_empty() {
835        Report::CouldNotCheck
836    } else if !advisories.is_empty() {
837        Report::Advisories(advisories)
838    } else {
839        Report::Clean
840    };
841    Merged {
842        report,
843        full,
844        waivable: unchecked.is_empty() && partial.is_empty(),
845        complete: unchecked.is_empty() && partial.is_empty(),
846    }
847}
848
849fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
850    let (settings, refs) = (ctx.settings, ctx.push.get());
851    if !has_lockfile("Cargo.lock") {
852        return Ran::Inert;
853    }
854    if common::which("cargo-audit").is_none() {
855        common::warn(
856            "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
857             the audit did NOT run",
858        );
859        return Ran::Unavailable;
860    }
861    let argv = vec![
862        common::program("cargo"),
863        "audit".into(),
864        "--color".into(),
865        "never".into(),
866    ];
867    let release = releasing(refs);
868    let merged = audit_each_dir(
869        settings,
870        "audit-rust",
871        "Cargo.lock",
872        |_| Some(argv.clone()),
873        read_cargo_audit,
874        |dir, mut report, out| {
875            if release {
876                if let Report::Vulnerabilities(ids) = report {
877                    let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
878                        cargo_tree_shipped(settings, dir, krate)
879                    });
880                    warn_dev_only("audit-rust", &dev_only);
881                    report = if shipped.is_empty() {
882                        Report::Clean
883                    } else {
884                        Report::Vulnerabilities(shipped)
885                    };
886                }
887            }
888            attribute(report, out, |krate| {
889                cargo_tree_inverse(settings, dir, krate)
890            })
891        },
892    );
893    Ran::Concluded(Concluded {
894        tool: "audit-rust".to_string(),
895        report: merged.report,
896        full: merged.full,
897        waivable: merged.waivable,
898        complete: merged.complete,
899    })
900}
901
902/// `cargo tree -i <crate>` over the edges a RELEASE ships: normal and build
903/// dependencies (a dependency's build script runs on every machine that
904/// compiles it), for every target and every feature, so nothing a consumer
905/// could switch on is mistaken for dev-only. None if it could not run.
906fn cargo_tree_shipped(
907    settings: &crate::config::Settings,
908    dir: &std::path::Path,
909    spec: &str,
910) -> Option<String> {
911    let argv = vec![
912        common::program("cargo"),
913        "tree".into(),
914        "--invert".into(),
915        spec.into(),
916        "--edges".into(),
917        "normal,build".into(),
918        "--target".into(),
919        "all".into(),
920        "--all-features".into(),
921        "--color".into(),
922        "never".into(),
923    ];
924    // Unlike the message-only inverse tree, a failure here must not read as
925    // "nothing reaches it": an error prints no local crate either.
926    audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
927}
928
929/// Does a shipped-edges inverse tree say the crate is dev-only? Only on
930/// positive evidence: no local crate reaches it AND cargo said there is
931/// nothing to print. Anything else — an unreadable tree — ships.
932fn tree_says_dev_only(tree: &str) -> bool {
933    local_dependents(tree).is_empty() && tree.contains("nothing to print")
934}
935
936/// Split a release's advisory ids into those that ship and those only the
937/// dev tree carries. An id whose crate is unknown, or whose tree could not
938/// be read, ships: an unknown is not a pass.
939fn split_shipped_crates(
940    ids: Vec<String>,
941    out: &str,
942    shipped_tree: impl Fn(&str) -> Option<String>,
943) -> (Vec<String>, Vec<String>) {
944    let specs = ids_with_specs(out);
945    let mut verdicts: Vec<(String, bool)> = Vec::new();
946    let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
947    for id in ids {
948        let spec = specs
949            .iter()
950            .find(|(pid, spec)| *pid == id && spec.is_some())
951            .and_then(|(_, spec)| spec.clone());
952        let ships = match spec {
953            None => true,
954            // Cached by name@version: two locked versions of one crate are
955            // two answers, and one being dev-only says nothing of the other.
956            Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
957                Some((_, v)) => *v,
958                None => {
959                    let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
960                    verdicts.push((spec, v));
961                    v
962                }
963            },
964        };
965        if ships {
966            shipped.push(id);
967        } else {
968            dev_only.push(id);
969        }
970    }
971    (shipped, dev_only)
972}
973
974/// Each advisory id with the package its OWN block names: `crate@version`
975/// when cargo audit printed a `Version:` in that block, the bare crate name
976/// otherwise, None for an id outside any block.
977fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
978    let mut pairs = Vec::new();
979    let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
980    for line in out.lines().map(str::trim) {
981        if let Some(rest) = line.strip_prefix("Crate:") {
982            krate = rest.split_whitespace().next().map(str::to_string);
983            version = None;
984        } else if let Some(rest) = line.strip_prefix("Version:") {
985            version = rest.split_whitespace().next().map(str::to_string);
986        } else if let Some(rest) = line.strip_prefix("ID:") {
987            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
988                let spec = krate.take().map(|k| match version.take() {
989                    Some(v) => format!("{k}@{v}"),
990                    None => k,
991                });
992                pairs.push((id.to_string(), spec));
993            }
994        }
995    }
996    pairs
997}
998
999/// Name what a release does not ship and therefore does not refuse.
1000fn warn_dev_only(tool: &str, dev_only: &[String]) {
1001    if !dev_only.is_empty() {
1002        common::warn(&format!(
1003            "{tool}: dev-only, only in development dependencies, which the release does not ship — not blocking: {}",
1004            dev_only.join("; ")
1005        ));
1006    }
1007}
1008
1009/// `cargo tree -i <crate>`, or None if it could not be run. Failure here is
1010/// never fatal: attribution is an improvement to a message, and an advisory
1011/// reported without it is still an advisory reported.
1012fn cargo_tree_inverse(
1013    settings: &crate::config::Settings,
1014    dir: &std::path::Path,
1015    krate: &str,
1016) -> Option<String> {
1017    let argv = vec![
1018        common::program("cargo"),
1019        "tree".into(),
1020        "--invert".into(),
1021        krate.into(),
1022        "--edges".into(),
1023        "normal".into(),
1024        "--color".into(),
1025        "never".into(),
1026    ];
1027    audited_in(settings, &argv, dir).map(|(_, out)| out)
1028}
1029
1030/// Name the crate behind each advisory, and which of this workspace's crates
1031/// reach it.
1032///
1033/// Deliberately spawns NOTHING on a clean report, which is every run that
1034/// matters: the `cargo tree` calls happen once per distinct affected crate,
1035/// only when there is already something to say. A hook on the push path does
1036/// not pay for a message nobody will read.
1037fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
1038    match report {
1039        Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
1040        Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
1041        // Clean and CouldNotCheck carry no ids, so there is nothing to
1042        // attribute and — the part that matters — nothing to spawn.
1043        other => other,
1044    }
1045}
1046
1047/// Each id, rewritten with its crate and what reaches it where both are
1048/// known. One `cargo tree` per distinct crate, not per advisory: `lru`
1049/// carried two advisories in the run that prompted this.
1050fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
1051    let pairs = ids_with_crates(out);
1052    let mut seen: Vec<(String, Vec<String>)> = Vec::new();
1053    ids.iter()
1054        .map(|id| {
1055            let krate = pairs
1056                .iter()
1057                .find(|(pid, k)| pid == id && k.is_some())
1058                .and_then(|(_, k)| k.clone());
1059            let Some(k) = krate else {
1060                return id.clone();
1061            };
1062            if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
1063                return describe(id, Some(&k), reaches);
1064            }
1065            let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
1066            seen.push((k.clone(), reaches.clone()));
1067            describe(id, Some(&k), &reaches)
1068        })
1069        .collect()
1070}
1071
1072/// Does the repository carry `lockfile` anywhere in its index? An audit
1073/// without a resolved tree audits a guess — and one asked about a
1074/// repository in another language has nothing to audit at all. That is
1075/// `Inert`, not "could not run": the dispatcher asks the same question
1076/// from the registry's scope, and this is the answer for a check invoked
1077/// by name.
1078fn has_lockfile(lockfile: &str) -> bool {
1079    crate::tracked_paths()
1080        .iter()
1081        .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1082}
1083
1084/// The directories holding a tracked `lockfile`, repo-relative ("" for the
1085/// root), sorted. npm resolves a project from its own directory, so a
1086/// repository whose packages live in subdirectories (`web/`, `mcp/`) has no
1087/// lockfile at the root at all.
1088fn lockfile_dirs(lockfile: &str) -> Vec<String> {
1089    let mut dirs: Vec<String> = crate::tracked_paths()
1090        .iter()
1091        .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1092        .map(|p| {
1093            p.rsplit_once('/')
1094                .map(|(d, _)| d.to_string())
1095                .unwrap_or_default()
1096        })
1097        .collect();
1098    dirs.sort();
1099    dirs.dedup();
1100    dirs
1101}
1102
1103/// One JS package manager `audit-js` knows how to ask: the lockfile that
1104/// opts a directory in, the tool that reads it, and how to read its answer.
1105struct JsAuditor {
1106    lockfile: &'static str,
1107    tool: &'static str,
1108    read: fn(bool, &str) -> Report,
1109    /// Extra arguments for a project in `dir`.
1110    args: fn(&str) -> Vec<String>,
1111    /// The flag that limits the audit to what the project ships — its
1112    /// production dependencies, without the dev tree.
1113    prod_only: &'static str,
1114}
1115
1116/// pnpm answers for the WORKSPACE it finds above a directory, not for the
1117/// directory: a standalone project with its own pnpm-lock.yaml inside a
1118/// workspace (a spike, an example) was reported with the workspace root's
1119/// findings, all of them, under its own name. `--ignore-workspace` makes it
1120/// read the lockfile it stands next to — except at a workspace's own root,
1121/// where the workspace IS the project and every member must be audited.
1122fn pnpm_args(dir: &str) -> Vec<String> {
1123    let manifest = if dir.is_empty() {
1124        "pnpm-workspace.yaml".to_string()
1125    } else {
1126        format!("{dir}/pnpm-workspace.yaml")
1127    };
1128    if crate::tracked_paths().contains(&manifest) {
1129        vec![]
1130    } else {
1131        vec!["--ignore-workspace".into()]
1132    }
1133}
1134
1135const JS_AUDITORS: [JsAuditor; 2] = [
1136    JsAuditor {
1137        lockfile: "package-lock.json",
1138        tool: "npm",
1139        read: read_npm_audit,
1140        args: |_| vec![],
1141        prod_only: "--omit=dev",
1142    },
1143    JsAuditor {
1144        lockfile: "pnpm-lock.yaml",
1145        tool: "pnpm",
1146        read: read_pnpm_audit,
1147        args: pnpm_args,
1148        prod_only: "--prod",
1149    },
1150];
1151
1152/// `npm audit` in every directory that tracks a `package-lock.json`, and
1153/// `pnpm audit` in every directory that tracks a `pnpm-lock.yaml`.
1154///
1155/// It used to run once at the repository root, where a repository whose
1156/// packages live in subdirectories has no lockfile: npm answered ENOLOCK,
1157/// the check said "could not complete", and a tree with 17 known
1158/// vulnerabilities (9 high) went unaudited release after release. Each
1159/// project is audited on its own; any finding counts, labelled with its
1160/// directory, and a project the tool could not answer for keeps the whole
1161/// result from reading clean.
1162///
1163/// And it only ever knew npm: a pnpm workspace has no `package-lock.json`,
1164/// so its whole tree — 28 vulnerable versions, two critical, in one
1165/// repository — was never audited and nothing said so. pnpm audits its own
1166/// lockfile, from the lockfile alone, the same way.
1167///
1168/// What blocks a release is what SHIPS: a finding is audited again with
1169/// the production dependencies only (`--omit=dev` / `--prod`), and one that
1170/// lives only in the dev tree — a build script's toolchain, a test runner —
1171/// is named but does not refuse the tag. Nobody who installs the package
1172/// installs it. A finding whose production re-audit cannot answer still
1173/// blocks: an unknown is not a pass, and that result is not recorded.
1174///
1175/// A branch push splits the same way (f189): it judges what a `v*` tag
1176/// would judge, so a branch run can check a waiver file. Before, it matched
1177/// waivers against the whole tree and warned "will BLOCK" over dev-only ids
1178/// a tag would never refuse.
1179fn js_run(ctx: &crate::registry::Ctx) -> Ran {
1180    let settings = ctx.settings;
1181    let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
1182        .iter()
1183        .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
1184        .collect();
1185    if projects.is_empty() {
1186        return Ran::Inert;
1187    }
1188    let root = std::path::PathBuf::from(common::repo_root());
1189    let mut found = Vec::new();
1190    let mut dev_only = Vec::new();
1191    let mut unchecked = Vec::new();
1192    let mut unsplit = false;
1193    let mut full = String::new();
1194    for (auditor, dir) in &projects {
1195        let label = if dir.is_empty() {
1196            ".".to_string()
1197        } else {
1198            dir.clone()
1199        };
1200        let mut argv = vec![common::program(auditor.tool), "audit".into()];
1201        argv.extend((auditor.args)(dir));
1202        let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
1203            common::warn(&format!(
1204                "audit-js: {} could not run in {label} — the audit did NOT run",
1205                auditor.tool
1206            ));
1207            return Ran::Unavailable;
1208        };
1209        match (auditor.read)(exit_ok, &out) {
1210            Report::Vulnerabilities(what) => {
1211                let mut prod = argv.clone();
1212                prod.push(auditor.prod_only.into());
1213                match audited_in(settings, &prod, &root.join(dir))
1214                    .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
1215                {
1216                    Some((Report::Clean | Report::Advisories(_), _)) => {
1217                        dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1218                    }
1219                    Some((Report::Vulnerabilities(shipped), pout)) => {
1220                        // The ids the whole tree names and the production
1221                        // tree does not: dev-only, named beside the verdict.
1222                        // Only when the production report names ids at all:
1223                        // text with none (npm's summary) says nothing about
1224                        // which whole-tree ids are the dev-only ones.
1225                        let prod_ids = advisory_ids(&pout);
1226                        let dev: Vec<String> = if prod_ids.is_empty() {
1227                            Vec::new()
1228                        } else {
1229                            advisory_ids(&out)
1230                                .into_iter()
1231                                .filter(|id| !prod_ids.contains(id))
1232                                .collect()
1233                        };
1234                        if !dev.is_empty() {
1235                            dev_only.push(format!("{label}: {}", dev.join(", ")));
1236                        }
1237                        found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
1238                        full.push_str(&format!(
1239                            "── {} audit {} in {label}\n{pout}\n",
1240                            auditor.tool, auditor.prod_only
1241                        ));
1242                    }
1243                    Some((Report::CouldNotCheck, _)) | None => {
1244                        common::warn(&format!(
1245                            "audit-js: could not audit production dependencies in {label}; \
1246                             judged the whole tree"
1247                        ));
1248                        unsplit = true;
1249                        found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1250                        full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1251                    }
1252                }
1253            }
1254            Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
1255            Report::Clean | Report::Advisories(_) => {}
1256        }
1257    }
1258    if !unchecked.is_empty() {
1259        common::warn(&format!(
1260            "audit-js: the audit could not answer in {} — those projects were NOT checked",
1261            unchecked.join(", ")
1262        ));
1263    }
1264    warn_dev_only("audit-js", &dev_only);
1265    let waivable = unchecked.is_empty();
1266    let report = if !found.is_empty() {
1267        Report::Vulnerabilities(found)
1268    } else if !unchecked.is_empty() {
1269        Report::CouldNotCheck
1270    } else {
1271        Report::Clean
1272    };
1273    Ran::Concluded(Concluded {
1274        tool: "audit-js".to_string(),
1275        report,
1276        full,
1277        waivable,
1278        // A split that could not answer is a gap: recorded, it would replay
1279        // a whole-tree verdict for a day instead of asking again.
1280        complete: !unsplit,
1281    })
1282}
1283
1284/// Go needs no production filter: modules have no dev-dependency set, and
1285/// `govulncheck ./...` without `-test` reports only vulnerabilities the
1286/// module's non-test code can reach — what ships, already.
1287///
1288/// A tools module (a `go.mod` with a `tool` directive and no package) has
1289/// nothing `./...` matches, and govulncheck answers "no packages matched";
1290/// its tools are audited through the `tool` pattern instead.
1291fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1292    let settings = ctx.settings;
1293    if !has_lockfile("go.sum") {
1294        return Ran::Inert;
1295    }
1296    if common::which("govulncheck").is_none() {
1297        common::warn(
1298            "audit-go: govulncheck is not installed \
1299             (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1300        );
1301        return Ran::Unavailable;
1302    }
1303    // Which directories are tools modules, worked out once, in `argv_in`,
1304    // and read back in `refine`.
1305    let tool_dirs = std::cell::RefCell::new(std::collections::HashSet::new());
1306    let argv_in = |dir: &std::path::Path| {
1307        let tools_only =
1308            !super::go_tools::has_go_package(dir) && super::go_tools::declares_tool(dir);
1309        if tools_only {
1310            tool_dirs.borrow_mut().insert(dir.to_path_buf());
1311        }
1312        let pattern = if tools_only { "tool" } else { "./..." };
1313        Some(vec![common::program("govulncheck"), pattern.into()])
1314    };
1315    // Tools do not ship: their findings warn and never block, on a branch or
1316    // a `v*` tag (ADR-0055, dev-only findings warn).
1317    let root = std::path::PathBuf::from(common::repo_root());
1318    let mut in_tools = Vec::new();
1319    let refine = |dir: &std::path::Path, report: Report, _: &str| match report {
1320        Report::Vulnerabilities(ids) if tool_dirs.borrow().contains(dir) => {
1321            let label = dir
1322                .strip_prefix(&root)
1323                .ok()
1324                .map(|d| d.display().to_string())
1325                .filter(|d| !d.is_empty())
1326                .unwrap_or_else(|| ".".into());
1327            in_tools.push(format!("{label} (govulncheck tool): {}", ids.join(", ")));
1328            Report::Clean
1329        }
1330        other => other,
1331    };
1332    let merged = audit_each_dir(
1333        settings,
1334        "audit-go",
1335        "go.sum",
1336        argv_in,
1337        read_govulncheck,
1338        refine,
1339    );
1340    if !in_tools.is_empty() {
1341        common::warn(&format!(
1342            "audit-go: in a tools module, whose tools the release does not ship — not blocking: {}",
1343            in_tools.join("; ")
1344        ));
1345    }
1346    Ran::Concluded(Concluded {
1347        tool: "audit-go".to_string(),
1348        report: merged.report,
1349        full: merged.full,
1350        waivable: merged.waivable,
1351        complete: merged.complete,
1352    })
1353}
1354
1355fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1356    let (settings, refs) = (ctx.settings, ctx.push.get());
1357    if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1358        return Ran::Inert;
1359    }
1360    if common::which("pip-audit").is_none() {
1361        common::warn(
1362            "audit-python: pip-audit is not installed (pip install pip-audit) — \
1363             the audit did NOT run",
1364        );
1365        return Ran::Unavailable;
1366    }
1367    let root = common::repo_root();
1368    // A requirements.txt is the production list by convention, audited in
1369    // its own directory — wherever the repository keeps one (amont#305).
1370    if !lockfile_dirs("requirements.txt").is_empty() {
1371        let root_path = std::path::PathBuf::from(&root);
1372        let rel_of = |dir: &std::path::Path| {
1373            dir.strip_prefix(&root_path)
1374                .map(|p| p.to_string_lossy().into_owned())
1375                .unwrap_or_default()
1376        };
1377        // The environment and pip's config files, read once for every
1378        // directory (decisions f142).
1379        // A value that is not UTF-8 is read lossily, never as "unset".
1380        let host = host_sources(
1381            &|var| std::env::var_os(var).map(|value| value.to_string_lossy().into_owned()),
1382            &read_config,
1383        );
1384        // One time budget for the whole run, shared by every directory.
1385        let budget = Budget::new(settings);
1386        let answer_in = |dir: &std::path::Path| {
1387            requirements_answer(settings, dir, &rel_of(dir), &host, &budget)
1388        };
1389        let merged = audit_each_dir_answered(
1390            "audit-python",
1391            "requirements.txt",
1392            answer_in,
1393            |_, report, _| report,
1394        );
1395        // A row whose advisory id is not one a waiver can name makes the
1396        // whole report unwaivable.
1397        let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1398        return Ran::Concluded(Concluded {
1399            tool: "audit-python".to_string(),
1400            report: merged.report,
1401            full: merged.full,
1402            waivable,
1403            complete: merged.complete,
1404        });
1405    }
1406    let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1407        // A uv/PEP-621 project has no requirements.txt, and EXPORTING one
1408        // does not work either: `uv export` emits the workspace's own
1409        // members and any private-index dependency, and pip-audit resolves
1410        // a requirements file in a throwaway venv that can reach neither —
1411        // it dies on "No matching distribution found". Auditing the
1412        // INSTALLED tree resolves nothing, and is the truer question
1413        // anyway: these are the versions actually imported.
1414        vec![
1415            common::program("pip-audit"),
1416            "--path".into(),
1417            site_packages,
1418            // Workspace members are installed editable and are not on
1419            // PyPI; without this each one is a line of noise.
1420            "--skip-editable".into(),
1421        ]
1422    } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1423        // No virtualenv: the lock says what would be installed.
1424        return python_lock_run(ctx);
1425    } else {
1426        common::warn(
1427            "audit-python: the audit did NOT run — found no requirements.txt,\n  \
1428             no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n  \
1429             Next: `uv sync`, or install uv so uv.lock can be audited.",
1430        );
1431        return Ran::Unavailable;
1432    };
1433    let Some((exit_ok, out)) = audited(settings, &argv) else {
1434        return Ran::Unavailable;
1435    };
1436    // A requirements.txt is the production list by convention (dev pins
1437    // live beside it, in requirements-dev.txt). A virtualenv or a lock holds
1438    // the dev groups too, so on a release its findings are checked against
1439    // what `uv export --no-dev` says ships — asked only when there are any.
1440    let report = read_pip_audit(exit_ok, &out);
1441    let production = if releasing(refs) && has_rows_to_split(&report, &out) {
1442        uv_production_names(settings, std::path::Path::new(&root))
1443    } else {
1444        None
1445    };
1446    let (report, waivable) = shipped_only(report, &out, production.as_ref());
1447    Ran::Concluded(Concluded {
1448        tool: "audit-python".to_string(),
1449        report,
1450        full: out,
1451        waivable,
1452        complete: true,
1453    })
1454}
1455
1456/// What one directory's requirements route sent pip-audit, beside its answer.
1457struct SentAnswer {
1458    answer: DirAnswer,
1459    /// Distinct names sent when the input is a closed set (hashed); None
1460    /// for a resolve, whose names are not known here.
1461    sent_names: Option<usize>,
1462    /// Names held back as another index's: said with pip-audit's skips.
1463    private: std::collections::BTreeSet<String>,
1464    /// Names held back unproven: the directory is not fully checked.
1465    unproven: bool,
1466}
1467
1468/// One directory's requirements.txt audited, sending pip-audit only the
1469/// names the route can show public (decisions f142, ADR-0055): with no
1470/// non-PyPI source and no pin from another index, the run is today's.
1471fn requirements_answer(
1472    settings: &crate::config::Settings,
1473    dir: &std::path::Path,
1474    rel: &str,
1475    host: &[IndexSource],
1476    budget: &Budget,
1477) -> DirAnswer {
1478    let prefix = requirements_prefix(rel);
1479    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1480    let held_back = |why: &str| DirAnswer::Read {
1481        report: Report::CouldNotCheck,
1482        out: String::new(),
1483        full: String::new(),
1484        gap: Some(why.to_string()),
1485    };
1486    // One budget for every directory: a directory reached after it is spent
1487    // is named NOT checked, never started.
1488    if budget.spent() {
1489        say(&format!(
1490            "out of time before this directory was reached — NOT checked\n  {TIMEOUT_NEXT}"
1491        ));
1492        return held_back("out of time");
1493    }
1494    let path = dir.join("requirements.txt");
1495    let text = std::fs::read_to_string(&path).ok();
1496    let mut sources = match text.as_deref() {
1497        Some(text) => file_sources(text, "requirements.txt", dir, &read_include),
1498        // There but unreadable here (not UTF-8, say): pip may still read
1499        // it, and nothing in it can be shown public.
1500        None if path.exists() => vec![IndexSource::unread_include("requirements.txt")],
1501        None => Vec::new(),
1502    };
1503    sources.extend(host.iter().cloned());
1504    let argv_of = |closed: &[&str]| -> Vec<String> {
1505        let mut argv = vec![
1506            common::program("pip-audit"),
1507            "-r".into(),
1508            "requirements.txt".into(),
1509        ];
1510        argv.extend(closed.iter().map(|flag| flag.to_string()));
1511        argv
1512    };
1513    let resolve_file = || answer_of(settings, &argv_of(&[]), dir, read_pip_audit);
1514    // A fully hashed file is a closed set: nothing to resolve, and
1515    // resolving it on this host can fail on a pin with no wheel here
1516    // (torch 2.14.0+cpu on Intel macOS, decisions f108).
1517    let audit_closed_file = || {
1518        answer_of(
1519            settings,
1520            &argv_of(&["--no-deps", "--disable-pip"]),
1521            dir,
1522            read_pip_audit,
1523        )
1524    };
1525    let sent = match text.as_deref().and_then(hashed_pins_in) {
1526        // A resolve sends every dependency's name, which no line here shows.
1527        None if !sources.is_empty() => {
1528            say(&format!(
1529                "not sent: {} is not PyPI, and a resolve sends every dependency — did NOT run\n  {ANNOTATE_NEXT}",
1530                sources_phrase(&sources)
1531            ));
1532            return held_back("names not shown public");
1533        }
1534        None => SentAnswer {
1535            answer: resolve_file(),
1536            sent_names: None,
1537            private: std::collections::BTreeSet::new(),
1538            unproven: false,
1539        },
1540        Some(pins) => {
1541            let held = provenance(&pins, &sources);
1542            if sources.is_empty() && held.private.is_empty() {
1543                let names = pins.names();
1544                let answer = if pins.marked {
1545                    audit_hashed_pins(settings, dir, rel, pins.pairs, 0, budget)
1546                } else {
1547                    audit_closed_file()
1548                };
1549                SentAnswer {
1550                    answer,
1551                    sent_names: Some(names),
1552                    private: held.private,
1553                    unproven: false,
1554                }
1555            } else {
1556                if !held.unproven.is_empty() {
1557                    say(&format!(
1558                        "{} not sent {}: no index shown for them, and {} is not PyPI — NOT fully checked\n  {ANNOTATE_NEXT}",
1559                        plural(held.unproven.len(), "package"),
1560                        names_phrase(&held.unproven),
1561                        sources_phrase(&sources)
1562                    ));
1563                }
1564                if held.sent.is_empty() {
1565                    if !held.private.is_empty() {
1566                        let names: Vec<String> =
1567                            held.private.iter().map(|n| printable(n)).collect();
1568                        let names: Vec<&str> = names.iter().map(String::as_str).collect();
1569                        common::warn(&skipped_line(&prefix, &names));
1570                    }
1571                    if held.unproven.is_empty() {
1572                        say(
1573                            "no PyPI package to audit — the audit did NOT run\n  \
1574                             Next: none if every package is private; else check its `# from` lines",
1575                        );
1576                    } else {
1577                        say("no PyPI package to audit — the audit did NOT run");
1578                    }
1579                    return held_back("no PyPI package to audit");
1580                }
1581                let sent: std::collections::BTreeSet<&str> =
1582                    held.sent.iter().map(|(name, _)| name.as_str()).collect();
1583                let sent_names = sent.len();
1584                let held_count = held.private.len() + held.unproven.len();
1585                // The kept pins only, written to a private directory: the
1586                // file itself, its index lines and held names, never reach
1587                // pip-audit.
1588                SentAnswer {
1589                    answer: audit_hashed_pins(settings, dir, rel, held.sent, held_count, budget),
1590                    sent_names: Some(sent_names),
1591                    private: held.private,
1592                    unproven: !held.unproven.is_empty(),
1593                }
1594            }
1595        }
1596    };
1597    let DirAnswer::Read {
1598        report,
1599        out,
1600        full,
1601        gap,
1602    } = sent.answer
1603    else {
1604        return sent.answer;
1605    };
1606    let skipped = pip_skipped_names(&out);
1607    // Every pin sent was skipped: nothing was audited, which is not clean.
1608    let all_skipped = !skipped.is_empty() && sent.sent_names.is_some_and(|n| skipped.len() >= n);
1609    let mut named: Vec<String> = sent.private.iter().map(|n| printable(n)).collect();
1610    named.extend(skipped);
1611    named.sort();
1612    named.dedup();
1613    if !named.is_empty() {
1614        let names: Vec<&str> = named.iter().map(String::as_str).collect();
1615        common::warn(&skipped_line(&prefix, &names));
1616    }
1617    let gap = if sent.unproven {
1618        gap.or_else(|| Some("names not shown public".to_string()))
1619    } else {
1620        gap
1621    };
1622    let report = match report {
1623        Report::Vulnerabilities(found) => Report::Vulnerabilities(found),
1624        Report::CouldNotCheck => Report::CouldNotCheck,
1625        Report::Clean | Report::Advisories(_) if all_skipped || gap.is_some() => {
1626            Report::CouldNotCheck
1627        }
1628        Report::Clean => Report::Clean,
1629        Report::Advisories(found) => Report::Advisories(found),
1630    };
1631    DirAnswer::Read {
1632        report,
1633        out,
1634        full,
1635        gap,
1636    }
1637}
1638
1639/// On a release, split pip-audit's findings into what ships and what only
1640/// the dev groups carry; the latter warn and do not block. `(report,
1641/// waivable)`: a row whose advisory id is not one a waiver can name (MAL-, a
1642/// new scheme) makes the whole report unwaivable. When the production names
1643/// are unknown (`None`) every finding is kept: an unknown is not a pass.
1644fn shipped_only(
1645    mut report: Report,
1646    out: &str,
1647    production: Option<&std::collections::HashSet<String>>,
1648) -> (Report, bool) {
1649    let mut waivable = pip_rows_all_named(out);
1650    if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1651        let rows = pip_vulnerable_rows(out);
1652        if !rows.is_empty() {
1653            let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1654                .into_iter()
1655                .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1656                .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1657                    if ships {
1658                        s.push(row);
1659                    } else {
1660                        d.push(row);
1661                    }
1662                    (s, d)
1663                });
1664            warn_dev_only("audit-python", &dev_only);
1665            waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1666            report = if shipped.is_empty() {
1667                Report::Clean
1668            } else {
1669                Report::Vulnerabilities(shipped)
1670            };
1671        }
1672    }
1673    (report, waivable)
1674}
1675
1676/// Would [`shipped_only`] split anything? Only a vulnerability report with
1677/// rows it can read; for every other report the production names change
1678/// nothing, so they are not worth a `uv export`.
1679fn has_rows_to_split(report: &Report, out: &str) -> bool {
1680    matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
1681}
1682
1683/// What one lock directory ships, asked of [`uv_production_names`] at most
1684/// once, and only on a release whose batch has findings to split.
1685enum Production {
1686    /// No release: never asked, every finding is kept.
1687    Never,
1688    /// A release, not asked yet: ask in this lock directory.
1689    Unasked(std::path::PathBuf),
1690    /// Asked; None when the export could not answer or time ran out.
1691    Asked(Option<std::collections::HashSet<String>>),
1692}
1693
1694impl Production {
1695    /// The production names, None when this is no release, the export
1696    /// cannot answer, or the budget is spent before it is asked (`say`
1697    /// warns once): every finding is then kept.
1698    fn names(
1699        &mut self,
1700        settings: &crate::config::Settings,
1701        budget: &Budget,
1702        say: &dyn Fn(&str),
1703    ) -> Option<&std::collections::HashSet<String>> {
1704        if let Production::Unasked(dir) = self {
1705            *self = Production::Asked(if budget.spent() {
1706                say(&format!(
1707                    "out of time before the dev-only split — every finding counts\n  {TIMEOUT_NEXT}"
1708                ));
1709                None
1710            } else {
1711                uv_production_names(settings, dir)
1712            });
1713        }
1714        match self {
1715            Production::Asked(names) => names.as_ref(),
1716            Production::Never | Production::Unasked(_) => None,
1717        }
1718    }
1719}
1720
1721/// The next step after the lock route ran out of time.
1722const TIMEOUT_NEXT: &str =
1723    "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";
1724
1725/// The next step after a scratch file could not be made, written or read.
1726const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";
1727
1728/// The next step after pip-audit could not answer, from its own reason: the
1729/// network when the reason names it, else pip-audit itself.
1730fn pip_audit_next(why: &str) -> &'static str {
1731    // holds-until: pip-audit's English error wording is the only signal; when
1732    // it reports an error class or a distinct exit code for the network,
1733    // decide on that instead of these words.
1734    let why = why.to_ascii_lowercase();
1735    let network = [
1736        "network",
1737        "connect",
1738        "timed out",
1739        "timeout",
1740        "resolve",
1741        "dns",
1742        "ssl",
1743        "certificate",
1744        "unreachable",
1745        "temporary failure",
1746    ]
1747    .iter()
1748    .any(|word| why.contains(word));
1749    if network {
1750        "Next: check the network, then push again"
1751    } else {
1752        "Next: `pip-audit --version` to check the install, then push again"
1753    }
1754}
1755
1756/// The only registry whose packages are looked up: ADR-0055 sends public
1757/// names to OSV and pip-audit asks PyPI, and nothing else may be sent.
1758const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1759
1760/// Columns a warning line may use.
1761const WARNING_COLUMNS: usize = 80;
1762
1763/// How many names a count in a warning spells out.
1764const NAMES_SHOWN: usize = 3;
1765
1766/// A directory only this process can enter, removed on every return and
1767/// panic. A signal leaves it behind, as `capture.rs` notes for its own.
1768struct PrivateDir {
1769    path: std::path::PathBuf,
1770}
1771
1772impl PrivateDir {
1773    /// A fresh directory under the temp dir, mode 0700, named unpredictably.
1774    fn create() -> std::io::Result<PrivateDir> {
1775        Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1776    }
1777
1778    /// `path` itself, created exclusively and not recursively: it fails when
1779    /// anything is already there, so nothing planted is ever written through.
1780    fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1781        #[cfg(unix)]
1782        let builder = {
1783            let mut unix_builder = std::fs::DirBuilder::new();
1784            std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1785            unix_builder
1786        };
1787        #[cfg(not(unix))]
1788        let builder = std::fs::DirBuilder::new();
1789        builder.create(&path)?;
1790        Ok(PrivateDir { path })
1791    }
1792
1793    fn path(&self) -> &std::path::Path {
1794        &self.path
1795    }
1796}
1797
1798impl Drop for PrivateDir {
1799    fn drop(&mut self) {
1800        let _ = std::fs::remove_dir_all(&self.path); // best effort: a leftover temp dir holds no secret, and a failure must not panic
1801    }
1802}
1803
1804/// One time budget for a run of several pip-audit calls: the whole lock
1805/// route, or every requirements file of the run.
1806struct Budget {
1807    started: std::time::Instant,
1808    /// None: `greengate.timeout 0` disables the ceiling.
1809    limit: Option<std::time::Duration>,
1810}
1811
1812impl Budget {
1813    fn new(settings: &crate::config::Settings) -> Budget {
1814        Budget {
1815            started: std::time::Instant::now(),
1816            limit: Some(common::check_timeout(settings))
1817                .filter(|secs| *secs > 0)
1818                .map(std::time::Duration::from_secs),
1819        }
1820    }
1821
1822    fn spent(&self) -> bool {
1823        self.limit
1824            .is_some_and(|limit| self.started.elapsed() >= limit)
1825    }
1826}
1827
1828/// Which `uv.lock` packages come from PyPI, by PEP 503 name.
1829#[derive(Debug, Default, PartialEq, Eq)]
1830struct LockSources {
1831    /// Every `[[package]]` block of the name has the PyPI registry.
1832    pypi: std::collections::BTreeSet<String>,
1833    /// Blocks with no name: counted, never classified.
1834    nameless: usize,
1835}
1836
1837/// An index URL that is PyPI's, trailing slash or not: the one test of
1838/// "public" both the lock route and the requirements route use.
1839fn is_pypi_url(url: &str) -> bool {
1840    url.trim_end_matches('/') == PYPI_REGISTRY
1841}
1842
1843/// `source = { registry = "<url>" }` naming PyPI, trailing slash or not.
1844fn is_pypi_source(source_field: &str) -> bool {
1845    source_field
1846        .split_once("registry = \"")
1847        .and_then(|(_, rest)| rest.split('"').next())
1848        .is_some_and(is_pypi_url)
1849}
1850
1851/// A std-only line scan of `uv.lock`'s `[[package]]` blocks (no TOML crate:
1852/// `scripts/check-no-deps.sh`). Only top-level `name` and `source` keys of a
1853/// block count; a name qualifies only when all its blocks come from PyPI.
1854fn scan_uv_lock(text: &str) -> LockSources {
1855    struct Block {
1856        name: Option<String>,
1857        pypi: bool,
1858    }
1859    let mut blocks: Vec<Block> = Vec::new();
1860    let mut top_level = false;
1861    for line in text.lines() {
1862        if line.starts_with('[') {
1863            top_level = line.trim() == "[[package]]";
1864            if top_level {
1865                blocks.push(Block {
1866                    name: None,
1867                    pypi: false,
1868                });
1869            }
1870            continue;
1871        }
1872        let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1873            continue;
1874        };
1875        if let Some(value) = line.strip_prefix("name = ") {
1876            if block.name.is_none() {
1877                block.name = value.split('"').nth(1).map(normalise);
1878            }
1879        } else if let Some(value) = line.strip_prefix("source = ") {
1880            block.pypi = is_pypi_source(value);
1881        }
1882    }
1883    let mut sources = LockSources::default();
1884    let mut rejected = std::collections::BTreeSet::new();
1885    for block in blocks {
1886        match block.name.filter(|n| !n.is_empty()) {
1887            None => sources.nameless += 1,
1888            Some(name) if block.pypi => {
1889                sources.pypi.insert(name);
1890            }
1891            Some(name) => {
1892                rejected.insert(name);
1893            }
1894        }
1895    }
1896    sources.pypi.retain(|name| !rejected.contains(name));
1897    sources
1898}
1899
1900/// What of an export may be sent to pip-audit.
1901#[derive(Debug, Default, PartialEq, Eq)]
1902struct ExportPins {
1903    /// Audit inputs: `name -> version`, one version per name in each batch,
1904    /// because pip-audit rejects conflicting pins in one requirements input.
1905    batches: Vec<std::collections::BTreeMap<String, String>>,
1906    /// Distinct (name, version) pairs across the batches.
1907    versions: usize,
1908    /// Exported names that are not PyPI's: never sent.
1909    skipped: std::collections::BTreeSet<String>,
1910    /// PyPI names whose line is not an exact `name==version` pin.
1911    unclassified: std::collections::BTreeSet<String>,
1912}
1913
1914/// `name==version` of one export line with its environment marker stripped,
1915/// so every platform and Python-version variant is audited whatever the host.
1916fn exact_pin(line: &str) -> Option<(String, String)> {
1917    let spec = line.split(';').next()?.trim();
1918    let (name, version) = spec.split_once("==")?;
1919    let name = name.split('[').next()?.trim();
1920    let version = version.trim();
1921    let name_ok = !name.is_empty()
1922        && name
1923            .chars()
1924            .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1925    let version_ok = !version.is_empty()
1926        && version
1927            .chars()
1928            .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1929    (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1930}
1931
1932fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1933    let mut pins = ExportPins::default();
1934    let mut pairs = std::collections::BTreeSet::new();
1935    for line in raw.lines().map(str::trim) {
1936        if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1937            continue;
1938        }
1939        let name = normalise(
1940            line.split(|c: char| "=<>!~;[ @".contains(c))
1941                .next()
1942                .unwrap_or_default(),
1943        );
1944        if name.is_empty() {
1945            continue;
1946        }
1947        if !pypi.contains(&name) {
1948            pins.skipped.insert(name);
1949            continue;
1950        }
1951        match exact_pin(line) {
1952            Some(pair) => {
1953                pairs.insert(pair);
1954            }
1955            None => {
1956                pins.unclassified.insert(name);
1957            }
1958        }
1959    }
1960    pins.versions = pairs.len();
1961    pins.batches = batches_of(pairs);
1962    pins
1963}
1964
1965/// `(name, version)` pairs split into pip-audit inputs, one version of a
1966/// name in each: pip-audit refuses two pins of one name in one run, even
1967/// across several `-r` files ("package jinja2 has duplicate requirements").
1968fn batches_of(
1969    pairs: std::collections::BTreeSet<(String, String)>,
1970) -> Vec<std::collections::BTreeMap<String, String>> {
1971    let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
1972    for (name, version) in pairs {
1973        match batches.iter().position(|batch| !batch.contains_key(&name)) {
1974            Some(index) => {
1975                batches[index].insert(name, version);
1976            }
1977            None => batches.push(std::collections::BTreeMap::from([(name, version)])),
1978        }
1979    }
1980    batches
1981}
1982
1983/// `requirements.txt` in the repository-relative directory `rel`.
1984fn requirements_path(rel: &str) -> String {
1985    if rel.is_empty() {
1986        "requirements.txt".to_string()
1987    } else {
1988        format!("{rel}/requirements.txt")
1989    }
1990}
1991
1992/// What a warning about `rel`'s requirements.txt starts with: nothing at
1993/// the root, so a root file reads as it always has.
1994fn requirements_prefix(rel: &str) -> String {
1995    if rel.is_empty() {
1996        String::new()
1997    } else {
1998        format!("{}: ", requirements_path(rel))
1999    }
2000}
2001
2002/// A hashed requirements.txt whose pins carry environment markers, audited
2003/// from its pins with the markers stripped, so every platform's pin is
2004/// audited whatever the host (decisions f118). pip-audit evaluates a marker
2005/// against the host and drops a pin it does not match without a word:
2006/// `jinja2==2.10 ; sys_platform == 'linux'` read clean on a Mac.
2007///
2008/// Each batch is a separate run (pip-audit refuses two pins of one name in
2009/// one run) and is read on its own: a clean batch's sentence would hide the
2010/// next one's finding. A gap keeps what the earlier batches found.
2011///
2012/// The same route sends a hashed file's public pins when some names are
2013/// held back (decisions f142); `held` counts them into the skipped total.
2014fn audit_hashed_pins(
2015    settings: &crate::config::Settings,
2016    dir: &std::path::Path,
2017    rel: &str,
2018    pairs: std::collections::BTreeSet<(String, String)>,
2019    held: usize,
2020    budget: &Budget,
2021) -> DirAnswer {
2022    let prefix = requirements_prefix(rel);
2023    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2024    let unchecked = |why: &str| DirAnswer::Read {
2025        report: Report::CouldNotCheck,
2026        out: String::new(),
2027        full: String::new(),
2028        gap: Some(why.to_string()),
2029    };
2030    let private = match PrivateDir::create() {
2031        Ok(private) => private,
2032        Err(why) => {
2033            say(&format!(
2034                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
2035                why.kind()
2036            ));
2037            return unchecked("no private directory");
2038        }
2039    };
2040    // Whatever pip-audit prints, the temp path stays out of it.
2041    let canonical = std::fs::canonicalize(private.path()).ok();
2042    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2043    let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
2044    let mut gap: Option<String> = None;
2045    // Pins (a name at one version) a batch answered, and of those the ones
2046    // pip-audit skipped: counted per batch, so a name pinned twice with one
2047    // version skipped counts one.
2048    let (mut answered, mut skipped_pins) = (0usize, 0usize);
2049    let batches = batches_of(pairs);
2050    for (index, batch) in batches.iter().enumerate() {
2051        if budget.spent() {
2052            say(&format!(
2053                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
2054            ));
2055            gap.get_or_insert_with(|| "out of time".to_string());
2056            break;
2057        }
2058        let file = private.path().join(format!("batch-{index}.txt"));
2059        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2060        if let Err(why) = std::fs::write(&file, body) {
2061            say(&format!(
2062                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
2063                why.kind()
2064            ));
2065            gap.get_or_insert_with(|| "could not write a batch file".to_string());
2066            break;
2067        }
2068        let argv = vec![
2069            common::program("pip-audit"),
2070            "-r".into(),
2071            file.to_string_lossy().into_owned(),
2072            "--no-deps".into(),
2073            "--disable-pip".into(),
2074        ];
2075        // A timeout is said by `audited_in` itself.
2076        let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
2077            if answered == 0 && gap.is_none() {
2078                return DirAnswer::TimedOut;
2079            }
2080            // `audited_in` named the knob: the run's own or its silence budget.
2081            say("timed out; unaudited versions remain — NOT fully checked");
2082            gap.get_or_insert_with(|| "timed out".to_string());
2083            break;
2084        };
2085        let batch_out = scrub(&batch_out);
2086        match read_pip_audit(exit_ok, &batch_out) {
2087            Report::Vulnerabilities(found) => {
2088                vulnerabilities.extend(found);
2089                full.push_str(&batch_out);
2090                answered += batch.len();
2091                skipped_pins += skipped_in(batch, &batch_out);
2092            }
2093            // pip-audit has no advisory class: read_pip_audit never says it.
2094            Report::Clean | Report::Advisories(_) => {
2095                answered += batch.len();
2096                skipped_pins += skipped_in(batch, &batch_out);
2097            }
2098            Report::CouldNotCheck => {
2099                let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
2100                say(&format!(
2101                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
2102                    clip(&why, WARNING_COLUMNS - 2),
2103                    pip_audit_next(&why)
2104                ));
2105                gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
2106            }
2107        }
2108        out.push_str(&batch_out);
2109    }
2110    let audited = answered - skipped_pins;
2111    if audited > 0 {
2112        common::ok(
2113            settings,
2114            &format!(
2115                "audit-python: audited {} ({}, {} skipped)",
2116                requirements_path(rel),
2117                plural(audited, "package version"),
2118                skipped_pins + held
2119            ),
2120        );
2121    }
2122    let report = if !vulnerabilities.is_empty() {
2123        Report::Vulnerabilities(vulnerabilities)
2124    } else if gap.is_some() {
2125        Report::CouldNotCheck
2126    } else {
2127        Report::Clean
2128    };
2129    DirAnswer::Read {
2130        report,
2131        out,
2132        full,
2133        gap,
2134    }
2135}
2136
2137/// How many pins of one batch pip-audit skipped. A batch holds one version
2138/// per name, so a skipped name is one skipped pin: the same name at another
2139/// version, in another batch, is counted by that batch's own answer.
2140fn skipped_in(batch: &std::collections::BTreeMap<String, String>, batch_out: &str) -> usize {
2141    let skipped = pip_skipped_names(batch_out);
2142    batch.keys().filter(|name| skipped.contains(name)).count()
2143}
2144
2145/// The pins of a fully hashed requirements.txt.
2146#[derive(Debug, Default, PartialEq, Eq)]
2147struct HashedPins {
2148    /// Distinct `(name, version)` pairs, markers and extras stripped.
2149    pairs: std::collections::BTreeSet<(String, String)>,
2150    /// Some pin carries an environment marker.
2151    marked: bool,
2152    /// Per name, the index each of its pins came from, as uv's
2153    /// `--emit-index-annotation` writes it (`# from <url>`), None where a
2154    /// pin has no annotation.
2155    from: std::collections::BTreeMap<String, Vec<Option<String>>>,
2156}
2157
2158impl HashedPins {
2159    /// How many distinct names the pins carry.
2160    fn names(&self) -> usize {
2161        let names: std::collections::BTreeSet<&str> =
2162            self.pairs.iter().map(|(name, _)| name.as_str()).collect();
2163        names.len()
2164    }
2165}
2166
2167/// The physical lines of a requirements file joined over their `\`
2168/// continuations, each with the 1-based number of its first line.
2169fn logical_lines(text: &str) -> Vec<(usize, String)> {
2170    let mut logical = Vec::new();
2171    let mut current = String::new();
2172    // A logical line is open from its first physical line to the one that
2173    // does not end in `\`, even when the first is a lone `\`.
2174    let mut open: Option<usize> = None;
2175    for (index, line) in text.lines().enumerate() {
2176        let first = *open.get_or_insert(index + 1);
2177        match line.strip_suffix('\\') {
2178            Some(head) => {
2179                current.push_str(head);
2180                current.push(' ');
2181            }
2182            None => {
2183                current.push_str(line);
2184                logical.push((first, std::mem::take(&mut current)));
2185                open = None;
2186            }
2187        }
2188    }
2189    if let Some(first) = open {
2190        logical.push((first, current));
2191    }
2192    logical
2193}
2194
2195/// A logical line without its comment: pip reads `#` as one only at the
2196/// start or after whitespace.
2197fn uncommented(line: &str) -> &str {
2198    if line.trim_start().starts_with('#') {
2199        return "";
2200    }
2201    match line.find(" #") {
2202        Some(cut) => line[..cut].trim(),
2203        None => line.trim(),
2204    }
2205}
2206
2207/// The URL of uv's `# from <url>` annotation line.
2208fn index_annotation(line: &str) -> Option<&str> {
2209    let url = line.trim().strip_prefix("# from ")?.trim();
2210    (url.contains("://") && !url.contains(char::is_whitespace)).then_some(url)
2211}
2212
2213/// The pins of `dir/requirements.txt` when every requirement is an exact
2214/// `name==version` pin carrying a `--hash`, else None.
2215///
2216/// Hashes are pip-compile's signal (and pip's `--require-hashes` mode): every
2217/// dependency is listed, so there is nothing to resolve. A file of `==` pins
2218/// without hashes lists its top-level packages only (homelab's rag-api,
2219/// websearch) and must still resolve; so must an include or an editable
2220/// (`-r`, `-c`, `-e`), any option outside the index family, a URL or path
2221/// requirement, and an empty file. An index option line (`--extra-index-url`
2222/// and kin) leaves the set closed: the hashes still pin every wheel. A pin
2223/// may carry an environment marker (a universal compile writes them), and
2224/// uv's `# from <url>` annotation after it (decisions f142).
2225fn hashed_pins_in(text: &str) -> Option<HashedPins> {
2226    let mut pins = HashedPins::default();
2227    let mut last: Option<String> = None;
2228    for (_, raw) in logical_lines(text) {
2229        if let Some(url) = index_annotation(&raw) {
2230            if let Some(slot) = last
2231                .as_ref()
2232                .and_then(|name| pins.from.get_mut(name))
2233                .and_then(|pins_of| pins_of.last_mut())
2234            {
2235                *slot = Some(url.to_string());
2236            }
2237            continue;
2238        }
2239        let line = uncommented(&raw);
2240        if line.is_empty() {
2241            continue;
2242        }
2243        if line.starts_with('-') {
2244            match option_line(line) {
2245                OptionLine::Index(_)
2246                | OptionLine::FindLinks(_)
2247                | OptionLine::NoIndex
2248                | OptionLine::TrustedHost => continue,
2249                OptionLine::Include(_) | OptionLine::Editable | OptionLine::Other => return None,
2250            }
2251        }
2252        let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
2253        let hashed = options
2254            .split_whitespace()
2255            .any(|option| option.starts_with("--hash"));
2256        if !hashed {
2257            return None;
2258        }
2259        let pair = exact_pin(spec)?;
2260        pins.from.entry(pair.0.clone()).or_default().push(None);
2261        last = Some(pair.0.clone());
2262        pins.pairs.insert(pair);
2263        pins.marked |= spec.contains(';');
2264    }
2265    (!pins.pairs.is_empty()).then_some(pins)
2266}
2267
2268/// One option line of a requirements file, as far as provenance cares.
2269#[derive(Debug, PartialEq, Eq)]
2270enum OptionLine<'a> {
2271    /// `-i`, `--index-url`, `--extra-index-url`, with its value.
2272    Index(&'a str),
2273    /// `-f`, `--find-links`, with its value.
2274    FindLinks(&'a str),
2275    NoIndex,
2276    /// `-r`, `--requirement`, `-c`, `--constraint`, with its value.
2277    Include(&'a str),
2278    /// `--trusted-host`: says how to reach an index, names none.
2279    TrustedHost,
2280    /// `-e`, `--editable`: a project from a path or a VCS URL.
2281    Editable,
2282    Other,
2283}
2284
2285/// The long options pip's requirements-file parser knows, for optparse's
2286/// unique-prefix matching (`--extra-index` is `--extra-index-url`).
2287const PIP_FILE_OPTIONS: &[&str] = &[
2288    "--index-url",
2289    "--extra-index-url",
2290    "--no-index",
2291    "--find-links",
2292    "--requirement",
2293    "--constraint",
2294    "--editable",
2295    "--trusted-host",
2296    "--pre",
2297    "--prefer-binary",
2298    "--require-hashes",
2299    "--only-binary",
2300    "--no-binary",
2301    "--use-feature",
2302    "--hash",
2303    "--config-settings",
2304    "--global-option",
2305];
2306
2307/// A long option's full name, matched exactly or by unique prefix as
2308/// optparse does; the name itself when it matches none or several.
2309fn long_option(name: &str) -> &str {
2310    if PIP_FILE_OPTIONS.contains(&name) {
2311        return name;
2312    }
2313    let mut matches = PIP_FILE_OPTIONS
2314        .iter()
2315        .filter(|full| full.starts_with(name));
2316    match (matches.next(), matches.next()) {
2317        (Some(full), None) => full,
2318        _ => name,
2319    }
2320}
2321
2322/// `--opt value`, `--opt=value`, or a short option with its value glued
2323/// on (`-ihttps://…`, `-rbase.txt`, `-e.`), as optparse reads them. A
2324/// missing value reads as empty, which no later test takes for PyPI.
2325fn option_line(line: &str) -> OptionLine<'_> {
2326    let mut words = line.split_whitespace();
2327    let first = words.next().unwrap_or_default();
2328    let (name, glued) = if first.starts_with("--") {
2329        match first.split_once('=') {
2330            Some((name, value)) => (long_option(name), Some(value)),
2331            None => (long_option(first), None),
2332        }
2333    } else if first.len() > 2 && first.is_char_boundary(2) {
2334        (&first[..2], Some(&first[2..]))
2335    } else {
2336        (first, None)
2337    };
2338    let value = glued.or_else(|| words.next()).unwrap_or_default();
2339    match name {
2340        "-i" | "--index-url" | "--extra-index-url" => OptionLine::Index(value),
2341        "-f" | "--find-links" => OptionLine::FindLinks(value),
2342        "--no-index" => OptionLine::NoIndex,
2343        "-r" | "--requirement" | "-c" | "--constraint" => OptionLine::Include(value),
2344        "--trusted-host" => OptionLine::TrustedHost,
2345        "-e" | "--editable" => OptionLine::Editable,
2346        _ => OptionLine::Other,
2347    }
2348}
2349
2350/// A place pip may take a requirements file's names from that is not
2351/// PyPI, said by what set it and where it points, never by its URL: an
2352/// index URL carries `user:token@` credentials.
2353#[derive(Debug, Clone, PartialEq, Eq)]
2354struct IndexSource {
2355    /// `requirements.txt line 3`, `PIP_EXTRA_INDEX_URL`, `~/.pip/pip.conf`.
2356    label: String,
2357    /// The host, or what the source is when it has none (`a local path`).
2358    what: String,
2359}
2360
2361impl IndexSource {
2362    fn new(label: &str, what: &str) -> IndexSource {
2363        IndexSource {
2364            label: printable(label),
2365            what: printable(what),
2366        }
2367    }
2368
2369    /// An index URL; None when it is PyPI's.
2370    fn index(label: &str, url: &str) -> Option<IndexSource> {
2371        (!is_pypi_url(url)).then(|| IndexSource::new(label, &host_of(url)))
2372    }
2373
2374    /// A find-links location: a page or a directory of wheels, never PyPI.
2375    fn find_links(label: &str, location: &str) -> IndexSource {
2376        let remote = location
2377            .split_once("://")
2378            .is_some_and(|(scheme, _)| !scheme.eq_ignore_ascii_case("file"));
2379        if remote {
2380            IndexSource::new(label, &host_of(location))
2381        } else {
2382            IndexSource::new(label, "a local path")
2383        }
2384    }
2385
2386    fn no_index(label: &str) -> IndexSource {
2387        IndexSource::new(label, "--no-index")
2388    }
2389
2390    fn unread_include(label: &str) -> IndexSource {
2391        IndexSource::new(label, "an unread include")
2392    }
2393
2394    fn unread_config(label: &str) -> IndexSource {
2395        IndexSource::new(label, "an unread config file")
2396    }
2397
2398    fn direct_reference(label: &str) -> IndexSource {
2399        IndexSource::new(label, "a direct reference")
2400    }
2401}
2402
2403/// A requirement that names its own location instead of an index: `name @
2404/// <url>`, a URL, a path or an archive. A PEP 508 name holds no `@`, `/`
2405/// or `\\`, and does not start with a dot.
2406fn is_direct_reference(line: &str) -> bool {
2407    let spec = line.split(" --").next().unwrap_or_default();
2408    let spec = spec.split(';').next().unwrap_or_default().trim();
2409    let archive = [".whl", ".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz"]
2410        .iter()
2411        .any(|ext| spec.to_ascii_lowercase().ends_with(ext));
2412    spec.contains(['@', '/', '\\']) || spec.starts_with('.') || archive
2413}
2414
2415/// The host of `url` with any userinfo dropped. The part after the LAST
2416/// `@` anywhere is taken, so a password holding `@` or `/` never shows; an
2417/// `@` in the path gives a wrong host, never a credential.
2418fn host_of(url: &str) -> String {
2419    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
2420    let rest = rest.rsplit('@').next().unwrap_or_default();
2421    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
2422    if host.is_empty() {
2423        "an index with no host".to_string()
2424    } else {
2425        host.to_string()
2426    }
2427}
2428
2429/// `text` with every control character escaped, so a name or a path read
2430/// from a file cannot forge an output line or drive the terminal.
2431fn printable(text: &str) -> String {
2432    let mut shown = String::with_capacity(text.len());
2433    for c in text.chars() {
2434        if c.is_control() {
2435            shown.extend(c.escape_default());
2436        } else {
2437            shown.push(c);
2438        }
2439    }
2440    shown
2441}
2442
2443/// How deep `-r`/`-c` includes are followed; a deeper one is unproven.
2444const INCLUDE_DEPTH: usize = 8;
2445
2446/// An include's text, or None when it is not a regular file that could be
2447/// read: a FIFO or a device (`/dev/stdin`) is never opened, so the hook
2448/// cannot block on it.
2449fn read_include(path: &std::path::Path) -> Option<String> {
2450    let meta = std::fs::metadata(path).ok()?;
2451    if !meta.is_file() {
2452        return None;
2453    }
2454    std::fs::read_to_string(path).ok()
2455}
2456
2457/// The non-PyPI sources a requirements file names in its option lines,
2458/// following its `-r`/`-c` includes (relative to the including file). An
2459/// include that is a URL, is not read (`read` says None), or lies past
2460/// [`INCLUDE_DEPTH`] is itself a source: what it says is unknown.
2461fn file_sources(
2462    text: &str,
2463    label: &str,
2464    dir: &std::path::Path,
2465    read: &dyn Fn(&std::path::Path) -> Option<String>,
2466) -> Vec<IndexSource> {
2467    let mut sources = Vec::new();
2468    let mut seen = std::collections::BTreeSet::new();
2469    // (text, label, its directory, depth): the file, then each include.
2470    let mut pending = vec![(text.to_string(), label.to_string(), dir.to_path_buf(), 0)];
2471    while let Some((text, label, dir, depth)) = pending.pop() {
2472        for (number, raw) in logical_lines(&text) {
2473            let line = uncommented(&raw);
2474            if line.is_empty() {
2475                continue;
2476            }
2477            let at = format!("{label} line {number}");
2478            if !line.starts_with('-') {
2479                if is_direct_reference(line) {
2480                    sources.push(IndexSource::direct_reference(&at));
2481                }
2482                continue;
2483            }
2484            match option_line(line) {
2485                OptionLine::Index(url) => sources.extend(IndexSource::index(&at, url)),
2486                OptionLine::FindLinks(location) => {
2487                    sources.push(IndexSource::find_links(&at, location));
2488                }
2489                OptionLine::NoIndex => sources.push(IndexSource::no_index(&at)),
2490                OptionLine::Include(target) => {
2491                    if target.is_empty() || target.contains("://") || depth + 1 > INCLUDE_DEPTH {
2492                        sources.push(IndexSource::unread_include(&at));
2493                        continue;
2494                    }
2495                    let path = dir.join(target);
2496                    let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
2497                    if !seen.insert(key) {
2498                        continue;
2499                    }
2500                    match read(&path) {
2501                        Some(included) => {
2502                            let parent = path.parent().unwrap_or(&dir).to_path_buf();
2503                            pending.push((included, target.to_string(), parent, depth + 1));
2504                        }
2505                        None => sources.push(IndexSource::unread_include(&at)),
2506                    }
2507                }
2508                OptionLine::Editable => sources.push(IndexSource::direct_reference(&at)),
2509                // An option this reader does not know that names a URL may
2510                // set an index some way it cannot see: fail closed.
2511                OptionLine::Other if line.contains("://") => {
2512                    sources.push(IndexSource::new(&at, "an unparsed option"));
2513                }
2514                OptionLine::TrustedHost | OptionLine::Other => {}
2515            }
2516        }
2517    }
2518    sources
2519}
2520
2521/// pip's reading of a boolean option: `1`, `true`, `yes`, `on`, any case.
2522fn pip_true(value: &str) -> bool {
2523    matches!(
2524        value.trim().to_ascii_lowercase().as_str(),
2525        "1" | "true" | "yes" | "on"
2526    )
2527}
2528
2529/// The non-PyPI sources the environment sets, read through `get`.
2530fn env_sources(get: &dyn Fn(&str) -> Option<String>) -> Vec<IndexSource> {
2531    let mut sources = Vec::new();
2532    for var in ["PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL"] {
2533        for url in get(var).unwrap_or_default().split_whitespace() {
2534            sources.extend(IndexSource::index(var, url));
2535        }
2536    }
2537    for location in get("PIP_FIND_LINKS").unwrap_or_default().split_whitespace() {
2538        sources.push(IndexSource::find_links("PIP_FIND_LINKS", location));
2539    }
2540    if get("PIP_NO_INDEX").is_some_and(|value| pip_true(&value)) {
2541        sources.push(IndexSource::no_index("PIP_NO_INDEX"));
2542    }
2543    sources
2544}
2545
2546/// The non-PyPI sources a pip config file sets, in any section: pip reads
2547/// `[global]` and the command's own, and reading more holds more back.
2548fn config_sources(text: &str, label: &str) -> Vec<IndexSource> {
2549    let mut sources = Vec::new();
2550    let mut key: Option<String> = None;
2551    let take = |key: &str, value: &str| -> Vec<IndexSource> {
2552        match key {
2553            "index-url" | "extra-index-url" => value
2554                .split_whitespace()
2555                .filter_map(|url| IndexSource::index(label, url))
2556                .collect(),
2557            "find-links" => value
2558                .split_whitespace()
2559                .map(|location| IndexSource::find_links(label, location))
2560                .collect(),
2561            "no-index" if pip_true(value) => vec![IndexSource::no_index(label)],
2562            _ => Vec::new(),
2563        }
2564    };
2565    for line in text.lines() {
2566        let trimmed = line.trim();
2567        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
2568            continue;
2569        }
2570        if line.starts_with([' ', '\t']) {
2571            // A continuation: more values of the key above.
2572            if let Some(key) = key.as_deref() {
2573                sources.extend(take(key, trimmed));
2574            }
2575            continue;
2576        }
2577        if trimmed.starts_with('[') {
2578            key = None;
2579            continue;
2580        }
2581        let Some(cut) = trimmed.find(['=', ':']) else {
2582            key = None;
2583            continue;
2584        };
2585        let name = trimmed[..cut].trim().to_ascii_lowercase().replace('_', "-");
2586        sources.extend(take(&name, trimmed[cut + 1..].trim()));
2587        key = Some(name);
2588    }
2589    sources
2590}
2591
2592/// The pip config files that may apply, each with the label it is said
2593/// by (`$HOME` written `~`); none when `PIP_CONFIG_FILE` is `/dev/null`,
2594/// pip's "no config". A superset of what pip reads on Linux and macOS;
2595/// Windows' `%APPDATA%\pip\pip.ini` is not read (the fleet pushes from
2596/// Unix hosts).
2597fn config_paths(get: &dyn Fn(&str) -> Option<String>) -> Vec<(std::path::PathBuf, String)> {
2598    let named = get("PIP_CONFIG_FILE").filter(|path| !path.is_empty());
2599    if named.as_deref() == Some("/dev/null") {
2600        return Vec::new();
2601    }
2602    let home = get("HOME").filter(|home| !home.is_empty());
2603    let mut paths: Vec<std::path::PathBuf> =
2604        ["/etc/pip.conf", "/Library/Application Support/pip/pip.conf"]
2605            .iter()
2606            .map(std::path::PathBuf::from)
2607            .collect();
2608    let xdg_dirs = get("XDG_CONFIG_DIRS").filter(|dirs| !dirs.is_empty());
2609    for dir in xdg_dirs.as_deref().unwrap_or("/etc/xdg").split(':') {
2610        if !dir.is_empty() {
2611            paths.push(std::path::Path::new(dir).join("pip/pip.conf"));
2612        }
2613    }
2614    if let Some(home) = home.as_deref() {
2615        let home = std::path::Path::new(home);
2616        paths.push(home.join(".pip/pip.conf"));
2617        paths.push(home.join("Library/Application Support/pip/pip.conf"));
2618        if get("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).is_none() {
2619            paths.push(home.join(".config/pip/pip.conf"));
2620        }
2621    }
2622    if let Some(xdg) = get("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
2623        paths.push(std::path::Path::new(&xdg).join("pip/pip.conf"));
2624    }
2625    if let Some(venv) = get("VIRTUAL_ENV").filter(|v| !v.is_empty()) {
2626        paths.push(std::path::Path::new(&venv).join("pip.conf"));
2627    }
2628    if let Some(named) = named {
2629        paths.push(std::path::PathBuf::from(named));
2630    }
2631    paths
2632        .into_iter()
2633        .map(|path| {
2634            let shown = path.to_string_lossy();
2635            let label = match home.as_deref().and_then(|h| shown.strip_prefix(h)) {
2636                Some(rest) if rest.starts_with('/') => format!("~{rest}"),
2637                _ => shown.into_owned(),
2638            };
2639            (path, label)
2640        })
2641        .collect()
2642}
2643
2644/// A config file as read: absent, its text, or there and unreadable.
2645#[derive(Debug, PartialEq, Eq)]
2646enum ConfigFile {
2647    Absent,
2648    Text(String),
2649    Unread,
2650}
2651
2652fn read_config(path: &std::path::Path) -> ConfigFile {
2653    // Why a file is unread only feeds a label, so the io cause is dropped.
2654    let parent_is_dir = path.parent().is_some_and(std::path::Path::is_dir);
2655    match std::fs::metadata(path) {
2656        Err(why) if why.kind() == std::io::ErrorKind::NotFound => ConfigFile::Absent,
2657        // `~/.pip` is a file, not a directory: there is no config under it.
2658        Err(_) if !parent_is_dir => ConfigFile::Absent,
2659        Ok(meta) if meta.is_file() => match std::fs::read_to_string(path) {
2660            Ok(text) => ConfigFile::Text(text),
2661            Err(_) => ConfigFile::Unread,
2662        },
2663        // Not a regular file (never opened), or not even statable.
2664        _ => ConfigFile::Unread,
2665    }
2666}
2667
2668/// Every non-PyPI source this host gives pip, outside the file: the
2669/// environment and the config files. Read once per run. A config file
2670/// that is there and cannot be read is a source: what it says is unknown.
2671fn host_sources(
2672    get: &dyn Fn(&str) -> Option<String>,
2673    read: &dyn Fn(&std::path::Path) -> ConfigFile,
2674) -> Vec<IndexSource> {
2675    let mut sources = env_sources(get);
2676    for (path, label) in config_paths(get) {
2677        match read(&path) {
2678            ConfigFile::Absent => {}
2679            ConfigFile::Text(text) => sources.extend(config_sources(&text, &label)),
2680            ConfigFile::Unread => sources.push(IndexSource::unread_config(&label)),
2681        }
2682    }
2683    sources
2684}
2685
2686/// Which pins of a hashed file may be sent (decisions f142, ADR-0055).
2687#[derive(Debug, Default, PartialEq, Eq)]
2688struct Provenance {
2689    /// The pins of names shown public.
2690    sent: std::collections::BTreeSet<(String, String)>,
2691    /// Names a pin of which uv annotated with another index.
2692    private: std::collections::BTreeSet<String>,
2693    /// Names with an unannotated pin while a non-PyPI source exists.
2694    unproven: std::collections::BTreeSet<String>,
2695}
2696
2697/// Each name of `pins` judged against its annotations and the non-PyPI
2698/// `sources` in sight: private when a pin came from another index, else
2699/// unproven when a pin has no annotation and any source exists.
2700fn provenance(pins: &HashedPins, sources: &[IndexSource]) -> Provenance {
2701    let mut held = Provenance::default();
2702    for (name, from) in &pins.from {
2703        if from
2704            .iter()
2705            .any(|url| url.as_deref().is_some_and(|url| !is_pypi_url(url)))
2706        {
2707            held.private.insert(name.clone());
2708        } else if !sources.is_empty() && from.iter().any(Option::is_none) {
2709            held.unproven.insert(name.clone());
2710        }
2711    }
2712    held.sent = pins
2713        .pairs
2714        .iter()
2715        .filter(|(name, _)| !held.private.contains(name) && !held.unproven.contains(name))
2716        .cloned()
2717        .collect();
2718    held
2719}
2720
2721/// "<what> (<label>)", and how many more there are.
2722fn sources_phrase(sources: &[IndexSource]) -> String {
2723    let Some(first) = sources.first() else {
2724        return String::new();
2725    };
2726    let more = match sources.len() - 1 {
2727        0 => String::new(),
2728        1 => " +1 more source".to_string(),
2729        n => format!(" +{n} more sources"),
2730    };
2731    format!("{} ({}){more}", first.what, first.label)
2732}
2733
2734/// "(a, b, c +K more)": as many names as [`NAMES_SHOWN`].
2735fn names_phrase<'a>(names: impl IntoIterator<Item = &'a String>) -> String {
2736    let names: Vec<&String> = names.into_iter().collect();
2737    let shown: Vec<String> = names
2738        .iter()
2739        .take(NAMES_SHOWN)
2740        .map(|n| printable(n))
2741        .collect();
2742    let more = names.len().saturating_sub(NAMES_SHOWN);
2743    if more == 0 {
2744        format!("({})", shown.join(", "))
2745    } else {
2746        format!("({} +{more} more)", shown.join(", "))
2747    }
2748}
2749
2750/// What to do about names that cannot be shown public.
2751const ANNOTATE_NEXT: &str = "Next: `uv pip compile --generate-hashes --emit-index-annotation` \
2752     (so each pin names its index)";
2753
2754/// The names in pip-audit's `Name  Skip Reason` table: packages it could not
2755/// audit (not on PyPI, or a local version such as `2.14.0+cpu`).
2756fn pip_skipped_names(out: &str) -> Vec<String> {
2757    let mut lines = out.lines().map(str::trim);
2758    let mut names = Vec::new();
2759    while let Some(line) = lines.next() {
2760        if !(line.starts_with("Name") && line.contains("Skip Reason")) {
2761            continue;
2762        }
2763        let rows = lines
2764            .by_ref()
2765            .skip_while(|l| l.starts_with('-'))
2766            .take_while(|l| !l.is_empty());
2767        names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
2768    }
2769    names.sort();
2770    names.dedup();
2771    names
2772}
2773
2774fn plural(count: usize, noun: &str) -> String {
2775    if count == 1 {
2776        format!("{count} {noun}")
2777    } else {
2778        format!("{count} {noun}s")
2779    }
2780}
2781
2782/// "N private/non-PyPI package(s) skipped (a, b, c +K more)", with as many
2783/// names as keep the line within the columns, and always at least one: a
2784/// long directory prefix once left "(+1 more)" naming nothing (f108).
2785fn skipped_line(prefix: &str, names: &[&str]) -> String {
2786    let head = format!(
2787        "audit-python: {prefix}{} skipped",
2788        plural(names.len(), "private/non-PyPI package")
2789    );
2790    let fewest = names.len().min(1);
2791    for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
2792        let list: Vec<&str> = names.iter().take(shown).copied().collect();
2793        let more = names.len() - shown;
2794        let detail = match (list.is_empty(), more) {
2795            (true, 0) => String::new(),
2796            (true, _) => format!(" (+{more} more)"),
2797            (false, 0) => format!(" ({})", list.join(", ")),
2798            (false, _) => format!(" ({} +{more} more)", list.join(", ")),
2799        };
2800        let line = format!("{head}{detail}");
2801        if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
2802            return line;
2803        }
2804    }
2805    head
2806}
2807
2808/// `text` cut to `columns` characters.
2809fn clip(text: &str, columns: usize) -> String {
2810    text.chars().take(columns).collect()
2811}
2812
2813/// `text` with the private directory named `<tmp>`, in the form it was
2814/// created under and in its canonical form (macOS spells `/var` as
2815/// `/private/var`). The canonical one goes first: the plain one is a suffix
2816/// of it.
2817fn scrub_private(
2818    text: &str,
2819    private: &std::path::Path,
2820    canonical: Option<&std::path::Path>,
2821) -> String {
2822    let plain = private.to_string_lossy();
2823    let mut scrubbed = text.to_string();
2824    if let Some(canonical) = canonical.filter(|c| *c != private) {
2825        scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
2826    }
2827    scrubbed.replace(plain.as_ref(), "<tmp>")
2828}
2829
2830/// What auditing one `uv.lock` found.
2831struct LockDirAudit {
2832    vulnerabilities: Vec<String>,
2833    advisories: Vec<String>,
2834    full: String,
2835    /// False when any part of the lock went unchecked (export or batch
2836    /// failed, time ran out): never Clean, never waivable.
2837    complete: bool,
2838    waivable: bool,
2839}
2840
2841impl LockDirAudit {
2842    fn unchecked() -> LockDirAudit {
2843        LockDirAudit {
2844            vulnerabilities: Vec::new(),
2845            advisories: Vec::new(),
2846            full: String::new(),
2847            complete: false,
2848            waivable: false,
2849        }
2850    }
2851}
2852
2853/// `uv export` of the lock in `dir`, filtered to PyPI pins, audited by
2854/// pip-audit without resolving anything (`--no-deps --disable-pip`).
2855///
2856/// `production` splits each batch's findings by what the lock ships, asked
2857/// the first time a batch has findings.
2858fn audit_uv_lock(
2859    settings: &crate::config::Settings,
2860    mut production: Production,
2861    dir: &str,
2862    budget: &Budget,
2863) -> LockDirAudit {
2864    let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
2865    let lock_path = if dir.is_empty() {
2866        "uv.lock".to_string()
2867    } else {
2868        format!("{dir}/uv.lock")
2869    };
2870    let prefix = if dir.is_empty() {
2871        String::new()
2872    } else {
2873        format!("{lock_path}: ")
2874    };
2875    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2876    let private = match PrivateDir::create() {
2877        Ok(private) => private,
2878        Err(why) => {
2879            say(&format!(
2880                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
2881                why.kind()
2882            ));
2883            return LockDirAudit::unchecked();
2884        }
2885    };
2886    // Whatever a tool prints, the temp path stays out of it.
2887    let canonical = std::fs::canonicalize(private.path()).ok();
2888    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2889    let export = private.path().join("export.txt");
2890    if budget.spent() {
2891        say(&format!(
2892            "out of time before the export — the audit did NOT run\n  {TIMEOUT_NEXT}"
2893        ));
2894        return LockDirAudit::unchecked();
2895    }
2896    let argv = vec![
2897        common::program("uv"),
2898        "export".into(),
2899        "--frozen".into(),
2900        "--all-packages".into(),
2901        "--all-groups".into(),
2902        "--all-extras".into(),
2903        "--no-hashes".into(),
2904        "--no-emit-workspace".into(),
2905        "--format".into(),
2906        "requirements-txt".into(),
2907        "-o".into(),
2908        export.to_string_lossy().into_owned(),
2909    ];
2910    let exported = audited_in(settings, &argv, &dir_path);
2911    if !matches!(exported, Some((true, _))) {
2912        let why = exported
2913            .and_then(|(_, out)| failure_line(&scrub(&out)))
2914            .unwrap_or_else(|| "uv did not answer".to_string());
2915        let place = if dir.is_empty() {
2916            "at the repo root".to_string()
2917        } else {
2918            format!("in {dir}")
2919        };
2920        say(&format!(
2921            "uv export failed — the audit did NOT run\n  {}\n  Next: `uv export --frozen` {place}",
2922            clip(&why, WARNING_COLUMNS - 2)
2923        ));
2924        return LockDirAudit::unchecked();
2925    }
2926    let raw = std::fs::read_to_string(&export);
2927    // The raw export has served; only the filtered pins stay on disk.
2928    let _ = std::fs::remove_file(&export); // best effort: the guard removes the directory
2929    let raw = match raw {
2930        Ok(raw) => raw,
2931        Err(why) => {
2932            say(&format!(
2933                "could not read export.txt ({}) — the audit did NOT run\n  {TMPDIR_NEXT}",
2934                why.kind()
2935            ));
2936            return LockDirAudit::unchecked();
2937        }
2938    };
2939    let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
2940        Ok(lock) => lock,
2941        Err(why) => {
2942            say(&format!(
2943                "could not read uv.lock ({}) — the audit did NOT run\n  \
2944                 Next: check that {lock_path} is readable, then push again",
2945                why.kind()
2946            ));
2947            return LockDirAudit::unchecked();
2948        }
2949    };
2950    let sources = scan_uv_lock(&lock);
2951    let pins = filter_export(&raw, &sources.pypi);
2952    if !pins.skipped.is_empty() {
2953        let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
2954        common::warn(&skipped_line(&prefix, &names));
2955    }
2956    let unclassified = pins.unclassified.len() + sources.nameless;
2957    if unclassified > 0 {
2958        let source = if prefix.is_empty() {
2959            " from uv.lock"
2960        } else {
2961            ""
2962        };
2963        say(&format!(
2964            "{} could not be classified{source}; not audited\n  \
2965             Next: check that each [[package]] in {lock_path} has a name and source",
2966            plural(unclassified, "package")
2967        ));
2968    }
2969    if pins.batches.is_empty() {
2970        say(&format!(
2971            "no PyPI package to audit — the audit did NOT run\n  \
2972             Next: none if every package is private; else check {lock_path} sources"
2973        ));
2974        return LockDirAudit::unchecked();
2975    }
2976    let mut audit = LockDirAudit {
2977        vulnerabilities: Vec::new(),
2978        advisories: Vec::new(),
2979        full: String::new(),
2980        complete: true,
2981        waivable: true,
2982    };
2983    let mut audited = 0;
2984    for (index, batch) in pins.batches.iter().enumerate() {
2985        let file = private.path().join(format!("batch-{index}.txt"));
2986        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2987        if budget.spent() {
2988            say(&format!(
2989                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
2990            ));
2991            audit.complete = false;
2992            break;
2993        }
2994        if let Err(why) = std::fs::write(&file, body) {
2995            say(&format!(
2996                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
2997                why.kind()
2998            ));
2999            audit.complete = false;
3000            break;
3001        }
3002        let argv = vec![
3003            common::program("pip-audit"),
3004            "-r".into(),
3005            file.to_string_lossy().into_owned(),
3006            "--no-deps".into(),
3007            "--disable-pip".into(),
3008        ];
3009        let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
3010            audit.complete = false;
3011            break;
3012        };
3013        let out = scrub(&out);
3014        let report = read_pip_audit(exit_ok, &out);
3015        let names = if has_rows_to_split(&report, &out) {
3016            production.names(settings, budget, &say)
3017        } else {
3018            None
3019        };
3020        let (report, waivable) = shipped_only(report, &out, names);
3021        audit.waivable &= waivable;
3022        match report {
3023            Report::Vulnerabilities(found) => {
3024                audit.vulnerabilities.extend(found);
3025                audit.full.push_str(&out);
3026                audited += batch.len();
3027            }
3028            Report::Advisories(found) => {
3029                audit.advisories.extend(found);
3030                audited += batch.len();
3031            }
3032            Report::Clean => audited += batch.len(),
3033            Report::CouldNotCheck => {
3034                audit.complete = false;
3035                let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
3036                say(&format!(
3037                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
3038                    clip(&why, WARNING_COLUMNS - 2),
3039                    pip_audit_next(&why)
3040                ));
3041            }
3042        }
3043    }
3044    if !audit.complete {
3045        audit.waivable = false;
3046    }
3047    if audited > 0 {
3048        common::ok(
3049            settings,
3050            &format!(
3051                "audit-python: audited {lock_path} ({}, {} skipped)",
3052                plural(audited, "package version"),
3053                pins.skipped.len()
3054            ),
3055        );
3056    }
3057    audit
3058}
3059
3060/// The lock route: each tracked `uv.lock` audited from its own directory.
3061/// The result is the worst directory's: findings block as ever, and a
3062/// directory that went unchecked is never hidden by a clean one.
3063fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
3064    let (settings, refs) = (ctx.settings, ctx.push.get());
3065    let release = releasing(refs);
3066    let budget = Budget::new(settings);
3067    let root = std::path::PathBuf::from(common::repo_root());
3068    let dirs = lockfile_dirs("uv.lock");
3069    let only_root = dirs.len() == 1 && dirs[0].is_empty();
3070    let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
3071    let mut full = String::new();
3072    let (mut complete, mut waivable) = (true, true);
3073    for dir in &dirs {
3074        let production = if release {
3075            Production::Unasked(root.join(dir))
3076        } else {
3077            Production::Never
3078        };
3079        let audit = audit_uv_lock(settings, production, dir, &budget);
3080        let label = |ids: Vec<String>| -> Vec<String> {
3081            if dir.is_empty() {
3082                ids
3083            } else {
3084                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
3085            }
3086        };
3087        vulnerabilities.extend(label(audit.vulnerabilities));
3088        advisories.extend(label(audit.advisories));
3089        if !audit.full.is_empty() {
3090            if only_root {
3091                full.push_str(&audit.full);
3092            } else {
3093                full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
3094            }
3095        }
3096        complete &= audit.complete;
3097        waivable &= audit.waivable;
3098    }
3099    let report = if !vulnerabilities.is_empty() {
3100        Report::Vulnerabilities(vulnerabilities)
3101    } else if !complete {
3102        return Ran::Unavailable;
3103    } else if !advisories.is_empty() {
3104        Report::Advisories(advisories)
3105    } else {
3106        Report::Clean
3107    };
3108    Ran::Concluded(Concluded {
3109        tool: "audit-python".to_string(),
3110        report,
3111        full,
3112        waivable: waivable && complete,
3113        complete,
3114    })
3115}
3116
3117/// Is `source`'s working tree exactly the commit checked out here, with its
3118/// Python manifests unmodified? Then its installed environment is this
3119/// commit's (as far as the hook in `source` would have known).
3120fn source_is_this_commit(source: &std::path::Path) -> bool {
3121    let src = source.to_string_lossy();
3122    let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
3123    let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
3124    let unmodified = crate::git::stdout(&[
3125        "-C",
3126        &src,
3127        "status",
3128        "--porcelain",
3129        "--untracked-files=no",
3130        "--",
3131        "*pyproject.toml",
3132        "*uv.lock",
3133        "*requirements*.txt",
3134    ])
3135    .is_some_and(|out| out.trim().is_empty());
3136    here.is_some() && here == there && unmodified
3137}
3138
3139/// PEP 503 normalised: `Foo_Bar.baz` and `foo-bar-baz` are one package.
3140fn normalise(name: &str) -> String {
3141    name.to_ascii_lowercase()
3142        .split(['-', '_', '.'])
3143        .filter(|p| !p.is_empty())
3144        .collect::<Vec<_>>()
3145        .join("-")
3146}
3147
3148/// The packages pip-audit's table names, one row per advisory:
3149/// `Name Version ID Fix Versions`. Only rows whose third column is an
3150/// advisory id count, so the header, the rule and the summary never do.
3151fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
3152    let mut rows: Vec<(String, String)> = out
3153        .lines()
3154        .filter_map(|l| {
3155            let cols: Vec<&str> = l.split_whitespace().collect();
3156            let id = cols.get(2)?;
3157            ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
3158                .iter()
3159                .any(|p| id.starts_with(p))
3160                .then(|| (normalise(cols[0]), (*id).to_string()))
3161        })
3162        .collect();
3163    rows.sort();
3164    rows.dedup();
3165    rows
3166}
3167
3168/// Does every advisory row of pip-audit's table carry an id a waiver can
3169/// name? A row is `name version id …`: a version starting with a digit and
3170/// an id shaped `PREFIX-…`, whatever the prefix.
3171fn pip_rows_all_named(out: &str) -> bool {
3172    out.lines().all(|l| {
3173        let cols: Vec<&str> = l.split_whitespace().collect();
3174        let is_row = cols.len() >= 3
3175            && cols[1].starts_with(|c: char| c.is_ascii_digit())
3176            && cols[2].contains('-')
3177            && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
3178        !is_row || !advisory_ids(cols[2]).is_empty()
3179    })
3180}
3181
3182/// What a uv project ships: `uv export --no-dev` of its lock in `dir`, names
3183/// only. None when there is no `uv.lock`, no `uv`, or the export fails — the
3184/// caller then keeps every finding, because an unknown is not a pass.
3185fn uv_production_names(
3186    settings: &crate::config::Settings,
3187    dir: &std::path::Path,
3188) -> Option<std::collections::HashSet<String>> {
3189    if !has_lockfile("uv.lock") || common::which("uv").is_none() {
3190        return None;
3191    }
3192    let argv = vec![
3193        common::program("uv"),
3194        "export".into(),
3195        "--frozen".into(),
3196        // The same members the audit exported, so scope and classification
3197        // cover one workspace.
3198        "--all-packages".into(),
3199        "--no-dev".into(),
3200        "--no-default-groups".into(),
3201        // Optional extras ship: a consumer who asks for one installs it.
3202        "--all-extras".into(),
3203        "--no-hashes".into(),
3204        "--no-emit-workspace".into(),
3205        "--format".into(),
3206        "requirements-txt".into(),
3207    ];
3208    let (ok, out) = audited_in(settings, &argv, dir)?;
3209    if !ok {
3210        return None;
3211    }
3212    Some(
3213        out.lines()
3214            .map(str::trim)
3215            .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
3216            .filter_map(|l| {
3217                l.split(|c: char| "=<>!~;[ ".contains(c))
3218                    .next()
3219                    .map(normalise)
3220            })
3221            .collect(),
3222    )
3223}
3224
3225/// The notes ref of audit records: local, never pushed, never a stamp.
3226pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
3227const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
3228/// How long a record answers for its lockfiles, in hours.
3229const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
3230/// A report that could not check anything answers for an hour only: an
3231/// offline push is never blocked, and the audit is tried again soon.
3232const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
3233/// The greengate that writes a record, the header's last field. An
3234/// unchecked record answers only to the version that wrote it: the next one
3235/// may have a route that can check (f03).
3236const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");
3237
3238/// Is `check` one of the dependency audits?
3239pub fn is_audit(check: &str) -> bool {
3240    check.starts_with("pre-push-audit-")
3241}
3242
3243/// The files (by name) whose content an audit's branch-mode report depends
3244/// on. A release reads the manifests too (its dev-only split), so a release
3245/// record is keyed by the whole tree instead. audit-js splits on a branch
3246/// too, so its branch key names `package.json`.
3247fn inputs_of(check: &str) -> &'static [&'static str] {
3248    match check {
3249        "pre-push-audit-rust" => &["Cargo.lock"],
3250        "pre-push-audit-js" => &[
3251            "package-lock.json",
3252            "pnpm-lock.yaml",
3253            "pnpm-workspace.yaml",
3254            // The dev/prod split reads the manifests (f189).
3255            "package.json",
3256        ],
3257        "pre-push-audit-go" => &["go.sum", "go.mod"],
3258        "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
3259        _ => &[],
3260    }
3261}
3262
3263/// The stakes a push's audit is judged and recorded under.
3264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3265enum AuditMode {
3266    /// A branch push: findings warn.
3267    Branch,
3268    /// A push carrying a `v*` tag: shipped vulnerabilities block.
3269    Release,
3270}
3271
3272impl AuditMode {
3273    fn of(refs: &[PushRef]) -> AuditMode {
3274        if releasing(refs) {
3275            AuditMode::Release
3276        } else {
3277            AuditMode::Branch
3278        }
3279    }
3280}
3281
3282/// What an audit concluded before the push's stakes were applied: what
3283/// `conclude_waivable` judges, and what a record keeps so a later push can
3284/// judge it again against that day's waivers and that push (ADR-0018).
3285#[derive(Debug, Clone, PartialEq, Eq)]
3286struct Concluded {
3287    tool: String,
3288    report: Report,
3289    full: String,
3290    waivable: bool,
3291    /// False when part of the audit did not answer (a timeout, a batch that
3292    /// never ran): such a result is never recorded, so the next push audits
3293    /// again instead of replaying a gap for a day.
3294    complete: bool,
3295}
3296
3297/// How one ecosystem's audit ended: with a report to judge, or before it had
3298/// one.
3299enum Ran {
3300    Concluded(Concluded),
3301    /// Nothing to audit here (no lockfile).
3302    Inert,
3303    /// It could not run: no tool, or a tool that would not start.
3304    Unavailable,
3305}
3306
3307/// A record waiting for the hook to decide it may be written: only where the
3308/// working tree is the keyed tip (the tools read the working tree).
3309#[derive(Debug, Clone)]
3310pub struct Pending {
3311    pub tip: String,
3312    material: String,
3313    body: String,
3314}
3315
3316/// One push's audit bookkeeping, owned by the hook and lent to each audit on
3317/// `Ctx`: the records the audits produced, and the reads both the refusal and
3318/// the replay ask for (each costs a git spawn while git holds the
3319/// connection open).
3320#[derive(Default)]
3321pub struct Ledger {
3322    pending: std::sync::Mutex<Vec<Pending>>,
3323    peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
3324    fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
3325}
3326
3327impl Ledger {
3328    /// The records this push's audits produced, handed to the hook.
3329    pub fn take_pending(&self) -> Vec<Pending> {
3330        std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
3331    }
3332
3333    /// `oid` peeled to its commit, asked of git once per push.
3334    fn peel(&self, oid: &str) -> Option<String> {
3335        if let Some(known) = self
3336            .peeled
3337            .lock()
3338            .unwrap_or_else(|e| e.into_inner())
3339            .get(oid)
3340        {
3341            return known.clone();
3342        }
3343        let commit =
3344            crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
3345        self.peeled
3346            .lock()
3347            .unwrap_or_else(|e| e.into_inner())
3348            .insert(oid.to_string(), commit.clone());
3349        commit
3350    }
3351
3352    /// The pushed commits: every non-deleting ref's tip, peeled to its commit.
3353    fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
3354        let mut commits: Vec<String> = refs
3355            .iter()
3356            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
3357            .filter_map(|r| self.peel(&r.local_oid))
3358            .collect();
3359        commits.sort();
3360        commits.dedup();
3361        commits
3362    }
3363}
3364
3365/// Write `pending` as a note on the blob of its key text. A failure is named
3366/// for the caller to report: the next push then owes the audit again.
3367pub fn write_pending(pending: &Pending) -> Result<(), String> {
3368    // `stdout_piped` keeps git's trailing newline; a key with one names no
3369    // object, and `notes add` would refuse it.
3370    let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
3371        .map(|k| k.trim().to_string())
3372        .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
3373    let written = crate::git::succeeds(&[
3374        "notes",
3375        "--ref",
3376        AUDIT_REF,
3377        "add",
3378        "-f",
3379        "-m",
3380        &pending.body,
3381        &key,
3382    ]);
3383    if written {
3384        Ok(())
3385    } else {
3386        Err(format!("git refused to write the audit record {key}"))
3387    }
3388}
3389
3390/// The text a record is keyed by (the key is its blob's oid).
3391fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
3392    // audit-js judges the production split in both modes since f189: its
3393    // keys carry a revision line, so no record from the whole-tree verdict
3394    // (or from a release that recorded an unanswered split) replays.
3395    let split = if check == "pre-push-audit-js" {
3396        "split\n"
3397    } else {
3398        ""
3399    };
3400    match mode {
3401        AuditMode::Release => {
3402            let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
3403            Some(format!("{AUDIT_FORMAT}\n{check}\n{split}release\n{tree}\n"))
3404        }
3405        AuditMode::Branch => {
3406            let names = inputs_of(check);
3407            let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
3408            let mut lines: Vec<String> = listing
3409                .lines()
3410                .filter_map(|entry| {
3411                    let (meta, path) = entry.split_once('\t')?;
3412                    let blob = meta.split_whitespace().nth(2)?;
3413                    let base = path.rsplit('/').next().unwrap_or(path);
3414                    names.contains(&base).then(|| format!("{path} {blob}"))
3415                })
3416                .collect();
3417            lines.sort();
3418            Some(format!(
3419                "{AUDIT_FORMAT}\n{check}\n{split}branch\n{}\n",
3420                lines.join("\n")
3421            ))
3422        }
3423    }
3424}
3425
3426fn now_secs() -> i64 {
3427    std::time::SystemTime::now()
3428        .duration_since(std::time::UNIX_EPOCH)
3429        .map(|d| d.as_secs() as i64)
3430        .unwrap_or(0)
3431}
3432
3433fn class_of(report: &Report) -> &'static str {
3434    match report {
3435        Report::Clean => "clean",
3436        Report::Advisories(_) => "advisories",
3437        Report::Vulnerabilities(_) => "vulnerabilities",
3438        Report::CouldNotCheck => "unchecked",
3439    }
3440}
3441
3442fn render(concluded: &Concluded, at: i64) -> String {
3443    let items: &[String] = match &concluded.report {
3444        Report::Advisories(v) | Report::Vulnerabilities(v) => v,
3445        Report::Clean | Report::CouldNotCheck => &[],
3446    };
3447    let mut body = format!(
3448        "{AUDIT_FORMAT} {at} {} {} {} {WRITER_VERSION}",
3449        class_of(&concluded.report),
3450        u8::from(concluded.waivable),
3451        concluded.tool
3452    );
3453    for item in items {
3454        body.push_str("\nitem ");
3455        body.push_str(item);
3456    }
3457    body.push_str("\n---\n");
3458    body.push_str(&concluded.full);
3459    body
3460}
3461
3462/// A record's time, the greengate that wrote it (None in a record from before
3463/// the version field), and what it concluded.
3464fn parse(body: &str) -> Option<(i64, Option<String>, Concluded)> {
3465    let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
3466    let mut fields = head.split_whitespace();
3467    if fields.next()? != AUDIT_FORMAT {
3468        return None;
3469    }
3470    let at: i64 = fields.next()?.parse().ok()?;
3471    let class = fields.next()?;
3472    let waivable = fields.next()? == "1";
3473    let tool = fields.next()?.to_string();
3474    let writer = fields.next().map(str::to_string);
3475    let (items_part, full) = match rest.split_once("---\n") {
3476        Some((i, full)) => (i, full.to_string()),
3477        None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
3478    };
3479    let items: Vec<String> = items_part
3480        .lines()
3481        .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
3482        .collect();
3483    let report = match class {
3484        "clean" => Report::Clean,
3485        "advisories" => Report::Advisories(items),
3486        "vulnerabilities" => Report::Vulnerabilities(items),
3487        "unchecked" => Report::CouldNotCheck,
3488        _ => return None,
3489    };
3490    Some((
3491        at,
3492        writer,
3493        Concluded {
3494            tool,
3495            report,
3496            full,
3497            waivable,
3498            complete: true,
3499        },
3500    ))
3501}
3502
3503/// The fresh record of `check` for `commit` in this mode, if any.
3504fn fresh_record(
3505    settings: &crate::config::Settings,
3506    check: &str,
3507    mode: AuditMode,
3508    commit: &str,
3509) -> Option<Concluded> {
3510    let material = key_material(check, mode, commit)?;
3511    let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
3512        .trim()
3513        .to_string();
3514    let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
3515    let (at, writer, concluded) = parse(&body)?;
3516    let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
3517        if writer.as_deref() != Some(WRITER_VERSION) {
3518            return None;
3519        }
3520        UNCHECKED_MAX_AGE_SECS
3521    } else {
3522        crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
3523    };
3524    let age = now_secs() - at;
3525    (0..=max_age).contains(&age).then_some(concluded)
3526}
3527
3528/// Does every commit `refs` pushes carry a fresh record of `check`, all the
3529/// same, in this push's mode? The one the push would replay, or None. Asked
3530/// by the refusal and again by the replay, so answered once per push:
3531/// nothing in one hook run writes a record before both have asked.
3532fn fresh_for_refs(
3533    settings: &crate::config::Settings,
3534    ledger: &Ledger,
3535    check: &str,
3536    refs: &[PushRef],
3537) -> Option<Concluded> {
3538    if !crate::gate_stamp::push_stamps_enabled(settings) {
3539        return None;
3540    }
3541    let memo_key = format!(
3542        "{check} {}",
3543        refs.iter()
3544            .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
3545            .collect::<Vec<_>>()
3546            .join(" ")
3547    );
3548    if let Some(known) = ledger
3549        .fresh
3550        .lock()
3551        .unwrap_or_else(|e| e.into_inner())
3552        .get(&memo_key)
3553    {
3554        return known.clone();
3555    }
3556    let mode = AuditMode::of(refs);
3557    let mut found: Option<Concluded> = None;
3558    for commit in ledger.pushed_commits(refs) {
3559        let Some(record) = fresh_record(settings, check, mode, &commit) else {
3560            found = None;
3561            break;
3562        };
3563        if found.as_ref().is_some_and(|prev| *prev != record) {
3564            found = None;
3565            break;
3566        }
3567        found = Some(record);
3568    }
3569    ledger
3570        .fresh
3571        .lock()
3572        .unwrap_or_else(|e| e.into_inner())
3573        .insert(memo_key, found.clone());
3574    found
3575}
3576
3577/// Is `check` owed by a push of `refs`: opted in, and with no fresh record?
3578pub fn owed(
3579    settings: &crate::config::Settings,
3580    ledger: &Ledger,
3581    check: &str,
3582    refs: &[PushRef],
3583) -> bool {
3584    !ledger.pushed_commits(refs).is_empty()
3585        && fresh_for_refs(settings, ledger, check, refs).is_none()
3586}
3587
3588/// Run an audit through its record: replay a fresh one, or run the tool and
3589/// keep what it concluded on the ledger (a tool that never got to a report
3590/// counts as "could not check").
3591fn recorded(
3592    check: &str,
3593    tool: &str,
3594    ctx: &crate::registry::Ctx,
3595    run: fn(&crate::registry::Ctx) -> Ran,
3596) -> Outcome {
3597    let (settings, refs) = (ctx.settings, ctx.push.get());
3598    let mode = AuditMode::of(refs);
3599    let releasing = mode == AuditMode::Release;
3600    if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
3601        common::ok(
3602            settings,
3603            &format!("{tool}: replaying the audit recorded for this push"),
3604        );
3605        return conclude_waivable(
3606            settings,
3607            &record.tool,
3608            record.report,
3609            releasing,
3610            &record.full,
3611            record.waivable,
3612        );
3613    }
3614    let (outcome, concluded) = match run(ctx) {
3615        Ran::Concluded(concluded) => (
3616            conclude_waivable(
3617                settings,
3618                &concluded.tool,
3619                concluded.report.clone(),
3620                releasing,
3621                &concluded.full,
3622                concluded.waivable,
3623            ),
3624            Some(concluded),
3625        ),
3626        Ran::Unavailable => (
3627            Outcome::Unavailable,
3628            Some(Concluded {
3629                tool: tool.to_string(),
3630                report: Report::CouldNotCheck,
3631                full: String::new(),
3632                waivable: false,
3633                complete: true,
3634            }),
3635        ),
3636        Ran::Inert => (Outcome::Inert, None),
3637    };
3638    // A result with a gap is not recorded; an unchecked one is, for an hour.
3639    let concluded = concluded.filter(|concluded| {
3640        concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
3641    });
3642    if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
3643        let body = render(&concluded, now_secs());
3644        let records: Vec<Pending> = ctx
3645            .audits
3646            .pushed_commits(refs)
3647            .into_iter()
3648            .filter_map(|commit| {
3649                key_material(check, mode, &commit).map(|material| Pending {
3650                    tip: commit,
3651                    material,
3652                    body: body.clone(),
3653                })
3654            })
3655            .collect();
3656        ctx.audits
3657            .pending
3658            .lock()
3659            .unwrap_or_else(|e| e.into_inner())
3660            .extend(records);
3661    }
3662    outcome
3663}
3664
3665pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
3666    recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
3667}
3668
3669pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
3670    recorded("pre-push-audit-js", "audit-js", ctx, js_run)
3671}
3672
3673pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
3674    recorded("pre-push-audit-go", "audit-go", ctx, go_run)
3675}
3676
3677pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
3678    recorded("pre-push-audit-python", "audit-python", ctx, python_run)
3679}
3680
3681#[cfg(test)]
3682mod tests {
3683    use super::*;
3684
3685    /// uv projects have no `requirements.txt`, so the venv is the only thing
3686    /// left to audit — and before this, `audit-python` looked for nothing
3687    /// else and reported "the audit did NOT run" forever. Six repositories
3688    /// in one fleet were in exactly that state, one of them carrying 53
3689    /// known vulnerabilities nobody had been told about.
3690    #[test]
3691    fn a_uv_project_is_audited_through_its_venv() {
3692        let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
3693        let _ = std::fs::remove_dir_all(&root);
3694
3695        // Nothing on disk: nothing to audit, and we say so rather than
3696        // inventing a target.
3697        std::fs::create_dir_all(&root).unwrap();
3698        assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
3699
3700        // The posix layout, with the python version DISCOVERED — hard-coding
3701        // `python3.13` would silently stop finding it after an upgrade.
3702        // Joined segment by segment, NOT as one "a/b/c" literal: on Windows
3703        // the literal keeps its forward slashes while the code under test
3704        // returns backslashes, and the test fails on a difference that is
3705        // only in the expectation.
3706        let sp = root
3707            .join(".venv")
3708            .join("lib")
3709            .join("python3.13")
3710            .join("site-packages");
3711        std::fs::create_dir_all(&sp).unwrap();
3712        assert_eq!(
3713            venv_site_packages(root.to_str().unwrap(), None),
3714            Some(sp.to_string_lossy().into_owned())
3715        );
3716
3717        // The Windows layout, which has no version directory at all.
3718        let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
3719        let _ = std::fs::remove_dir_all(&win);
3720        let wsp = win.join(".venv").join("Lib").join("site-packages");
3721        std::fs::create_dir_all(&wsp).unwrap();
3722        assert_eq!(
3723            venv_site_packages(win.to_str().unwrap(), None),
3724            Some(wsp.to_string_lossy().into_owned())
3725        );
3726
3727        let _ = std::fs::remove_dir_all(&root);
3728        let _ = std::fs::remove_dir_all(&win);
3729    }
3730
3731    fn tag(name: &str) -> PushRef {
3732        PushRef {
3733            local_ref: name.to_string(),
3734            local_oid: "a".repeat(40),
3735            remote_ref: name.to_string(),
3736            remote_oid: "0".repeat(40),
3737        }
3738    }
3739
3740    /// `v` + digit gates; a branch, a bare-word tag, or a tag merely
3741    /// starting with the letter v does not.
3742    #[test]
3743    fn pip_audit_rows_name_their_packages_normalised() {
3744        let out = "Name       Version ID                  Fix Versions\n\
3745                   ---------- ------- ------------------- ------------\n\
3746                   Pytest_Cov 4.0.0   GHSA-aaaa-bbbb-cccc 4.1.0\n\
3747                   requests   2.31.0  PYSEC-2023-74       2.31.1\n\
3748                   requests   2.31.0  CVE-2024-35195      2.32.0\n\
3749                   Found 3 known vulnerabilities in 2 packages\n";
3750        let names: Vec<String> = pip_vulnerable_rows(out)
3751            .into_iter()
3752            .map(|(n, _)| n)
3753            .collect();
3754        assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
3755        assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
3756    }
3757
3758    #[test]
3759    fn advisory_ids_are_found_wherever_they_sit() {
3760        let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
3761                    ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
3762        assert_eq!(
3763            advisory_ids(text),
3764            vec![
3765                "CVE-2024-35195",
3766                "GHSA-h3mg-xc3c-68pw",
3767                "GO-2024-2687",
3768                "OSV-2024-12",
3769                "PYSEC-2023-74",
3770                "RUSTSEC-2025-0001"
3771            ]
3772        );
3773    }
3774
3775    #[test]
3776    fn a_waiver_is_reasoned_dated_and_bounded() {
3777        let today = days_from_date("2026-10-05").unwrap();
3778        let w = Waivers::parse(
3779            "# id expires reason\n\
3780             GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
3781             GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
3782             GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
3783             GHSA-jjjj-kkkk-llll 2026-11-01\n\
3784             GHSA-mmmm-nnnn-oooo soon no date\n",
3785            today,
3786        );
3787        assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
3788        assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
3789        assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
3790        assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
3791        assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
3792        assert_eq!(w.problems().len(), 4);
3793        assert_eq!(days_from_date("1970-01-01"), Some(0));
3794        assert_eq!(days_from_date("2026-02-30"), None);
3795        assert!(days_from_date("2028-02-29").is_some());
3796        assert_eq!(days_from_date("2026-13-01"), None);
3797    }
3798
3799    #[test]
3800    fn two_locked_versions_are_two_answers() {
3801        let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
3802                   Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
3803        let ids = vec![
3804            "RUSTSEC-2025-0010".to_string(),
3805            "RUSTSEC-2025-0011".to_string(),
3806        ];
3807        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3808            "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
3809            "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
3810            _ => None,
3811        });
3812        assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
3813        assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
3814    }
3815
3816    #[test]
3817    fn a_pip_row_without_a_nameable_id_is_unwaivable() {
3818        let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
3819        let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
3820        assert!(pip_rows_all_named(named));
3821        assert!(!pip_rows_all_named(unnamed));
3822    }
3823
3824    #[test]
3825    fn a_crate_ships_unless_its_tree_says_otherwise() {
3826        let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
3827                   Crate: app\nID: RUSTSEC-2025-0002\n\
3828                   Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
3829        let ids = vec![
3830            "RUSTSEC-2025-0001".to_string(),
3831            "RUSTSEC-2025-0002".to_string(),
3832            "RUSTSEC-2025-0003".to_string(),
3833            "RUSTSEC-2025-0004".to_string(),
3834        ];
3835        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3836            // Asked by name@version when cargo audit gave the version.
3837            "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
3838            "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
3839            // A tree that says neither: not proof of dev-only.
3840            "odd" => Some("odd v1.0.0\n".into()),
3841            _ => None,
3842        });
3843        // 0003 has no crate, 0004's tree is unclear: unknowns ship.
3844        assert_eq!(
3845            shipped,
3846            vec![
3847                "RUSTSEC-2025-0002",
3848                "RUSTSEC-2025-0003",
3849                "RUSTSEC-2025-0004"
3850            ]
3851        );
3852        assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
3853    }
3854
3855    #[test]
3856    fn a_release_is_a_v_number_tag() {
3857        assert!(releasing(&[tag("refs/tags/v1.6.6")]));
3858        assert!(releasing(&[tag("refs/tags/v2")]));
3859        assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
3860        assert!(!releasing(&[tag("refs/tags/release")]));
3861        assert!(!releasing(&[tag("refs/heads/v1-styles")]));
3862        assert!(!releasing(&[tag("refs/heads/main")]));
3863        // A mixed push gates: the tag is in there.
3864        assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
3865    }
3866
3867    /// ci.yaml's lesson, pinned at the unit level: the ids decide, the exit
3868    /// code only classifies them.
3869    #[test]
3870    fn cargo_audit_ids_decide_not_the_exit_code() {
3871        assert_eq!(
3872            read_cargo_audit(true, "ok, 312 crates checked"),
3873            Report::Clean
3874        );
3875        assert_eq!(
3876            read_cargo_audit(false, "error: couldn't fetch advisory database"),
3877            Report::CouldNotCheck
3878        );
3879        let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
3880        assert_eq!(
3881            read_cargo_audit(true, warn),
3882            Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
3883        );
3884        let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
3885        assert_eq!(
3886            read_cargo_audit(false, vuln),
3887            Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
3888        );
3889        // A lookalike is not an id.
3890        assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
3891    }
3892
3893    /// The real report shape, trimmed from the run that prompted this: two
3894    /// advisories against ONE crate, and one against another.
3895    fn real_report() -> String {
3896        [
3897            "Crate:     paste",
3898            "Version:   1.0.15",
3899            "Warning:   unmaintained",
3900            "ID:        RUSTSEC-2024-0436",
3901            "URL:       https://rustsec.org/advisories/RUSTSEC-2024-0436",
3902            "",
3903            "Crate:     lru",
3904            "Version:   0.12.5",
3905            "Warning:   unsound",
3906            "ID:        RUSTSEC-2026-0253",
3907            "",
3908            "Crate:     lru",
3909            "Version:   0.12.5",
3910            "ID:        RUSTSEC-2026-0002",
3911            "",
3912            "warning: 3 allowed warnings found",
3913        ]
3914        .join("\n")
3915    }
3916
3917    #[test]
3918    fn an_advisory_is_paired_with_its_crate() {
3919        let pairs = ids_with_crates(&real_report());
3920        assert_eq!(
3921            pairs,
3922            vec![
3923                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3924                ("RUSTSEC-2026-0253".into(), Some("lru".into())),
3925                ("RUSTSEC-2026-0002".into(), Some("lru".into())),
3926            ]
3927        );
3928    }
3929
3930    /// A `Crate:` binds to ONE id. An id printed loose reports no crate
3931    /// rather than inheriting whichever block happened to precede it.
3932    #[test]
3933    fn a_loose_id_borrows_no_crate() {
3934        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
3935        assert_eq!(
3936            ids_with_crates(out),
3937            vec![
3938                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3939                ("RUSTSEC-2025-0001".into(), None),
3940            ]
3941        );
3942    }
3943
3944    /// Local crates carry a path; registry crates do not. That is the whole
3945    /// discriminator, and it has to work without knowing the member names.
3946    #[test]
3947    fn only_local_crates_are_named_as_reached() {
3948        let tree =
3949            "lru v0.12.5\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
3950        assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
3951        assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
3952    }
3953
3954    /// End to end on the real report, with the tree calls faked: each id
3955    /// names its crate and the workspace crate that reaches it, and `lru`'s
3956    /// two advisories cost ONE lookup.
3957    #[test]
3958    fn the_warning_names_the_crate_and_what_reaches_it() {
3959        let calls = std::cell::RefCell::new(Vec::new());
3960        let fake = |k: &str| {
3961            calls.borrow_mut().push(k.to_string());
3962            Some(format!(
3963                "{k} v1\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
3964            ))
3965        };
3966        let out = real_report();
3967        let got = attribute(read_cargo_audit(true, &out), &out, fake);
3968        assert_eq!(
3969            got,
3970            Report::Advisories(vec![
3971                "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
3972                "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
3973                "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
3974            ])
3975        );
3976        assert_eq!(
3977            calls.into_inner(),
3978            vec!["paste", "lru"],
3979            "one call per crate"
3980        );
3981    }
3982
3983    /// A lock-file-only crate — an optional dependency of a feature nobody
3984    /// enabled — is reported as such. `cargo audit` reads Cargo.lock, so this
3985    /// is a real and confusing case, and naming it is the point.
3986    #[test]
3987    fn a_crate_outside_the_build_graph_says_so() {
3988        let out = "Crate:     wezterm-input-types\nID:        RUSTSEC-2025-0001";
3989        let got = attribute(read_cargo_audit(true, out), out, |_| {
3990            Some("warning: nothing to print.".into())
3991        });
3992        assert_eq!(
3993            got,
3994            Report::Advisories(vec![
3995                "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
3996            ])
3997        );
3998    }
3999
4000    /// Attribution is a better message, never a gate. A clean report spawns
4001    /// nothing, and a `cargo tree` that cannot run still reports the id.
4002    #[test]
4003    fn attribution_never_changes_the_verdict() {
4004        let spawned = std::cell::Cell::new(false);
4005        let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
4006            spawned.set(true);
4007            None
4008        });
4009        assert_eq!(clean, Report::Clean);
4010        assert!(!spawned.get(), "a clean report must spawn nothing");
4011
4012        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436";
4013        let blind = attribute(read_cargo_audit(false, out), out, |_| None);
4014        assert_eq!(
4015            blind,
4016            Report::Vulnerabilities(vec![
4017                "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
4018            ])
4019        );
4020    }
4021
4022    #[test]
4023    fn npm_audit_summary_decides() {
4024        assert_eq!(
4025            read_npm_audit(true, "found 0 vulnerabilities\n"),
4026            Report::Clean
4027        );
4028        assert_eq!(
4029            read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
4030            Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
4031        );
4032        // npm 7+ dropped the verb: this is what every current npm prints,
4033        // and what read as "never answered" until the parser learned it.
4034        assert_eq!(
4035            read_npm_audit(
4036                false,
4037                "# npm audit report\n\nvite  6.0.0 - 6.1.5\nSeverity: high\n\n\
4038                 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n  npm audit fix\n"
4039            ),
4040            Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
4041        );
4042        assert_eq!(
4043            read_npm_audit(false, "1 vulnerability (1 high)\n"),
4044            Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
4045        );
4046        assert_eq!(
4047            read_npm_audit(true, "up to date, audited 100 packages\n"),
4048            Report::Clean
4049        );
4050        assert_eq!(
4051            read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
4052            Report::CouldNotCheck
4053        );
4054    }
4055
4056    #[test]
4057    fn pnpm_audit_summary_decides() {
4058        assert_eq!(
4059            read_pnpm_audit(true, "No known vulnerabilities found\n"),
4060            Report::Clean
4061        );
4062        // What pnpm prints after its table: the count, then the severities,
4063        // which the finding carries so the warning says how bad.
4064        assert_eq!(
4065            read_pnpm_audit(
4066                false,
4067                "│ More info │ https://github.com/advisories/GHSA-395f │\n\
4068                 └───────────┴──────────────────────────────────────────┘\n\
4069                 107 vulnerabilities found\n\
4070                 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
4071            ),
4072            Report::Vulnerabilities(vec![
4073                "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
4074            ])
4075        );
4076        assert_eq!(
4077            read_pnpm_audit(false, "1 vulnerabilities found\n"),
4078            Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
4079        );
4080        assert_eq!(
4081            read_pnpm_audit(
4082                false,
4083                " ERR_PNPM_AUDIT_BAD_RESPONSE  The audit endpoint responded with 503\n"
4084            ),
4085            Report::CouldNotCheck
4086        );
4087    }
4088
4089    /// The cargo-audit split, spoken in Go: ids decide, the exit code says
4090    /// whether the analysed code is actually affected.
4091    #[test]
4092    fn govulncheck_ids_decide_not_the_exit_code() {
4093        assert_eq!(
4094            read_govulncheck(true, "No vulnerabilities found.\n"),
4095            Report::Clean
4096        );
4097        assert_eq!(
4098            read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
4099            Report::CouldNotCheck
4100        );
4101        // Informational: the module is vulnerable, the analysed code never
4102        // calls it — exit 0, ids present.
4103        assert_eq!(
4104            read_govulncheck(
4105                true,
4106                "=== Informational ===\nVulnerability #1: GO-2023-1840\n  More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
4107            ),
4108            Report::Advisories(vec!["GO-2023-1840".into()])
4109        );
4110        assert_eq!(
4111            read_govulncheck(
4112                false,
4113                "Vulnerability #1: GO-2022-0969\n  Your code calls it.\nGO-2022-0969 again\n"
4114            ),
4115            Report::Vulnerabilities(vec!["GO-2022-0969".into()])
4116        );
4117        // A lookalike is not an id.
4118        assert_eq!(
4119            read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
4120            Report::Clean
4121        );
4122    }
4123
4124    #[test]
4125    fn pip_audit_sentence_decides() {
4126        assert_eq!(
4127            read_pip_audit(true, "No known vulnerabilities found\n"),
4128            Report::Clean
4129        );
4130        assert_eq!(
4131            read_pip_audit(
4132                false,
4133                "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
4134            ),
4135            Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
4136        );
4137        assert_eq!(
4138            read_pip_audit(false, "ERROR: could not resolve\n"),
4139            Report::CouldNotCheck
4140        );
4141    }
4142
4143    fn lock_block(name: Option<&str>, source: &str) -> String {
4144        let mut block = String::from("[[package]]\n");
4145        if let Some(name) = name {
4146            block.push_str(&format!("name = \"{name}\"\n"));
4147        }
4148        block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
4149        block
4150    }
4151
4152    #[test]
4153    fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
4154        let pypi = "{ registry = \"https://pypi.org/simple\" }";
4155        let lock = [
4156            lock_block(Some("Requests"), pypi),
4157            lock_block(
4158                Some("slashed"),
4159                "{ registry = \"https://pypi.org/simple/\" }",
4160            ),
4161            lock_block(
4162                Some("mirror"),
4163                "{ registry = \"https://mirror.example/simple\" }",
4164            ),
4165            lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
4166            lock_block(Some("pathdep"), "{ path = \"../x\" }"),
4167            lock_block(Some("edit"), "{ editable = \".\" }"),
4168            lock_block(Some("virt"), "{ virtual = \".\" }"),
4169            lock_block(Some("twice"), pypi),
4170            lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
4171            lock_block(None, pypi),
4172            "[package.metadata]\nname = \"ignored\"\n".to_string(),
4173        ]
4174        .concat();
4175        let sources = scan_uv_lock(&lock);
4176        let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
4177        assert_eq!(admitted, ["requests", "slashed"]);
4178        assert_eq!(sources.nameless, 1);
4179    }
4180
4181    #[test]
4182    fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
4183        let pypi: std::collections::BTreeSet<String> =
4184            ["numpy", "idna", "requests"].map(String::from).into();
4185        let raw = "\
4186# generated
4187numpy==1.26.4 ; python_full_version < '3.12'
4188numpy==2.1.0 ; python_full_version >= '3.12'
4189numpy==2.1.0 ; sys_platform == 'win32'
4190idna==3.7
4191platform-kernel==0.1.0
4192requests @ https://example.com/r.whl
4193";
4194        let pins = filter_export(raw, &pypi);
4195        assert_eq!(pins.versions, 3);
4196        assert_eq!(pins.batches.len(), 2);
4197        assert_eq!(
4198            pins.batches[0].get("numpy").map(String::as_str),
4199            Some("1.26.4")
4200        );
4201        assert_eq!(
4202            pins.batches[1].get("numpy").map(String::as_str),
4203            Some("2.1.0")
4204        );
4205        assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
4206        assert!(pins.skipped.contains("platform-kernel"));
4207        assert!(pins.unclassified.contains("requests"));
4208    }
4209
4210    /// pip-compile's shape, as homelab's laya-decisions has it (f108).
4211    const HASHED: &str = "\
4212# This file was autogenerated by uv via the following command:
4213#    ./compile-requirements.sh
4214anyio==4.15.1 \\
4215    --hash=sha256:6152 \\
4216    --hash=sha256:9f28
4217    # via
4218    #   starlette
4219idna==3.7 \\
4220    --hash=sha256:aaaa
4221torch==2.14.0+cpu \\
4222    --hash=sha256:bbbb
4223    # via -r requirements.in
4224";
4225
4226    #[test]
4227    fn only_a_fully_hashed_file_skips_the_resolve() {
4228        let pins = hashed_pins_in(HASHED).expect("hashed");
4229        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
4230        // Top-level `==` pins without hashes: their dependencies are unlisted.
4231        assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
4232        let one_unhashed = format!("{HASHED}idna==3.7\n");
4233        assert_eq!(hashed_pins_in(&one_unhashed), None);
4234        let ranged = "requests>=2.0 \\\n    --hash=sha256:cccc\n";
4235        assert_eq!(hashed_pins_in(ranged), None);
4236        let included = format!("-r requirements-upload.txt\n{HASHED}");
4237        assert_eq!(hashed_pins_in(&included), None);
4238        // An index line leaves the set closed: the hashes still pin every
4239        // wheel, and the line is a source the provenance check reads (f142).
4240        let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
4241        assert!(hashed_pins_in(&indexed).is_some());
4242        let editable = format!("-e .\n{HASHED}");
4243        assert_eq!(hashed_pins_in(&editable), None);
4244        // A marked pin is still a closed set: it takes the batch route.
4245        let marked =
4246            format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n    --hash=sha256:dddd\n");
4247        assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
4248        assert_eq!(
4249            hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
4250            None
4251        );
4252        assert_eq!(hashed_pins_in("# fixture\n"), None);
4253        assert_eq!(hashed_pins_in(""), None);
4254    }
4255
4256    #[test]
4257    fn marked_pins_are_stripped_and_their_versions_batched_apart() {
4258        let text = "\
4259six==1.16.0 \\
4260    --hash=sha256:aaaa
4261numpy==1.26.4 ; python_version == '3.9' \\
4262    --hash=sha256:bbbb
4263numpy==2.1.0 ; python_version == '3.12' \\
4264    --hash=sha256:cccc
4265";
4266        let pins = hashed_pins_in(text).expect("hashed");
4267        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
4268        let batches = batches_of(pins.pairs);
4269        assert_eq!(batches.len(), 2);
4270        assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
4271        assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
4272        assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
4273    }
4274
4275    /// pip-audit 2.10.1's output on laya-decisions with `--no-deps
4276    /// --disable-pip`, cut to two rows.
4277    const SKIPPING: &str = "\
4278Found 2 known vulnerabilities in 1 package
4279Name      Version ID              Fix Versions
4280--------- ------- --------------- ------------
4281starlette 0.41.3  PYSEC-2026-1941 0.47.2
4282starlette 0.41.3  PYSEC-2026-1942 0.49.1
4283
4284Name  Skip Reason
4285----- -------------------------------------------------------------------------
4286torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
4287";
4288
4289    #[test]
4290    fn the_skip_table_names_its_packages_and_is_no_finding() {
4291        assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
4292        assert_eq!(
4293            pip_vulnerable_rows(SKIPPING),
4294            vec![
4295                ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
4296                ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
4297            ]
4298        );
4299        assert!(pip_rows_all_named(SKIPPING));
4300        let clean = "No known vulnerabilities found\nName  Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
4301        assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
4302        assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
4303    }
4304
4305    #[test]
4306    fn the_skipped_line_names_three_and_counts_the_rest() {
4307        let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
4308        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
4309        assert_eq!(
4310            skipped_line("", &refs),
4311            "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
4312        );
4313        assert_eq!(
4314            skipped_line("", &refs[..1]),
4315            "audit-python: 1 private/non-PyPI package skipped (a)"
4316        );
4317        let long = "services/laya-decisions/requirements.txt: ";
4318        assert_eq!(
4319            skipped_line(long, &["torch", "triton"]),
4320            format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
4321        );
4322    }
4323
4324    #[test]
4325    fn scrub_names_the_canonical_private_path_too() {
4326        let plain = std::path::Path::new("/var/folders/a/audit-1");
4327        let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
4328        assert_eq!(
4329            scrub_private(
4330                "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
4331                plain,
4332                canonical
4333            ),
4334            "x <tmp>/b and <tmp>/c"
4335        );
4336    }
4337
4338    #[test]
4339    fn production_names_are_never_asked_off_a_release_or_out_of_time() {
4340        let settings = crate::config::Settings::default();
4341        let spent = Budget {
4342            started: std::time::Instant::now(),
4343            limit: Some(std::time::Duration::ZERO),
4344        };
4345        let said = std::cell::RefCell::new(Vec::<String>::new());
4346        let say = |m: &str| said.borrow_mut().push(m.to_string());
4347        let dir = std::env::temp_dir();
4348
4349        let mut off = Production::Never;
4350        assert!(off.names(&settings, &spent, &say).is_none());
4351        assert!(matches!(off, Production::Never), "no release never asks");
4352        assert!(said.borrow().is_empty());
4353
4354        let mut late = Production::Unasked(dir.clone());
4355        assert!(late.names(&settings, &spent, &say).is_none());
4356        assert!(late.names(&settings, &spent, &say).is_none());
4357        assert!(
4358            matches!(late, Production::Asked(None)),
4359            "spent is remembered as unknown"
4360        );
4361
4362        // In time it asks, once: this checkout tracks no uv.lock, so the
4363        // answer is unknown and stays the answer.
4364        let fresh = Budget {
4365            started: std::time::Instant::now(),
4366            limit: None,
4367        };
4368        let mut asked = Production::Unasked(dir);
4369        assert!(asked.names(&settings, &fresh, &say).is_none());
4370        assert!(matches!(asked, Production::Asked(None)));
4371        let said = said.borrow();
4372        assert_eq!(said.len(), 1, "warned once: {said:?}");
4373        assert!(said[0].contains("every finding counts"), "{said:?}");
4374        assert!(said[0].contains("greengate.timeout"), "{said:?}");
4375    }
4376
4377    #[test]
4378    fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
4379        for why in [
4380            "ConnectionError: Max retries exceeded",
4381            "error: request timed out",
4382            "SSL: CERTIFICATE_VERIFY_FAILED",
4383            "Temporary failure in name resolution",
4384        ] {
4385            assert!(pip_audit_next(why).contains("the network"), "{why}");
4386        }
4387        for why in [
4388            "(no output)",
4389            "ModuleNotFoundError: No module named 'pip_audit'",
4390        ] {
4391            assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
4392        }
4393    }
4394
4395    #[test]
4396    fn only_readable_vulnerability_rows_need_the_split() {
4397        let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
4398        assert!(has_rows_to_split(
4399            &Report::Vulnerabilities(vec!["certifi".into()]),
4400            rows
4401        ));
4402        assert!(!has_rows_to_split(
4403            &Report::Vulnerabilities(vec!["x".into()]),
4404            "Found 1\n"
4405        ));
4406        assert!(!has_rows_to_split(&Report::Clean, rows));
4407        assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
4408    }
4409
4410    #[test]
4411    fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
4412        let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
4413        let guard = PrivateDir::create_at(path.clone()).unwrap();
4414        #[cfg(unix)]
4415        {
4416            use std::os::unix::fs::PermissionsExt;
4417            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
4418            assert_eq!(mode & 0o777, 0o700);
4419        }
4420        assert!(PrivateDir::create_at(path.clone()).is_err());
4421        assert!(path.is_dir(), "the refused attempt must leave it alone");
4422        drop(guard);
4423        assert!(!path.exists());
4424    }
4425
4426    // ---- decisions f142: names sent by provenance ----
4427
4428    fn no_include(_: &std::path::Path) -> Option<String> {
4429        None
4430    }
4431
4432    fn whats(sources: &[IndexSource]) -> Vec<(String, String)> {
4433        sources
4434            .iter()
4435            .map(|s| (s.label.clone(), s.what.clone()))
4436            .collect()
4437    }
4438
4439    #[test]
4440    fn a_file_names_its_non_pypi_sources_by_label_and_host() {
4441        let text = "\
4442--extra-index-url https://u:tok@pkgs.example/simple
4443--index-url=https://pypi.org/simple/
4444-f ./wheels
4445--find-links https://wheels.example/list
4446--no-index
4447--trusted-host pkgs.example
4448six==1.16.0
4449";
4450        let sources = file_sources(
4451            text,
4452            "requirements.txt",
4453            std::path::Path::new("."),
4454            &no_include,
4455        );
4456        assert_eq!(
4457            whats(&sources),
4458            [
4459                ("requirements.txt line 1", "pkgs.example"),
4460                ("requirements.txt line 3", "a local path"),
4461                ("requirements.txt line 4", "wheels.example"),
4462                ("requirements.txt line 5", "--no-index"),
4463            ]
4464            .map(|(l, w)| (l.to_string(), w.to_string()))
4465        );
4466        assert!(!format!("{sources:?}").contains("tok"));
4467    }
4468
4469    #[test]
4470    fn a_host_never_carries_its_userinfo() {
4471        assert_eq!(host_of("https://u:p@ss@h.example/simple"), "h.example");
4472        assert_eq!(host_of("u:tok@h.example/x"), "h.example");
4473        assert_eq!(host_of("https://h.example:8443/simple/"), "h.example:8443");
4474        assert_eq!(host_of("https:///simple"), "an index with no host");
4475        // An `@` in the path gives a wrong host, never a credential.
4476        assert!(!host_of("https://u:secret@h.example/simple/@x").contains("secret"));
4477        let escaped = IndexSource::new("a\u{1b}[31mb", "h\nx");
4478        assert_eq!(
4479            (escaped.label.as_str(), escaped.what.as_str()),
4480            ("a\\u{1b}[31mb", "h\\nx")
4481        );
4482    }
4483
4484    #[test]
4485    fn pypi_is_the_lock_routes_registry_with_or_without_its_slash() {
4486        assert!(is_pypi_url("https://pypi.org/simple"));
4487        assert!(is_pypi_url("https://pypi.org/simple/"));
4488        assert!(!is_pypi_url("https://download.pytorch.org/whl/cpu"));
4489        assert!(!is_pypi_url("https://u:tok@pypi.org/simple"));
4490        assert!(is_pypi_source(
4491            "{ registry = \"https://pypi.org/simple/\" }"
4492        ));
4493    }
4494
4495    #[test]
4496    fn includes_are_followed_and_an_unread_one_is_a_source() {
4497        let dir = std::env::temp_dir().join(common::unique_name("f142-includes"));
4498        std::fs::create_dir_all(dir.join("sub")).expect("mkdir");
4499        std::fs::write(dir.join("base.txt"), "-r sub/more.txt\n").expect("write");
4500        std::fs::write(
4501            dir.join("sub/more.txt"),
4502            "--extra-index-url https://private.example/simple\n-c ../base.txt\n",
4503        )
4504        .expect("write");
4505        let text = "-r base.txt\n-r missing.txt\n-r https://example.com/r.txt\nsix==1.16.0\n";
4506        let sources = file_sources(text, "requirements.txt", &dir, &read_include);
4507        assert_eq!(
4508            whats(&sources),
4509            [
4510                // The file's own lines come first, then each include's.
4511                ("requirements.txt line 2", "an unread include"),
4512                ("requirements.txt line 3", "an unread include"),
4513                ("sub/more.txt line 1", "private.example"),
4514            ]
4515            .map(|(l, w)| (l.to_string(), w.to_string()))
4516        );
4517        // A FIFO is never opened: reading it would block with no writer.
4518        #[cfg(unix)]
4519        {
4520            let fifo = dir.join("fifo.txt");
4521            let made = std::process::Command::new(common::program("mkfifo"))
4522                .arg(&fifo)
4523                .status()
4524                .is_ok_and(|s| s.success());
4525            assert!(made, "mkfifo failed: the FIFO case would go unchecked");
4526            assert_eq!(read_include(&fifo), None);
4527            let sources = file_sources("-r fifo.txt\n", "requirements.txt", &dir, &read_include);
4528            assert_eq!(sources.len(), 1);
4529            assert_eq!(read_config(&fifo), ConfigFile::Unread);
4530        }
4531        let _ = std::fs::remove_dir_all(&dir); // best effort: a temp dir
4532    }
4533
4534    #[test]
4535    fn a_direct_reference_is_a_source() {
4536        let text = "-e .\nlib @ git+https://git.example/lib.git\n./pkg.tar.gz\nsix==1.16.0\nnumpy>=1.0 ; python_version < '3.12'\n";
4537        let sources = file_sources(
4538            text,
4539            "requirements.txt",
4540            std::path::Path::new("."),
4541            &no_include,
4542        );
4543        assert_eq!(
4544            whats(&sources),
4545            [
4546                ("requirements.txt line 1", "a direct reference"),
4547                ("requirements.txt line 2", "a direct reference"),
4548                ("requirements.txt line 3", "a direct reference"),
4549            ]
4550            .map(|(l, w)| (l.to_string(), w.to_string()))
4551        );
4552        assert!(!format!("{sources:?}").contains("git.example"));
4553    }
4554
4555    // The config paths are Unix ones (Linux, macOS): on Windows pip reads
4556    // `%APPDATA%\pip\pip.ini`, which this route does not know.
4557    #[cfg(unix)]
4558    #[test]
4559    fn the_environment_and_config_files_are_sources() {
4560        let env = |vars: &'static [(&'static str, &'static str)]| {
4561            move |var: &str| {
4562                vars.iter()
4563                    .find(|(k, _)| *k == var)
4564                    .map(|(_, v)| v.to_string())
4565            }
4566        };
4567        let get = env(&[
4568            (
4569                "PIP_EXTRA_INDEX_URL",
4570                "https://pypi.org/simple https://x.example/simple",
4571            ),
4572            ("PIP_NO_INDEX", "0"),
4573        ]);
4574        assert_eq!(
4575            whats(&env_sources(&get)),
4576            [("PIP_EXTRA_INDEX_URL".to_string(), "x.example".to_string())]
4577        );
4578        for on in ["1", "TRUE", "yes", "On"] {
4579            assert!(pip_true(on), "{on}");
4580        }
4581        for off in ["0", "false", "no", "off", ""] {
4582            assert!(!pip_true(off), "{off}");
4583        }
4584        let conf = "[global]\ntimeout = 5\n[install]\nextra_index_url =\n    https://pypi.org/simple\n    https://u:tok@conf.example/simple\nfind-links: /opt/wheels\n";
4585        assert_eq!(
4586            whats(&config_sources(conf, "~/.pip/pip.conf")),
4587            [
4588                ("~/.pip/pip.conf", "conf.example"),
4589                ("~/.pip/pip.conf", "a local path"),
4590            ]
4591            .map(|(l, w)| (l.to_string(), w.to_string()))
4592        );
4593        // pip's "no config": no file is read at all.
4594        let devnull = env(&[("PIP_CONFIG_FILE", "/dev/null"), ("HOME", "/home/me")]);
4595        assert!(config_paths(&devnull).is_empty());
4596        let home = env(&[
4597            ("HOME", "/home/me"),
4598            ("XDG_CONFIG_DIRS", "/opt/xdg:/etc/xdg"),
4599        ]);
4600        let labels: Vec<String> = config_paths(&home).into_iter().map(|(_, l)| l).collect();
4601        assert!(
4602            labels.contains(&"~/.config/pip/pip.conf".to_string()),
4603            "{labels:?}"
4604        );
4605        assert!(
4606            labels.contains(&"~/.pip/pip.conf".to_string()),
4607            "{labels:?}"
4608        );
4609        assert!(
4610            labels.contains(&"/opt/xdg/pip/pip.conf".to_string()),
4611            "{labels:?}"
4612        );
4613        // An index set only in an XDG_CONFIG_DIRS file, and a config file
4614        // that is there but unreadable.
4615        let read = |path: &std::path::Path| match path.to_str() {
4616            Some("/opt/xdg/pip/pip.conf") => {
4617                ConfigFile::Text("[global]\nindex-url = https://xdg.example/simple\n".into())
4618            }
4619            Some("/home/me/.pip/pip.conf") => ConfigFile::Unread,
4620            _ => ConfigFile::Absent,
4621        };
4622        assert_eq!(
4623            whats(&host_sources(&home, &read)),
4624            [
4625                ("/opt/xdg/pip/pip.conf", "xdg.example"),
4626                ("~/.pip/pip.conf", "an unread config file"),
4627            ]
4628            .map(|(l, w)| (l.to_string(), w.to_string()))
4629        );
4630    }
4631
4632    /// laya-decisions' shape: uv's `# via` and `# from` lines after each pin.
4633    const ANNOTATED: &str = "\
4634# This file was autogenerated by uv via the following command:
4635#    ./compile-requirements.sh
4636anyio==4.15.1 \\
4637    --hash=sha256:6152
4638    # via
4639    #   starlette
4640    # from https://pypi.org/simple
4641six==1.16.0 \\
4642    --hash=sha256:aaaa
4643    # from https://pypi.org/simple/
4644torch==2.14.0+cpu \\
4645    --hash=sha256:bbbb
4646    # via -r requirements.in
4647    # from https://download.pytorch.org/whl/cpu
4648internal-lib==1.0 \\
4649    --hash=sha256:cccc
4650";
4651
4652    #[test]
4653    fn an_annotation_holds_its_name_and_an_unannotated_one_needs_no_source() {
4654        let pins = hashed_pins_in(ANNOTATED).expect("hashed");
4655        assert_eq!(
4656            pins.from.get("torch"),
4657            Some(&vec![Some(
4658                "https://download.pytorch.org/whl/cpu".to_string()
4659            )])
4660        );
4661        assert_eq!(pins.from.get("internal-lib"), Some(&vec![None]));
4662        // No non-PyPI source: torch is held by its annotation alone.
4663        let held = provenance(&pins, &[]);
4664        assert_eq!(held.private, set(&["torch"]));
4665        assert!(held.unproven.is_empty());
4666        let sent: Vec<&str> = held.sent.iter().map(|(n, _)| n.as_str()).collect();
4667        assert_eq!(sent, ["anyio", "internal-lib", "six"]);
4668        // With one: the unannotated name cannot be shown public.
4669        let held = provenance(&pins, &[IndexSource::no_index("PIP_NO_INDEX")]);
4670        assert_eq!(
4671            (held.private, held.unproven),
4672            (set(&["torch"]), set(&["internal-lib"]))
4673        );
4674        // One name pinned twice, one pin from PyPI and one from elsewhere.
4675        let twice = "numpy==1.26.4 ; python_version == '3.9' \\\n    --hash=sha256:a\n    # from https://pypi.org/simple\nnumpy==2.1.0 ; python_version == '3.12' \\\n    --hash=sha256:b\n    # from https://mirror.example/simple\n";
4676        let held = provenance(&hashed_pins_in(twice).expect("hashed"), &[]);
4677        assert_eq!(held.private, set(&["numpy"]));
4678        assert!(held.sent.is_empty());
4679    }
4680
4681    #[test]
4682    fn held_names_are_named_three_at_a_time() {
4683        let names: Vec<String> = ["a", "b", "c", "d\u{7}"].map(String::from).into();
4684        assert_eq!(names_phrase(&names), "(a, b, c +1 more)");
4685        assert_eq!(names_phrase(&names[3..]), "(d\\u{7})");
4686        assert_eq!(names_phrase(&set(&["b", "a"])), "(a, b)");
4687        let sources = [
4688            IndexSource::new("PIP_INDEX_URL", "x.example"),
4689            IndexSource::no_index("pip.conf"),
4690        ];
4691        assert_eq!(
4692            sources_phrase(&sources),
4693            "x.example (PIP_INDEX_URL) +1 more source"
4694        );
4695        assert_eq!(sources_phrase(&sources[1..]), "--no-index (pip.conf)");
4696    }
4697
4698    fn set(names: &[&str]) -> std::collections::BTreeSet<String> {
4699        names.iter().map(|n| n.to_string()).collect()
4700    }
4701
4702    /// Two blocks of laya-decisions' real requirements.txt (hashes cut to
4703    /// two for torch), as `uv pip compile --emit-index-annotation` wrote it.
4704    const LAYA_EXCERPT: &str = "\
4705# This file was autogenerated by uv via the following command:
4706#    ./compile-requirements.sh
4707annotated-doc==0.0.5 \\
4708    --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \\
4709    --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb
4710    # via
4711    #   fastapi
4712    #   typer
4713    # from https://pypi.org/simple
4714torch==2.14.0+cpu \\
4715    --hash=sha256:019463a7566401db8b1ed142026086db8fa680abda49ec41a60a8718d88e891d \\
4716    --hash=sha256:ff2e3a049e4c6d406d2f87acad9b2907d5052a3fa6d0e658b5f6e48d46bae11b
4717    # via
4718    #   laya-decisions (pyproject.toml)
4719    #   laya
4720    # from https://download.pytorch.org/whl/cpu
4721";
4722
4723    #[test]
4724    fn laya_decisions_holds_torch_and_sends_the_rest() {
4725        let pins = hashed_pins_in(LAYA_EXCERPT).expect("hashed");
4726        for sources in [vec![], vec![IndexSource::no_index("PIP_NO_INDEX")]] {
4727            let held = provenance(&pins, &sources);
4728            assert_eq!(held.private, set(&["torch"]));
4729            assert!(held.unproven.is_empty(), "every pin is annotated");
4730            let sent: Vec<&str> = held.sent.iter().map(|(n, _)| n.as_str()).collect();
4731            assert_eq!(sent, ["annotated-doc"]);
4732        }
4733    }
4734
4735    #[test]
4736    fn glued_and_abbreviated_options_are_read_as_pip_reads_them() {
4737        assert_eq!(
4738            option_line("-ihttps://u:tok@h.example/s"),
4739            OptionLine::Index("https://u:tok@h.example/s")
4740        );
4741        assert_eq!(option_line("-rbase.txt"), OptionLine::Include("base.txt"));
4742        assert_eq!(option_line("-fwheels"), OptionLine::FindLinks("wheels"));
4743        assert_eq!(option_line("-e."), OptionLine::Editable);
4744        assert_eq!(
4745            option_line("--extra-index https://x.example/simple"),
4746            OptionLine::Index("https://x.example/simple")
4747        );
4748        assert_eq!(
4749            option_line("--extra=https://x.example/simple"),
4750            OptionLine::Index("https://x.example/simple")
4751        );
4752        // Ambiguous (`--no-index`, `--no-binary`): not taken for either.
4753        assert_eq!(option_line("--no"), OptionLine::Other);
4754        let text = "-ihttps://u:tok@h.example/s\n--mystery-index=https://m.example/simple\n--pre\n";
4755        let sources = file_sources(
4756            text,
4757            "requirements.txt",
4758            std::path::Path::new("."),
4759            &no_include,
4760        );
4761        assert_eq!(
4762            whats(&sources),
4763            [
4764                ("requirements.txt line 1", "h.example"),
4765                ("requirements.txt line 2", "an unparsed option"),
4766            ]
4767            .map(|(l, w)| (l.to_string(), w.to_string()))
4768        );
4769    }
4770
4771    #[test]
4772    fn an_include_chain_past_the_depth_is_unproven_and_its_references_count() {
4773        let files: std::collections::BTreeMap<String, String> = (0..=INCLUDE_DEPTH + 1)
4774            .map(|n| (format!("r{n}.txt"), format!("-r r{}.txt\n", n + 1)))
4775            .chain([(
4776                "refs.txt".to_string(),
4777                "lib @ git+https://git.example/lib\n".to_string(),
4778            )])
4779            .collect();
4780        let read = |path: &std::path::Path| {
4781            let name = path.file_name()?.to_str()?;
4782            files.get(name).cloned()
4783        };
4784        let sources = file_sources(
4785            "-r r0.txt\n-r refs.txt\n",
4786            "requirements.txt",
4787            std::path::Path::new("/x"),
4788            &read,
4789        );
4790        assert_eq!(
4791            whats(&sources),
4792            [
4793                ("refs.txt line 1", "a direct reference"),
4794                (
4795                    &*format!("r{}.txt line 1", INCLUDE_DEPTH - 1),
4796                    "an unread include"
4797                ),
4798            ]
4799            .map(|(l, w)| (l.to_string(), w.to_string()))
4800        );
4801    }
4802
4803    #[test]
4804    fn a_lone_continuation_keeps_the_next_lines_number() {
4805        assert_eq!(
4806            logical_lines("\\\nsix==1\nidna==3\n"),
4807            [(1, " six==1".to_string()), (3, "idna==3".to_string())]
4808        );
4809    }
4810}