Skip to main content

amont_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` for JS, `pip-audit` for Python — each opted in by the
13//! 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, 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.
58fn conclude(
59    settings: &crate::config::Settings,
60    tool: &str,
61    report: Report,
62    releasing: bool,
63    full: &str,
64) -> Outcome {
65    match report {
66        Report::Clean => {
67            common::ok(settings, &format!("{tool}: no known vulnerabilities"));
68            Outcome::Passed
69        }
70        Report::Advisories(ids) => {
71            common::warn(&format!(
72                "{tool}: advisories against the dependency tree (warnings — unmaintained/unsound): {}",
73                ids.join(", ")
74            ));
75            Outcome::Warned
76        }
77        Report::Vulnerabilities(what) => {
78            if releasing {
79                for line in full.lines() {
80                    crate::say!("{line}");
81                }
82                common::fail(&format!(
83                    "{tool}: known vulnerabilities in the dependency tree — a v* tag \
84                     does not ship with these: {}",
85                    what.join(", ")
86                ));
87                Outcome::Failed
88            } else {
89                common::warn(&format!(
90                    "{tool}: known vulnerabilities in the dependency tree ({}) — \
91                     this will BLOCK a v* tag push",
92                    what.join(", ")
93                ));
94                Outcome::Warned
95            }
96        }
97        Report::CouldNotCheck => {
98            common::warn(&format!(
99                "{tool} could not complete — the dependency tree was NOT checked. \
100                 This is not a clean result."
101            ));
102            Outcome::Unavailable
103        }
104    }
105}
106
107/// Is this word a RUSTSEC id? `RUSTSEC-` + 4 digits + `-` + 4 digits.
108fn is_advisory_id(w: &str) -> bool {
109    w.len() == 17
110        && w.starts_with("RUSTSEC-")
111        && w[8..12].bytes().all(|b| b.is_ascii_digit())
112        && w.as_bytes()[12] == b'-'
113        && w[13..17].bytes().all(|b| b.is_ascii_digit())
114}
115
116/// Pair each advisory with the crate it was raised against.
117///
118/// `cargo audit`'s terminal report is blocks — `Crate:` … `ID:` — and the
119/// id alone does not say which crate carries it, let alone which of YOUR
120/// crates depends on that. Answering "is this on the commit path or only in
121/// an opt-in tool?" meant running `cargo tree -i` by hand every time.
122///
123/// A `Crate:` binds to the next `ID:` and is then spent, so an id appearing
124/// outside a block — a summary line, a URL — reports no crate rather than
125/// inheriting the previous block's.
126fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
127    let mut pairs: Vec<(String, Option<String>)> = Vec::new();
128    let mut pending: Option<String> = None;
129    for line in out.lines() {
130        let t = line.trim();
131        if let Some(rest) = t.strip_prefix("Crate:") {
132            pending = rest.split_whitespace().next().map(str::to_string);
133            continue;
134        }
135        if let Some(rest) = t.strip_prefix("ID:") {
136            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
137                pairs.push((id.to_string(), pending.take()));
138                continue;
139            }
140        }
141        // Ids outside a block still count — the older summary-line shapes
142        // and anything cargo audit prints loose.
143        for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
144            pairs.push((w.to_string(), None));
145        }
146    }
147    pairs
148}
149
150/// Which of THIS workspace's crates reach `crate`, read from `cargo tree -i`.
151///
152/// Cargo prints a local package with its path in parentheses and a registry
153/// package without one, which is the only discriminator needed and works in
154/// any repository — the hook cannot know a given workspace's member names.
155///
156/// An empty result is an answer, not a failure: `cargo tree` prints
157/// "nothing to print" for a crate that is in `Cargo.lock` but not in the
158/// build graph. `cargo audit` reads the lock file, so an advisory can name a
159/// crate nothing compiles — an optional dependency of a feature nobody
160/// enabled. Saying so is more useful than naming no crate at all.
161fn local_dependents(tree_out: &str) -> Vec<String> {
162    let mut names: Vec<String> = tree_out
163        .lines()
164        .filter(|l| l.contains(" (/"))
165        .filter_map(|l| {
166            l.split_whitespace()
167                .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
168                .map(str::to_string)
169        })
170        .collect();
171    names.sort();
172    names.dedup();
173    names
174}
175
176/// One advisory, said in full: the id, the crate it is against, and which of
177/// this workspace's crates actually reach it.
178fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
179    match (krate, reaches.is_empty()) {
180        (None, _) => id.to_string(),
181        (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
182        (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
183    }
184}
185
186/// `cargo audit`, ci.yaml's rules verbatim: the RUSTSEC ids decide, the
187/// exit code only says which class they are.
188fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
189    let mut ids: Vec<String> = out
190        .split_whitespace()
191        .filter(|w| {
192            w.len() == 17
193                && w.starts_with("RUSTSEC-")
194                && w[8..12].bytes().all(|b| b.is_ascii_digit())
195                && w.as_bytes()[12] == b'-'
196                && w[13..17].bytes().all(|b| b.is_ascii_digit())
197        })
198        .map(|w| w.to_string())
199        .collect();
200    ids.sort();
201    ids.dedup();
202    match (ids.is_empty(), exit_ok) {
203        (true, true) => Report::Clean,
204        (true, false) => Report::CouldNotCheck,
205        (false, true) => Report::Advisories(ids),
206        (false, false) => Report::Vulnerabilities(ids),
207    }
208}
209
210/// `npm audit`: the summary line decides. A clean tree is `found 0
211/// vulnerabilities` on every npm. A finding is `found N vulnerabilities`
212/// on npm 6 and `N vulnerabilities (a moderate, b high)` — the verb dropped,
213/// `1 vulnerability` in the singular — on npm 7 and later, which is every
214/// npm shipped since 2020. No recognisable summary plus a refusal to exit
215/// clean is a tool that never answered.
216fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
217    let summary = out.lines().rev().map(str::trim).find(|l| {
218        l.contains("vulnerabilit")
219            && (l.starts_with("found ")
220                || l.split_whitespace()
221                    .next()
222                    .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
223    });
224    match summary {
225        Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
226        Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
227        None if exit_ok => Report::Clean,
228        None => Report::CouldNotCheck,
229    }
230}
231
232/// `govulncheck`: the GO- ids decide, the exit code classifies them — the
233/// same split cargo-audit taught. The tool exits non-zero only when the
234/// analysed CODE is affected; ids with a clean exit are the informational
235/// section (vulnerable modules whose functions are never called), which is
236/// advisory-grade. No ids plus a refusal to exit clean is a tool that never
237/// answered (no network, no vulnerability database).
238fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
239    let mut ids: Vec<String> = out
240        .split_whitespace()
241        .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
242        .filter(|w| {
243            w.len() >= 12
244                && w.starts_with("GO-")
245                && w[3..7].bytes().all(|b| b.is_ascii_digit())
246                && w.as_bytes()[7] == b'-'
247                && w[8..].bytes().all(|b| b.is_ascii_digit())
248        })
249        .map(|w| w.to_string())
250        .collect();
251    ids.sort();
252    ids.dedup();
253    match (ids.is_empty(), exit_ok) {
254        (true, true) => Report::Clean,
255        (true, false) => Report::CouldNotCheck,
256        (false, true) => Report::Advisories(ids),
257        (false, false) => Report::Vulnerabilities(ids),
258    }
259}
260
261/// `pip-audit`: its own closing sentence decides.
262fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
263    if out.contains("No known vulnerabilities found") {
264        return Report::Clean;
265    }
266    if let Some(line) = out
267        .lines()
268        .map(str::trim)
269        .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
270    {
271        return Report::Vulnerabilities(vec![line.to_string()]);
272    }
273    if exit_ok {
274        Report::Clean
275    } else {
276        Report::CouldNotCheck
277    }
278}
279
280/// The `site-packages` of the environment this project actually uses, if
281/// one is on disk.
282///
283/// `$VIRTUAL_ENV` first — an activated environment is the one whose imports
284/// are live — then the `.venv` uv and PEP 668 tooling create by convention.
285/// Layout differs by platform: `lib/python3.13/site-packages` everywhere
286/// except Windows, which uses `Lib/site-packages`, so the python-version
287/// directory is discovered rather than guessed.
288fn venv_site_packages(root: &str) -> Option<String> {
289    let candidates = std::env::var_os("VIRTUAL_ENV")
290        .map(std::path::PathBuf::from)
291        .into_iter()
292        .chain(std::iter::once(std::path::Path::new(root).join(".venv")));
293    for venv in candidates {
294        let windows = venv.join("Lib").join("site-packages");
295        if windows.is_dir() {
296            return Some(windows.to_string_lossy().into_owned());
297        }
298        let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
299            continue;
300        };
301        for e in entries.flatten() {
302            if !e.file_name().to_string_lossy().starts_with("python") {
303                continue;
304            }
305            let sp = e.path().join("site-packages");
306            if sp.is_dir() {
307                return Some(sp.to_string_lossy().into_owned());
308            }
309        }
310    }
311    None
312}
313
314/// Run one audit tool from the repo root and read its answer.
315fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
316    let root = common::repo_root();
317    let mut cmd = std::process::Command::new(&argv[0]);
318    cmd.args(&argv[1..])
319        .current_dir(&root)
320        .stdin(std::process::Stdio::null());
321    common::strip_git_env(&mut cmd);
322    let (ran, out) = common::capture_within(settings, &mut cmd)?;
323    match ran {
324        common::Ran::Status(s) => Some((s.success(), out)),
325        common::Ran::TimedOut(budget) => {
326            common::say_timed_out(&argv[0], budget);
327            None
328        }
329    }
330}
331
332pub fn rust(settings: &crate::config::Settings, refs: &[PushRef]) -> Outcome {
333    if !has_lockfile("Cargo.lock") {
334        return Outcome::Inert;
335    }
336    if common::which("cargo-audit").is_none() {
337        common::warn(
338            "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
339             the audit did NOT run",
340        );
341        return Outcome::Unavailable;
342    }
343    let argv = vec![
344        common::program("cargo"),
345        "audit".into(),
346        "--color".into(),
347        "never".into(),
348    ];
349    let Some((exit_ok, out)) = audited(settings, &argv) else {
350        return Outcome::Unavailable;
351    };
352    conclude(
353        settings,
354        "audit-rust",
355        attribute(read_cargo_audit(exit_ok, &out), &out, |krate| {
356            cargo_tree_inverse(settings, krate)
357        }),
358        releasing(refs),
359        &out,
360    )
361}
362
363/// `cargo tree -i <crate>`, or None if it could not be run. Failure here is
364/// never fatal: attribution is an improvement to a message, and an advisory
365/// reported without it is still an advisory reported.
366fn cargo_tree_inverse(settings: &crate::config::Settings, krate: &str) -> Option<String> {
367    let argv = vec![
368        common::program("cargo"),
369        "tree".into(),
370        "--invert".into(),
371        krate.into(),
372        "--edges".into(),
373        "normal".into(),
374        "--color".into(),
375        "never".into(),
376    ];
377    audited(settings, &argv).map(|(_, out)| out)
378}
379
380/// Name the crate behind each advisory, and which of this workspace's crates
381/// reach it.
382///
383/// Deliberately spawns NOTHING on a clean report, which is every run that
384/// matters: the `cargo tree` calls happen once per distinct affected crate,
385/// only when there is already something to say. A hook on the push path does
386/// not pay for a message nobody will read.
387fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
388    match report {
389        Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
390        Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
391        // Clean and CouldNotCheck carry no ids, so there is nothing to
392        // attribute and — the part that matters — nothing to spawn.
393        other => other,
394    }
395}
396
397/// Each id, rewritten with its crate and what reaches it where both are
398/// known. One `cargo tree` per distinct crate, not per advisory: `lru`
399/// carried two advisories in the run that prompted this.
400fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
401    let pairs = ids_with_crates(out);
402    let mut seen: Vec<(String, Vec<String>)> = Vec::new();
403    ids.iter()
404        .map(|id| {
405            let krate = pairs
406                .iter()
407                .find(|(pid, k)| pid == id && k.is_some())
408                .and_then(|(_, k)| k.clone());
409            let Some(k) = krate else {
410                return id.clone();
411            };
412            if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
413                return describe(id, Some(&k), reaches);
414            }
415            let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
416            seen.push((k.clone(), reaches.clone()));
417            describe(id, Some(&k), &reaches)
418        })
419        .collect()
420}
421
422/// Does the repository carry `lockfile` anywhere in its index? An audit
423/// without a resolved tree audits a guess — and one asked about a
424/// repository in another language has nothing to audit at all. That is
425/// `Inert`, not "could not run": the dispatcher asks the same question
426/// from the registry's scope, and this is the answer for a check invoked
427/// by name.
428fn has_lockfile(lockfile: &str) -> bool {
429    crate::tracked_paths()
430        .iter()
431        .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
432}
433
434pub fn js(settings: &crate::config::Settings, refs: &[PushRef]) -> Outcome {
435    if !has_lockfile("package-lock.json") {
436        return Outcome::Inert;
437    }
438    let argv = vec![common::program("npm"), "audit".into()];
439    let Some((exit_ok, out)) = audited(settings, &argv) else {
440        common::warn("audit-js: npm could not run — the audit did NOT run");
441        return Outcome::Unavailable;
442    };
443    conclude(
444        settings,
445        "audit-js",
446        read_npm_audit(exit_ok, &out),
447        releasing(refs),
448        &out,
449    )
450}
451
452pub fn go(settings: &crate::config::Settings, refs: &[PushRef]) -> Outcome {
453    if !has_lockfile("go.sum") {
454        return Outcome::Inert;
455    }
456    if common::which("govulncheck").is_none() {
457        common::warn(
458            "audit-go: govulncheck is not installed \
459             (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
460        );
461        return Outcome::Unavailable;
462    }
463    let argv = vec![common::program("govulncheck"), "./...".into()];
464    let Some((exit_ok, out)) = audited(settings, &argv) else {
465        return Outcome::Unavailable;
466    };
467    conclude(
468        settings,
469        "audit-go",
470        read_govulncheck(exit_ok, &out),
471        releasing(refs),
472        &out,
473    )
474}
475
476pub fn python(settings: &crate::config::Settings, refs: &[PushRef]) -> Outcome {
477    if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
478        return Outcome::Inert;
479    }
480    if common::which("pip-audit").is_none() {
481        common::warn(
482            "audit-python: pip-audit is not installed (pip install pip-audit) — \
483             the audit did NOT run",
484        );
485        return Outcome::Unavailable;
486    }
487    let root = common::repo_root();
488    let argv = if std::path::Path::new(&root)
489        .join("requirements.txt")
490        .exists()
491    {
492        vec![
493            common::program("pip-audit"),
494            "-r".into(),
495            "requirements.txt".into(),
496        ]
497    } else if let Some(site_packages) = venv_site_packages(&root) {
498        // A uv/PEP-621 project has no requirements.txt, and EXPORTING one
499        // does not work either: `uv export` emits the workspace's own
500        // members and any private-index dependency, and pip-audit resolves
501        // a requirements file in a throwaway venv that can reach neither —
502        // it dies on "No matching distribution found". Auditing the
503        // INSTALLED tree resolves nothing, and is the truer question
504        // anyway: these are the versions actually imported.
505        vec![
506            common::program("pip-audit"),
507            "--path".into(),
508            site_packages,
509            // Workspace members are installed editable and are not on
510            // PyPI; without this each one is a line of noise.
511            "--skip-editable".into(),
512        ]
513    } else {
514        common::warn(
515            "audit-python: no requirements.txt, and no virtualenv to audit \
516             (looked at $VIRTUAL_ENV and .venv) — the audit did NOT run",
517        );
518        return Outcome::Unavailable;
519    };
520    let Some((exit_ok, out)) = audited(settings, &argv) else {
521        return Outcome::Unavailable;
522    };
523    conclude(
524        settings,
525        "audit-python",
526        read_pip_audit(exit_ok, &out),
527        releasing(refs),
528        &out,
529    )
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    /// uv projects have no `requirements.txt`, so the venv is the only thing
537    /// left to audit — and before this, `audit-python` looked for nothing
538    /// else and reported "the audit did NOT run" forever. Six repositories
539    /// in one fleet were in exactly that state, one of them carrying 53
540    /// known vulnerabilities nobody had been told about.
541    #[test]
542    fn a_uv_project_is_audited_through_its_venv() {
543        let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
544        let _ = std::fs::remove_dir_all(&root);
545
546        // Nothing on disk: nothing to audit, and we say so rather than
547        // inventing a target.
548        std::fs::create_dir_all(&root).unwrap();
549        assert_eq!(venv_site_packages(root.to_str().unwrap()), None);
550
551        // The posix layout, with the python version DISCOVERED — hard-coding
552        // `python3.13` would silently stop finding it after an upgrade.
553        // Joined segment by segment, NOT as one "a/b/c" literal: on Windows
554        // the literal keeps its forward slashes while the code under test
555        // returns backslashes, and the test fails on a difference that is
556        // only in the expectation.
557        let sp = root
558            .join(".venv")
559            .join("lib")
560            .join("python3.13")
561            .join("site-packages");
562        std::fs::create_dir_all(&sp).unwrap();
563        assert_eq!(
564            venv_site_packages(root.to_str().unwrap()),
565            Some(sp.to_string_lossy().into_owned())
566        );
567
568        // The Windows layout, which has no version directory at all.
569        let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
570        let _ = std::fs::remove_dir_all(&win);
571        let wsp = win.join(".venv").join("Lib").join("site-packages");
572        std::fs::create_dir_all(&wsp).unwrap();
573        assert_eq!(
574            venv_site_packages(win.to_str().unwrap()),
575            Some(wsp.to_string_lossy().into_owned())
576        );
577
578        let _ = std::fs::remove_dir_all(&root);
579        let _ = std::fs::remove_dir_all(&win);
580    }
581
582    fn tag(name: &str) -> PushRef {
583        PushRef {
584            local_ref: name.to_string(),
585            local_oid: "a".repeat(40),
586            remote_ref: name.to_string(),
587            remote_oid: "0".repeat(40),
588        }
589    }
590
591    /// `v` + digit gates; a branch, a bare-word tag, or a tag merely
592    /// starting with the letter v does not.
593    #[test]
594    fn a_release_is_a_v_number_tag() {
595        assert!(releasing(&[tag("refs/tags/v1.6.6")]));
596        assert!(releasing(&[tag("refs/tags/v2")]));
597        assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
598        assert!(!releasing(&[tag("refs/tags/release")]));
599        assert!(!releasing(&[tag("refs/heads/v1-styles")]));
600        assert!(!releasing(&[tag("refs/heads/main")]));
601        // A mixed push gates: the tag is in there.
602        assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
603    }
604
605    /// ci.yaml's lesson, pinned at the unit level: the ids decide, the exit
606    /// code only classifies them.
607    #[test]
608    fn cargo_audit_ids_decide_not_the_exit_code() {
609        assert_eq!(
610            read_cargo_audit(true, "ok, 312 crates checked"),
611            Report::Clean
612        );
613        assert_eq!(
614            read_cargo_audit(false, "error: couldn't fetch advisory database"),
615            Report::CouldNotCheck
616        );
617        let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
618        assert_eq!(
619            read_cargo_audit(true, warn),
620            Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
621        );
622        let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
623        assert_eq!(
624            read_cargo_audit(false, vuln),
625            Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
626        );
627        // A lookalike is not an id.
628        assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
629    }
630
631    /// The real report shape, trimmed from the run that prompted this: two
632    /// advisories against ONE crate, and one against another.
633    fn real_report() -> String {
634        [
635            "Crate:     paste",
636            "Version:   1.0.15",
637            "Warning:   unmaintained",
638            "ID:        RUSTSEC-2024-0436",
639            "URL:       https://rustsec.org/advisories/RUSTSEC-2024-0436",
640            "",
641            "Crate:     lru",
642            "Version:   0.12.5",
643            "Warning:   unsound",
644            "ID:        RUSTSEC-2026-0253",
645            "",
646            "Crate:     lru",
647            "Version:   0.12.5",
648            "ID:        RUSTSEC-2026-0002",
649            "",
650            "warning: 3 allowed warnings found",
651        ]
652        .join("\n")
653    }
654
655    #[test]
656    fn an_advisory_is_paired_with_its_crate() {
657        let pairs = ids_with_crates(&real_report());
658        assert_eq!(
659            pairs,
660            vec![
661                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
662                ("RUSTSEC-2026-0253".into(), Some("lru".into())),
663                ("RUSTSEC-2026-0002".into(), Some("lru".into())),
664            ]
665        );
666    }
667
668    /// A `Crate:` binds to ONE id. An id printed loose reports no crate
669    /// rather than inheriting whichever block happened to precede it.
670    #[test]
671    fn a_loose_id_borrows_no_crate() {
672        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
673        assert_eq!(
674            ids_with_crates(out),
675            vec![
676                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
677                ("RUSTSEC-2025-0001".into(), None),
678            ]
679        );
680    }
681
682    /// Local crates carry a path; registry crates do not. That is the whole
683    /// discriminator, and it has to work without knowing the member names.
684    #[test]
685    fn only_local_crates_are_named_as_reached() {
686        let tree =
687            "lru v0.12.5\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
688        assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
689        assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
690    }
691
692    /// End to end on the real report, with the tree calls faked: each id
693    /// names its crate and the workspace crate that reaches it, and `lru`'s
694    /// two advisories cost ONE lookup.
695    #[test]
696    fn the_warning_names_the_crate_and_what_reaches_it() {
697        let calls = std::cell::RefCell::new(Vec::new());
698        let fake = |k: &str| {
699            calls.borrow_mut().push(k.to_string());
700            Some(format!(
701                "{k} v1\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
702            ))
703        };
704        let out = real_report();
705        let got = attribute(read_cargo_audit(true, &out), &out, fake);
706        assert_eq!(
707            got,
708            Report::Advisories(vec![
709                "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
710                "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
711                "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
712            ])
713        );
714        assert_eq!(
715            calls.into_inner(),
716            vec!["paste", "lru"],
717            "one call per crate"
718        );
719    }
720
721    /// A lock-file-only crate — an optional dependency of a feature nobody
722    /// enabled — is reported as such. `cargo audit` reads Cargo.lock, so this
723    /// is a real and confusing case, and naming it is the point.
724    #[test]
725    fn a_crate_outside_the_build_graph_says_so() {
726        let out = "Crate:     wezterm-input-types\nID:        RUSTSEC-2025-0001";
727        let got = attribute(read_cargo_audit(true, out), out, |_| {
728            Some("warning: nothing to print.".into())
729        });
730        assert_eq!(
731            got,
732            Report::Advisories(vec![
733                "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
734            ])
735        );
736    }
737
738    /// Attribution is a better message, never a gate. A clean report spawns
739    /// nothing, and a `cargo tree` that cannot run still reports the id.
740    #[test]
741    fn attribution_never_changes_the_verdict() {
742        let spawned = std::cell::Cell::new(false);
743        let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
744            spawned.set(true);
745            None
746        });
747        assert_eq!(clean, Report::Clean);
748        assert!(!spawned.get(), "a clean report must spawn nothing");
749
750        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436";
751        let blind = attribute(read_cargo_audit(false, out), out, |_| None);
752        assert_eq!(
753            blind,
754            Report::Vulnerabilities(vec![
755                "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
756            ])
757        );
758    }
759
760    #[test]
761    fn npm_audit_summary_decides() {
762        assert_eq!(
763            read_npm_audit(true, "found 0 vulnerabilities\n"),
764            Report::Clean
765        );
766        assert_eq!(
767            read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
768            Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
769        );
770        // npm 7+ dropped the verb: this is what every current npm prints,
771        // and what read as "never answered" until the parser learned it.
772        assert_eq!(
773            read_npm_audit(
774                false,
775                "# npm audit report\n\nvite  6.0.0 - 6.1.5\nSeverity: high\n\n\
776                 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n  npm audit fix\n"
777            ),
778            Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
779        );
780        assert_eq!(
781            read_npm_audit(false, "1 vulnerability (1 high)\n"),
782            Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
783        );
784        assert_eq!(
785            read_npm_audit(true, "up to date, audited 100 packages\n"),
786            Report::Clean
787        );
788        assert_eq!(
789            read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
790            Report::CouldNotCheck
791        );
792    }
793
794    /// The cargo-audit split, spoken in Go: ids decide, the exit code says
795    /// whether the analysed code is actually affected.
796    #[test]
797    fn govulncheck_ids_decide_not_the_exit_code() {
798        assert_eq!(
799            read_govulncheck(true, "No vulnerabilities found.\n"),
800            Report::Clean
801        );
802        assert_eq!(
803            read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
804            Report::CouldNotCheck
805        );
806        // Informational: the module is vulnerable, the analysed code never
807        // calls it — exit 0, ids present.
808        assert_eq!(
809            read_govulncheck(
810                true,
811                "=== Informational ===\nVulnerability #1: GO-2023-1840\n  More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
812            ),
813            Report::Advisories(vec!["GO-2023-1840".into()])
814        );
815        assert_eq!(
816            read_govulncheck(
817                false,
818                "Vulnerability #1: GO-2022-0969\n  Your code calls it.\nGO-2022-0969 again\n"
819            ),
820            Report::Vulnerabilities(vec!["GO-2022-0969".into()])
821        );
822        // A lookalike is not an id.
823        assert_eq!(
824            read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
825            Report::Clean
826        );
827    }
828
829    #[test]
830    fn pip_audit_sentence_decides() {
831        assert_eq!(
832            read_pip_audit(true, "No known vulnerabilities found\n"),
833            Report::Clean
834        );
835        assert_eq!(
836            read_pip_audit(
837                false,
838                "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
839            ),
840            Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
841        );
842        assert_eq!(
843            read_pip_audit(false, "ERROR: could not resolve\n"),
844            Report::CouldNotCheck
845        );
846    }
847}