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 complete: bool,
681}
682
683fn audit_each_dir(
697 settings: &crate::config::Settings,
698 tool: &str,
699 lockfile: &str,
700 argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
701 read: fn(bool, &str) -> Report,
702 refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
703) -> Merged {
704 let answer_in = |path: &std::path::Path| match argv_in(path) {
705 None => DirAnswer::Nothing,
706 Some(argv) => answer_of(settings, &argv, path, read),
707 };
708 audit_each_dir_answered(tool, lockfile, answer_in, refine)
709}
710
711fn answer_of(
713 settings: &crate::config::Settings,
714 argv: &[String],
715 dir: &std::path::Path,
716 read: fn(bool, &str) -> Report,
717) -> DirAnswer {
718 match audited_in(settings, argv, dir) {
719 None => DirAnswer::TimedOut,
720 Some((exit_ok, out)) => DirAnswer::Read {
721 report: read(exit_ok, &out),
722 full: out.clone(),
723 out,
724 gap: None,
725 },
726 }
727}
728
729enum DirAnswer {
731 Nothing,
733 TimedOut,
736 Read {
742 report: Report,
743 out: String,
744 full: String,
745 gap: Option<String>,
746 },
747}
748
749fn audit_each_dir_answered(
752 tool: &str,
753 lockfile: &str,
754 mut answer_in: impl FnMut(&std::path::Path) -> DirAnswer,
755 mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
756) -> Merged {
757 let root = std::path::PathBuf::from(common::repo_root());
758 let dirs = lockfile_dirs(lockfile);
759 let only_root = dirs.len() == 1 && dirs[0].is_empty();
760 let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
761 let mut partial = Vec::new();
762 let mut full = String::new();
763 for dir in &dirs {
764 let path = root.join(dir);
765 let label = if dir.is_empty() { "." } else { dir.as_str() };
766 let label_ids = |ids: Vec<String>| -> Vec<String> {
767 if dir.is_empty() {
768 ids
769 } else {
770 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
771 }
772 };
773 let (report, out, dir_full, gap) = match answer_in(&path) {
774 DirAnswer::Nothing => {
775 unchecked.push(format!("{label} (nothing to audit there)"));
776 continue;
777 }
778 DirAnswer::TimedOut => {
781 unchecked.push(format!("{label} (timed out)"));
782 continue;
783 }
784 DirAnswer::Read {
785 report,
786 out,
787 full,
788 gap,
789 } => (report, out, full, gap),
790 };
791 let report = refine(&path, report, &out);
792 if gap.is_some() && !matches!(report, Report::CouldNotCheck) {
793 partial.push(label.to_string());
794 }
795 match report {
796 Report::Vulnerabilities(ids) => {
797 vulns.extend(label_ids(ids));
798 if only_root {
799 full.push_str(&dir_full);
800 } else {
801 full.push_str(&format!("── {tool} in {label}\n{dir_full}\n"));
802 }
803 }
804 Report::Advisories(ids) => advisories.extend(label_ids(ids)),
805 Report::CouldNotCheck => unchecked.push(match gap.or_else(|| failure_line(&out)) {
806 Some(why) => format!("{label} ({why})"),
807 None => label.to_string(),
808 }),
809 Report::Clean => {}
810 }
811 }
812 if !unchecked.is_empty() {
813 common::warn(&format!(
814 "{tool}: the audit could not answer in {} — NOT checked there",
815 unchecked.join(", ")
816 ));
817 }
818 if !partial.is_empty() {
820 common::warn(&format!(
821 "{tool}: NOT fully checked in {} (part of the audit did not answer)",
822 partial.join(", ")
823 ));
824 }
825 let report = if !vulns.is_empty() {
826 Report::Vulnerabilities(vulns)
827 } else if !unchecked.is_empty() || !partial.is_empty() {
828 Report::CouldNotCheck
829 } else if !advisories.is_empty() {
830 Report::Advisories(advisories)
831 } else {
832 Report::Clean
833 };
834 Merged {
835 report,
836 full,
837 waivable: unchecked.is_empty() && partial.is_empty(),
838 complete: unchecked.is_empty() && partial.is_empty(),
839 }
840}
841
842fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
843 let (settings, refs) = (ctx.settings, ctx.push.get());
844 if !has_lockfile("Cargo.lock") {
845 return Ran::Inert;
846 }
847 if common::which("cargo-audit").is_none() {
848 common::warn(
849 "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
850 the audit did NOT run",
851 );
852 return Ran::Unavailable;
853 }
854 let argv = vec![
855 common::program("cargo"),
856 "audit".into(),
857 "--color".into(),
858 "never".into(),
859 ];
860 let release = releasing(refs);
861 let merged = audit_each_dir(
862 settings,
863 "audit-rust",
864 "Cargo.lock",
865 |_| Some(argv.clone()),
866 read_cargo_audit,
867 |dir, mut report, out| {
868 if release {
869 if let Report::Vulnerabilities(ids) = report {
870 let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
871 cargo_tree_shipped(settings, dir, krate)
872 });
873 warn_dev_only("audit-rust", &dev_only);
874 report = if shipped.is_empty() {
875 Report::Clean
876 } else {
877 Report::Vulnerabilities(shipped)
878 };
879 }
880 }
881 attribute(report, out, |krate| {
882 cargo_tree_inverse(settings, dir, krate)
883 })
884 },
885 );
886 Ran::Concluded(Concluded {
887 tool: "audit-rust".to_string(),
888 report: merged.report,
889 full: merged.full,
890 waivable: merged.waivable,
891 complete: merged.complete,
892 })
893}
894
895fn cargo_tree_shipped(
900 settings: &crate::config::Settings,
901 dir: &std::path::Path,
902 spec: &str,
903) -> Option<String> {
904 let argv = vec![
905 common::program("cargo"),
906 "tree".into(),
907 "--invert".into(),
908 spec.into(),
909 "--edges".into(),
910 "normal,build".into(),
911 "--target".into(),
912 "all".into(),
913 "--all-features".into(),
914 "--color".into(),
915 "never".into(),
916 ];
917 audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
920}
921
922fn tree_says_dev_only(tree: &str) -> bool {
926 local_dependents(tree).is_empty() && tree.contains("nothing to print")
927}
928
929fn split_shipped_crates(
933 ids: Vec<String>,
934 out: &str,
935 shipped_tree: impl Fn(&str) -> Option<String>,
936) -> (Vec<String>, Vec<String>) {
937 let specs = ids_with_specs(out);
938 let mut verdicts: Vec<(String, bool)> = Vec::new();
939 let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
940 for id in ids {
941 let spec = specs
942 .iter()
943 .find(|(pid, spec)| *pid == id && spec.is_some())
944 .and_then(|(_, spec)| spec.clone());
945 let ships = match spec {
946 None => true,
947 Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
950 Some((_, v)) => *v,
951 None => {
952 let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
953 verdicts.push((spec, v));
954 v
955 }
956 },
957 };
958 if ships {
959 shipped.push(id);
960 } else {
961 dev_only.push(id);
962 }
963 }
964 (shipped, dev_only)
965}
966
967fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
971 let mut pairs = Vec::new();
972 let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
973 for line in out.lines().map(str::trim) {
974 if let Some(rest) = line.strip_prefix("Crate:") {
975 krate = rest.split_whitespace().next().map(str::to_string);
976 version = None;
977 } else if let Some(rest) = line.strip_prefix("Version:") {
978 version = rest.split_whitespace().next().map(str::to_string);
979 } else if let Some(rest) = line.strip_prefix("ID:") {
980 if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
981 let spec = krate.take().map(|k| match version.take() {
982 Some(v) => format!("{k}@{v}"),
983 None => k,
984 });
985 pairs.push((id.to_string(), spec));
986 }
987 }
988 }
989 pairs
990}
991
992fn warn_dev_only(tool: &str, dev_only: &[String]) {
994 if !dev_only.is_empty() {
995 common::warn(&format!(
996 "{tool}: dev-only, only in development dependencies, which the release does not ship — not blocking: {}",
997 dev_only.join("; ")
998 ));
999 }
1000}
1001
1002fn cargo_tree_inverse(
1006 settings: &crate::config::Settings,
1007 dir: &std::path::Path,
1008 krate: &str,
1009) -> Option<String> {
1010 let argv = vec![
1011 common::program("cargo"),
1012 "tree".into(),
1013 "--invert".into(),
1014 krate.into(),
1015 "--edges".into(),
1016 "normal".into(),
1017 "--color".into(),
1018 "never".into(),
1019 ];
1020 audited_in(settings, &argv, dir).map(|(_, out)| out)
1021}
1022
1023fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
1031 match report {
1032 Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
1033 Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
1034 other => other,
1037 }
1038}
1039
1040fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
1044 let pairs = ids_with_crates(out);
1045 let mut seen: Vec<(String, Vec<String>)> = Vec::new();
1046 ids.iter()
1047 .map(|id| {
1048 let krate = pairs
1049 .iter()
1050 .find(|(pid, k)| pid == id && k.is_some())
1051 .and_then(|(_, k)| k.clone());
1052 let Some(k) = krate else {
1053 return id.clone();
1054 };
1055 if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
1056 return describe(id, Some(&k), reaches);
1057 }
1058 let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
1059 seen.push((k.clone(), reaches.clone()));
1060 describe(id, Some(&k), &reaches)
1061 })
1062 .collect()
1063}
1064
1065fn has_lockfile(lockfile: &str) -> bool {
1072 crate::tracked_paths()
1073 .iter()
1074 .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1075}
1076
1077fn lockfile_dirs(lockfile: &str) -> Vec<String> {
1082 let mut dirs: Vec<String> = crate::tracked_paths()
1083 .iter()
1084 .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1085 .map(|p| {
1086 p.rsplit_once('/')
1087 .map(|(d, _)| d.to_string())
1088 .unwrap_or_default()
1089 })
1090 .collect();
1091 dirs.sort();
1092 dirs.dedup();
1093 dirs
1094}
1095
1096struct JsAuditor {
1099 lockfile: &'static str,
1100 tool: &'static str,
1101 read: fn(bool, &str) -> Report,
1102 args: fn(&str) -> Vec<String>,
1104 prod_only: &'static str,
1107}
1108
1109fn pnpm_args(dir: &str) -> Vec<String> {
1116 let manifest = if dir.is_empty() {
1117 "pnpm-workspace.yaml".to_string()
1118 } else {
1119 format!("{dir}/pnpm-workspace.yaml")
1120 };
1121 if crate::tracked_paths().contains(&manifest) {
1122 vec![]
1123 } else {
1124 vec!["--ignore-workspace".into()]
1125 }
1126}
1127
1128const JS_AUDITORS: [JsAuditor; 2] = [
1129 JsAuditor {
1130 lockfile: "package-lock.json",
1131 tool: "npm",
1132 read: read_npm_audit,
1133 args: |_| vec![],
1134 prod_only: "--omit=dev",
1135 },
1136 JsAuditor {
1137 lockfile: "pnpm-lock.yaml",
1138 tool: "pnpm",
1139 read: read_pnpm_audit,
1140 args: pnpm_args,
1141 prod_only: "--prod",
1142 },
1143];
1144
1145fn js_run(ctx: &crate::registry::Ctx) -> Ran {
1168 let (settings, refs) = (ctx.settings, ctx.push.get());
1169 let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
1170 .iter()
1171 .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
1172 .collect();
1173 if projects.is_empty() {
1174 return Ran::Inert;
1175 }
1176 let root = std::path::PathBuf::from(common::repo_root());
1177 let release = releasing(refs);
1178 let mut found = Vec::new();
1179 let mut dev_only = Vec::new();
1180 let mut unchecked = Vec::new();
1181 let mut full = String::new();
1182 for (auditor, dir) in &projects {
1183 let label = if dir.is_empty() {
1184 ".".to_string()
1185 } else {
1186 dir.clone()
1187 };
1188 let mut argv = vec![common::program(auditor.tool), "audit".into()];
1189 argv.extend((auditor.args)(dir));
1190 let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
1191 common::warn(&format!(
1192 "audit-js: {} could not run in {label} — the audit did NOT run",
1193 auditor.tool
1194 ));
1195 return Ran::Unavailable;
1196 };
1197 match (auditor.read)(exit_ok, &out) {
1198 Report::Vulnerabilities(what) if release => {
1199 let mut prod = argv.clone();
1200 prod.push(auditor.prod_only.into());
1201 match audited_in(settings, &prod, &root.join(dir))
1202 .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
1203 {
1204 Some((Report::Clean | Report::Advisories(_), _)) => {
1205 dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1206 }
1207 Some((Report::Vulnerabilities(shipped), pout)) => {
1208 found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
1209 full.push_str(&format!(
1210 "── {} audit {} in {label}\n{pout}\n",
1211 auditor.tool, auditor.prod_only
1212 ));
1213 }
1214 Some((Report::CouldNotCheck, _)) | None => {
1215 found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1216 full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1217 }
1218 }
1219 }
1220 Report::Vulnerabilities(what) => {
1221 found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1222 full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1223 }
1224 Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
1225 Report::Clean | Report::Advisories(_) => {}
1226 }
1227 }
1228 if !unchecked.is_empty() {
1229 common::warn(&format!(
1230 "audit-js: the audit could not answer in {} — those projects were NOT checked",
1231 unchecked.join(", ")
1232 ));
1233 }
1234 warn_dev_only("audit-js", &dev_only);
1235 let waivable = unchecked.is_empty();
1236 let report = if !found.is_empty() {
1237 Report::Vulnerabilities(found)
1238 } else if !unchecked.is_empty() {
1239 Report::CouldNotCheck
1240 } else {
1241 Report::Clean
1242 };
1243 Ran::Concluded(Concluded {
1244 tool: "audit-js".to_string(),
1245 report,
1246 full,
1247 waivable,
1248 complete: true,
1249 })
1250}
1251
1252fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1260 let settings = ctx.settings;
1261 if !has_lockfile("go.sum") {
1262 return Ran::Inert;
1263 }
1264 if common::which("govulncheck").is_none() {
1265 common::warn(
1266 "audit-go: govulncheck is not installed \
1267 (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1268 );
1269 return Ran::Unavailable;
1270 }
1271 let tool_dirs = std::cell::RefCell::new(std::collections::HashSet::new());
1274 let argv_in = |dir: &std::path::Path| {
1275 let tools_only =
1276 !super::go_tools::has_go_package(dir) && super::go_tools::declares_tool(dir);
1277 if tools_only {
1278 tool_dirs.borrow_mut().insert(dir.to_path_buf());
1279 }
1280 let pattern = if tools_only { "tool" } else { "./..." };
1281 Some(vec![common::program("govulncheck"), pattern.into()])
1282 };
1283 let root = std::path::PathBuf::from(common::repo_root());
1286 let mut in_tools = Vec::new();
1287 let refine = |dir: &std::path::Path, report: Report, _: &str| match report {
1288 Report::Vulnerabilities(ids) if tool_dirs.borrow().contains(dir) => {
1289 let label = dir
1290 .strip_prefix(&root)
1291 .ok()
1292 .map(|d| d.display().to_string())
1293 .filter(|d| !d.is_empty())
1294 .unwrap_or_else(|| ".".into());
1295 in_tools.push(format!("{label} (govulncheck tool): {}", ids.join(", ")));
1296 Report::Clean
1297 }
1298 other => other,
1299 };
1300 let merged = audit_each_dir(
1301 settings,
1302 "audit-go",
1303 "go.sum",
1304 argv_in,
1305 read_govulncheck,
1306 refine,
1307 );
1308 if !in_tools.is_empty() {
1309 common::warn(&format!(
1310 "audit-go: in a tools module, whose tools the release does not ship — not blocking: {}",
1311 in_tools.join("; ")
1312 ));
1313 }
1314 Ran::Concluded(Concluded {
1315 tool: "audit-go".to_string(),
1316 report: merged.report,
1317 full: merged.full,
1318 waivable: merged.waivable,
1319 complete: merged.complete,
1320 })
1321}
1322
1323fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1324 let (settings, refs) = (ctx.settings, ctx.push.get());
1325 if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1326 return Ran::Inert;
1327 }
1328 if common::which("pip-audit").is_none() {
1329 common::warn(
1330 "audit-python: pip-audit is not installed (pip install pip-audit) — \
1331 the audit did NOT run",
1332 );
1333 return Ran::Unavailable;
1334 }
1335 let root = common::repo_root();
1336 if !lockfile_dirs("requirements.txt").is_empty() {
1339 let root_path = std::path::PathBuf::from(&root);
1340 let rel_of = |dir: &std::path::Path| {
1341 dir.strip_prefix(&root_path)
1342 .map(|p| p.to_string_lossy().into_owned())
1343 .unwrap_or_default()
1344 };
1345 let answer_in = |dir: &std::path::Path| {
1346 let pins = hashed_pins(dir);
1347 let names = pins.as_ref().map(HashedPins::names);
1348 let answer = match pins {
1349 Some(pins) if pins.marked => audit_marked_pins(settings, dir, &rel_of(dir), pins),
1350 hashed => {
1351 let mut argv = vec![
1352 common::program("pip-audit"),
1353 "-r".into(),
1354 "requirements.txt".into(),
1355 ];
1356 if hashed.is_some() {
1360 argv.extend(["--no-deps".into(), "--disable-pip".into()]);
1361 }
1362 answer_of(settings, &argv, dir, read_pip_audit)
1363 }
1364 };
1365 let DirAnswer::Read {
1366 report,
1367 out,
1368 full,
1369 gap,
1370 } = answer
1371 else {
1372 return answer;
1373 };
1374 let skipped = pip_skipped_names(&out);
1375 if skipped.is_empty() {
1376 return DirAnswer::Read {
1377 report,
1378 out,
1379 full,
1380 gap,
1381 };
1382 }
1383 let skipped_names: Vec<&str> = skipped.iter().map(String::as_str).collect();
1384 common::warn(&skipped_line(
1385 &requirements_prefix(&rel_of(dir)),
1386 &skipped_names,
1387 ));
1388 let all_skipped = names.is_some_and(|n| skipped.len() >= n);
1390 let report = if all_skipped && !matches!(report, Report::Vulnerabilities(_)) {
1391 Report::CouldNotCheck
1392 } else {
1393 report
1394 };
1395 DirAnswer::Read {
1396 report,
1397 out,
1398 full,
1399 gap,
1400 }
1401 };
1402 let merged = audit_each_dir_answered(
1403 "audit-python",
1404 "requirements.txt",
1405 answer_in,
1406 |_, report, _| report,
1407 );
1408 let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1411 return Ran::Concluded(Concluded {
1412 tool: "audit-python".to_string(),
1413 report: merged.report,
1414 full: merged.full,
1415 waivable,
1416 complete: merged.complete,
1417 });
1418 }
1419 let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1420 vec![
1428 common::program("pip-audit"),
1429 "--path".into(),
1430 site_packages,
1431 "--skip-editable".into(),
1434 ]
1435 } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1436 return python_lock_run(ctx);
1438 } else {
1439 common::warn(
1440 "audit-python: the audit did NOT run — found no requirements.txt,\n \
1441 no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n \
1442 Next: `uv sync`, or install uv so uv.lock can be audited.",
1443 );
1444 return Ran::Unavailable;
1445 };
1446 let Some((exit_ok, out)) = audited(settings, &argv) else {
1447 return Ran::Unavailable;
1448 };
1449 let report = read_pip_audit(exit_ok, &out);
1454 let production = if releasing(refs) && has_rows_to_split(&report, &out) {
1455 uv_production_names(settings, std::path::Path::new(&root))
1456 } else {
1457 None
1458 };
1459 let (report, waivable) = shipped_only(report, &out, production.as_ref());
1460 Ran::Concluded(Concluded {
1461 tool: "audit-python".to_string(),
1462 report,
1463 full: out,
1464 waivable,
1465 complete: true,
1466 })
1467}
1468
1469fn shipped_only(
1475 mut report: Report,
1476 out: &str,
1477 production: Option<&std::collections::HashSet<String>>,
1478) -> (Report, bool) {
1479 let mut waivable = pip_rows_all_named(out);
1480 if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1481 let rows = pip_vulnerable_rows(out);
1482 if !rows.is_empty() {
1483 let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1484 .into_iter()
1485 .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1486 .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1487 if ships {
1488 s.push(row);
1489 } else {
1490 d.push(row);
1491 }
1492 (s, d)
1493 });
1494 warn_dev_only("audit-python", &dev_only);
1495 waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1496 report = if shipped.is_empty() {
1497 Report::Clean
1498 } else {
1499 Report::Vulnerabilities(shipped)
1500 };
1501 }
1502 }
1503 (report, waivable)
1504}
1505
1506fn has_rows_to_split(report: &Report, out: &str) -> bool {
1510 matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
1511}
1512
1513enum Production {
1516 Never,
1518 Unasked(std::path::PathBuf),
1520 Asked(Option<std::collections::HashSet<String>>),
1522}
1523
1524impl Production {
1525 fn names(
1529 &mut self,
1530 settings: &crate::config::Settings,
1531 budget: &Budget,
1532 say: &dyn Fn(&str),
1533 ) -> Option<&std::collections::HashSet<String>> {
1534 if let Production::Unasked(dir) = self {
1535 *self = Production::Asked(if budget.spent() {
1536 say(&format!(
1537 "out of time before the dev-only split — every finding counts\n {TIMEOUT_NEXT}"
1538 ));
1539 None
1540 } else {
1541 uv_production_names(settings, dir)
1542 });
1543 }
1544 match self {
1545 Production::Asked(names) => names.as_ref(),
1546 Production::Never | Production::Unasked(_) => None,
1547 }
1548 }
1549}
1550
1551const TIMEOUT_NEXT: &str =
1553 "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";
1554
1555const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";
1557
1558fn pip_audit_next(why: &str) -> &'static str {
1561 let why = why.to_ascii_lowercase();
1565 let network = [
1566 "network",
1567 "connect",
1568 "timed out",
1569 "timeout",
1570 "resolve",
1571 "dns",
1572 "ssl",
1573 "certificate",
1574 "unreachable",
1575 "temporary failure",
1576 ]
1577 .iter()
1578 .any(|word| why.contains(word));
1579 if network {
1580 "Next: check the network, then push again"
1581 } else {
1582 "Next: `pip-audit --version` to check the install, then push again"
1583 }
1584}
1585
1586const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1589
1590const WARNING_COLUMNS: usize = 80;
1592
1593const NAMES_SHOWN: usize = 3;
1595
1596struct PrivateDir {
1599 path: std::path::PathBuf,
1600}
1601
1602impl PrivateDir {
1603 fn create() -> std::io::Result<PrivateDir> {
1605 Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1606 }
1607
1608 fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1611 #[cfg(unix)]
1612 let builder = {
1613 let mut unix_builder = std::fs::DirBuilder::new();
1614 std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1615 unix_builder
1616 };
1617 #[cfg(not(unix))]
1618 let builder = std::fs::DirBuilder::new();
1619 builder.create(&path)?;
1620 Ok(PrivateDir { path })
1621 }
1622
1623 fn path(&self) -> &std::path::Path {
1624 &self.path
1625 }
1626}
1627
1628impl Drop for PrivateDir {
1629 fn drop(&mut self) {
1630 let _ = std::fs::remove_dir_all(&self.path); }
1632}
1633
1634struct Budget {
1637 started: std::time::Instant,
1638 limit: Option<std::time::Duration>,
1640}
1641
1642impl Budget {
1643 fn new(settings: &crate::config::Settings) -> Budget {
1644 Budget {
1645 started: std::time::Instant::now(),
1646 limit: Some(common::check_timeout(settings))
1647 .filter(|secs| *secs > 0)
1648 .map(std::time::Duration::from_secs),
1649 }
1650 }
1651
1652 fn spent(&self) -> bool {
1653 self.limit
1654 .is_some_and(|limit| self.started.elapsed() >= limit)
1655 }
1656}
1657
1658#[derive(Debug, Default, PartialEq, Eq)]
1660struct LockSources {
1661 pypi: std::collections::BTreeSet<String>,
1663 nameless: usize,
1665}
1666
1667fn is_pypi_source(source_field: &str) -> bool {
1669 source_field
1670 .split_once("registry = \"")
1671 .and_then(|(_, rest)| rest.split('"').next())
1672 .is_some_and(|url| url.trim_end_matches('/') == PYPI_REGISTRY)
1673}
1674
1675fn scan_uv_lock(text: &str) -> LockSources {
1679 struct Block {
1680 name: Option<String>,
1681 pypi: bool,
1682 }
1683 let mut blocks: Vec<Block> = Vec::new();
1684 let mut top_level = false;
1685 for line in text.lines() {
1686 if line.starts_with('[') {
1687 top_level = line.trim() == "[[package]]";
1688 if top_level {
1689 blocks.push(Block {
1690 name: None,
1691 pypi: false,
1692 });
1693 }
1694 continue;
1695 }
1696 let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1697 continue;
1698 };
1699 if let Some(value) = line.strip_prefix("name = ") {
1700 if block.name.is_none() {
1701 block.name = value.split('"').nth(1).map(normalise);
1702 }
1703 } else if let Some(value) = line.strip_prefix("source = ") {
1704 block.pypi = is_pypi_source(value);
1705 }
1706 }
1707 let mut sources = LockSources::default();
1708 let mut rejected = std::collections::BTreeSet::new();
1709 for block in blocks {
1710 match block.name.filter(|n| !n.is_empty()) {
1711 None => sources.nameless += 1,
1712 Some(name) if block.pypi => {
1713 sources.pypi.insert(name);
1714 }
1715 Some(name) => {
1716 rejected.insert(name);
1717 }
1718 }
1719 }
1720 sources.pypi.retain(|name| !rejected.contains(name));
1721 sources
1722}
1723
1724#[derive(Debug, Default, PartialEq, Eq)]
1726struct ExportPins {
1727 batches: Vec<std::collections::BTreeMap<String, String>>,
1730 versions: usize,
1732 skipped: std::collections::BTreeSet<String>,
1734 unclassified: std::collections::BTreeSet<String>,
1736}
1737
1738fn exact_pin(line: &str) -> Option<(String, String)> {
1741 let spec = line.split(';').next()?.trim();
1742 let (name, version) = spec.split_once("==")?;
1743 let name = name.split('[').next()?.trim();
1744 let version = version.trim();
1745 let name_ok = !name.is_empty()
1746 && name
1747 .chars()
1748 .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1749 let version_ok = !version.is_empty()
1750 && version
1751 .chars()
1752 .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1753 (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1754}
1755
1756fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1757 let mut pins = ExportPins::default();
1758 let mut pairs = std::collections::BTreeSet::new();
1759 for line in raw.lines().map(str::trim) {
1760 if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1761 continue;
1762 }
1763 let name = normalise(
1764 line.split(|c: char| "=<>!~;[ @".contains(c))
1765 .next()
1766 .unwrap_or_default(),
1767 );
1768 if name.is_empty() {
1769 continue;
1770 }
1771 if !pypi.contains(&name) {
1772 pins.skipped.insert(name);
1773 continue;
1774 }
1775 match exact_pin(line) {
1776 Some(pair) => {
1777 pairs.insert(pair);
1778 }
1779 None => {
1780 pins.unclassified.insert(name);
1781 }
1782 }
1783 }
1784 pins.versions = pairs.len();
1785 pins.batches = batches_of(pairs);
1786 pins
1787}
1788
1789fn batches_of(
1793 pairs: std::collections::BTreeSet<(String, String)>,
1794) -> Vec<std::collections::BTreeMap<String, String>> {
1795 let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
1796 for (name, version) in pairs {
1797 match batches.iter().position(|batch| !batch.contains_key(&name)) {
1798 Some(index) => {
1799 batches[index].insert(name, version);
1800 }
1801 None => batches.push(std::collections::BTreeMap::from([(name, version)])),
1802 }
1803 }
1804 batches
1805}
1806
1807fn requirements_path(rel: &str) -> String {
1809 if rel.is_empty() {
1810 "requirements.txt".to_string()
1811 } else {
1812 format!("{rel}/requirements.txt")
1813 }
1814}
1815
1816fn requirements_prefix(rel: &str) -> String {
1819 if rel.is_empty() {
1820 String::new()
1821 } else {
1822 format!("{}: ", requirements_path(rel))
1823 }
1824}
1825
1826fn audit_marked_pins(
1836 settings: &crate::config::Settings,
1837 dir: &std::path::Path,
1838 rel: &str,
1839 pins: HashedPins,
1840) -> DirAnswer {
1841 let prefix = requirements_prefix(rel);
1842 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1843 let unchecked = |why: &str| DirAnswer::Read {
1844 report: Report::CouldNotCheck,
1845 out: String::new(),
1846 full: String::new(),
1847 gap: Some(why.to_string()),
1848 };
1849 let budget = Budget::new(settings);
1850 let private = match PrivateDir::create() {
1851 Ok(private) => private,
1852 Err(why) => {
1853 say(&format!(
1854 "no private directory ({}) — did NOT run\n {TMPDIR_NEXT}",
1855 why.kind()
1856 ));
1857 return unchecked("no private directory");
1858 }
1859 };
1860 let canonical = std::fs::canonicalize(private.path()).ok();
1862 let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
1863 let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
1864 let mut gap: Option<String> = None;
1865 let mut answered: Vec<&str> = Vec::new();
1866 let batches = batches_of(pins.pairs);
1867 for (index, batch) in batches.iter().enumerate() {
1868 if budget.spent() {
1869 say(&format!(
1870 "out of time; unaudited versions remain — NOT fully checked\n {TIMEOUT_NEXT}"
1871 ));
1872 gap.get_or_insert_with(|| "out of time".to_string());
1873 break;
1874 }
1875 let file = private.path().join(format!("batch-{index}.txt"));
1876 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
1877 if let Err(why) = std::fs::write(&file, body) {
1878 say(&format!(
1879 "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n {TMPDIR_NEXT}",
1880 why.kind()
1881 ));
1882 gap.get_or_insert_with(|| "could not write a batch file".to_string());
1883 break;
1884 }
1885 let argv = vec![
1886 common::program("pip-audit"),
1887 "-r".into(),
1888 file.to_string_lossy().into_owned(),
1889 "--no-deps".into(),
1890 "--disable-pip".into(),
1891 ];
1892 let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
1894 if answered.is_empty() && gap.is_none() {
1895 return DirAnswer::TimedOut;
1896 }
1897 say("timed out; unaudited versions remain — NOT fully checked");
1899 gap.get_or_insert_with(|| "timed out".to_string());
1900 break;
1901 };
1902 let batch_out = scrub(&batch_out);
1903 match read_pip_audit(exit_ok, &batch_out) {
1904 Report::Vulnerabilities(found) => {
1905 vulnerabilities.extend(found);
1906 full.push_str(&batch_out);
1907 answered.extend(batch.keys().map(String::as_str));
1908 }
1909 Report::Clean | Report::Advisories(_) => {
1911 answered.extend(batch.keys().map(String::as_str));
1912 }
1913 Report::CouldNotCheck => {
1914 let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
1915 say(&format!(
1916 "pip-audit could not answer — NOT fully checked\n {}\n {}",
1917 clip(&why, WARNING_COLUMNS - 2),
1918 pip_audit_next(&why)
1919 ));
1920 gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
1921 }
1922 }
1923 out.push_str(&batch_out);
1924 }
1925 let skipped = pip_skipped_names(&out);
1926 let audited = answered
1927 .iter()
1928 .filter(|name| !skipped.iter().any(|s| s == *name))
1929 .count();
1930 if audited > 0 {
1931 common::ok(
1932 settings,
1933 &format!(
1934 "audit-python: audited {} ({}, {} skipped)",
1935 requirements_path(rel),
1936 plural(audited, "package version"),
1937 answered.len() - audited
1938 ),
1939 );
1940 }
1941 let report = if !vulnerabilities.is_empty() {
1942 Report::Vulnerabilities(vulnerabilities)
1943 } else if gap.is_some() {
1944 Report::CouldNotCheck
1945 } else {
1946 Report::Clean
1947 };
1948 DirAnswer::Read {
1949 report,
1950 out,
1951 full,
1952 gap,
1953 }
1954}
1955
1956#[derive(Debug, Default, PartialEq, Eq)]
1958struct HashedPins {
1959 pairs: std::collections::BTreeSet<(String, String)>,
1961 marked: bool,
1963}
1964
1965impl HashedPins {
1966 fn names(&self) -> usize {
1968 let names: std::collections::BTreeSet<&str> =
1969 self.pairs.iter().map(|(name, _)| name.as_str()).collect();
1970 names.len()
1971 }
1972}
1973
1974fn hashed_pins(dir: &std::path::Path) -> Option<HashedPins> {
1984 let text = std::fs::read_to_string(dir.join("requirements.txt")).ok()?;
1985 hashed_pins_in(&text)
1986}
1987
1988fn hashed_pins_in(text: &str) -> Option<HashedPins> {
1989 let mut logical = Vec::new();
1990 let mut current = String::new();
1991 for line in text.lines() {
1992 match line.strip_suffix('\\') {
1993 Some(head) => {
1994 current.push_str(head);
1995 current.push(' ');
1996 }
1997 None => {
1998 current.push_str(line);
1999 logical.push(std::mem::take(&mut current));
2000 }
2001 }
2002 }
2003 logical.push(current);
2004 let mut pins = HashedPins::default();
2005 for line in &logical {
2006 let line = match line.find(" #") {
2008 Some(cut) => &line[..cut],
2009 None => line.as_str(),
2010 };
2011 let line = line.trim();
2012 if line.is_empty() || line.starts_with('#') {
2013 continue;
2014 }
2015 if line.starts_with('-') {
2016 return None;
2017 }
2018 let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
2019 let hashed = options
2020 .split_whitespace()
2021 .any(|option| option.starts_with("--hash"));
2022 if !hashed {
2023 return None;
2024 }
2025 pins.pairs.insert(exact_pin(spec)?);
2026 pins.marked |= spec.contains(';');
2027 }
2028 (!pins.pairs.is_empty()).then_some(pins)
2029}
2030
2031fn pip_skipped_names(out: &str) -> Vec<String> {
2034 let mut lines = out.lines().map(str::trim);
2035 let mut names = Vec::new();
2036 while let Some(line) = lines.next() {
2037 if !(line.starts_with("Name") && line.contains("Skip Reason")) {
2038 continue;
2039 }
2040 let rows = lines
2041 .by_ref()
2042 .skip_while(|l| l.starts_with('-'))
2043 .take_while(|l| !l.is_empty());
2044 names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
2045 }
2046 names.sort();
2047 names.dedup();
2048 names
2049}
2050
2051fn plural(count: usize, noun: &str) -> String {
2052 if count == 1 {
2053 format!("{count} {noun}")
2054 } else {
2055 format!("{count} {noun}s")
2056 }
2057}
2058
2059fn skipped_line(prefix: &str, names: &[&str]) -> String {
2063 let head = format!(
2064 "audit-python: {prefix}{} skipped",
2065 plural(names.len(), "private/non-PyPI package")
2066 );
2067 let fewest = names.len().min(1);
2068 for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
2069 let list: Vec<&str> = names.iter().take(shown).copied().collect();
2070 let more = names.len() - shown;
2071 let detail = match (list.is_empty(), more) {
2072 (true, 0) => String::new(),
2073 (true, _) => format!(" (+{more} more)"),
2074 (false, 0) => format!(" ({})", list.join(", ")),
2075 (false, _) => format!(" ({} +{more} more)", list.join(", ")),
2076 };
2077 let line = format!("{head}{detail}");
2078 if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
2079 return line;
2080 }
2081 }
2082 head
2083}
2084
2085fn clip(text: &str, columns: usize) -> String {
2087 text.chars().take(columns).collect()
2088}
2089
2090fn scrub_private(
2095 text: &str,
2096 private: &std::path::Path,
2097 canonical: Option<&std::path::Path>,
2098) -> String {
2099 let plain = private.to_string_lossy();
2100 let mut scrubbed = text.to_string();
2101 if let Some(canonical) = canonical.filter(|c| *c != private) {
2102 scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
2103 }
2104 scrubbed.replace(plain.as_ref(), "<tmp>")
2105}
2106
2107struct LockDirAudit {
2109 vulnerabilities: Vec<String>,
2110 advisories: Vec<String>,
2111 full: String,
2112 complete: bool,
2115 waivable: bool,
2116}
2117
2118impl LockDirAudit {
2119 fn unchecked() -> LockDirAudit {
2120 LockDirAudit {
2121 vulnerabilities: Vec::new(),
2122 advisories: Vec::new(),
2123 full: String::new(),
2124 complete: false,
2125 waivable: false,
2126 }
2127 }
2128}
2129
2130fn audit_uv_lock(
2136 settings: &crate::config::Settings,
2137 mut production: Production,
2138 dir: &str,
2139 budget: &Budget,
2140) -> LockDirAudit {
2141 let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
2142 let lock_path = if dir.is_empty() {
2143 "uv.lock".to_string()
2144 } else {
2145 format!("{dir}/uv.lock")
2146 };
2147 let prefix = if dir.is_empty() {
2148 String::new()
2149 } else {
2150 format!("{lock_path}: ")
2151 };
2152 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2153 let private = match PrivateDir::create() {
2154 Ok(private) => private,
2155 Err(why) => {
2156 say(&format!(
2157 "no private directory ({}) — did NOT run\n {TMPDIR_NEXT}",
2158 why.kind()
2159 ));
2160 return LockDirAudit::unchecked();
2161 }
2162 };
2163 let canonical = std::fs::canonicalize(private.path()).ok();
2165 let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2166 let export = private.path().join("export.txt");
2167 if budget.spent() {
2168 say(&format!(
2169 "out of time before the export — the audit did NOT run\n {TIMEOUT_NEXT}"
2170 ));
2171 return LockDirAudit::unchecked();
2172 }
2173 let argv = vec![
2174 common::program("uv"),
2175 "export".into(),
2176 "--frozen".into(),
2177 "--all-packages".into(),
2178 "--all-groups".into(),
2179 "--all-extras".into(),
2180 "--no-hashes".into(),
2181 "--no-emit-workspace".into(),
2182 "--format".into(),
2183 "requirements-txt".into(),
2184 "-o".into(),
2185 export.to_string_lossy().into_owned(),
2186 ];
2187 let exported = audited_in(settings, &argv, &dir_path);
2188 if !matches!(exported, Some((true, _))) {
2189 let why = exported
2190 .and_then(|(_, out)| failure_line(&scrub(&out)))
2191 .unwrap_or_else(|| "uv did not answer".to_string());
2192 let place = if dir.is_empty() {
2193 "at the repo root".to_string()
2194 } else {
2195 format!("in {dir}")
2196 };
2197 say(&format!(
2198 "uv export failed — the audit did NOT run\n {}\n Next: `uv export --frozen` {place}",
2199 clip(&why, WARNING_COLUMNS - 2)
2200 ));
2201 return LockDirAudit::unchecked();
2202 }
2203 let raw = std::fs::read_to_string(&export);
2204 let _ = std::fs::remove_file(&export); let raw = match raw {
2207 Ok(raw) => raw,
2208 Err(why) => {
2209 say(&format!(
2210 "could not read export.txt ({}) — the audit did NOT run\n {TMPDIR_NEXT}",
2211 why.kind()
2212 ));
2213 return LockDirAudit::unchecked();
2214 }
2215 };
2216 let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
2217 Ok(lock) => lock,
2218 Err(why) => {
2219 say(&format!(
2220 "could not read uv.lock ({}) — the audit did NOT run\n \
2221 Next: check that {lock_path} is readable, then push again",
2222 why.kind()
2223 ));
2224 return LockDirAudit::unchecked();
2225 }
2226 };
2227 let sources = scan_uv_lock(&lock);
2228 let pins = filter_export(&raw, &sources.pypi);
2229 if !pins.skipped.is_empty() {
2230 let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
2231 common::warn(&skipped_line(&prefix, &names));
2232 }
2233 let unclassified = pins.unclassified.len() + sources.nameless;
2234 if unclassified > 0 {
2235 let source = if prefix.is_empty() {
2236 " from uv.lock"
2237 } else {
2238 ""
2239 };
2240 say(&format!(
2241 "{} could not be classified{source}; not audited\n \
2242 Next: check that each [[package]] in {lock_path} has a name and source",
2243 plural(unclassified, "package")
2244 ));
2245 }
2246 if pins.batches.is_empty() {
2247 say(&format!(
2248 "no PyPI package to audit — the audit did NOT run\n \
2249 Next: none if every package is private; else check {lock_path} sources"
2250 ));
2251 return LockDirAudit::unchecked();
2252 }
2253 let mut audit = LockDirAudit {
2254 vulnerabilities: Vec::new(),
2255 advisories: Vec::new(),
2256 full: String::new(),
2257 complete: true,
2258 waivable: true,
2259 };
2260 let mut audited = 0;
2261 for (index, batch) in pins.batches.iter().enumerate() {
2262 let file = private.path().join(format!("batch-{index}.txt"));
2263 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2264 if budget.spent() {
2265 say(&format!(
2266 "out of time; unaudited versions remain — NOT fully checked\n {TIMEOUT_NEXT}"
2267 ));
2268 audit.complete = false;
2269 break;
2270 }
2271 if let Err(why) = std::fs::write(&file, body) {
2272 say(&format!(
2273 "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n {TMPDIR_NEXT}",
2274 why.kind()
2275 ));
2276 audit.complete = false;
2277 break;
2278 }
2279 let argv = vec![
2280 common::program("pip-audit"),
2281 "-r".into(),
2282 file.to_string_lossy().into_owned(),
2283 "--no-deps".into(),
2284 "--disable-pip".into(),
2285 ];
2286 let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
2287 audit.complete = false;
2288 break;
2289 };
2290 let out = scrub(&out);
2291 let report = read_pip_audit(exit_ok, &out);
2292 let names = if has_rows_to_split(&report, &out) {
2293 production.names(settings, budget, &say)
2294 } else {
2295 None
2296 };
2297 let (report, waivable) = shipped_only(report, &out, names);
2298 audit.waivable &= waivable;
2299 match report {
2300 Report::Vulnerabilities(found) => {
2301 audit.vulnerabilities.extend(found);
2302 audit.full.push_str(&out);
2303 audited += batch.len();
2304 }
2305 Report::Advisories(found) => {
2306 audit.advisories.extend(found);
2307 audited += batch.len();
2308 }
2309 Report::Clean => audited += batch.len(),
2310 Report::CouldNotCheck => {
2311 audit.complete = false;
2312 let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
2313 say(&format!(
2314 "pip-audit could not answer — NOT fully checked\n {}\n {}",
2315 clip(&why, WARNING_COLUMNS - 2),
2316 pip_audit_next(&why)
2317 ));
2318 }
2319 }
2320 }
2321 if !audit.complete {
2322 audit.waivable = false;
2323 }
2324 if audited > 0 {
2325 common::ok(
2326 settings,
2327 &format!(
2328 "audit-python: audited {lock_path} ({}, {} skipped)",
2329 plural(audited, "package version"),
2330 pins.skipped.len()
2331 ),
2332 );
2333 }
2334 audit
2335}
2336
2337fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
2341 let (settings, refs) = (ctx.settings, ctx.push.get());
2342 let release = releasing(refs);
2343 let budget = Budget::new(settings);
2344 let root = std::path::PathBuf::from(common::repo_root());
2345 let dirs = lockfile_dirs("uv.lock");
2346 let only_root = dirs.len() == 1 && dirs[0].is_empty();
2347 let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
2348 let mut full = String::new();
2349 let (mut complete, mut waivable) = (true, true);
2350 for dir in &dirs {
2351 let production = if release {
2352 Production::Unasked(root.join(dir))
2353 } else {
2354 Production::Never
2355 };
2356 let audit = audit_uv_lock(settings, production, dir, &budget);
2357 let label = |ids: Vec<String>| -> Vec<String> {
2358 if dir.is_empty() {
2359 ids
2360 } else {
2361 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
2362 }
2363 };
2364 vulnerabilities.extend(label(audit.vulnerabilities));
2365 advisories.extend(label(audit.advisories));
2366 if !audit.full.is_empty() {
2367 if only_root {
2368 full.push_str(&audit.full);
2369 } else {
2370 full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
2371 }
2372 }
2373 complete &= audit.complete;
2374 waivable &= audit.waivable;
2375 }
2376 let report = if !vulnerabilities.is_empty() {
2377 Report::Vulnerabilities(vulnerabilities)
2378 } else if !complete {
2379 return Ran::Unavailable;
2380 } else if !advisories.is_empty() {
2381 Report::Advisories(advisories)
2382 } else {
2383 Report::Clean
2384 };
2385 Ran::Concluded(Concluded {
2386 tool: "audit-python".to_string(),
2387 report,
2388 full,
2389 waivable: waivable && complete,
2390 complete,
2391 })
2392}
2393
2394fn source_is_this_commit(source: &std::path::Path) -> bool {
2398 let src = source.to_string_lossy();
2399 let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
2400 let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
2401 let unmodified = crate::git::stdout(&[
2402 "-C",
2403 &src,
2404 "status",
2405 "--porcelain",
2406 "--untracked-files=no",
2407 "--",
2408 "*pyproject.toml",
2409 "*uv.lock",
2410 "*requirements*.txt",
2411 ])
2412 .is_some_and(|out| out.trim().is_empty());
2413 here.is_some() && here == there && unmodified
2414}
2415
2416fn normalise(name: &str) -> String {
2418 name.to_ascii_lowercase()
2419 .split(['-', '_', '.'])
2420 .filter(|p| !p.is_empty())
2421 .collect::<Vec<_>>()
2422 .join("-")
2423}
2424
2425fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
2429 let mut rows: Vec<(String, String)> = out
2430 .lines()
2431 .filter_map(|l| {
2432 let cols: Vec<&str> = l.split_whitespace().collect();
2433 let id = cols.get(2)?;
2434 ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
2435 .iter()
2436 .any(|p| id.starts_with(p))
2437 .then(|| (normalise(cols[0]), (*id).to_string()))
2438 })
2439 .collect();
2440 rows.sort();
2441 rows.dedup();
2442 rows
2443}
2444
2445fn pip_rows_all_named(out: &str) -> bool {
2449 out.lines().all(|l| {
2450 let cols: Vec<&str> = l.split_whitespace().collect();
2451 let is_row = cols.len() >= 3
2452 && cols[1].starts_with(|c: char| c.is_ascii_digit())
2453 && cols[2].contains('-')
2454 && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
2455 !is_row || !advisory_ids(cols[2]).is_empty()
2456 })
2457}
2458
2459fn uv_production_names(
2463 settings: &crate::config::Settings,
2464 dir: &std::path::Path,
2465) -> Option<std::collections::HashSet<String>> {
2466 if !has_lockfile("uv.lock") || common::which("uv").is_none() {
2467 return None;
2468 }
2469 let argv = vec![
2470 common::program("uv"),
2471 "export".into(),
2472 "--frozen".into(),
2473 "--all-packages".into(),
2476 "--no-dev".into(),
2477 "--no-default-groups".into(),
2478 "--all-extras".into(),
2480 "--no-hashes".into(),
2481 "--no-emit-workspace".into(),
2482 "--format".into(),
2483 "requirements-txt".into(),
2484 ];
2485 let (ok, out) = audited_in(settings, &argv, dir)?;
2486 if !ok {
2487 return None;
2488 }
2489 Some(
2490 out.lines()
2491 .map(str::trim)
2492 .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
2493 .filter_map(|l| {
2494 l.split(|c: char| "=<>!~;[ ".contains(c))
2495 .next()
2496 .map(normalise)
2497 })
2498 .collect(),
2499 )
2500}
2501
2502pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
2504const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
2505const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
2507const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
2510const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");
2514
2515pub fn is_audit(check: &str) -> bool {
2517 check.starts_with("pre-push-audit-")
2518}
2519
2520fn inputs_of(check: &str) -> &'static [&'static str] {
2524 match check {
2525 "pre-push-audit-rust" => &["Cargo.lock"],
2526 "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
2527 "pre-push-audit-go" => &["go.sum", "go.mod"],
2528 "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
2529 _ => &[],
2530 }
2531}
2532
2533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2535enum AuditMode {
2536 Branch,
2538 Release,
2540}
2541
2542impl AuditMode {
2543 fn of(refs: &[PushRef]) -> AuditMode {
2544 if releasing(refs) {
2545 AuditMode::Release
2546 } else {
2547 AuditMode::Branch
2548 }
2549 }
2550}
2551
2552#[derive(Debug, Clone, PartialEq, Eq)]
2556struct Concluded {
2557 tool: String,
2558 report: Report,
2559 full: String,
2560 waivable: bool,
2561 complete: bool,
2565}
2566
2567enum Ran {
2570 Concluded(Concluded),
2571 Inert,
2573 Unavailable,
2575}
2576
2577#[derive(Debug, Clone)]
2580pub struct Pending {
2581 pub tip: String,
2582 material: String,
2583 body: String,
2584}
2585
2586#[derive(Default)]
2591pub struct Ledger {
2592 pending: std::sync::Mutex<Vec<Pending>>,
2593 peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
2594 fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
2595}
2596
2597impl Ledger {
2598 pub fn take_pending(&self) -> Vec<Pending> {
2600 std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
2601 }
2602
2603 fn peel(&self, oid: &str) -> Option<String> {
2605 if let Some(known) = self
2606 .peeled
2607 .lock()
2608 .unwrap_or_else(|e| e.into_inner())
2609 .get(oid)
2610 {
2611 return known.clone();
2612 }
2613 let commit =
2614 crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
2615 self.peeled
2616 .lock()
2617 .unwrap_or_else(|e| e.into_inner())
2618 .insert(oid.to_string(), commit.clone());
2619 commit
2620 }
2621
2622 fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
2624 let mut commits: Vec<String> = refs
2625 .iter()
2626 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
2627 .filter_map(|r| self.peel(&r.local_oid))
2628 .collect();
2629 commits.sort();
2630 commits.dedup();
2631 commits
2632 }
2633}
2634
2635pub fn write_pending(pending: &Pending) -> Result<(), String> {
2638 let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
2641 .map(|k| k.trim().to_string())
2642 .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
2643 let written = crate::git::succeeds(&[
2644 "notes",
2645 "--ref",
2646 AUDIT_REF,
2647 "add",
2648 "-f",
2649 "-m",
2650 &pending.body,
2651 &key,
2652 ]);
2653 if written {
2654 Ok(())
2655 } else {
2656 Err(format!("git refused to write the audit record {key}"))
2657 }
2658}
2659
2660fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
2662 match mode {
2663 AuditMode::Release => {
2664 let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
2665 Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
2666 }
2667 AuditMode::Branch => {
2668 let names = inputs_of(check);
2669 let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
2670 let mut lines: Vec<String> = listing
2671 .lines()
2672 .filter_map(|entry| {
2673 let (meta, path) = entry.split_once('\t')?;
2674 let blob = meta.split_whitespace().nth(2)?;
2675 let base = path.rsplit('/').next().unwrap_or(path);
2676 names.contains(&base).then(|| format!("{path} {blob}"))
2677 })
2678 .collect();
2679 lines.sort();
2680 Some(format!(
2681 "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
2682 lines.join("\n")
2683 ))
2684 }
2685 }
2686}
2687
2688fn now_secs() -> i64 {
2689 std::time::SystemTime::now()
2690 .duration_since(std::time::UNIX_EPOCH)
2691 .map(|d| d.as_secs() as i64)
2692 .unwrap_or(0)
2693}
2694
2695fn class_of(report: &Report) -> &'static str {
2696 match report {
2697 Report::Clean => "clean",
2698 Report::Advisories(_) => "advisories",
2699 Report::Vulnerabilities(_) => "vulnerabilities",
2700 Report::CouldNotCheck => "unchecked",
2701 }
2702}
2703
2704fn render(concluded: &Concluded, at: i64) -> String {
2705 let items: &[String] = match &concluded.report {
2706 Report::Advisories(v) | Report::Vulnerabilities(v) => v,
2707 Report::Clean | Report::CouldNotCheck => &[],
2708 };
2709 let mut body = format!(
2710 "{AUDIT_FORMAT} {at} {} {} {} {WRITER_VERSION}",
2711 class_of(&concluded.report),
2712 u8::from(concluded.waivable),
2713 concluded.tool
2714 );
2715 for item in items {
2716 body.push_str("\nitem ");
2717 body.push_str(item);
2718 }
2719 body.push_str("\n---\n");
2720 body.push_str(&concluded.full);
2721 body
2722}
2723
2724fn parse(body: &str) -> Option<(i64, Option<String>, Concluded)> {
2727 let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
2728 let mut fields = head.split_whitespace();
2729 if fields.next()? != AUDIT_FORMAT {
2730 return None;
2731 }
2732 let at: i64 = fields.next()?.parse().ok()?;
2733 let class = fields.next()?;
2734 let waivable = fields.next()? == "1";
2735 let tool = fields.next()?.to_string();
2736 let writer = fields.next().map(str::to_string);
2737 let (items_part, full) = match rest.split_once("---\n") {
2738 Some((i, full)) => (i, full.to_string()),
2739 None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
2740 };
2741 let items: Vec<String> = items_part
2742 .lines()
2743 .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
2744 .collect();
2745 let report = match class {
2746 "clean" => Report::Clean,
2747 "advisories" => Report::Advisories(items),
2748 "vulnerabilities" => Report::Vulnerabilities(items),
2749 "unchecked" => Report::CouldNotCheck,
2750 _ => return None,
2751 };
2752 Some((
2753 at,
2754 writer,
2755 Concluded {
2756 tool,
2757 report,
2758 full,
2759 waivable,
2760 complete: true,
2761 },
2762 ))
2763}
2764
2765fn fresh_record(
2767 settings: &crate::config::Settings,
2768 check: &str,
2769 mode: AuditMode,
2770 commit: &str,
2771) -> Option<Concluded> {
2772 let material = key_material(check, mode, commit)?;
2773 let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
2774 .trim()
2775 .to_string();
2776 let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
2777 let (at, writer, concluded) = parse(&body)?;
2778 let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
2779 if writer.as_deref() != Some(WRITER_VERSION) {
2780 return None;
2781 }
2782 UNCHECKED_MAX_AGE_SECS
2783 } else {
2784 crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
2785 };
2786 let age = now_secs() - at;
2787 (0..=max_age).contains(&age).then_some(concluded)
2788}
2789
2790fn fresh_for_refs(
2795 settings: &crate::config::Settings,
2796 ledger: &Ledger,
2797 check: &str,
2798 refs: &[PushRef],
2799) -> Option<Concluded> {
2800 if !crate::gate_stamp::push_stamps_enabled(settings) {
2801 return None;
2802 }
2803 let memo_key = format!(
2804 "{check} {}",
2805 refs.iter()
2806 .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
2807 .collect::<Vec<_>>()
2808 .join(" ")
2809 );
2810 if let Some(known) = ledger
2811 .fresh
2812 .lock()
2813 .unwrap_or_else(|e| e.into_inner())
2814 .get(&memo_key)
2815 {
2816 return known.clone();
2817 }
2818 let mode = AuditMode::of(refs);
2819 let mut found: Option<Concluded> = None;
2820 for commit in ledger.pushed_commits(refs) {
2821 let Some(record) = fresh_record(settings, check, mode, &commit) else {
2822 found = None;
2823 break;
2824 };
2825 if found.as_ref().is_some_and(|prev| *prev != record) {
2826 found = None;
2827 break;
2828 }
2829 found = Some(record);
2830 }
2831 ledger
2832 .fresh
2833 .lock()
2834 .unwrap_or_else(|e| e.into_inner())
2835 .insert(memo_key, found.clone());
2836 found
2837}
2838
2839pub fn owed(
2841 settings: &crate::config::Settings,
2842 ledger: &Ledger,
2843 check: &str,
2844 refs: &[PushRef],
2845) -> bool {
2846 !ledger.pushed_commits(refs).is_empty()
2847 && fresh_for_refs(settings, ledger, check, refs).is_none()
2848}
2849
2850fn recorded(
2854 check: &str,
2855 tool: &str,
2856 ctx: &crate::registry::Ctx,
2857 run: fn(&crate::registry::Ctx) -> Ran,
2858) -> Outcome {
2859 let (settings, refs) = (ctx.settings, ctx.push.get());
2860 let mode = AuditMode::of(refs);
2861 let releasing = mode == AuditMode::Release;
2862 if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
2863 common::ok(
2864 settings,
2865 &format!("{tool}: replaying the audit recorded for this push"),
2866 );
2867 return conclude_waivable(
2868 settings,
2869 &record.tool,
2870 record.report,
2871 releasing,
2872 &record.full,
2873 record.waivable,
2874 );
2875 }
2876 let (outcome, concluded) = match run(ctx) {
2877 Ran::Concluded(concluded) => (
2878 conclude_waivable(
2879 settings,
2880 &concluded.tool,
2881 concluded.report.clone(),
2882 releasing,
2883 &concluded.full,
2884 concluded.waivable,
2885 ),
2886 Some(concluded),
2887 ),
2888 Ran::Unavailable => (
2889 Outcome::Unavailable,
2890 Some(Concluded {
2891 tool: tool.to_string(),
2892 report: Report::CouldNotCheck,
2893 full: String::new(),
2894 waivable: false,
2895 complete: true,
2896 }),
2897 ),
2898 Ran::Inert => (Outcome::Inert, None),
2899 };
2900 let concluded = concluded.filter(|concluded| {
2902 concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
2903 });
2904 if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
2905 let body = render(&concluded, now_secs());
2906 let records: Vec<Pending> = ctx
2907 .audits
2908 .pushed_commits(refs)
2909 .into_iter()
2910 .filter_map(|commit| {
2911 key_material(check, mode, &commit).map(|material| Pending {
2912 tip: commit,
2913 material,
2914 body: body.clone(),
2915 })
2916 })
2917 .collect();
2918 ctx.audits
2919 .pending
2920 .lock()
2921 .unwrap_or_else(|e| e.into_inner())
2922 .extend(records);
2923 }
2924 outcome
2925}
2926
2927pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
2928 recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
2929}
2930
2931pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
2932 recorded("pre-push-audit-js", "audit-js", ctx, js_run)
2933}
2934
2935pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
2936 recorded("pre-push-audit-go", "audit-go", ctx, go_run)
2937}
2938
2939pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
2940 recorded("pre-push-audit-python", "audit-python", ctx, python_run)
2941}
2942
2943#[cfg(test)]
2944mod tests {
2945 use super::*;
2946
2947 #[test]
2953 fn a_uv_project_is_audited_through_its_venv() {
2954 let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
2955 let _ = std::fs::remove_dir_all(&root);
2956
2957 std::fs::create_dir_all(&root).unwrap();
2960 assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
2961
2962 let sp = root
2969 .join(".venv")
2970 .join("lib")
2971 .join("python3.13")
2972 .join("site-packages");
2973 std::fs::create_dir_all(&sp).unwrap();
2974 assert_eq!(
2975 venv_site_packages(root.to_str().unwrap(), None),
2976 Some(sp.to_string_lossy().into_owned())
2977 );
2978
2979 let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
2981 let _ = std::fs::remove_dir_all(&win);
2982 let wsp = win.join(".venv").join("Lib").join("site-packages");
2983 std::fs::create_dir_all(&wsp).unwrap();
2984 assert_eq!(
2985 venv_site_packages(win.to_str().unwrap(), None),
2986 Some(wsp.to_string_lossy().into_owned())
2987 );
2988
2989 let _ = std::fs::remove_dir_all(&root);
2990 let _ = std::fs::remove_dir_all(&win);
2991 }
2992
2993 fn tag(name: &str) -> PushRef {
2994 PushRef {
2995 local_ref: name.to_string(),
2996 local_oid: "a".repeat(40),
2997 remote_ref: name.to_string(),
2998 remote_oid: "0".repeat(40),
2999 }
3000 }
3001
3002 #[test]
3005 fn pip_audit_rows_name_their_packages_normalised() {
3006 let out = "Name Version ID Fix Versions\n\
3007 ---------- ------- ------------------- ------------\n\
3008 Pytest_Cov 4.0.0 GHSA-aaaa-bbbb-cccc 4.1.0\n\
3009 requests 2.31.0 PYSEC-2023-74 2.31.1\n\
3010 requests 2.31.0 CVE-2024-35195 2.32.0\n\
3011 Found 3 known vulnerabilities in 2 packages\n";
3012 let names: Vec<String> = pip_vulnerable_rows(out)
3013 .into_iter()
3014 .map(|(n, _)| n)
3015 .collect();
3016 assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
3017 assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
3018 }
3019
3020 #[test]
3021 fn advisory_ids_are_found_wherever_they_sit() {
3022 let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
3023 ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
3024 assert_eq!(
3025 advisory_ids(text),
3026 vec![
3027 "CVE-2024-35195",
3028 "GHSA-h3mg-xc3c-68pw",
3029 "GO-2024-2687",
3030 "OSV-2024-12",
3031 "PYSEC-2023-74",
3032 "RUSTSEC-2025-0001"
3033 ]
3034 );
3035 }
3036
3037 #[test]
3038 fn a_waiver_is_reasoned_dated_and_bounded() {
3039 let today = days_from_date("2026-10-05").unwrap();
3040 let w = Waivers::parse(
3041 "# id expires reason\n\
3042 GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
3043 GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
3044 GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
3045 GHSA-jjjj-kkkk-llll 2026-11-01\n\
3046 GHSA-mmmm-nnnn-oooo soon no date\n",
3047 today,
3048 );
3049 assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
3050 assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
3051 assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
3052 assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
3053 assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
3054 assert_eq!(w.problems().len(), 4);
3055 assert_eq!(days_from_date("1970-01-01"), Some(0));
3056 assert_eq!(days_from_date("2026-02-30"), None);
3057 assert!(days_from_date("2028-02-29").is_some());
3058 assert_eq!(days_from_date("2026-13-01"), None);
3059 }
3060
3061 #[test]
3062 fn two_locked_versions_are_two_answers() {
3063 let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
3064 Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
3065 let ids = vec![
3066 "RUSTSEC-2025-0010".to_string(),
3067 "RUSTSEC-2025-0011".to_string(),
3068 ];
3069 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3070 "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
3071 "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
3072 _ => None,
3073 });
3074 assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
3075 assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
3076 }
3077
3078 #[test]
3079 fn a_pip_row_without_a_nameable_id_is_unwaivable() {
3080 let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
3081 let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
3082 assert!(pip_rows_all_named(named));
3083 assert!(!pip_rows_all_named(unnamed));
3084 }
3085
3086 #[test]
3087 fn a_crate_ships_unless_its_tree_says_otherwise() {
3088 let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
3089 Crate: app\nID: RUSTSEC-2025-0002\n\
3090 Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
3091 let ids = vec![
3092 "RUSTSEC-2025-0001".to_string(),
3093 "RUSTSEC-2025-0002".to_string(),
3094 "RUSTSEC-2025-0003".to_string(),
3095 "RUSTSEC-2025-0004".to_string(),
3096 ];
3097 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3098 "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
3100 "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
3101 "odd" => Some("odd v1.0.0\n".into()),
3103 _ => None,
3104 });
3105 assert_eq!(
3107 shipped,
3108 vec![
3109 "RUSTSEC-2025-0002",
3110 "RUSTSEC-2025-0003",
3111 "RUSTSEC-2025-0004"
3112 ]
3113 );
3114 assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
3115 }
3116
3117 #[test]
3118 fn a_release_is_a_v_number_tag() {
3119 assert!(releasing(&[tag("refs/tags/v1.6.6")]));
3120 assert!(releasing(&[tag("refs/tags/v2")]));
3121 assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
3122 assert!(!releasing(&[tag("refs/tags/release")]));
3123 assert!(!releasing(&[tag("refs/heads/v1-styles")]));
3124 assert!(!releasing(&[tag("refs/heads/main")]));
3125 assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
3127 }
3128
3129 #[test]
3132 fn cargo_audit_ids_decide_not_the_exit_code() {
3133 assert_eq!(
3134 read_cargo_audit(true, "ok, 312 crates checked"),
3135 Report::Clean
3136 );
3137 assert_eq!(
3138 read_cargo_audit(false, "error: couldn't fetch advisory database"),
3139 Report::CouldNotCheck
3140 );
3141 let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
3142 assert_eq!(
3143 read_cargo_audit(true, warn),
3144 Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
3145 );
3146 let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
3147 assert_eq!(
3148 read_cargo_audit(false, vuln),
3149 Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
3150 );
3151 assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
3153 }
3154
3155 fn real_report() -> String {
3158 [
3159 "Crate: paste",
3160 "Version: 1.0.15",
3161 "Warning: unmaintained",
3162 "ID: RUSTSEC-2024-0436",
3163 "URL: https://rustsec.org/advisories/RUSTSEC-2024-0436",
3164 "",
3165 "Crate: lru",
3166 "Version: 0.12.5",
3167 "Warning: unsound",
3168 "ID: RUSTSEC-2026-0253",
3169 "",
3170 "Crate: lru",
3171 "Version: 0.12.5",
3172 "ID: RUSTSEC-2026-0002",
3173 "",
3174 "warning: 3 allowed warnings found",
3175 ]
3176 .join("\n")
3177 }
3178
3179 #[test]
3180 fn an_advisory_is_paired_with_its_crate() {
3181 let pairs = ids_with_crates(&real_report());
3182 assert_eq!(
3183 pairs,
3184 vec![
3185 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3186 ("RUSTSEC-2026-0253".into(), Some("lru".into())),
3187 ("RUSTSEC-2026-0002".into(), Some("lru".into())),
3188 ]
3189 );
3190 }
3191
3192 #[test]
3195 fn a_loose_id_borrows_no_crate() {
3196 let out = "Crate: paste\nID: RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
3197 assert_eq!(
3198 ids_with_crates(out),
3199 vec![
3200 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3201 ("RUSTSEC-2025-0001".into(), None),
3202 ]
3203 );
3204 }
3205
3206 #[test]
3209 fn only_local_crates_are_named_as_reached() {
3210 let tree =
3211 "lru v0.12.5\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
3212 assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
3213 assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
3214 }
3215
3216 #[test]
3220 fn the_warning_names_the_crate_and_what_reaches_it() {
3221 let calls = std::cell::RefCell::new(Vec::new());
3222 let fake = |k: &str| {
3223 calls.borrow_mut().push(k.to_string());
3224 Some(format!(
3225 "{k} v1\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
3226 ))
3227 };
3228 let out = real_report();
3229 let got = attribute(read_cargo_audit(true, &out), &out, fake);
3230 assert_eq!(
3231 got,
3232 Report::Advisories(vec![
3233 "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
3234 "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
3235 "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
3236 ])
3237 );
3238 assert_eq!(
3239 calls.into_inner(),
3240 vec!["paste", "lru"],
3241 "one call per crate"
3242 );
3243 }
3244
3245 #[test]
3249 fn a_crate_outside_the_build_graph_says_so() {
3250 let out = "Crate: wezterm-input-types\nID: RUSTSEC-2025-0001";
3251 let got = attribute(read_cargo_audit(true, out), out, |_| {
3252 Some("warning: nothing to print.".into())
3253 });
3254 assert_eq!(
3255 got,
3256 Report::Advisories(vec![
3257 "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
3258 ])
3259 );
3260 }
3261
3262 #[test]
3265 fn attribution_never_changes_the_verdict() {
3266 let spawned = std::cell::Cell::new(false);
3267 let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
3268 spawned.set(true);
3269 None
3270 });
3271 assert_eq!(clean, Report::Clean);
3272 assert!(!spawned.get(), "a clean report must spawn nothing");
3273
3274 let out = "Crate: paste\nID: RUSTSEC-2024-0436";
3275 let blind = attribute(read_cargo_audit(false, out), out, |_| None);
3276 assert_eq!(
3277 blind,
3278 Report::Vulnerabilities(vec![
3279 "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
3280 ])
3281 );
3282 }
3283
3284 #[test]
3285 fn npm_audit_summary_decides() {
3286 assert_eq!(
3287 read_npm_audit(true, "found 0 vulnerabilities\n"),
3288 Report::Clean
3289 );
3290 assert_eq!(
3291 read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
3292 Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
3293 );
3294 assert_eq!(
3297 read_npm_audit(
3298 false,
3299 "# npm audit report\n\nvite 6.0.0 - 6.1.5\nSeverity: high\n\n\
3300 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n npm audit fix\n"
3301 ),
3302 Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
3303 );
3304 assert_eq!(
3305 read_npm_audit(false, "1 vulnerability (1 high)\n"),
3306 Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
3307 );
3308 assert_eq!(
3309 read_npm_audit(true, "up to date, audited 100 packages\n"),
3310 Report::Clean
3311 );
3312 assert_eq!(
3313 read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
3314 Report::CouldNotCheck
3315 );
3316 }
3317
3318 #[test]
3319 fn pnpm_audit_summary_decides() {
3320 assert_eq!(
3321 read_pnpm_audit(true, "No known vulnerabilities found\n"),
3322 Report::Clean
3323 );
3324 assert_eq!(
3327 read_pnpm_audit(
3328 false,
3329 "│ More info │ https://github.com/advisories/GHSA-395f │\n\
3330 └───────────┴──────────────────────────────────────────┘\n\
3331 107 vulnerabilities found\n\
3332 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
3333 ),
3334 Report::Vulnerabilities(vec![
3335 "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
3336 ])
3337 );
3338 assert_eq!(
3339 read_pnpm_audit(false, "1 vulnerabilities found\n"),
3340 Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
3341 );
3342 assert_eq!(
3343 read_pnpm_audit(
3344 false,
3345 " ERR_PNPM_AUDIT_BAD_RESPONSE The audit endpoint responded with 503\n"
3346 ),
3347 Report::CouldNotCheck
3348 );
3349 }
3350
3351 #[test]
3354 fn govulncheck_ids_decide_not_the_exit_code() {
3355 assert_eq!(
3356 read_govulncheck(true, "No vulnerabilities found.\n"),
3357 Report::Clean
3358 );
3359 assert_eq!(
3360 read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
3361 Report::CouldNotCheck
3362 );
3363 assert_eq!(
3366 read_govulncheck(
3367 true,
3368 "=== Informational ===\nVulnerability #1: GO-2023-1840\n More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
3369 ),
3370 Report::Advisories(vec!["GO-2023-1840".into()])
3371 );
3372 assert_eq!(
3373 read_govulncheck(
3374 false,
3375 "Vulnerability #1: GO-2022-0969\n Your code calls it.\nGO-2022-0969 again\n"
3376 ),
3377 Report::Vulnerabilities(vec!["GO-2022-0969".into()])
3378 );
3379 assert_eq!(
3381 read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
3382 Report::Clean
3383 );
3384 }
3385
3386 #[test]
3387 fn pip_audit_sentence_decides() {
3388 assert_eq!(
3389 read_pip_audit(true, "No known vulnerabilities found\n"),
3390 Report::Clean
3391 );
3392 assert_eq!(
3393 read_pip_audit(
3394 false,
3395 "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
3396 ),
3397 Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
3398 );
3399 assert_eq!(
3400 read_pip_audit(false, "ERROR: could not resolve\n"),
3401 Report::CouldNotCheck
3402 );
3403 }
3404
3405 fn lock_block(name: Option<&str>, source: &str) -> String {
3406 let mut block = String::from("[[package]]\n");
3407 if let Some(name) = name {
3408 block.push_str(&format!("name = \"{name}\"\n"));
3409 }
3410 block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
3411 block
3412 }
3413
3414 #[test]
3415 fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
3416 let pypi = "{ registry = \"https://pypi.org/simple\" }";
3417 let lock = [
3418 lock_block(Some("Requests"), pypi),
3419 lock_block(
3420 Some("slashed"),
3421 "{ registry = \"https://pypi.org/simple/\" }",
3422 ),
3423 lock_block(
3424 Some("mirror"),
3425 "{ registry = \"https://mirror.example/simple\" }",
3426 ),
3427 lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
3428 lock_block(Some("pathdep"), "{ path = \"../x\" }"),
3429 lock_block(Some("edit"), "{ editable = \".\" }"),
3430 lock_block(Some("virt"), "{ virtual = \".\" }"),
3431 lock_block(Some("twice"), pypi),
3432 lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
3433 lock_block(None, pypi),
3434 "[package.metadata]\nname = \"ignored\"\n".to_string(),
3435 ]
3436 .concat();
3437 let sources = scan_uv_lock(&lock);
3438 let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
3439 assert_eq!(admitted, ["requests", "slashed"]);
3440 assert_eq!(sources.nameless, 1);
3441 }
3442
3443 #[test]
3444 fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
3445 let pypi: std::collections::BTreeSet<String> =
3446 ["numpy", "idna", "requests"].map(String::from).into();
3447 let raw = "\
3448# generated
3449numpy==1.26.4 ; python_full_version < '3.12'
3450numpy==2.1.0 ; python_full_version >= '3.12'
3451numpy==2.1.0 ; sys_platform == 'win32'
3452idna==3.7
3453platform-kernel==0.1.0
3454requests @ https://example.com/r.whl
3455";
3456 let pins = filter_export(raw, &pypi);
3457 assert_eq!(pins.versions, 3);
3458 assert_eq!(pins.batches.len(), 2);
3459 assert_eq!(
3460 pins.batches[0].get("numpy").map(String::as_str),
3461 Some("1.26.4")
3462 );
3463 assert_eq!(
3464 pins.batches[1].get("numpy").map(String::as_str),
3465 Some("2.1.0")
3466 );
3467 assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
3468 assert!(pins.skipped.contains("platform-kernel"));
3469 assert!(pins.unclassified.contains("requests"));
3470 }
3471
3472 const HASHED: &str = "\
3474# This file was autogenerated by uv via the following command:
3475# ./compile-requirements.sh
3476anyio==4.15.1 \\
3477 --hash=sha256:6152 \\
3478 --hash=sha256:9f28
3479 # via
3480 # starlette
3481idna==3.7 \\
3482 --hash=sha256:aaaa
3483torch==2.14.0+cpu \\
3484 --hash=sha256:bbbb
3485 # via -r requirements.in
3486";
3487
3488 #[test]
3489 fn only_a_fully_hashed_file_skips_the_resolve() {
3490 let pins = hashed_pins_in(HASHED).expect("hashed");
3491 assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
3492 assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
3494 let one_unhashed = format!("{HASHED}idna==3.7\n");
3495 assert_eq!(hashed_pins_in(&one_unhashed), None);
3496 let ranged = "requests>=2.0 \\\n --hash=sha256:cccc\n";
3497 assert_eq!(hashed_pins_in(ranged), None);
3498 let included = format!("-r requirements-upload.txt\n{HASHED}");
3499 assert_eq!(hashed_pins_in(&included), None);
3500 let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
3501 assert_eq!(hashed_pins_in(&indexed), None);
3502 let marked =
3504 format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n --hash=sha256:dddd\n");
3505 assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
3506 assert_eq!(
3507 hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
3508 None
3509 );
3510 assert_eq!(hashed_pins_in("# fixture\n"), None);
3511 assert_eq!(hashed_pins_in(""), None);
3512 }
3513
3514 #[test]
3515 fn marked_pins_are_stripped_and_their_versions_batched_apart() {
3516 let text = "\
3517six==1.16.0 \\
3518 --hash=sha256:aaaa
3519numpy==1.26.4 ; python_version == '3.9' \\
3520 --hash=sha256:bbbb
3521numpy==2.1.0 ; python_version == '3.12' \\
3522 --hash=sha256:cccc
3523";
3524 let pins = hashed_pins_in(text).expect("hashed");
3525 assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
3526 let batches = batches_of(pins.pairs);
3527 assert_eq!(batches.len(), 2);
3528 assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
3529 assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
3530 assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
3531 }
3532
3533 const SKIPPING: &str = "\
3536Found 2 known vulnerabilities in 1 package
3537Name Version ID Fix Versions
3538--------- ------- --------------- ------------
3539starlette 0.41.3 PYSEC-2026-1941 0.47.2
3540starlette 0.41.3 PYSEC-2026-1942 0.49.1
3541
3542Name Skip Reason
3543----- -------------------------------------------------------------------------
3544torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
3545";
3546
3547 #[test]
3548 fn the_skip_table_names_its_packages_and_is_no_finding() {
3549 assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
3550 assert_eq!(
3551 pip_vulnerable_rows(SKIPPING),
3552 vec![
3553 ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
3554 ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
3555 ]
3556 );
3557 assert!(pip_rows_all_named(SKIPPING));
3558 let clean = "No known vulnerabilities found\nName Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
3559 assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
3560 assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
3561 }
3562
3563 #[test]
3564 fn the_skipped_line_names_three_and_counts_the_rest() {
3565 let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
3566 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
3567 assert_eq!(
3568 skipped_line("", &refs),
3569 "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
3570 );
3571 assert_eq!(
3572 skipped_line("", &refs[..1]),
3573 "audit-python: 1 private/non-PyPI package skipped (a)"
3574 );
3575 let long = "services/laya-decisions/requirements.txt: ";
3576 assert_eq!(
3577 skipped_line(long, &["torch", "triton"]),
3578 format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
3579 );
3580 }
3581
3582 #[test]
3583 fn scrub_names_the_canonical_private_path_too() {
3584 let plain = std::path::Path::new("/var/folders/a/audit-1");
3585 let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
3586 assert_eq!(
3587 scrub_private(
3588 "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
3589 plain,
3590 canonical
3591 ),
3592 "x <tmp>/b and <tmp>/c"
3593 );
3594 }
3595
3596 #[test]
3597 fn production_names_are_never_asked_off_a_release_or_out_of_time() {
3598 let settings = crate::config::Settings::default();
3599 let spent = Budget {
3600 started: std::time::Instant::now(),
3601 limit: Some(std::time::Duration::ZERO),
3602 };
3603 let said = std::cell::RefCell::new(Vec::<String>::new());
3604 let say = |m: &str| said.borrow_mut().push(m.to_string());
3605 let dir = std::env::temp_dir();
3606
3607 let mut off = Production::Never;
3608 assert!(off.names(&settings, &spent, &say).is_none());
3609 assert!(matches!(off, Production::Never), "no release never asks");
3610 assert!(said.borrow().is_empty());
3611
3612 let mut late = Production::Unasked(dir.clone());
3613 assert!(late.names(&settings, &spent, &say).is_none());
3614 assert!(late.names(&settings, &spent, &say).is_none());
3615 assert!(
3616 matches!(late, Production::Asked(None)),
3617 "spent is remembered as unknown"
3618 );
3619
3620 let fresh = Budget {
3623 started: std::time::Instant::now(),
3624 limit: None,
3625 };
3626 let mut asked = Production::Unasked(dir);
3627 assert!(asked.names(&settings, &fresh, &say).is_none());
3628 assert!(matches!(asked, Production::Asked(None)));
3629 let said = said.borrow();
3630 assert_eq!(said.len(), 1, "warned once: {said:?}");
3631 assert!(said[0].contains("every finding counts"), "{said:?}");
3632 assert!(said[0].contains("greengate.timeout"), "{said:?}");
3633 }
3634
3635 #[test]
3636 fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
3637 for why in [
3638 "ConnectionError: Max retries exceeded",
3639 "error: request timed out",
3640 "SSL: CERTIFICATE_VERIFY_FAILED",
3641 "Temporary failure in name resolution",
3642 ] {
3643 assert!(pip_audit_next(why).contains("the network"), "{why}");
3644 }
3645 for why in [
3646 "(no output)",
3647 "ModuleNotFoundError: No module named 'pip_audit'",
3648 ] {
3649 assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
3650 }
3651 }
3652
3653 #[test]
3654 fn only_readable_vulnerability_rows_need_the_split() {
3655 let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
3656 assert!(has_rows_to_split(
3657 &Report::Vulnerabilities(vec!["certifi".into()]),
3658 rows
3659 ));
3660 assert!(!has_rows_to_split(
3661 &Report::Vulnerabilities(vec!["x".into()]),
3662 "Found 1\n"
3663 ));
3664 assert!(!has_rows_to_split(&Report::Clean, rows));
3665 assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
3666 }
3667
3668 #[test]
3669 fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
3670 let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
3671 let guard = PrivateDir::create_at(path.clone()).unwrap();
3672 #[cfg(unix)]
3673 {
3674 use std::os::unix::fs::PermissionsExt;
3675 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
3676 assert_eq!(mode & 0o777, 0o700);
3677 }
3678 assert!(PrivateDir::create_at(path.clone()).is_err());
3679 assert!(path.is_dir(), "the refused attempt must leave it alone");
3680 drop(guard);
3681 assert!(!path.exists());
3682 }
3683}