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