1use crate::check::Outcome;
26use crate::pushrefs::PushRef;
27
28use super::common;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32enum Report {
33 Clean,
34 Advisories(Vec<String>),
37 Vulnerabilities(Vec<String>),
39 CouldNotCheck,
41}
42
43fn 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
55fn 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 let mut ids = advisory_ids(&what.join(" "));
87 if ids.is_empty() {
88 ids = advisory_ids(full);
89 }
90 let unwaived: Vec<&String> = ids.iter().filter(|id| !waivers.covers(id)).collect();
91 let all_waived = waivable && !ids.is_empty() && unwaived.is_empty();
92 if releasing {
93 if all_waived {
94 common::warn(&format!(
95 "{tool}: known vulnerabilities shipped under a reviewed waiver \
96 ({}) — not blocking this release: {}",
97 waivers.file.unwrap_or(WAIVERS_FILE),
98 ids.iter()
99 .map(|id| waivers.describe(id))
100 .collect::<Vec<_>>()
101 .join("; ")
102 ));
103 return Outcome::Warned;
104 }
105 for line in full.lines() {
106 crate::say!("{line}");
107 }
108 for note in waivers.problems() {
109 common::warn(&format!("{tool}: {note}"));
110 }
111 common::fail(&format!(
112 "{tool}: known vulnerabilities in the dependency tree — a v* tag \
113 does not ship with these: {}{}",
114 what.join(", "),
115 if ids.is_empty() {
116 " (no advisory id to match a waiver against)".to_string()
117 } else {
118 format!(
119 " — not waived: {}",
120 unwaived
121 .iter()
122 .map(|s| s.as_str())
123 .collect::<Vec<_>>()
124 .join(", ")
125 )
126 }
127 ));
128 Outcome::Failed
129 } else if all_waived {
130 common::warn(&format!(
131 "{tool}: known vulnerabilities ({}) — covered by a reviewed waiver \
132 ({}), so a v* tag push will pass while it holds: {}",
133 what.join(", "),
134 waivers.file.unwrap_or(WAIVERS_FILE),
135 ids.iter()
136 .map(|id| waivers.describe(id))
137 .collect::<Vec<_>>()
138 .join("; ")
139 ));
140 Outcome::Warned
141 } else {
142 common::warn(&format!(
143 "{tool}: known vulnerabilities in the dependency tree ({}) — \
144 this will BLOCK a v* tag push",
145 what.join(", ")
146 ));
147 Outcome::Warned
148 }
149 }
150 Report::CouldNotCheck => {
151 common::warn(&format!(
152 "{tool} could not complete — the dependency tree was NOT checked. \
153 This is not a clean result."
154 ));
155 Outcome::Unavailable
156 }
157 }
158}
159
160const WAIVERS_FILE: &str = crate::names::AUDIT_WAIVERS;
162
163const OLD_WAIVERS_FILE: &str = crate::names::old::AUDIT_WAIVERS;
166
167const MAX_WAIVER_DAYS: i64 = 90;
171
172#[derive(Debug)]
174struct Waiver {
175 id: String,
176 expires: String,
177 reason: String,
178 valid: bool,
179}
180
181#[derive(Debug, Default)]
190struct Waivers {
191 entries: Vec<Waiver>,
192 problems: Vec<String>,
193 file: Option<&'static str>,
196}
197
198impl Waivers {
199 fn load(root: &str, today: i64) -> Self {
200 let root = std::path::Path::new(root);
201 let read = |file: &'static str| (file, std::fs::read_to_string(root.join(file)));
202 let (mut file, mut got) = read(WAIVERS_FILE);
203 if matches!(&got, Err(e) if e.kind() == std::io::ErrorKind::NotFound) {
204 (file, got) = read(OLD_WAIVERS_FILE);
205 } else if root.join(OLD_WAIVERS_FILE).exists() {
206 common::warn(&format!(
207 "{OLD_WAIVERS_FILE} is ignored: {WAIVERS_FILE} exists — \
208 delete the old file"
209 ));
210 }
211 match got {
212 Ok(text) => Self {
213 file: Some(file),
214 ..Self::parse(&text, today)
215 },
216 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
217 Err(e) => Self {
218 entries: Vec::new(),
219 problems: vec![format!(
220 "{file} could not be read ({e}) — it waives nothing"
221 )],
222 file: Some(file),
223 },
224 }
225 }
226
227 fn parse(text: &str, today: i64) -> Self {
228 let mut w = Self::default();
229 for line in text.lines().map(str::trim) {
230 if line.is_empty() || line.starts_with('#') {
231 continue;
232 }
233 let mut parts = line.splitn(3, char::is_whitespace);
234 let id = parts.next().unwrap_or_default().to_string();
235 let expires = parts.next().unwrap_or_default().trim().to_string();
236 let reason = parts.next().unwrap_or_default().trim().to_string();
237 let valid = match days_from_date(&expires) {
238 None => {
239 w.problems.push(format!(
240 "waiver for {id} has no readable expiry date (YYYY-MM-DD) — it waives nothing"
241 ));
242 false
243 }
244 Some(_) if reason.is_empty() => {
245 w.problems.push(format!(
246 "waiver for {id} gives no reason — it waives nothing"
247 ));
248 false
249 }
250 Some(d) if d < today => {
251 w.problems
252 .push(format!("waiver for {id} expired on {expires}"));
253 false
254 }
255 Some(d) if d - today > MAX_WAIVER_DAYS => {
256 w.problems.push(format!(
257 "waiver for {id} runs to {expires}, more than {MAX_WAIVER_DAYS} days \
258 ahead — it waives nothing; date it sooner and revisit"
259 ));
260 false
261 }
262 Some(_) => true,
263 };
264 w.entries.push(Waiver {
265 id,
266 expires,
267 reason,
268 valid,
269 });
270 }
271 w
272 }
273
274 fn covers(&self, id: &str) -> bool {
275 self.entries.iter().any(|w| w.valid && w.id == id)
276 }
277
278 fn describe(&self, id: &str) -> String {
279 match self.entries.iter().find(|w| w.valid && w.id == id) {
280 Some(w) => format!("{id} until {} ({})", w.expires, w.reason),
281 None => id.to_string(),
282 }
283 }
284
285 fn problems(&self) -> &[String] {
286 &self.problems
287 }
288}
289
290fn days_from_date(date: &str) -> Option<i64> {
292 let mut it = date.split('-');
293 let (y, m, d): (i64, i64, i64) = (
294 it.next()?.parse().ok()?,
295 it.next()?.parse().ok()?,
296 it.next()?.parse().ok()?,
297 );
298 let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
299 let month_days = [
300 31,
301 if leap { 29 } else { 28 },
302 31,
303 30,
304 31,
305 30,
306 31,
307 31,
308 30,
309 31,
310 30,
311 31,
312 ];
313 if it.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > month_days[(m - 1) as usize] {
314 return None;
315 }
316 let y = if m <= 2 { y - 1 } else { y };
318 let era = if y >= 0 { y } else { y - 399 } / 400;
319 let yoe = y - era * 400;
320 let mp = (m + 9) % 12;
321 let doy = (153 * mp + 2) / 5 + d - 1;
322 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
323 Some(era * 146_097 + doe - 719_468)
324}
325
326fn today() -> i64 {
328 std::time::SystemTime::now()
329 .duration_since(std::time::UNIX_EPOCH)
330 .map(|d| (d.as_secs() / 86_400) as i64)
331 .unwrap_or(0)
332}
333
334fn advisory_ids(text: &str) -> Vec<String> {
337 let mut ids: Vec<String> = text
338 .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
339 .filter(|w| {
340 let parts: Vec<&str> = w.split('-').collect();
341 match parts.as_slice() {
342 ["GHSA", a, b, c] => [a, b, c]
343 .iter()
344 .all(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphanumeric())),
345 ["RUSTSEC" | "GO" | "PYSEC" | "CVE" | "OSV", year, num] => {
346 year.len() == 4
347 && year.bytes().all(|b| b.is_ascii_digit())
348 && !num.is_empty()
349 && num.bytes().all(|b| b.is_ascii_digit())
350 }
351 _ => false,
352 }
353 })
354 .map(str::to_string)
355 .collect();
356 ids.sort();
357 ids.dedup();
358 ids
359}
360
361fn is_advisory_id(w: &str) -> bool {
363 w.len() == 17
364 && w.starts_with("RUSTSEC-")
365 && w[8..12].bytes().all(|b| b.is_ascii_digit())
366 && w.as_bytes()[12] == b'-'
367 && w[13..17].bytes().all(|b| b.is_ascii_digit())
368}
369
370fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
381 let mut pairs: Vec<(String, Option<String>)> = Vec::new();
382 let mut pending: Option<String> = None;
383 for line in out.lines() {
384 let t = line.trim();
385 if let Some(rest) = t.strip_prefix("Crate:") {
386 pending = rest.split_whitespace().next().map(str::to_string);
387 continue;
388 }
389 if let Some(rest) = t.strip_prefix("ID:") {
390 if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
391 pairs.push((id.to_string(), pending.take()));
392 continue;
393 }
394 }
395 for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
398 pairs.push((w.to_string(), None));
399 }
400 }
401 pairs
402}
403
404fn local_dependents(tree_out: &str) -> Vec<String> {
416 let mut names: Vec<String> = tree_out
417 .lines()
418 .filter(|l| l.contains(" (/"))
419 .filter_map(|l| {
420 l.split_whitespace()
421 .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
422 .map(str::to_string)
423 })
424 .collect();
425 names.sort();
426 names.dedup();
427 names
428}
429
430fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
433 match (krate, reaches.is_empty()) {
434 (None, _) => id.to_string(),
435 (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
436 (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
437 }
438}
439
440fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
443 let mut ids: Vec<String> = out
444 .split_whitespace()
445 .filter(|w| {
446 w.len() == 17
447 && w.starts_with("RUSTSEC-")
448 && w[8..12].bytes().all(|b| b.is_ascii_digit())
449 && w.as_bytes()[12] == b'-'
450 && w[13..17].bytes().all(|b| b.is_ascii_digit())
451 })
452 .map(|w| w.to_string())
453 .collect();
454 ids.sort();
455 ids.dedup();
456 match (ids.is_empty(), exit_ok) {
457 (true, true) => Report::Clean,
458 (true, false) => Report::CouldNotCheck,
459 (false, true) => Report::Advisories(ids),
460 (false, false) => Report::Vulnerabilities(ids),
461 }
462}
463
464fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
471 let summary = out.lines().rev().map(str::trim).find(|l| {
472 l.contains("vulnerabilit")
473 && (l.starts_with("found ")
474 || l.split_whitespace()
475 .next()
476 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
477 });
478 match summary {
479 Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
480 Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
481 None if exit_ok => Report::Clean,
482 None => Report::CouldNotCheck,
483 }
484}
485
486fn read_pnpm_audit(exit_ok: bool, out: &str) -> Report {
492 let lines: Vec<&str> = out.lines().map(str::trim).collect();
493 if lines
494 .iter()
495 .any(|l| l.starts_with("No known vulnerabilities found"))
496 {
497 return Report::Clean;
498 }
499 let found = lines.iter().enumerate().rev().find(|(_, l)| {
500 let mut w = l.split_whitespace();
501 w.next()
502 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
503 && w.next().is_some_and(|v| v.starts_with("vulnerabilit"))
504 && w.next() == Some("found")
505 });
506 match found {
507 Some((_, l)) if l.starts_with("0 ") => Report::Clean,
508 Some((i, l)) => {
509 let severity = lines
510 .get(i + 1)
511 .and_then(|n| n.strip_prefix("Severity:"))
512 .map(str::trim);
513 Report::Vulnerabilities(vec![match severity {
514 Some(sev) => format!("{l} ({sev})"),
515 None => l.to_string(),
516 }])
517 }
518 None if exit_ok => Report::Clean,
519 None => Report::CouldNotCheck,
520 }
521}
522
523fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
530 let mut ids: Vec<String> = out
531 .split_whitespace()
532 .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
533 .filter(|w| {
534 w.len() >= 12
535 && w.starts_with("GO-")
536 && w[3..7].bytes().all(|b| b.is_ascii_digit())
537 && w.as_bytes()[7] == b'-'
538 && w[8..].bytes().all(|b| b.is_ascii_digit())
539 })
540 .map(|w| w.to_string())
541 .collect();
542 ids.sort();
543 ids.dedup();
544 match (ids.is_empty(), exit_ok) {
545 (true, true) => Report::Clean,
546 (true, false) => Report::CouldNotCheck,
547 (false, true) => Report::Advisories(ids),
548 (false, false) => Report::Vulnerabilities(ids),
549 }
550}
551
552fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
554 if out.contains("No known vulnerabilities found") {
555 return Report::Clean;
556 }
557 if let Some(line) = out
558 .lines()
559 .map(str::trim)
560 .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
561 {
562 return Report::Vulnerabilities(vec![line.to_string()]);
563 }
564 if exit_ok {
565 Report::Clean
566 } else {
567 Report::CouldNotCheck
568 }
569}
570
571fn venv_site_packages(root: &str, source: Option<&std::path::Path>) -> Option<String> {
580 let source_venv = source
586 .filter(|src| {
587 let answers = source_is_this_commit(src);
588 if !answers {
589 common::warn(
590 "audit-python: the source worktree's virtualenv is not this commit's \
591 (another HEAD, or modified Python manifests) — not auditing it",
592 );
593 }
594 answers
595 })
596 .map(|src| src.join(".venv"));
597 let candidates = std::env::var_os("VIRTUAL_ENV")
598 .map(std::path::PathBuf::from)
599 .into_iter()
600 .chain(std::iter::once(std::path::Path::new(root).join(".venv")))
601 .chain(source_venv);
602 for venv in candidates {
603 let windows = venv.join("Lib").join("site-packages");
604 if windows.is_dir() {
605 return Some(windows.to_string_lossy().into_owned());
606 }
607 let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
608 continue;
609 };
610 for e in entries.flatten() {
611 if !e.file_name().to_string_lossy().starts_with("python") {
612 continue;
613 }
614 let sp = e.path().join("site-packages");
615 if sp.is_dir() {
616 return Some(sp.to_string_lossy().into_owned());
617 }
618 }
619 }
620 None
621}
622
623fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
625 audited_in(settings, argv, std::path::Path::new(&common::repo_root()))
626}
627
628fn audited_in(
630 settings: &crate::config::Settings,
631 argv: &[String],
632 dir: &std::path::Path,
633) -> Option<(bool, String)> {
634 let mut cmd = std::process::Command::new(&argv[0]);
635 cmd.args(&argv[1..])
636 .current_dir(dir)
637 .stdin(std::process::Stdio::null());
638 common::strip_git_env(&mut cmd);
639 let (ran, out) = common::capture_within(settings, &mut cmd)?;
640 match ran {
641 common::Ran::Status(s) => Some((s.success(), out)),
642 common::Ran::TimedOut(budget) => {
643 common::say_timed_out(&argv[0], budget);
644 None
645 }
646 }
647}
648
649fn failure_line(out: &str) -> Option<String> {
655 let lines: Vec<&str> = out
656 .lines()
657 .map(str::trim)
658 .filter(|l| !l.is_empty())
659 .collect();
660 let line = lines
661 .iter()
662 .rev()
663 .find(|l| l.to_ascii_lowercase().contains("error"))
664 .or(lines.last())?;
665 let mut s: String = line.chars().take(200).collect();
666 if line.chars().count() > 200 {
667 s.push('…');
668 }
669 Some(s)
670}
671
672struct Merged {
674 report: Report,
675 full: String,
678 waivable: bool,
679}
680
681fn audit_each_dir(
695 settings: &crate::config::Settings,
696 tool: &str,
697 lockfile: &str,
698 argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
699 read: fn(bool, &str) -> Report,
700 mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
701) -> Option<Merged> {
702 let root = std::path::PathBuf::from(common::repo_root());
703 let dirs = lockfile_dirs(lockfile);
704 let only_root = dirs.len() == 1 && dirs[0].is_empty();
705 let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
706 let mut full = String::new();
707 for dir in &dirs {
708 let path = root.join(dir);
709 let label = if dir.is_empty() { "." } else { dir.as_str() };
710 let label_ids = |ids: Vec<String>| -> Vec<String> {
711 if dir.is_empty() {
712 ids
713 } else {
714 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
715 }
716 };
717 let Some(argv) = argv_in(&path) else {
718 unchecked.push(format!("{label} (nothing to audit there)"));
719 continue;
720 };
721 let (exit_ok, out) = audited_in(settings, &argv, &path)?;
723 match refine(&path, read(exit_ok, &out), &out) {
724 Report::Vulnerabilities(ids) => {
725 vulns.extend(label_ids(ids));
726 if only_root {
727 full.push_str(&out);
728 } else {
729 full.push_str(&format!("── {tool} in {label}\n{out}\n"));
730 }
731 }
732 Report::Advisories(ids) => advisories.extend(label_ids(ids)),
733 Report::CouldNotCheck => unchecked.push(match failure_line(&out) {
734 Some(why) => format!("{label} ({why})"),
735 None => label.to_string(),
736 }),
737 Report::Clean => {}
738 }
739 }
740 if !unchecked.is_empty() {
741 common::warn(&format!(
742 "{tool}: the audit could not answer in {} — NOT checked there",
743 unchecked.join(", ")
744 ));
745 }
746 let report = if !vulns.is_empty() {
747 Report::Vulnerabilities(vulns)
748 } else if !unchecked.is_empty() {
749 Report::CouldNotCheck
750 } else if !advisories.is_empty() {
751 Report::Advisories(advisories)
752 } else {
753 Report::Clean
754 };
755 Some(Merged {
756 report,
757 full,
758 waivable: unchecked.is_empty(),
759 })
760}
761
762fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
763 let (settings, refs) = (ctx.settings, ctx.push.get());
764 if !has_lockfile("Cargo.lock") {
765 return Ran::Inert;
766 }
767 if common::which("cargo-audit").is_none() {
768 common::warn(
769 "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
770 the audit did NOT run",
771 );
772 return Ran::Unavailable;
773 }
774 let argv = vec![
775 common::program("cargo"),
776 "audit".into(),
777 "--color".into(),
778 "never".into(),
779 ];
780 let release = releasing(refs);
781 let Some(merged) = audit_each_dir(
782 settings,
783 "audit-rust",
784 "Cargo.lock",
785 |_| Some(argv.clone()),
786 read_cargo_audit,
787 |dir, mut report, out| {
788 if release {
789 if let Report::Vulnerabilities(ids) = report {
790 let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
791 cargo_tree_shipped(settings, dir, krate)
792 });
793 warn_dev_only("audit-rust", &dev_only);
794 report = if shipped.is_empty() {
795 Report::Clean
796 } else {
797 Report::Vulnerabilities(shipped)
798 };
799 }
800 }
801 attribute(report, out, |krate| {
802 cargo_tree_inverse(settings, dir, krate)
803 })
804 },
805 ) else {
806 return Ran::Unavailable;
807 };
808 Ran::Concluded(Concluded {
809 tool: "audit-rust".to_string(),
810 report: merged.report,
811 full: merged.full,
812 waivable: merged.waivable,
813 })
814}
815
816fn cargo_tree_shipped(
821 settings: &crate::config::Settings,
822 dir: &std::path::Path,
823 spec: &str,
824) -> Option<String> {
825 let argv = vec![
826 common::program("cargo"),
827 "tree".into(),
828 "--invert".into(),
829 spec.into(),
830 "--edges".into(),
831 "normal,build".into(),
832 "--target".into(),
833 "all".into(),
834 "--all-features".into(),
835 "--color".into(),
836 "never".into(),
837 ];
838 audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
841}
842
843fn tree_says_dev_only(tree: &str) -> bool {
847 local_dependents(tree).is_empty() && tree.contains("nothing to print")
848}
849
850fn split_shipped_crates(
854 ids: Vec<String>,
855 out: &str,
856 shipped_tree: impl Fn(&str) -> Option<String>,
857) -> (Vec<String>, Vec<String>) {
858 let specs = ids_with_specs(out);
859 let mut verdicts: Vec<(String, bool)> = Vec::new();
860 let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
861 for id in ids {
862 let spec = specs
863 .iter()
864 .find(|(pid, spec)| *pid == id && spec.is_some())
865 .and_then(|(_, spec)| spec.clone());
866 let ships = match spec {
867 None => true,
868 Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
871 Some((_, v)) => *v,
872 None => {
873 let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
874 verdicts.push((spec, v));
875 v
876 }
877 },
878 };
879 if ships {
880 shipped.push(id);
881 } else {
882 dev_only.push(id);
883 }
884 }
885 (shipped, dev_only)
886}
887
888fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
892 let mut pairs = Vec::new();
893 let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
894 for line in out.lines().map(str::trim) {
895 if let Some(rest) = line.strip_prefix("Crate:") {
896 krate = rest.split_whitespace().next().map(str::to_string);
897 version = None;
898 } else if let Some(rest) = line.strip_prefix("Version:") {
899 version = rest.split_whitespace().next().map(str::to_string);
900 } else if let Some(rest) = line.strip_prefix("ID:") {
901 if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
902 let spec = krate.take().map(|k| match version.take() {
903 Some(v) => format!("{k}@{v}"),
904 None => k,
905 });
906 pairs.push((id.to_string(), spec));
907 }
908 }
909 }
910 pairs
911}
912
913fn warn_dev_only(tool: &str, dev_only: &[String]) {
915 if !dev_only.is_empty() {
916 common::warn(&format!(
917 "{tool}: dev-only, only in development dependencies, which the release does not ship — not blocking: {}",
918 dev_only.join("; ")
919 ));
920 }
921}
922
923fn cargo_tree_inverse(
927 settings: &crate::config::Settings,
928 dir: &std::path::Path,
929 krate: &str,
930) -> Option<String> {
931 let argv = vec![
932 common::program("cargo"),
933 "tree".into(),
934 "--invert".into(),
935 krate.into(),
936 "--edges".into(),
937 "normal".into(),
938 "--color".into(),
939 "never".into(),
940 ];
941 audited_in(settings, &argv, dir).map(|(_, out)| out)
942}
943
944fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
952 match report {
953 Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
954 Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
955 other => other,
958 }
959}
960
961fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
965 let pairs = ids_with_crates(out);
966 let mut seen: Vec<(String, Vec<String>)> = Vec::new();
967 ids.iter()
968 .map(|id| {
969 let krate = pairs
970 .iter()
971 .find(|(pid, k)| pid == id && k.is_some())
972 .and_then(|(_, k)| k.clone());
973 let Some(k) = krate else {
974 return id.clone();
975 };
976 if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
977 return describe(id, Some(&k), reaches);
978 }
979 let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
980 seen.push((k.clone(), reaches.clone()));
981 describe(id, Some(&k), &reaches)
982 })
983 .collect()
984}
985
986fn has_lockfile(lockfile: &str) -> bool {
993 crate::tracked_paths()
994 .iter()
995 .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
996}
997
998fn lockfile_dirs(lockfile: &str) -> Vec<String> {
1003 let mut dirs: Vec<String> = crate::tracked_paths()
1004 .iter()
1005 .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1006 .map(|p| {
1007 p.rsplit_once('/')
1008 .map(|(d, _)| d.to_string())
1009 .unwrap_or_default()
1010 })
1011 .collect();
1012 dirs.sort();
1013 dirs.dedup();
1014 dirs
1015}
1016
1017struct JsAuditor {
1020 lockfile: &'static str,
1021 tool: &'static str,
1022 read: fn(bool, &str) -> Report,
1023 args: fn(&str) -> Vec<String>,
1025 prod_only: &'static str,
1028}
1029
1030fn pnpm_args(dir: &str) -> Vec<String> {
1037 let manifest = if dir.is_empty() {
1038 "pnpm-workspace.yaml".to_string()
1039 } else {
1040 format!("{dir}/pnpm-workspace.yaml")
1041 };
1042 if crate::tracked_paths().contains(&manifest) {
1043 vec![]
1044 } else {
1045 vec!["--ignore-workspace".into()]
1046 }
1047}
1048
1049const JS_AUDITORS: [JsAuditor; 2] = [
1050 JsAuditor {
1051 lockfile: "package-lock.json",
1052 tool: "npm",
1053 read: read_npm_audit,
1054 args: |_| vec![],
1055 prod_only: "--omit=dev",
1056 },
1057 JsAuditor {
1058 lockfile: "pnpm-lock.yaml",
1059 tool: "pnpm",
1060 read: read_pnpm_audit,
1061 args: pnpm_args,
1062 prod_only: "--prod",
1063 },
1064];
1065
1066fn js_run(ctx: &crate::registry::Ctx) -> Ran {
1089 let (settings, refs) = (ctx.settings, ctx.push.get());
1090 let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
1091 .iter()
1092 .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
1093 .collect();
1094 if projects.is_empty() {
1095 return Ran::Inert;
1096 }
1097 let root = std::path::PathBuf::from(common::repo_root());
1098 let release = releasing(refs);
1099 let mut found = Vec::new();
1100 let mut dev_only = Vec::new();
1101 let mut unchecked = Vec::new();
1102 let mut full = String::new();
1103 for (auditor, dir) in &projects {
1104 let label = if dir.is_empty() {
1105 ".".to_string()
1106 } else {
1107 dir.clone()
1108 };
1109 let mut argv = vec![common::program(auditor.tool), "audit".into()];
1110 argv.extend((auditor.args)(dir));
1111 let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
1112 common::warn(&format!(
1113 "audit-js: {} could not run in {label} — the audit did NOT run",
1114 auditor.tool
1115 ));
1116 return Ran::Unavailable;
1117 };
1118 match (auditor.read)(exit_ok, &out) {
1119 Report::Vulnerabilities(what) if release => {
1120 let mut prod = argv.clone();
1121 prod.push(auditor.prod_only.into());
1122 match audited_in(settings, &prod, &root.join(dir))
1123 .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
1124 {
1125 Some((Report::Clean | Report::Advisories(_), _)) => {
1126 dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1127 }
1128 Some((Report::Vulnerabilities(shipped), pout)) => {
1129 found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
1130 full.push_str(&format!(
1131 "── {} audit {} in {label}\n{pout}\n",
1132 auditor.tool, auditor.prod_only
1133 ));
1134 }
1135 Some((Report::CouldNotCheck, _)) | None => {
1136 found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1137 full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1138 }
1139 }
1140 }
1141 Report::Vulnerabilities(what) => {
1142 found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1143 full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1144 }
1145 Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
1146 Report::Clean | Report::Advisories(_) => {}
1147 }
1148 }
1149 if !unchecked.is_empty() {
1150 common::warn(&format!(
1151 "audit-js: the audit could not answer in {} — those projects were NOT checked",
1152 unchecked.join(", ")
1153 ));
1154 }
1155 warn_dev_only("audit-js", &dev_only);
1156 let waivable = unchecked.is_empty();
1157 let report = if !found.is_empty() {
1158 Report::Vulnerabilities(found)
1159 } else if !unchecked.is_empty() {
1160 Report::CouldNotCheck
1161 } else {
1162 Report::Clean
1163 };
1164 Ran::Concluded(Concluded {
1165 tool: "audit-js".to_string(),
1166 report,
1167 full,
1168 waivable,
1169 })
1170}
1171
1172fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1176 let settings = ctx.settings;
1177 if !has_lockfile("go.sum") {
1178 return Ran::Inert;
1179 }
1180 if common::which("govulncheck").is_none() {
1181 common::warn(
1182 "audit-go: govulncheck is not installed \
1183 (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1184 );
1185 return Ran::Unavailable;
1186 }
1187 let argv = vec![common::program("govulncheck"), "./...".into()];
1188 let Some(merged) = audit_each_dir(
1189 settings,
1190 "audit-go",
1191 "go.sum",
1192 |_| Some(argv.clone()),
1193 read_govulncheck,
1194 |_, report, _| report,
1195 ) else {
1196 return Ran::Unavailable;
1197 };
1198 Ran::Concluded(Concluded {
1199 tool: "audit-go".to_string(),
1200 report: merged.report,
1201 full: merged.full,
1202 waivable: merged.waivable,
1203 })
1204}
1205
1206fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1207 let (settings, refs) = (ctx.settings, ctx.push.get());
1208 if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1209 return Ran::Inert;
1210 }
1211 if common::which("pip-audit").is_none() {
1212 common::warn(
1213 "audit-python: pip-audit is not installed (pip install pip-audit) — \
1214 the audit did NOT run",
1215 );
1216 return Ran::Unavailable;
1217 }
1218 let root = common::repo_root();
1219 if !lockfile_dirs("requirements.txt").is_empty() {
1222 let argv = vec![
1223 common::program("pip-audit"),
1224 "-r".into(),
1225 "requirements.txt".into(),
1226 ];
1227 let Some(merged) = audit_each_dir(
1228 settings,
1229 "audit-python",
1230 "requirements.txt",
1231 |_| Some(argv.clone()),
1232 read_pip_audit,
1233 |_, report, _| report,
1234 ) else {
1235 return Ran::Unavailable;
1236 };
1237 let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1240 return Ran::Concluded(Concluded {
1241 tool: "audit-python".to_string(),
1242 report: merged.report,
1243 full: merged.full,
1244 waivable,
1245 });
1246 }
1247 let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1248 vec![
1256 common::program("pip-audit"),
1257 "--path".into(),
1258 site_packages,
1259 "--skip-editable".into(),
1262 ]
1263 } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1264 return python_lock_run(ctx);
1266 } else {
1267 common::warn(
1268 "audit-python: the audit did NOT run — found no requirements.txt,\n \
1269 no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n \
1270 Next: `uv sync`, or install uv so uv.lock can be audited.",
1271 );
1272 return Ran::Unavailable;
1273 };
1274 let Some((exit_ok, out)) = audited(settings, &argv) else {
1275 return Ran::Unavailable;
1276 };
1277 let release = releasing(refs);
1278 let production = if release {
1283 uv_production_names(settings, std::path::Path::new(&root))
1284 } else {
1285 None
1286 };
1287 let (report, waivable) = shipped_only(read_pip_audit(exit_ok, &out), &out, production.as_ref());
1288 Ran::Concluded(Concluded {
1289 tool: "audit-python".to_string(),
1290 report,
1291 full: out,
1292 waivable,
1293 })
1294}
1295
1296fn shipped_only(
1302 mut report: Report,
1303 out: &str,
1304 production: Option<&std::collections::HashSet<String>>,
1305) -> (Report, bool) {
1306 let mut waivable = pip_rows_all_named(out);
1307 if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1308 let rows = pip_vulnerable_rows(out);
1309 if !rows.is_empty() {
1310 let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1311 .into_iter()
1312 .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1313 .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1314 if ships {
1315 s.push(row);
1316 } else {
1317 d.push(row);
1318 }
1319 (s, d)
1320 });
1321 warn_dev_only("audit-python", &dev_only);
1322 waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1323 report = if shipped.is_empty() {
1324 Report::Clean
1325 } else {
1326 Report::Vulnerabilities(shipped)
1327 };
1328 }
1329 }
1330 (report, waivable)
1331}
1332
1333const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1336
1337const WARNING_COLUMNS: usize = 80;
1339
1340const NAMES_SHOWN: usize = 3;
1342
1343struct PrivateDir {
1346 path: std::path::PathBuf,
1347}
1348
1349impl PrivateDir {
1350 fn create() -> std::io::Result<PrivateDir> {
1352 Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1353 }
1354
1355 fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1358 #[cfg(unix)]
1359 let builder = {
1360 let mut unix_builder = std::fs::DirBuilder::new();
1361 std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1362 unix_builder
1363 };
1364 #[cfg(not(unix))]
1365 let builder = std::fs::DirBuilder::new();
1366 builder.create(&path)?;
1367 Ok(PrivateDir { path })
1368 }
1369
1370 fn path(&self) -> &std::path::Path {
1371 &self.path
1372 }
1373}
1374
1375impl Drop for PrivateDir {
1376 fn drop(&mut self) {
1377 let _ = std::fs::remove_dir_all(&self.path); }
1379}
1380
1381struct Budget {
1384 started: std::time::Instant,
1385 limit: Option<std::time::Duration>,
1387}
1388
1389impl Budget {
1390 fn new(settings: &crate::config::Settings) -> Budget {
1391 Budget {
1392 started: std::time::Instant::now(),
1393 limit: Some(common::check_timeout(settings))
1394 .filter(|secs| *secs > 0)
1395 .map(std::time::Duration::from_secs),
1396 }
1397 }
1398
1399 fn spent(&self) -> bool {
1400 self.limit
1401 .is_some_and(|limit| self.started.elapsed() >= limit)
1402 }
1403}
1404
1405#[derive(Debug, Default, PartialEq, Eq)]
1407struct LockSources {
1408 pypi: std::collections::BTreeSet<String>,
1410 nameless: usize,
1412}
1413
1414fn is_pypi_source(source_field: &str) -> bool {
1416 source_field
1417 .split_once("registry = \"")
1418 .and_then(|(_, rest)| rest.split('"').next())
1419 .is_some_and(|url| url.trim_end_matches('/') == PYPI_REGISTRY)
1420}
1421
1422fn scan_uv_lock(text: &str) -> LockSources {
1426 struct Block {
1427 name: Option<String>,
1428 pypi: bool,
1429 }
1430 let mut blocks: Vec<Block> = Vec::new();
1431 let mut top_level = false;
1432 for line in text.lines() {
1433 if line.starts_with('[') {
1434 top_level = line.trim() == "[[package]]";
1435 if top_level {
1436 blocks.push(Block {
1437 name: None,
1438 pypi: false,
1439 });
1440 }
1441 continue;
1442 }
1443 let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1444 continue;
1445 };
1446 if let Some(value) = line.strip_prefix("name = ") {
1447 if block.name.is_none() {
1448 block.name = value.split('"').nth(1).map(normalise);
1449 }
1450 } else if let Some(value) = line.strip_prefix("source = ") {
1451 block.pypi = is_pypi_source(value);
1452 }
1453 }
1454 let mut sources = LockSources::default();
1455 let mut rejected = std::collections::BTreeSet::new();
1456 for block in blocks {
1457 match block.name.filter(|n| !n.is_empty()) {
1458 None => sources.nameless += 1,
1459 Some(name) if block.pypi => {
1460 sources.pypi.insert(name);
1461 }
1462 Some(name) => {
1463 rejected.insert(name);
1464 }
1465 }
1466 }
1467 sources.pypi.retain(|name| !rejected.contains(name));
1468 sources
1469}
1470
1471#[derive(Debug, Default, PartialEq, Eq)]
1473struct ExportPins {
1474 batches: Vec<std::collections::BTreeMap<String, String>>,
1477 versions: usize,
1479 skipped: std::collections::BTreeSet<String>,
1481 unclassified: std::collections::BTreeSet<String>,
1483}
1484
1485fn exact_pin(line: &str) -> Option<(String, String)> {
1488 let spec = line.split(';').next()?.trim();
1489 let (name, version) = spec.split_once("==")?;
1490 let name = name.split('[').next()?.trim();
1491 let version = version.trim();
1492 let name_ok = !name.is_empty()
1493 && name
1494 .chars()
1495 .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1496 let version_ok = !version.is_empty()
1497 && version
1498 .chars()
1499 .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1500 (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1501}
1502
1503fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1504 let mut pins = ExportPins::default();
1505 let mut pairs = std::collections::BTreeSet::new();
1506 for line in raw.lines().map(str::trim) {
1507 if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1508 continue;
1509 }
1510 let name = normalise(
1511 line.split(|c: char| "=<>!~;[ @".contains(c))
1512 .next()
1513 .unwrap_or_default(),
1514 );
1515 if name.is_empty() {
1516 continue;
1517 }
1518 if !pypi.contains(&name) {
1519 pins.skipped.insert(name);
1520 continue;
1521 }
1522 match exact_pin(line) {
1523 Some(pair) => {
1524 pairs.insert(pair);
1525 }
1526 None => {
1527 pins.unclassified.insert(name);
1528 }
1529 }
1530 }
1531 pins.versions = pairs.len();
1532 for (name, version) in pairs {
1533 let slot = pins
1534 .batches
1535 .iter()
1536 .position(|batch| !batch.contains_key(&name));
1537 if let Some(index) = slot {
1538 pins.batches[index].insert(name, version);
1539 } else {
1540 pins.batches
1541 .push(std::collections::BTreeMap::from([(name, version)]));
1542 }
1543 }
1544 pins
1545}
1546
1547fn plural(count: usize, noun: &str) -> String {
1548 if count == 1 {
1549 format!("{count} {noun}")
1550 } else {
1551 format!("{count} {noun}s")
1552 }
1553}
1554
1555fn skipped_line(prefix: &str, names: &[&str]) -> String {
1558 let head = format!(
1559 "audit-python: {prefix}{} skipped",
1560 plural(names.len(), "private/non-PyPI package")
1561 );
1562 for shown in (0..=NAMES_SHOWN.min(names.len())).rev() {
1563 let list: Vec<&str> = names.iter().take(shown).copied().collect();
1564 let more = names.len() - shown;
1565 let detail = match (list.is_empty(), more) {
1566 (true, 0) => String::new(),
1567 (true, _) => format!(" (+{more} more)"),
1568 (false, 0) => format!(" ({})", list.join(", ")),
1569 (false, _) => format!(" ({} +{more} more)", list.join(", ")),
1570 };
1571 let line = format!("{head}{detail}");
1572 if line.chars().count() <= WARNING_COLUMNS || shown == 0 {
1573 return line;
1574 }
1575 }
1576 head
1577}
1578
1579fn clip(text: &str, columns: usize) -> String {
1581 text.chars().take(columns).collect()
1582}
1583
1584fn scrub_private(
1589 text: &str,
1590 private: &std::path::Path,
1591 canonical: Option<std::path::PathBuf>,
1592) -> String {
1593 let plain = private.to_string_lossy();
1594 let mut scrubbed = text.to_string();
1595 if let Some(canonical) = canonical.filter(|c| c != private) {
1596 scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
1597 }
1598 scrubbed.replace(plain.as_ref(), "<tmp>")
1599}
1600
1601struct LockDirAudit {
1603 vulnerabilities: Vec<String>,
1604 advisories: Vec<String>,
1605 full: String,
1606 complete: bool,
1609 waivable: bool,
1610}
1611
1612impl LockDirAudit {
1613 fn unchecked() -> LockDirAudit {
1614 LockDirAudit {
1615 vulnerabilities: Vec::new(),
1616 advisories: Vec::new(),
1617 full: String::new(),
1618 complete: false,
1619 waivable: false,
1620 }
1621 }
1622}
1623
1624fn audit_uv_lock(
1630 settings: &crate::config::Settings,
1631 production: Option<&std::collections::HashSet<String>>,
1632 dir: &str,
1633 budget: &Budget,
1634) -> LockDirAudit {
1635 let root = std::path::PathBuf::from(common::repo_root());
1636 let dir_path = root.join(dir);
1637 let lock_path = if dir.is_empty() {
1638 "uv.lock".to_string()
1639 } else {
1640 format!("{dir}/uv.lock")
1641 };
1642 let prefix = if dir.is_empty() {
1643 String::new()
1644 } else {
1645 format!("{lock_path}: ")
1646 };
1647 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1648 let private = match PrivateDir::create() {
1649 Ok(private) => private,
1650 Err(why) => {
1651 say(&format!(
1652 "no private directory ({}) — did NOT run",
1653 why.kind()
1654 ));
1655 return LockDirAudit::unchecked();
1656 }
1657 };
1658 let scrub = |text: &str| {
1660 scrub_private(
1661 text,
1662 private.path(),
1663 std::fs::canonicalize(private.path()).ok(),
1664 )
1665 };
1666 let export = private.path().join("export.txt");
1667 if budget.spent() {
1668 say("out of time before the export — the audit did NOT run");
1669 return LockDirAudit::unchecked();
1670 }
1671 let argv = vec![
1672 common::program("uv"),
1673 "export".into(),
1674 "--frozen".into(),
1675 "--all-packages".into(),
1676 "--all-groups".into(),
1677 "--all-extras".into(),
1678 "--no-hashes".into(),
1679 "--no-emit-workspace".into(),
1680 "--format".into(),
1681 "requirements-txt".into(),
1682 "-o".into(),
1683 export.to_string_lossy().into_owned(),
1684 ];
1685 let exported = audited_in(settings, &argv, &dir_path);
1686 if !matches!(exported, Some((true, _))) {
1687 let why = exported
1688 .and_then(|(_, out)| failure_line(&scrub(&out)))
1689 .unwrap_or_else(|| "uv did not answer".to_string());
1690 let place = if dir.is_empty() {
1691 "at the repo root".to_string()
1692 } else {
1693 format!("in {dir}")
1694 };
1695 say(&format!(
1696 "uv export failed — the audit did NOT run\n {}\n Next: `uv export --frozen` {place}",
1697 clip(&why, WARNING_COLUMNS - 2)
1698 ));
1699 return LockDirAudit::unchecked();
1700 }
1701 let raw = std::fs::read_to_string(&export);
1702 let _ = std::fs::remove_file(&export); let raw = match raw {
1705 Ok(raw) => raw,
1706 Err(why) => {
1707 say(&format!(
1708 "could not read export.txt ({}) — the audit did NOT run",
1709 why.kind()
1710 ));
1711 return LockDirAudit::unchecked();
1712 }
1713 };
1714 let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
1715 Ok(lock) => lock,
1716 Err(why) => {
1717 say(&format!(
1718 "could not read uv.lock ({}) — the audit did NOT run",
1719 why.kind()
1720 ));
1721 return LockDirAudit::unchecked();
1722 }
1723 };
1724 let sources = scan_uv_lock(&lock);
1725 let pins = filter_export(&raw, &sources.pypi);
1726 if !pins.skipped.is_empty() {
1727 let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
1728 common::warn(&skipped_line(&prefix, &names));
1729 }
1730 let unclassified = pins.unclassified.len() + sources.nameless;
1731 if unclassified > 0 {
1732 let source = if prefix.is_empty() {
1733 " from uv.lock"
1734 } else {
1735 ""
1736 };
1737 say(&format!(
1738 "{} could not be classified{source}; not audited",
1739 plural(unclassified, "package")
1740 ));
1741 }
1742 if pins.batches.is_empty() {
1743 say("no PyPI package to audit — the audit did NOT run");
1744 return LockDirAudit::unchecked();
1745 }
1746 let mut audit = LockDirAudit {
1747 vulnerabilities: Vec::new(),
1748 advisories: Vec::new(),
1749 full: String::new(),
1750 complete: true,
1751 waivable: true,
1752 };
1753 let mut audited = 0;
1754 for (index, batch) in pins.batches.iter().enumerate() {
1755 let file = private.path().join(format!("batch-{index}.txt"));
1756 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
1757 if budget.spent() {
1758 say("out of time; unaudited versions remain — NOT fully checked");
1759 audit.complete = false;
1760 break;
1761 }
1762 if let Err(why) = std::fs::write(&file, body) {
1763 say(&format!(
1764 "could not write a batch file ({}); unaudited versions remain — NOT fully checked",
1765 why.kind()
1766 ));
1767 audit.complete = false;
1768 break;
1769 }
1770 let argv = vec![
1771 common::program("pip-audit"),
1772 "-r".into(),
1773 file.to_string_lossy().into_owned(),
1774 "--no-deps".into(),
1775 "--disable-pip".into(),
1776 ];
1777 let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
1778 audit.complete = false;
1779 break;
1780 };
1781 let out = scrub(&out);
1782 let (report, waivable) = shipped_only(read_pip_audit(exit_ok, &out), &out, production);
1783 audit.waivable &= waivable;
1784 match report {
1785 Report::Vulnerabilities(found) => {
1786 audit.vulnerabilities.extend(found);
1787 audit.full.push_str(&out);
1788 audited += batch.len();
1789 }
1790 Report::Advisories(found) => {
1791 audit.advisories.extend(found);
1792 audited += batch.len();
1793 }
1794 Report::Clean => audited += batch.len(),
1795 Report::CouldNotCheck => {
1796 audit.complete = false;
1797 let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
1798 say(&format!(
1799 "pip-audit could not answer — NOT fully checked\n {}\n Next: check the network, then push again",
1800 clip(&why, WARNING_COLUMNS - 2)
1801 ));
1802 }
1803 }
1804 }
1805 if !audit.complete {
1806 audit.waivable = false;
1807 }
1808 if audited > 0 {
1809 common::ok(
1810 settings,
1811 &format!(
1812 "audit-python: audited {lock_path} ({}, {} skipped)",
1813 plural(audited, "package version"),
1814 pins.skipped.len()
1815 ),
1816 );
1817 }
1818 audit
1819}
1820
1821fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
1825 let (settings, refs) = (ctx.settings, ctx.push.get());
1826 let release = releasing(refs);
1827 let budget = Budget::new(settings);
1828 let root = common::repo_root();
1829 let dirs = lockfile_dirs("uv.lock");
1830 let only_root = dirs.len() == 1 && dirs[0].is_empty();
1831 let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
1832 let mut full = String::new();
1833 let (mut complete, mut waivable) = (true, true);
1834 for dir in &dirs {
1835 let production = if release {
1836 uv_production_names(settings, &std::path::Path::new(&root).join(dir))
1837 } else {
1838 None
1839 };
1840 let audit = audit_uv_lock(settings, production.as_ref(), dir, &budget);
1841 let label = |ids: Vec<String>| -> Vec<String> {
1842 if dir.is_empty() {
1843 ids
1844 } else {
1845 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
1846 }
1847 };
1848 vulnerabilities.extend(label(audit.vulnerabilities));
1849 advisories.extend(label(audit.advisories));
1850 if !audit.full.is_empty() {
1851 if only_root {
1852 full.push_str(&audit.full);
1853 } else {
1854 full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
1855 }
1856 }
1857 complete &= audit.complete;
1858 waivable &= audit.waivable;
1859 }
1860 let report = if !vulnerabilities.is_empty() {
1861 Report::Vulnerabilities(vulnerabilities)
1862 } else if !complete {
1863 return Ran::Unavailable;
1864 } else if !advisories.is_empty() {
1865 Report::Advisories(advisories)
1866 } else {
1867 Report::Clean
1868 };
1869 Ran::Concluded(Concluded {
1870 tool: "audit-python".to_string(),
1871 report,
1872 full,
1873 waivable: waivable && complete,
1874 })
1875}
1876
1877fn source_is_this_commit(source: &std::path::Path) -> bool {
1881 let src = source.to_string_lossy();
1882 let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1883 let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
1884 let unmodified = crate::git::stdout(&[
1885 "-C",
1886 &src,
1887 "status",
1888 "--porcelain",
1889 "--untracked-files=no",
1890 "--",
1891 "*pyproject.toml",
1892 "*uv.lock",
1893 "*requirements*.txt",
1894 ])
1895 .is_some_and(|out| out.trim().is_empty());
1896 here.is_some() && here == there && unmodified
1897}
1898
1899fn normalise(name: &str) -> String {
1901 name.to_ascii_lowercase()
1902 .split(['-', '_', '.'])
1903 .filter(|p| !p.is_empty())
1904 .collect::<Vec<_>>()
1905 .join("-")
1906}
1907
1908fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
1912 let mut rows: Vec<(String, String)> = out
1913 .lines()
1914 .filter_map(|l| {
1915 let cols: Vec<&str> = l.split_whitespace().collect();
1916 let id = cols.get(2)?;
1917 ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
1918 .iter()
1919 .any(|p| id.starts_with(p))
1920 .then(|| (normalise(cols[0]), (*id).to_string()))
1921 })
1922 .collect();
1923 rows.sort();
1924 rows.dedup();
1925 rows
1926}
1927
1928fn pip_rows_all_named(out: &str) -> bool {
1932 out.lines().all(|l| {
1933 let cols: Vec<&str> = l.split_whitespace().collect();
1934 let is_row = cols.len() >= 3
1935 && cols[1].starts_with(|c: char| c.is_ascii_digit())
1936 && cols[2].contains('-')
1937 && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
1938 !is_row || !advisory_ids(cols[2]).is_empty()
1939 })
1940}
1941
1942fn uv_production_names(
1946 settings: &crate::config::Settings,
1947 dir: &std::path::Path,
1948) -> Option<std::collections::HashSet<String>> {
1949 if !has_lockfile("uv.lock") || common::which("uv").is_none() {
1950 return None;
1951 }
1952 let argv = vec![
1953 common::program("uv"),
1954 "export".into(),
1955 "--frozen".into(),
1956 "--all-packages".into(),
1959 "--no-dev".into(),
1960 "--no-default-groups".into(),
1961 "--all-extras".into(),
1963 "--no-hashes".into(),
1964 "--no-emit-workspace".into(),
1965 "--format".into(),
1966 "requirements-txt".into(),
1967 ];
1968 let (ok, out) = audited_in(settings, &argv, dir)?;
1969 if !ok {
1970 return None;
1971 }
1972 Some(
1973 out.lines()
1974 .map(str::trim)
1975 .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
1976 .filter_map(|l| {
1977 l.split(|c: char| "=<>!~;[ ".contains(c))
1978 .next()
1979 .map(normalise)
1980 })
1981 .collect(),
1982 )
1983}
1984
1985pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
1987const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
1988const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
1990const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
1993
1994pub fn is_audit(check: &str) -> bool {
1996 check.starts_with("pre-push-audit-")
1997}
1998
1999fn inputs_of(check: &str) -> &'static [&'static str] {
2003 match check {
2004 "pre-push-audit-rust" => &["Cargo.lock"],
2005 "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
2006 "pre-push-audit-go" => &["go.sum", "go.mod"],
2007 "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
2008 _ => &[],
2009 }
2010}
2011
2012#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2014enum AuditMode {
2015 Branch,
2017 Release,
2019}
2020
2021impl AuditMode {
2022 fn of(refs: &[PushRef]) -> AuditMode {
2023 if releasing(refs) {
2024 AuditMode::Release
2025 } else {
2026 AuditMode::Branch
2027 }
2028 }
2029}
2030
2031#[derive(Debug, Clone, PartialEq, Eq)]
2035struct Concluded {
2036 tool: String,
2037 report: Report,
2038 full: String,
2039 waivable: bool,
2040}
2041
2042enum Ran {
2045 Concluded(Concluded),
2046 Inert,
2048 Unavailable,
2050}
2051
2052#[derive(Debug, Clone)]
2055pub struct Pending {
2056 pub tip: String,
2057 material: String,
2058 body: String,
2059}
2060
2061#[derive(Default)]
2066pub struct Ledger {
2067 pending: std::sync::Mutex<Vec<Pending>>,
2068 peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
2069 fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
2070}
2071
2072impl Ledger {
2073 pub fn take_pending(&self) -> Vec<Pending> {
2075 std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
2076 }
2077
2078 fn peel(&self, oid: &str) -> Option<String> {
2080 if let Some(known) = self
2081 .peeled
2082 .lock()
2083 .unwrap_or_else(|e| e.into_inner())
2084 .get(oid)
2085 {
2086 return known.clone();
2087 }
2088 let commit =
2089 crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
2090 self.peeled
2091 .lock()
2092 .unwrap_or_else(|e| e.into_inner())
2093 .insert(oid.to_string(), commit.clone());
2094 commit
2095 }
2096
2097 fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
2099 let mut commits: Vec<String> = refs
2100 .iter()
2101 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
2102 .filter_map(|r| self.peel(&r.local_oid))
2103 .collect();
2104 commits.sort();
2105 commits.dedup();
2106 commits
2107 }
2108}
2109
2110pub fn write_pending(pending: &Pending) -> Result<(), String> {
2113 let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
2116 .map(|k| k.trim().to_string())
2117 .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
2118 let written = crate::git::succeeds(&[
2119 "notes",
2120 "--ref",
2121 AUDIT_REF,
2122 "add",
2123 "-f",
2124 "-m",
2125 &pending.body,
2126 &key,
2127 ]);
2128 if written {
2129 Ok(())
2130 } else {
2131 Err(format!("git refused to write the audit record {key}"))
2132 }
2133}
2134
2135fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
2137 match mode {
2138 AuditMode::Release => {
2139 let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
2140 Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
2141 }
2142 AuditMode::Branch => {
2143 let names = inputs_of(check);
2144 let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
2145 let mut lines: Vec<String> = listing
2146 .lines()
2147 .filter_map(|entry| {
2148 let (meta, path) = entry.split_once('\t')?;
2149 let blob = meta.split_whitespace().nth(2)?;
2150 let base = path.rsplit('/').next().unwrap_or(path);
2151 names.contains(&base).then(|| format!("{path} {blob}"))
2152 })
2153 .collect();
2154 lines.sort();
2155 Some(format!(
2156 "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
2157 lines.join("\n")
2158 ))
2159 }
2160 }
2161}
2162
2163fn now_secs() -> i64 {
2164 std::time::SystemTime::now()
2165 .duration_since(std::time::UNIX_EPOCH)
2166 .map(|d| d.as_secs() as i64)
2167 .unwrap_or(0)
2168}
2169
2170fn class_of(report: &Report) -> &'static str {
2171 match report {
2172 Report::Clean => "clean",
2173 Report::Advisories(_) => "advisories",
2174 Report::Vulnerabilities(_) => "vulnerabilities",
2175 Report::CouldNotCheck => "unchecked",
2176 }
2177}
2178
2179fn render(concluded: &Concluded, at: i64) -> String {
2180 let items: &[String] = match &concluded.report {
2181 Report::Advisories(v) | Report::Vulnerabilities(v) => v,
2182 Report::Clean | Report::CouldNotCheck => &[],
2183 };
2184 let mut body = format!(
2185 "{AUDIT_FORMAT} {at} {} {} {}",
2186 class_of(&concluded.report),
2187 u8::from(concluded.waivable),
2188 concluded.tool
2189 );
2190 for item in items {
2191 body.push_str("\nitem ");
2192 body.push_str(item);
2193 }
2194 body.push_str("\n---\n");
2195 body.push_str(&concluded.full);
2196 body
2197}
2198
2199fn parse(body: &str) -> Option<(i64, Concluded)> {
2200 let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
2201 let mut fields = head.split_whitespace();
2202 if fields.next()? != AUDIT_FORMAT {
2203 return None;
2204 }
2205 let at: i64 = fields.next()?.parse().ok()?;
2206 let class = fields.next()?;
2207 let waivable = fields.next()? == "1";
2208 let tool = fields.next()?.to_string();
2209 let (items_part, full) = match rest.split_once("---\n") {
2210 Some((i, full)) => (i, full.to_string()),
2211 None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
2212 };
2213 let items: Vec<String> = items_part
2214 .lines()
2215 .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
2216 .collect();
2217 let report = match class {
2218 "clean" => Report::Clean,
2219 "advisories" => Report::Advisories(items),
2220 "vulnerabilities" => Report::Vulnerabilities(items),
2221 "unchecked" => Report::CouldNotCheck,
2222 _ => return None,
2223 };
2224 Some((
2225 at,
2226 Concluded {
2227 tool,
2228 report,
2229 full,
2230 waivable,
2231 },
2232 ))
2233}
2234
2235fn fresh_record(
2237 settings: &crate::config::Settings,
2238 check: &str,
2239 mode: AuditMode,
2240 commit: &str,
2241) -> Option<Concluded> {
2242 let material = key_material(check, mode, commit)?;
2243 let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
2244 .trim()
2245 .to_string();
2246 let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
2247 let (at, concluded) = parse(&body)?;
2248 let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
2249 UNCHECKED_MAX_AGE_SECS
2250 } else {
2251 crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
2252 };
2253 let age = now_secs() - at;
2254 (0..=max_age).contains(&age).then_some(concluded)
2255}
2256
2257fn fresh_for_refs(
2262 settings: &crate::config::Settings,
2263 ledger: &Ledger,
2264 check: &str,
2265 refs: &[PushRef],
2266) -> Option<Concluded> {
2267 if !crate::gate_stamp::push_stamps_enabled(settings) {
2268 return None;
2269 }
2270 let memo_key = format!(
2271 "{check} {}",
2272 refs.iter()
2273 .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
2274 .collect::<Vec<_>>()
2275 .join(" ")
2276 );
2277 if let Some(known) = ledger
2278 .fresh
2279 .lock()
2280 .unwrap_or_else(|e| e.into_inner())
2281 .get(&memo_key)
2282 {
2283 return known.clone();
2284 }
2285 let mode = AuditMode::of(refs);
2286 let mut found: Option<Concluded> = None;
2287 for commit in ledger.pushed_commits(refs) {
2288 let Some(record) = fresh_record(settings, check, mode, &commit) else {
2289 found = None;
2290 break;
2291 };
2292 if found.as_ref().is_some_and(|prev| *prev != record) {
2293 found = None;
2294 break;
2295 }
2296 found = Some(record);
2297 }
2298 ledger
2299 .fresh
2300 .lock()
2301 .unwrap_or_else(|e| e.into_inner())
2302 .insert(memo_key, found.clone());
2303 found
2304}
2305
2306pub fn owed(
2308 settings: &crate::config::Settings,
2309 ledger: &Ledger,
2310 check: &str,
2311 refs: &[PushRef],
2312) -> bool {
2313 !ledger.pushed_commits(refs).is_empty()
2314 && fresh_for_refs(settings, ledger, check, refs).is_none()
2315}
2316
2317fn recorded(
2321 check: &str,
2322 tool: &str,
2323 ctx: &crate::registry::Ctx,
2324 run: fn(&crate::registry::Ctx) -> Ran,
2325) -> Outcome {
2326 let (settings, refs) = (ctx.settings, ctx.push.get());
2327 let mode = AuditMode::of(refs);
2328 let releasing = mode == AuditMode::Release;
2329 if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
2330 common::ok(
2331 settings,
2332 &format!("{tool}: replaying the audit recorded for this push"),
2333 );
2334 return conclude_waivable(
2335 settings,
2336 &record.tool,
2337 record.report,
2338 releasing,
2339 &record.full,
2340 record.waivable,
2341 );
2342 }
2343 let (outcome, concluded) = match run(ctx) {
2344 Ran::Concluded(concluded) => (
2345 conclude_waivable(
2346 settings,
2347 &concluded.tool,
2348 concluded.report.clone(),
2349 releasing,
2350 &concluded.full,
2351 concluded.waivable,
2352 ),
2353 Some(concluded),
2354 ),
2355 Ran::Unavailable => (
2356 Outcome::Unavailable,
2357 Some(Concluded {
2358 tool: tool.to_string(),
2359 report: Report::CouldNotCheck,
2360 full: String::new(),
2361 waivable: false,
2362 }),
2363 ),
2364 Ran::Inert => (Outcome::Inert, None),
2365 };
2366 if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
2367 let body = render(&concluded, now_secs());
2368 let records: Vec<Pending> = ctx
2369 .audits
2370 .pushed_commits(refs)
2371 .into_iter()
2372 .filter_map(|commit| {
2373 key_material(check, mode, &commit).map(|material| Pending {
2374 tip: commit,
2375 material,
2376 body: body.clone(),
2377 })
2378 })
2379 .collect();
2380 ctx.audits
2381 .pending
2382 .lock()
2383 .unwrap_or_else(|e| e.into_inner())
2384 .extend(records);
2385 }
2386 outcome
2387}
2388
2389pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
2390 recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
2391}
2392
2393pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
2394 recorded("pre-push-audit-js", "audit-js", ctx, js_run)
2395}
2396
2397pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
2398 recorded("pre-push-audit-go", "audit-go", ctx, go_run)
2399}
2400
2401pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
2402 recorded("pre-push-audit-python", "audit-python", ctx, python_run)
2403}
2404
2405#[cfg(test)]
2406mod tests {
2407 use super::*;
2408
2409 #[test]
2415 fn a_uv_project_is_audited_through_its_venv() {
2416 let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
2417 let _ = std::fs::remove_dir_all(&root);
2418
2419 std::fs::create_dir_all(&root).unwrap();
2422 assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
2423
2424 let sp = root
2431 .join(".venv")
2432 .join("lib")
2433 .join("python3.13")
2434 .join("site-packages");
2435 std::fs::create_dir_all(&sp).unwrap();
2436 assert_eq!(
2437 venv_site_packages(root.to_str().unwrap(), None),
2438 Some(sp.to_string_lossy().into_owned())
2439 );
2440
2441 let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
2443 let _ = std::fs::remove_dir_all(&win);
2444 let wsp = win.join(".venv").join("Lib").join("site-packages");
2445 std::fs::create_dir_all(&wsp).unwrap();
2446 assert_eq!(
2447 venv_site_packages(win.to_str().unwrap(), None),
2448 Some(wsp.to_string_lossy().into_owned())
2449 );
2450
2451 let _ = std::fs::remove_dir_all(&root);
2452 let _ = std::fs::remove_dir_all(&win);
2453 }
2454
2455 fn tag(name: &str) -> PushRef {
2456 PushRef {
2457 local_ref: name.to_string(),
2458 local_oid: "a".repeat(40),
2459 remote_ref: name.to_string(),
2460 remote_oid: "0".repeat(40),
2461 }
2462 }
2463
2464 #[test]
2467 fn pip_audit_rows_name_their_packages_normalised() {
2468 let out = "Name Version ID Fix Versions\n\
2469 ---------- ------- ------------------- ------------\n\
2470 Pytest_Cov 4.0.0 GHSA-aaaa-bbbb-cccc 4.1.0\n\
2471 requests 2.31.0 PYSEC-2023-74 2.31.1\n\
2472 requests 2.31.0 CVE-2024-35195 2.32.0\n\
2473 Found 3 known vulnerabilities in 2 packages\n";
2474 let names: Vec<String> = pip_vulnerable_rows(out)
2475 .into_iter()
2476 .map(|(n, _)| n)
2477 .collect();
2478 assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
2479 assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
2480 }
2481
2482 #[test]
2483 fn advisory_ids_are_found_wherever_they_sit() {
2484 let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
2485 ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
2486 assert_eq!(
2487 advisory_ids(text),
2488 vec![
2489 "CVE-2024-35195",
2490 "GHSA-h3mg-xc3c-68pw",
2491 "GO-2024-2687",
2492 "OSV-2024-12",
2493 "PYSEC-2023-74",
2494 "RUSTSEC-2025-0001"
2495 ]
2496 );
2497 }
2498
2499 #[test]
2500 fn a_waiver_is_reasoned_dated_and_bounded() {
2501 let today = days_from_date("2026-10-05").unwrap();
2502 let w = Waivers::parse(
2503 "# id expires reason\n\
2504 GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
2505 GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
2506 GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
2507 GHSA-jjjj-kkkk-llll 2026-11-01\n\
2508 GHSA-mmmm-nnnn-oooo soon no date\n",
2509 today,
2510 );
2511 assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
2512 assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
2513 assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
2514 assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
2515 assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
2516 assert_eq!(w.problems().len(), 4);
2517 assert_eq!(days_from_date("1970-01-01"), Some(0));
2518 assert_eq!(days_from_date("2026-02-30"), None);
2519 assert!(days_from_date("2028-02-29").is_some());
2520 assert_eq!(days_from_date("2026-13-01"), None);
2521 }
2522
2523 #[test]
2524 fn two_locked_versions_are_two_answers() {
2525 let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
2526 Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
2527 let ids = vec![
2528 "RUSTSEC-2025-0010".to_string(),
2529 "RUSTSEC-2025-0011".to_string(),
2530 ];
2531 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
2532 "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
2533 "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
2534 _ => None,
2535 });
2536 assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
2537 assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
2538 }
2539
2540 #[test]
2541 fn a_pip_row_without_a_nameable_id_is_unwaivable() {
2542 let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
2543 let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
2544 assert!(pip_rows_all_named(named));
2545 assert!(!pip_rows_all_named(unnamed));
2546 }
2547
2548 #[test]
2549 fn a_crate_ships_unless_its_tree_says_otherwise() {
2550 let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
2551 Crate: app\nID: RUSTSEC-2025-0002\n\
2552 Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
2553 let ids = vec![
2554 "RUSTSEC-2025-0001".to_string(),
2555 "RUSTSEC-2025-0002".to_string(),
2556 "RUSTSEC-2025-0003".to_string(),
2557 "RUSTSEC-2025-0004".to_string(),
2558 ];
2559 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
2560 "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
2562 "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
2563 "odd" => Some("odd v1.0.0\n".into()),
2565 _ => None,
2566 });
2567 assert_eq!(
2569 shipped,
2570 vec![
2571 "RUSTSEC-2025-0002",
2572 "RUSTSEC-2025-0003",
2573 "RUSTSEC-2025-0004"
2574 ]
2575 );
2576 assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
2577 }
2578
2579 #[test]
2580 fn a_release_is_a_v_number_tag() {
2581 assert!(releasing(&[tag("refs/tags/v1.6.6")]));
2582 assert!(releasing(&[tag("refs/tags/v2")]));
2583 assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
2584 assert!(!releasing(&[tag("refs/tags/release")]));
2585 assert!(!releasing(&[tag("refs/heads/v1-styles")]));
2586 assert!(!releasing(&[tag("refs/heads/main")]));
2587 assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
2589 }
2590
2591 #[test]
2594 fn cargo_audit_ids_decide_not_the_exit_code() {
2595 assert_eq!(
2596 read_cargo_audit(true, "ok, 312 crates checked"),
2597 Report::Clean
2598 );
2599 assert_eq!(
2600 read_cargo_audit(false, "error: couldn't fetch advisory database"),
2601 Report::CouldNotCheck
2602 );
2603 let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
2604 assert_eq!(
2605 read_cargo_audit(true, warn),
2606 Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
2607 );
2608 let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
2609 assert_eq!(
2610 read_cargo_audit(false, vuln),
2611 Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
2612 );
2613 assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
2615 }
2616
2617 fn real_report() -> String {
2620 [
2621 "Crate: paste",
2622 "Version: 1.0.15",
2623 "Warning: unmaintained",
2624 "ID: RUSTSEC-2024-0436",
2625 "URL: https://rustsec.org/advisories/RUSTSEC-2024-0436",
2626 "",
2627 "Crate: lru",
2628 "Version: 0.12.5",
2629 "Warning: unsound",
2630 "ID: RUSTSEC-2026-0253",
2631 "",
2632 "Crate: lru",
2633 "Version: 0.12.5",
2634 "ID: RUSTSEC-2026-0002",
2635 "",
2636 "warning: 3 allowed warnings found",
2637 ]
2638 .join("\n")
2639 }
2640
2641 #[test]
2642 fn an_advisory_is_paired_with_its_crate() {
2643 let pairs = ids_with_crates(&real_report());
2644 assert_eq!(
2645 pairs,
2646 vec![
2647 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
2648 ("RUSTSEC-2026-0253".into(), Some("lru".into())),
2649 ("RUSTSEC-2026-0002".into(), Some("lru".into())),
2650 ]
2651 );
2652 }
2653
2654 #[test]
2657 fn a_loose_id_borrows_no_crate() {
2658 let out = "Crate: paste\nID: RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
2659 assert_eq!(
2660 ids_with_crates(out),
2661 vec![
2662 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
2663 ("RUSTSEC-2025-0001".into(), None),
2664 ]
2665 );
2666 }
2667
2668 #[test]
2671 fn only_local_crates_are_named_as_reached() {
2672 let tree =
2673 "lru v0.12.5\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
2674 assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
2675 assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
2676 }
2677
2678 #[test]
2682 fn the_warning_names_the_crate_and_what_reaches_it() {
2683 let calls = std::cell::RefCell::new(Vec::new());
2684 let fake = |k: &str| {
2685 calls.borrow_mut().push(k.to_string());
2686 Some(format!(
2687 "{k} v1\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
2688 ))
2689 };
2690 let out = real_report();
2691 let got = attribute(read_cargo_audit(true, &out), &out, fake);
2692 assert_eq!(
2693 got,
2694 Report::Advisories(vec![
2695 "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
2696 "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
2697 "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
2698 ])
2699 );
2700 assert_eq!(
2701 calls.into_inner(),
2702 vec!["paste", "lru"],
2703 "one call per crate"
2704 );
2705 }
2706
2707 #[test]
2711 fn a_crate_outside_the_build_graph_says_so() {
2712 let out = "Crate: wezterm-input-types\nID: RUSTSEC-2025-0001";
2713 let got = attribute(read_cargo_audit(true, out), out, |_| {
2714 Some("warning: nothing to print.".into())
2715 });
2716 assert_eq!(
2717 got,
2718 Report::Advisories(vec![
2719 "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
2720 ])
2721 );
2722 }
2723
2724 #[test]
2727 fn attribution_never_changes_the_verdict() {
2728 let spawned = std::cell::Cell::new(false);
2729 let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
2730 spawned.set(true);
2731 None
2732 });
2733 assert_eq!(clean, Report::Clean);
2734 assert!(!spawned.get(), "a clean report must spawn nothing");
2735
2736 let out = "Crate: paste\nID: RUSTSEC-2024-0436";
2737 let blind = attribute(read_cargo_audit(false, out), out, |_| None);
2738 assert_eq!(
2739 blind,
2740 Report::Vulnerabilities(vec![
2741 "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
2742 ])
2743 );
2744 }
2745
2746 #[test]
2747 fn npm_audit_summary_decides() {
2748 assert_eq!(
2749 read_npm_audit(true, "found 0 vulnerabilities\n"),
2750 Report::Clean
2751 );
2752 assert_eq!(
2753 read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
2754 Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
2755 );
2756 assert_eq!(
2759 read_npm_audit(
2760 false,
2761 "# npm audit report\n\nvite 6.0.0 - 6.1.5\nSeverity: high\n\n\
2762 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n npm audit fix\n"
2763 ),
2764 Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
2765 );
2766 assert_eq!(
2767 read_npm_audit(false, "1 vulnerability (1 high)\n"),
2768 Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
2769 );
2770 assert_eq!(
2771 read_npm_audit(true, "up to date, audited 100 packages\n"),
2772 Report::Clean
2773 );
2774 assert_eq!(
2775 read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
2776 Report::CouldNotCheck
2777 );
2778 }
2779
2780 #[test]
2781 fn pnpm_audit_summary_decides() {
2782 assert_eq!(
2783 read_pnpm_audit(true, "No known vulnerabilities found\n"),
2784 Report::Clean
2785 );
2786 assert_eq!(
2789 read_pnpm_audit(
2790 false,
2791 "│ More info │ https://github.com/advisories/GHSA-395f │\n\
2792 └───────────┴──────────────────────────────────────────┘\n\
2793 107 vulnerabilities found\n\
2794 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
2795 ),
2796 Report::Vulnerabilities(vec![
2797 "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
2798 ])
2799 );
2800 assert_eq!(
2801 read_pnpm_audit(false, "1 vulnerabilities found\n"),
2802 Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
2803 );
2804 assert_eq!(
2805 read_pnpm_audit(
2806 false,
2807 " ERR_PNPM_AUDIT_BAD_RESPONSE The audit endpoint responded with 503\n"
2808 ),
2809 Report::CouldNotCheck
2810 );
2811 }
2812
2813 #[test]
2816 fn govulncheck_ids_decide_not_the_exit_code() {
2817 assert_eq!(
2818 read_govulncheck(true, "No vulnerabilities found.\n"),
2819 Report::Clean
2820 );
2821 assert_eq!(
2822 read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
2823 Report::CouldNotCheck
2824 );
2825 assert_eq!(
2828 read_govulncheck(
2829 true,
2830 "=== Informational ===\nVulnerability #1: GO-2023-1840\n More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
2831 ),
2832 Report::Advisories(vec!["GO-2023-1840".into()])
2833 );
2834 assert_eq!(
2835 read_govulncheck(
2836 false,
2837 "Vulnerability #1: GO-2022-0969\n Your code calls it.\nGO-2022-0969 again\n"
2838 ),
2839 Report::Vulnerabilities(vec!["GO-2022-0969".into()])
2840 );
2841 assert_eq!(
2843 read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
2844 Report::Clean
2845 );
2846 }
2847
2848 #[test]
2849 fn pip_audit_sentence_decides() {
2850 assert_eq!(
2851 read_pip_audit(true, "No known vulnerabilities found\n"),
2852 Report::Clean
2853 );
2854 assert_eq!(
2855 read_pip_audit(
2856 false,
2857 "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
2858 ),
2859 Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
2860 );
2861 assert_eq!(
2862 read_pip_audit(false, "ERROR: could not resolve\n"),
2863 Report::CouldNotCheck
2864 );
2865 }
2866
2867 fn lock_block(name: Option<&str>, source: &str) -> String {
2868 let mut block = String::from("[[package]]\n");
2869 if let Some(name) = name {
2870 block.push_str(&format!("name = \"{name}\"\n"));
2871 }
2872 block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
2873 block
2874 }
2875
2876 #[test]
2877 fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
2878 let pypi = "{ registry = \"https://pypi.org/simple\" }";
2879 let lock = [
2880 lock_block(Some("Requests"), pypi),
2881 lock_block(
2882 Some("slashed"),
2883 "{ registry = \"https://pypi.org/simple/\" }",
2884 ),
2885 lock_block(
2886 Some("mirror"),
2887 "{ registry = \"https://mirror.example/simple\" }",
2888 ),
2889 lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
2890 lock_block(Some("pathdep"), "{ path = \"../x\" }"),
2891 lock_block(Some("edit"), "{ editable = \".\" }"),
2892 lock_block(Some("virt"), "{ virtual = \".\" }"),
2893 lock_block(Some("twice"), pypi),
2894 lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
2895 lock_block(None, pypi),
2896 "[package.metadata]\nname = \"ignored\"\n".to_string(),
2897 ]
2898 .concat();
2899 let sources = scan_uv_lock(&lock);
2900 let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
2901 assert_eq!(admitted, ["requests", "slashed"]);
2902 assert_eq!(sources.nameless, 1);
2903 }
2904
2905 #[test]
2906 fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
2907 let pypi: std::collections::BTreeSet<String> =
2908 ["numpy", "idna", "requests"].map(String::from).into();
2909 let raw = "\
2910# generated
2911numpy==1.26.4 ; python_full_version < '3.12'
2912numpy==2.1.0 ; python_full_version >= '3.12'
2913numpy==2.1.0 ; sys_platform == 'win32'
2914idna==3.7
2915platform-kernel==0.1.0
2916requests @ https://example.com/r.whl
2917";
2918 let pins = filter_export(raw, &pypi);
2919 assert_eq!(pins.versions, 3);
2920 assert_eq!(pins.batches.len(), 2);
2921 assert_eq!(
2922 pins.batches[0].get("numpy").map(String::as_str),
2923 Some("1.26.4")
2924 );
2925 assert_eq!(
2926 pins.batches[1].get("numpy").map(String::as_str),
2927 Some("2.1.0")
2928 );
2929 assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
2930 assert!(pins.skipped.contains("platform-kernel"));
2931 assert!(pins.unclassified.contains("requests"));
2932 }
2933
2934 #[test]
2935 fn the_skipped_line_names_three_and_counts_the_rest() {
2936 let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
2937 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
2938 assert_eq!(
2939 skipped_line("", &refs),
2940 "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
2941 );
2942 assert_eq!(
2943 skipped_line("", &refs[..1]),
2944 "audit-python: 1 private/non-PyPI package skipped (a)"
2945 );
2946 }
2947
2948 #[test]
2949 fn scrub_names_the_canonical_private_path_too() {
2950 let plain = std::path::Path::new("/var/folders/a/audit-1");
2951 let canonical = Some(std::path::PathBuf::from("/private/var/folders/a/audit-1"));
2952 assert_eq!(
2953 scrub_private(
2954 "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
2955 plain,
2956 canonical
2957 ),
2958 "x <tmp>/b and <tmp>/c"
2959 );
2960 }
2961
2962 #[test]
2963 fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
2964 let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
2965 let guard = PrivateDir::create_at(path.clone()).unwrap();
2966 #[cfg(unix)]
2967 {
2968 use std::os::unix::fs::PermissionsExt;
2969 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
2970 assert_eq!(mode & 0o777, 0o700);
2971 }
2972 assert!(PrivateDir::create_at(path.clone()).is_err());
2973 assert!(path.is_dir(), "the refused attempt must leave it alone");
2974 drop(guard);
2975 assert!(!path.exists());
2976 }
2977}