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}: 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 {
1264 common::warn(
1265 "audit-python: no requirements.txt, and no virtualenv to audit \
1266 (looked at $VIRTUAL_ENV and .venv) — the audit did NOT run",
1267 );
1268 return Ran::Unavailable;
1269 };
1270 let Some((exit_ok, out)) = audited(settings, &argv) else {
1271 return Ran::Unavailable;
1272 };
1273 let release = releasing(refs);
1274 let mut report = read_pip_audit(exit_ok, &out);
1275 let venv_mode = argv.iter().any(|a| a == "--path");
1280 let mut waivable = pip_rows_all_named(&out);
1283 if release && venv_mode && matches!(report, Report::Vulnerabilities(_)) {
1284 let rows = pip_vulnerable_rows(&out);
1285 if let (false, Some(prod)) = (rows.is_empty(), uv_production_names(settings)) {
1286 let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1287 .into_iter()
1288 .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1289 .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1290 if ships {
1291 s.push(row);
1292 } else {
1293 d.push(row);
1294 }
1295 (s, d)
1296 });
1297 warn_dev_only("audit-python", &dev_only);
1298 waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1299 report = if shipped.is_empty() {
1300 Report::Clean
1301 } else {
1302 Report::Vulnerabilities(shipped)
1303 };
1304 }
1305 }
1306 Ran::Concluded(Concluded {
1307 tool: "audit-python".to_string(),
1308 report,
1309 full: out,
1310 waivable,
1311 })
1312}
1313
1314fn source_is_this_commit(source: &std::path::Path) -> bool {
1318 let src = source.to_string_lossy();
1319 let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1320 let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
1321 let unmodified = crate::git::stdout(&[
1322 "-C",
1323 &src,
1324 "status",
1325 "--porcelain",
1326 "--untracked-files=no",
1327 "--",
1328 "*pyproject.toml",
1329 "*uv.lock",
1330 "*requirements*.txt",
1331 ])
1332 .is_some_and(|out| out.trim().is_empty());
1333 here.is_some() && here == there && unmodified
1334}
1335
1336fn normalise(name: &str) -> String {
1338 name.to_ascii_lowercase()
1339 .split(['-', '_', '.'])
1340 .filter(|p| !p.is_empty())
1341 .collect::<Vec<_>>()
1342 .join("-")
1343}
1344
1345fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
1349 let mut rows: Vec<(String, String)> = out
1350 .lines()
1351 .filter_map(|l| {
1352 let cols: Vec<&str> = l.split_whitespace().collect();
1353 let id = cols.get(2)?;
1354 ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
1355 .iter()
1356 .any(|p| id.starts_with(p))
1357 .then(|| (normalise(cols[0]), (*id).to_string()))
1358 })
1359 .collect();
1360 rows.sort();
1361 rows.dedup();
1362 rows
1363}
1364
1365fn pip_rows_all_named(out: &str) -> bool {
1369 out.lines().all(|l| {
1370 let cols: Vec<&str> = l.split_whitespace().collect();
1371 let is_row = cols.len() >= 3
1372 && cols[1].starts_with(|c: char| c.is_ascii_digit())
1373 && cols[2].contains('-')
1374 && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
1375 !is_row || !advisory_ids(cols[2]).is_empty()
1376 })
1377}
1378
1379fn uv_production_names(
1383 settings: &crate::config::Settings,
1384) -> Option<std::collections::HashSet<String>> {
1385 if !has_lockfile("uv.lock") || common::which("uv").is_none() {
1386 return None;
1387 }
1388 let argv = vec![
1389 common::program("uv"),
1390 "export".into(),
1391 "--frozen".into(),
1392 "--no-dev".into(),
1393 "--all-extras".into(),
1395 "--no-hashes".into(),
1396 "--no-emit-workspace".into(),
1397 "--format".into(),
1398 "requirements-txt".into(),
1399 ];
1400 let (ok, out) = audited(settings, &argv)?;
1401 if !ok {
1402 return None;
1403 }
1404 Some(
1405 out.lines()
1406 .map(str::trim)
1407 .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
1408 .filter_map(|l| {
1409 l.split(|c: char| "=<>!~;[ ".contains(c))
1410 .next()
1411 .map(normalise)
1412 })
1413 .collect(),
1414 )
1415}
1416
1417pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
1419const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
1420const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
1422const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
1425
1426pub fn is_audit(check: &str) -> bool {
1428 check.starts_with("pre-push-audit-")
1429}
1430
1431fn inputs_of(check: &str) -> &'static [&'static str] {
1435 match check {
1436 "pre-push-audit-rust" => &["Cargo.lock"],
1437 "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
1438 "pre-push-audit-go" => &["go.sum", "go.mod"],
1439 "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
1440 _ => &[],
1441 }
1442}
1443
1444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1446enum AuditMode {
1447 Branch,
1449 Release,
1451}
1452
1453impl AuditMode {
1454 fn of(refs: &[PushRef]) -> AuditMode {
1455 if releasing(refs) {
1456 AuditMode::Release
1457 } else {
1458 AuditMode::Branch
1459 }
1460 }
1461}
1462
1463#[derive(Debug, Clone, PartialEq, Eq)]
1467struct Concluded {
1468 tool: String,
1469 report: Report,
1470 full: String,
1471 waivable: bool,
1472}
1473
1474enum Ran {
1477 Concluded(Concluded),
1478 Inert,
1480 Unavailable,
1482}
1483
1484#[derive(Debug, Clone)]
1487pub struct Pending {
1488 pub tip: String,
1489 material: String,
1490 body: String,
1491}
1492
1493#[derive(Default)]
1498pub struct Ledger {
1499 pending: std::sync::Mutex<Vec<Pending>>,
1500 peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
1501 fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
1502}
1503
1504impl Ledger {
1505 pub fn take_pending(&self) -> Vec<Pending> {
1507 std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
1508 }
1509
1510 fn peel(&self, oid: &str) -> Option<String> {
1512 if let Some(known) = self
1513 .peeled
1514 .lock()
1515 .unwrap_or_else(|e| e.into_inner())
1516 .get(oid)
1517 {
1518 return known.clone();
1519 }
1520 let commit =
1521 crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
1522 self.peeled
1523 .lock()
1524 .unwrap_or_else(|e| e.into_inner())
1525 .insert(oid.to_string(), commit.clone());
1526 commit
1527 }
1528
1529 fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
1531 let mut commits: Vec<String> = refs
1532 .iter()
1533 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1534 .filter_map(|r| self.peel(&r.local_oid))
1535 .collect();
1536 commits.sort();
1537 commits.dedup();
1538 commits
1539 }
1540}
1541
1542pub fn write_pending(pending: &Pending) -> Result<(), String> {
1545 let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
1548 .map(|k| k.trim().to_string())
1549 .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
1550 let written = crate::git::succeeds(&[
1551 "notes",
1552 "--ref",
1553 AUDIT_REF,
1554 "add",
1555 "-f",
1556 "-m",
1557 &pending.body,
1558 &key,
1559 ]);
1560 if written {
1561 Ok(())
1562 } else {
1563 Err(format!("git refused to write the audit record {key}"))
1564 }
1565}
1566
1567fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
1569 match mode {
1570 AuditMode::Release => {
1571 let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
1572 Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
1573 }
1574 AuditMode::Branch => {
1575 let names = inputs_of(check);
1576 let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
1577 let mut lines: Vec<String> = listing
1578 .lines()
1579 .filter_map(|entry| {
1580 let (meta, path) = entry.split_once('\t')?;
1581 let blob = meta.split_whitespace().nth(2)?;
1582 let base = path.rsplit('/').next().unwrap_or(path);
1583 names.contains(&base).then(|| format!("{path} {blob}"))
1584 })
1585 .collect();
1586 lines.sort();
1587 Some(format!(
1588 "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
1589 lines.join("\n")
1590 ))
1591 }
1592 }
1593}
1594
1595fn now_secs() -> i64 {
1596 std::time::SystemTime::now()
1597 .duration_since(std::time::UNIX_EPOCH)
1598 .map(|d| d.as_secs() as i64)
1599 .unwrap_or(0)
1600}
1601
1602fn class_of(report: &Report) -> &'static str {
1603 match report {
1604 Report::Clean => "clean",
1605 Report::Advisories(_) => "advisories",
1606 Report::Vulnerabilities(_) => "vulnerabilities",
1607 Report::CouldNotCheck => "unchecked",
1608 }
1609}
1610
1611fn render(concluded: &Concluded, at: i64) -> String {
1612 let items: &[String] = match &concluded.report {
1613 Report::Advisories(v) | Report::Vulnerabilities(v) => v,
1614 Report::Clean | Report::CouldNotCheck => &[],
1615 };
1616 let mut body = format!(
1617 "{AUDIT_FORMAT} {at} {} {} {}",
1618 class_of(&concluded.report),
1619 u8::from(concluded.waivable),
1620 concluded.tool
1621 );
1622 for item in items {
1623 body.push_str("\nitem ");
1624 body.push_str(item);
1625 }
1626 body.push_str("\n---\n");
1627 body.push_str(&concluded.full);
1628 body
1629}
1630
1631fn parse(body: &str) -> Option<(i64, Concluded)> {
1632 let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
1633 let mut fields = head.split_whitespace();
1634 if fields.next()? != AUDIT_FORMAT {
1635 return None;
1636 }
1637 let at: i64 = fields.next()?.parse().ok()?;
1638 let class = fields.next()?;
1639 let waivable = fields.next()? == "1";
1640 let tool = fields.next()?.to_string();
1641 let (items_part, full) = match rest.split_once("---\n") {
1642 Some((i, full)) => (i, full.to_string()),
1643 None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
1644 };
1645 let items: Vec<String> = items_part
1646 .lines()
1647 .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
1648 .collect();
1649 let report = match class {
1650 "clean" => Report::Clean,
1651 "advisories" => Report::Advisories(items),
1652 "vulnerabilities" => Report::Vulnerabilities(items),
1653 "unchecked" => Report::CouldNotCheck,
1654 _ => return None,
1655 };
1656 Some((
1657 at,
1658 Concluded {
1659 tool,
1660 report,
1661 full,
1662 waivable,
1663 },
1664 ))
1665}
1666
1667fn fresh_record(
1669 settings: &crate::config::Settings,
1670 check: &str,
1671 mode: AuditMode,
1672 commit: &str,
1673) -> Option<Concluded> {
1674 let material = key_material(check, mode, commit)?;
1675 let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
1676 .trim()
1677 .to_string();
1678 let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
1679 let (at, concluded) = parse(&body)?;
1680 let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
1681 UNCHECKED_MAX_AGE_SECS
1682 } else {
1683 crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
1684 };
1685 let age = now_secs() - at;
1686 (0..=max_age).contains(&age).then_some(concluded)
1687}
1688
1689fn fresh_for_refs(
1694 settings: &crate::config::Settings,
1695 ledger: &Ledger,
1696 check: &str,
1697 refs: &[PushRef],
1698) -> Option<Concluded> {
1699 if !crate::gate_stamp::push_stamps_enabled(settings) {
1700 return None;
1701 }
1702 let memo_key = format!(
1703 "{check} {}",
1704 refs.iter()
1705 .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
1706 .collect::<Vec<_>>()
1707 .join(" ")
1708 );
1709 if let Some(known) = ledger
1710 .fresh
1711 .lock()
1712 .unwrap_or_else(|e| e.into_inner())
1713 .get(&memo_key)
1714 {
1715 return known.clone();
1716 }
1717 let mode = AuditMode::of(refs);
1718 let mut found: Option<Concluded> = None;
1719 for commit in ledger.pushed_commits(refs) {
1720 let Some(record) = fresh_record(settings, check, mode, &commit) else {
1721 found = None;
1722 break;
1723 };
1724 if found.as_ref().is_some_and(|prev| *prev != record) {
1725 found = None;
1726 break;
1727 }
1728 found = Some(record);
1729 }
1730 ledger
1731 .fresh
1732 .lock()
1733 .unwrap_or_else(|e| e.into_inner())
1734 .insert(memo_key, found.clone());
1735 found
1736}
1737
1738pub fn owed(
1740 settings: &crate::config::Settings,
1741 ledger: &Ledger,
1742 check: &str,
1743 refs: &[PushRef],
1744) -> bool {
1745 !ledger.pushed_commits(refs).is_empty()
1746 && fresh_for_refs(settings, ledger, check, refs).is_none()
1747}
1748
1749fn recorded(
1753 check: &str,
1754 tool: &str,
1755 ctx: &crate::registry::Ctx,
1756 run: fn(&crate::registry::Ctx) -> Ran,
1757) -> Outcome {
1758 let (settings, refs) = (ctx.settings, ctx.push.get());
1759 let mode = AuditMode::of(refs);
1760 let releasing = mode == AuditMode::Release;
1761 if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
1762 common::ok(
1763 settings,
1764 &format!("{tool}: replaying the audit recorded for this push"),
1765 );
1766 return conclude_waivable(
1767 settings,
1768 &record.tool,
1769 record.report,
1770 releasing,
1771 &record.full,
1772 record.waivable,
1773 );
1774 }
1775 let (outcome, concluded) = match run(ctx) {
1776 Ran::Concluded(concluded) => (
1777 conclude_waivable(
1778 settings,
1779 &concluded.tool,
1780 concluded.report.clone(),
1781 releasing,
1782 &concluded.full,
1783 concluded.waivable,
1784 ),
1785 Some(concluded),
1786 ),
1787 Ran::Unavailable => (
1788 Outcome::Unavailable,
1789 Some(Concluded {
1790 tool: tool.to_string(),
1791 report: Report::CouldNotCheck,
1792 full: String::new(),
1793 waivable: false,
1794 }),
1795 ),
1796 Ran::Inert => (Outcome::Inert, None),
1797 };
1798 if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
1799 let body = render(&concluded, now_secs());
1800 let records: Vec<Pending> = ctx
1801 .audits
1802 .pushed_commits(refs)
1803 .into_iter()
1804 .filter_map(|commit| {
1805 key_material(check, mode, &commit).map(|material| Pending {
1806 tip: commit,
1807 material,
1808 body: body.clone(),
1809 })
1810 })
1811 .collect();
1812 ctx.audits
1813 .pending
1814 .lock()
1815 .unwrap_or_else(|e| e.into_inner())
1816 .extend(records);
1817 }
1818 outcome
1819}
1820
1821pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
1822 recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
1823}
1824
1825pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
1826 recorded("pre-push-audit-js", "audit-js", ctx, js_run)
1827}
1828
1829pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
1830 recorded("pre-push-audit-go", "audit-go", ctx, go_run)
1831}
1832
1833pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
1834 recorded("pre-push-audit-python", "audit-python", ctx, python_run)
1835}
1836
1837#[cfg(test)]
1838mod tests {
1839 use super::*;
1840
1841 #[test]
1847 fn a_uv_project_is_audited_through_its_venv() {
1848 let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
1849 let _ = std::fs::remove_dir_all(&root);
1850
1851 std::fs::create_dir_all(&root).unwrap();
1854 assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
1855
1856 let sp = root
1863 .join(".venv")
1864 .join("lib")
1865 .join("python3.13")
1866 .join("site-packages");
1867 std::fs::create_dir_all(&sp).unwrap();
1868 assert_eq!(
1869 venv_site_packages(root.to_str().unwrap(), None),
1870 Some(sp.to_string_lossy().into_owned())
1871 );
1872
1873 let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
1875 let _ = std::fs::remove_dir_all(&win);
1876 let wsp = win.join(".venv").join("Lib").join("site-packages");
1877 std::fs::create_dir_all(&wsp).unwrap();
1878 assert_eq!(
1879 venv_site_packages(win.to_str().unwrap(), None),
1880 Some(wsp.to_string_lossy().into_owned())
1881 );
1882
1883 let _ = std::fs::remove_dir_all(&root);
1884 let _ = std::fs::remove_dir_all(&win);
1885 }
1886
1887 fn tag(name: &str) -> PushRef {
1888 PushRef {
1889 local_ref: name.to_string(),
1890 local_oid: "a".repeat(40),
1891 remote_ref: name.to_string(),
1892 remote_oid: "0".repeat(40),
1893 }
1894 }
1895
1896 #[test]
1899 fn pip_audit_rows_name_their_packages_normalised() {
1900 let out = "Name Version ID Fix Versions\n\
1901 ---------- ------- ------------------- ------------\n\
1902 Pytest_Cov 4.0.0 GHSA-aaaa-bbbb-cccc 4.1.0\n\
1903 requests 2.31.0 PYSEC-2023-74 2.31.1\n\
1904 requests 2.31.0 CVE-2024-35195 2.32.0\n\
1905 Found 3 known vulnerabilities in 2 packages\n";
1906 let names: Vec<String> = pip_vulnerable_rows(out)
1907 .into_iter()
1908 .map(|(n, _)| n)
1909 .collect();
1910 assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
1911 assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
1912 }
1913
1914 #[test]
1915 fn advisory_ids_are_found_wherever_they_sit() {
1916 let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
1917 ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
1918 assert_eq!(
1919 advisory_ids(text),
1920 vec![
1921 "CVE-2024-35195",
1922 "GHSA-h3mg-xc3c-68pw",
1923 "GO-2024-2687",
1924 "OSV-2024-12",
1925 "PYSEC-2023-74",
1926 "RUSTSEC-2025-0001"
1927 ]
1928 );
1929 }
1930
1931 #[test]
1932 fn a_waiver_is_reasoned_dated_and_bounded() {
1933 let today = days_from_date("2026-10-05").unwrap();
1934 let w = Waivers::parse(
1935 "# id expires reason\n\
1936 GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
1937 GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
1938 GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
1939 GHSA-jjjj-kkkk-llll 2026-11-01\n\
1940 GHSA-mmmm-nnnn-oooo soon no date\n",
1941 today,
1942 );
1943 assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
1944 assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
1945 assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
1946 assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
1947 assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
1948 assert_eq!(w.problems().len(), 4);
1949 assert_eq!(days_from_date("1970-01-01"), Some(0));
1950 assert_eq!(days_from_date("2026-02-30"), None);
1951 assert!(days_from_date("2028-02-29").is_some());
1952 assert_eq!(days_from_date("2026-13-01"), None);
1953 }
1954
1955 #[test]
1956 fn two_locked_versions_are_two_answers() {
1957 let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
1958 Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
1959 let ids = vec![
1960 "RUSTSEC-2025-0010".to_string(),
1961 "RUSTSEC-2025-0011".to_string(),
1962 ];
1963 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
1964 "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
1965 "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
1966 _ => None,
1967 });
1968 assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
1969 assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
1970 }
1971
1972 #[test]
1973 fn a_pip_row_without_a_nameable_id_is_unwaivable() {
1974 let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
1975 let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
1976 assert!(pip_rows_all_named(named));
1977 assert!(!pip_rows_all_named(unnamed));
1978 }
1979
1980 #[test]
1981 fn a_crate_ships_unless_its_tree_says_otherwise() {
1982 let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
1983 Crate: app\nID: RUSTSEC-2025-0002\n\
1984 Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
1985 let ids = vec![
1986 "RUSTSEC-2025-0001".to_string(),
1987 "RUSTSEC-2025-0002".to_string(),
1988 "RUSTSEC-2025-0003".to_string(),
1989 "RUSTSEC-2025-0004".to_string(),
1990 ];
1991 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
1992 "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
1994 "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
1995 "odd" => Some("odd v1.0.0\n".into()),
1997 _ => None,
1998 });
1999 assert_eq!(
2001 shipped,
2002 vec![
2003 "RUSTSEC-2025-0002",
2004 "RUSTSEC-2025-0003",
2005 "RUSTSEC-2025-0004"
2006 ]
2007 );
2008 assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
2009 }
2010
2011 #[test]
2012 fn a_release_is_a_v_number_tag() {
2013 assert!(releasing(&[tag("refs/tags/v1.6.6")]));
2014 assert!(releasing(&[tag("refs/tags/v2")]));
2015 assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
2016 assert!(!releasing(&[tag("refs/tags/release")]));
2017 assert!(!releasing(&[tag("refs/heads/v1-styles")]));
2018 assert!(!releasing(&[tag("refs/heads/main")]));
2019 assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
2021 }
2022
2023 #[test]
2026 fn cargo_audit_ids_decide_not_the_exit_code() {
2027 assert_eq!(
2028 read_cargo_audit(true, "ok, 312 crates checked"),
2029 Report::Clean
2030 );
2031 assert_eq!(
2032 read_cargo_audit(false, "error: couldn't fetch advisory database"),
2033 Report::CouldNotCheck
2034 );
2035 let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
2036 assert_eq!(
2037 read_cargo_audit(true, warn),
2038 Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
2039 );
2040 let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
2041 assert_eq!(
2042 read_cargo_audit(false, vuln),
2043 Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
2044 );
2045 assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
2047 }
2048
2049 fn real_report() -> String {
2052 [
2053 "Crate: paste",
2054 "Version: 1.0.15",
2055 "Warning: unmaintained",
2056 "ID: RUSTSEC-2024-0436",
2057 "URL: https://rustsec.org/advisories/RUSTSEC-2024-0436",
2058 "",
2059 "Crate: lru",
2060 "Version: 0.12.5",
2061 "Warning: unsound",
2062 "ID: RUSTSEC-2026-0253",
2063 "",
2064 "Crate: lru",
2065 "Version: 0.12.5",
2066 "ID: RUSTSEC-2026-0002",
2067 "",
2068 "warning: 3 allowed warnings found",
2069 ]
2070 .join("\n")
2071 }
2072
2073 #[test]
2074 fn an_advisory_is_paired_with_its_crate() {
2075 let pairs = ids_with_crates(&real_report());
2076 assert_eq!(
2077 pairs,
2078 vec![
2079 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
2080 ("RUSTSEC-2026-0253".into(), Some("lru".into())),
2081 ("RUSTSEC-2026-0002".into(), Some("lru".into())),
2082 ]
2083 );
2084 }
2085
2086 #[test]
2089 fn a_loose_id_borrows_no_crate() {
2090 let out = "Crate: paste\nID: RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
2091 assert_eq!(
2092 ids_with_crates(out),
2093 vec![
2094 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
2095 ("RUSTSEC-2025-0001".into(), None),
2096 ]
2097 );
2098 }
2099
2100 #[test]
2103 fn only_local_crates_are_named_as_reached() {
2104 let tree =
2105 "lru v0.12.5\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
2106 assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
2107 assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
2108 }
2109
2110 #[test]
2114 fn the_warning_names_the_crate_and_what_reaches_it() {
2115 let calls = std::cell::RefCell::new(Vec::new());
2116 let fake = |k: &str| {
2117 calls.borrow_mut().push(k.to_string());
2118 Some(format!(
2119 "{k} v1\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
2120 ))
2121 };
2122 let out = real_report();
2123 let got = attribute(read_cargo_audit(true, &out), &out, fake);
2124 assert_eq!(
2125 got,
2126 Report::Advisories(vec![
2127 "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
2128 "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
2129 "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
2130 ])
2131 );
2132 assert_eq!(
2133 calls.into_inner(),
2134 vec!["paste", "lru"],
2135 "one call per crate"
2136 );
2137 }
2138
2139 #[test]
2143 fn a_crate_outside_the_build_graph_says_so() {
2144 let out = "Crate: wezterm-input-types\nID: RUSTSEC-2025-0001";
2145 let got = attribute(read_cargo_audit(true, out), out, |_| {
2146 Some("warning: nothing to print.".into())
2147 });
2148 assert_eq!(
2149 got,
2150 Report::Advisories(vec![
2151 "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
2152 ])
2153 );
2154 }
2155
2156 #[test]
2159 fn attribution_never_changes_the_verdict() {
2160 let spawned = std::cell::Cell::new(false);
2161 let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
2162 spawned.set(true);
2163 None
2164 });
2165 assert_eq!(clean, Report::Clean);
2166 assert!(!spawned.get(), "a clean report must spawn nothing");
2167
2168 let out = "Crate: paste\nID: RUSTSEC-2024-0436";
2169 let blind = attribute(read_cargo_audit(false, out), out, |_| None);
2170 assert_eq!(
2171 blind,
2172 Report::Vulnerabilities(vec![
2173 "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
2174 ])
2175 );
2176 }
2177
2178 #[test]
2179 fn npm_audit_summary_decides() {
2180 assert_eq!(
2181 read_npm_audit(true, "found 0 vulnerabilities\n"),
2182 Report::Clean
2183 );
2184 assert_eq!(
2185 read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
2186 Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
2187 );
2188 assert_eq!(
2191 read_npm_audit(
2192 false,
2193 "# npm audit report\n\nvite 6.0.0 - 6.1.5\nSeverity: high\n\n\
2194 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n npm audit fix\n"
2195 ),
2196 Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
2197 );
2198 assert_eq!(
2199 read_npm_audit(false, "1 vulnerability (1 high)\n"),
2200 Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
2201 );
2202 assert_eq!(
2203 read_npm_audit(true, "up to date, audited 100 packages\n"),
2204 Report::Clean
2205 );
2206 assert_eq!(
2207 read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
2208 Report::CouldNotCheck
2209 );
2210 }
2211
2212 #[test]
2213 fn pnpm_audit_summary_decides() {
2214 assert_eq!(
2215 read_pnpm_audit(true, "No known vulnerabilities found\n"),
2216 Report::Clean
2217 );
2218 assert_eq!(
2221 read_pnpm_audit(
2222 false,
2223 "│ More info │ https://github.com/advisories/GHSA-395f │\n\
2224 └───────────┴──────────────────────────────────────────┘\n\
2225 107 vulnerabilities found\n\
2226 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
2227 ),
2228 Report::Vulnerabilities(vec![
2229 "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
2230 ])
2231 );
2232 assert_eq!(
2233 read_pnpm_audit(false, "1 vulnerabilities found\n"),
2234 Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
2235 );
2236 assert_eq!(
2237 read_pnpm_audit(
2238 false,
2239 " ERR_PNPM_AUDIT_BAD_RESPONSE The audit endpoint responded with 503\n"
2240 ),
2241 Report::CouldNotCheck
2242 );
2243 }
2244
2245 #[test]
2248 fn govulncheck_ids_decide_not_the_exit_code() {
2249 assert_eq!(
2250 read_govulncheck(true, "No vulnerabilities found.\n"),
2251 Report::Clean
2252 );
2253 assert_eq!(
2254 read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
2255 Report::CouldNotCheck
2256 );
2257 assert_eq!(
2260 read_govulncheck(
2261 true,
2262 "=== Informational ===\nVulnerability #1: GO-2023-1840\n More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
2263 ),
2264 Report::Advisories(vec!["GO-2023-1840".into()])
2265 );
2266 assert_eq!(
2267 read_govulncheck(
2268 false,
2269 "Vulnerability #1: GO-2022-0969\n Your code calls it.\nGO-2022-0969 again\n"
2270 ),
2271 Report::Vulnerabilities(vec!["GO-2022-0969".into()])
2272 );
2273 assert_eq!(
2275 read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
2276 Report::Clean
2277 );
2278 }
2279
2280 #[test]
2281 fn pip_audit_sentence_decides() {
2282 assert_eq!(
2283 read_pip_audit(true, "No known vulnerabilities found\n"),
2284 Report::Clean
2285 );
2286 assert_eq!(
2287 read_pip_audit(
2288 false,
2289 "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
2290 ),
2291 Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
2292 );
2293 assert_eq!(
2294 read_pip_audit(false, "ERROR: could not resolve\n"),
2295 Report::CouldNotCheck
2296 );
2297 }
2298}