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 {
1256 let settings = ctx.settings;
1257 if !has_lockfile("go.sum") {
1258 return Ran::Inert;
1259 }
1260 if common::which("govulncheck").is_none() {
1261 common::warn(
1262 "audit-go: govulncheck is not installed \
1263 (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1264 );
1265 return Ran::Unavailable;
1266 }
1267 let argv = vec![common::program("govulncheck"), "./...".into()];
1268 let merged = audit_each_dir(
1269 settings,
1270 "audit-go",
1271 "go.sum",
1272 |_| Some(argv.clone()),
1273 read_govulncheck,
1274 |_, report, _| report,
1275 );
1276 Ran::Concluded(Concluded {
1277 tool: "audit-go".to_string(),
1278 report: merged.report,
1279 full: merged.full,
1280 waivable: merged.waivable,
1281 complete: merged.complete,
1282 })
1283}
1284
1285fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1286 let (settings, refs) = (ctx.settings, ctx.push.get());
1287 if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1288 return Ran::Inert;
1289 }
1290 if common::which("pip-audit").is_none() {
1291 common::warn(
1292 "audit-python: pip-audit is not installed (pip install pip-audit) — \
1293 the audit did NOT run",
1294 );
1295 return Ran::Unavailable;
1296 }
1297 let root = common::repo_root();
1298 if !lockfile_dirs("requirements.txt").is_empty() {
1301 let root_path = std::path::PathBuf::from(&root);
1302 let rel_of = |dir: &std::path::Path| {
1303 dir.strip_prefix(&root_path)
1304 .map(|p| p.to_string_lossy().into_owned())
1305 .unwrap_or_default()
1306 };
1307 let answer_in = |dir: &std::path::Path| {
1308 let pins = hashed_pins(dir);
1309 let names = pins.as_ref().map(HashedPins::names);
1310 let answer = match pins {
1311 Some(pins) if pins.marked => audit_marked_pins(settings, dir, &rel_of(dir), pins),
1312 hashed => {
1313 let mut argv = vec![
1314 common::program("pip-audit"),
1315 "-r".into(),
1316 "requirements.txt".into(),
1317 ];
1318 if hashed.is_some() {
1322 argv.extend(["--no-deps".into(), "--disable-pip".into()]);
1323 }
1324 answer_of(settings, &argv, dir, read_pip_audit)
1325 }
1326 };
1327 let DirAnswer::Read {
1328 report,
1329 out,
1330 full,
1331 gap,
1332 } = answer
1333 else {
1334 return answer;
1335 };
1336 let skipped = pip_skipped_names(&out);
1337 if skipped.is_empty() {
1338 return DirAnswer::Read {
1339 report,
1340 out,
1341 full,
1342 gap,
1343 };
1344 }
1345 let skipped_names: Vec<&str> = skipped.iter().map(String::as_str).collect();
1346 common::warn(&skipped_line(
1347 &requirements_prefix(&rel_of(dir)),
1348 &skipped_names,
1349 ));
1350 let all_skipped = names.is_some_and(|n| skipped.len() >= n);
1352 let report = if all_skipped && !matches!(report, Report::Vulnerabilities(_)) {
1353 Report::CouldNotCheck
1354 } else {
1355 report
1356 };
1357 DirAnswer::Read {
1358 report,
1359 out,
1360 full,
1361 gap,
1362 }
1363 };
1364 let merged = audit_each_dir_answered(
1365 "audit-python",
1366 "requirements.txt",
1367 answer_in,
1368 |_, report, _| report,
1369 );
1370 let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1373 return Ran::Concluded(Concluded {
1374 tool: "audit-python".to_string(),
1375 report: merged.report,
1376 full: merged.full,
1377 waivable,
1378 complete: merged.complete,
1379 });
1380 }
1381 let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1382 vec![
1390 common::program("pip-audit"),
1391 "--path".into(),
1392 site_packages,
1393 "--skip-editable".into(),
1396 ]
1397 } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1398 return python_lock_run(ctx);
1400 } else {
1401 common::warn(
1402 "audit-python: the audit did NOT run — found no requirements.txt,\n \
1403 no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n \
1404 Next: `uv sync`, or install uv so uv.lock can be audited.",
1405 );
1406 return Ran::Unavailable;
1407 };
1408 let Some((exit_ok, out)) = audited(settings, &argv) else {
1409 return Ran::Unavailable;
1410 };
1411 let report = read_pip_audit(exit_ok, &out);
1416 let production = if releasing(refs) && has_rows_to_split(&report, &out) {
1417 uv_production_names(settings, std::path::Path::new(&root))
1418 } else {
1419 None
1420 };
1421 let (report, waivable) = shipped_only(report, &out, production.as_ref());
1422 Ran::Concluded(Concluded {
1423 tool: "audit-python".to_string(),
1424 report,
1425 full: out,
1426 waivable,
1427 complete: true,
1428 })
1429}
1430
1431fn shipped_only(
1437 mut report: Report,
1438 out: &str,
1439 production: Option<&std::collections::HashSet<String>>,
1440) -> (Report, bool) {
1441 let mut waivable = pip_rows_all_named(out);
1442 if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1443 let rows = pip_vulnerable_rows(out);
1444 if !rows.is_empty() {
1445 let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1446 .into_iter()
1447 .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1448 .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1449 if ships {
1450 s.push(row);
1451 } else {
1452 d.push(row);
1453 }
1454 (s, d)
1455 });
1456 warn_dev_only("audit-python", &dev_only);
1457 waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1458 report = if shipped.is_empty() {
1459 Report::Clean
1460 } else {
1461 Report::Vulnerabilities(shipped)
1462 };
1463 }
1464 }
1465 (report, waivable)
1466}
1467
1468fn has_rows_to_split(report: &Report, out: &str) -> bool {
1472 matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
1473}
1474
1475enum Production {
1478 Never,
1480 Unasked(std::path::PathBuf),
1482 Asked(Option<std::collections::HashSet<String>>),
1484}
1485
1486impl Production {
1487 fn names(
1491 &mut self,
1492 settings: &crate::config::Settings,
1493 budget: &Budget,
1494 say: &dyn Fn(&str),
1495 ) -> Option<&std::collections::HashSet<String>> {
1496 if let Production::Unasked(dir) = self {
1497 *self = Production::Asked(if budget.spent() {
1498 say(&format!(
1499 "out of time before the dev-only split — every finding counts\n {TIMEOUT_NEXT}"
1500 ));
1501 None
1502 } else {
1503 uv_production_names(settings, dir)
1504 });
1505 }
1506 match self {
1507 Production::Asked(names) => names.as_ref(),
1508 Production::Never | Production::Unasked(_) => None,
1509 }
1510 }
1511}
1512
1513const TIMEOUT_NEXT: &str =
1515 "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";
1516
1517const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";
1519
1520fn pip_audit_next(why: &str) -> &'static str {
1523 let why = why.to_ascii_lowercase();
1527 let network = [
1528 "network",
1529 "connect",
1530 "timed out",
1531 "timeout",
1532 "resolve",
1533 "dns",
1534 "ssl",
1535 "certificate",
1536 "unreachable",
1537 "temporary failure",
1538 ]
1539 .iter()
1540 .any(|word| why.contains(word));
1541 if network {
1542 "Next: check the network, then push again"
1543 } else {
1544 "Next: `pip-audit --version` to check the install, then push again"
1545 }
1546}
1547
1548const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1551
1552const WARNING_COLUMNS: usize = 80;
1554
1555const NAMES_SHOWN: usize = 3;
1557
1558struct PrivateDir {
1561 path: std::path::PathBuf,
1562}
1563
1564impl PrivateDir {
1565 fn create() -> std::io::Result<PrivateDir> {
1567 Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1568 }
1569
1570 fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1573 #[cfg(unix)]
1574 let builder = {
1575 let mut unix_builder = std::fs::DirBuilder::new();
1576 std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1577 unix_builder
1578 };
1579 #[cfg(not(unix))]
1580 let builder = std::fs::DirBuilder::new();
1581 builder.create(&path)?;
1582 Ok(PrivateDir { path })
1583 }
1584
1585 fn path(&self) -> &std::path::Path {
1586 &self.path
1587 }
1588}
1589
1590impl Drop for PrivateDir {
1591 fn drop(&mut self) {
1592 let _ = std::fs::remove_dir_all(&self.path); }
1594}
1595
1596struct Budget {
1599 started: std::time::Instant,
1600 limit: Option<std::time::Duration>,
1602}
1603
1604impl Budget {
1605 fn new(settings: &crate::config::Settings) -> Budget {
1606 Budget {
1607 started: std::time::Instant::now(),
1608 limit: Some(common::check_timeout(settings))
1609 .filter(|secs| *secs > 0)
1610 .map(std::time::Duration::from_secs),
1611 }
1612 }
1613
1614 fn spent(&self) -> bool {
1615 self.limit
1616 .is_some_and(|limit| self.started.elapsed() >= limit)
1617 }
1618}
1619
1620#[derive(Debug, Default, PartialEq, Eq)]
1622struct LockSources {
1623 pypi: std::collections::BTreeSet<String>,
1625 nameless: usize,
1627}
1628
1629fn is_pypi_source(source_field: &str) -> bool {
1631 source_field
1632 .split_once("registry = \"")
1633 .and_then(|(_, rest)| rest.split('"').next())
1634 .is_some_and(|url| url.trim_end_matches('/') == PYPI_REGISTRY)
1635}
1636
1637fn scan_uv_lock(text: &str) -> LockSources {
1641 struct Block {
1642 name: Option<String>,
1643 pypi: bool,
1644 }
1645 let mut blocks: Vec<Block> = Vec::new();
1646 let mut top_level = false;
1647 for line in text.lines() {
1648 if line.starts_with('[') {
1649 top_level = line.trim() == "[[package]]";
1650 if top_level {
1651 blocks.push(Block {
1652 name: None,
1653 pypi: false,
1654 });
1655 }
1656 continue;
1657 }
1658 let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1659 continue;
1660 };
1661 if let Some(value) = line.strip_prefix("name = ") {
1662 if block.name.is_none() {
1663 block.name = value.split('"').nth(1).map(normalise);
1664 }
1665 } else if let Some(value) = line.strip_prefix("source = ") {
1666 block.pypi = is_pypi_source(value);
1667 }
1668 }
1669 let mut sources = LockSources::default();
1670 let mut rejected = std::collections::BTreeSet::new();
1671 for block in blocks {
1672 match block.name.filter(|n| !n.is_empty()) {
1673 None => sources.nameless += 1,
1674 Some(name) if block.pypi => {
1675 sources.pypi.insert(name);
1676 }
1677 Some(name) => {
1678 rejected.insert(name);
1679 }
1680 }
1681 }
1682 sources.pypi.retain(|name| !rejected.contains(name));
1683 sources
1684}
1685
1686#[derive(Debug, Default, PartialEq, Eq)]
1688struct ExportPins {
1689 batches: Vec<std::collections::BTreeMap<String, String>>,
1692 versions: usize,
1694 skipped: std::collections::BTreeSet<String>,
1696 unclassified: std::collections::BTreeSet<String>,
1698}
1699
1700fn exact_pin(line: &str) -> Option<(String, String)> {
1703 let spec = line.split(';').next()?.trim();
1704 let (name, version) = spec.split_once("==")?;
1705 let name = name.split('[').next()?.trim();
1706 let version = version.trim();
1707 let name_ok = !name.is_empty()
1708 && name
1709 .chars()
1710 .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1711 let version_ok = !version.is_empty()
1712 && version
1713 .chars()
1714 .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1715 (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1716}
1717
1718fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1719 let mut pins = ExportPins::default();
1720 let mut pairs = std::collections::BTreeSet::new();
1721 for line in raw.lines().map(str::trim) {
1722 if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1723 continue;
1724 }
1725 let name = normalise(
1726 line.split(|c: char| "=<>!~;[ @".contains(c))
1727 .next()
1728 .unwrap_or_default(),
1729 );
1730 if name.is_empty() {
1731 continue;
1732 }
1733 if !pypi.contains(&name) {
1734 pins.skipped.insert(name);
1735 continue;
1736 }
1737 match exact_pin(line) {
1738 Some(pair) => {
1739 pairs.insert(pair);
1740 }
1741 None => {
1742 pins.unclassified.insert(name);
1743 }
1744 }
1745 }
1746 pins.versions = pairs.len();
1747 pins.batches = batches_of(pairs);
1748 pins
1749}
1750
1751fn batches_of(
1755 pairs: std::collections::BTreeSet<(String, String)>,
1756) -> Vec<std::collections::BTreeMap<String, String>> {
1757 let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
1758 for (name, version) in pairs {
1759 match batches.iter().position(|batch| !batch.contains_key(&name)) {
1760 Some(index) => {
1761 batches[index].insert(name, version);
1762 }
1763 None => batches.push(std::collections::BTreeMap::from([(name, version)])),
1764 }
1765 }
1766 batches
1767}
1768
1769fn requirements_path(rel: &str) -> String {
1771 if rel.is_empty() {
1772 "requirements.txt".to_string()
1773 } else {
1774 format!("{rel}/requirements.txt")
1775 }
1776}
1777
1778fn requirements_prefix(rel: &str) -> String {
1781 if rel.is_empty() {
1782 String::new()
1783 } else {
1784 format!("{}: ", requirements_path(rel))
1785 }
1786}
1787
1788fn audit_marked_pins(
1798 settings: &crate::config::Settings,
1799 dir: &std::path::Path,
1800 rel: &str,
1801 pins: HashedPins,
1802) -> DirAnswer {
1803 let prefix = requirements_prefix(rel);
1804 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1805 let unchecked = |why: &str| DirAnswer::Read {
1806 report: Report::CouldNotCheck,
1807 out: String::new(),
1808 full: String::new(),
1809 gap: Some(why.to_string()),
1810 };
1811 let budget = Budget::new(settings);
1812 let private = match PrivateDir::create() {
1813 Ok(private) => private,
1814 Err(why) => {
1815 say(&format!(
1816 "no private directory ({}) — did NOT run\n {TMPDIR_NEXT}",
1817 why.kind()
1818 ));
1819 return unchecked("no private directory");
1820 }
1821 };
1822 let canonical = std::fs::canonicalize(private.path()).ok();
1824 let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
1825 let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
1826 let mut gap: Option<String> = None;
1827 let mut answered: Vec<&str> = Vec::new();
1828 let batches = batches_of(pins.pairs);
1829 for (index, batch) in batches.iter().enumerate() {
1830 if budget.spent() {
1831 say(&format!(
1832 "out of time; unaudited versions remain — NOT fully checked\n {TIMEOUT_NEXT}"
1833 ));
1834 gap.get_or_insert_with(|| "out of time".to_string());
1835 break;
1836 }
1837 let file = private.path().join(format!("batch-{index}.txt"));
1838 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
1839 if let Err(why) = std::fs::write(&file, body) {
1840 say(&format!(
1841 "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n {TMPDIR_NEXT}",
1842 why.kind()
1843 ));
1844 gap.get_or_insert_with(|| "could not write a batch file".to_string());
1845 break;
1846 }
1847 let argv = vec![
1848 common::program("pip-audit"),
1849 "-r".into(),
1850 file.to_string_lossy().into_owned(),
1851 "--no-deps".into(),
1852 "--disable-pip".into(),
1853 ];
1854 let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
1856 if answered.is_empty() && gap.is_none() {
1857 return DirAnswer::TimedOut;
1858 }
1859 say("timed out; unaudited versions remain — NOT fully checked");
1861 gap.get_or_insert_with(|| "timed out".to_string());
1862 break;
1863 };
1864 let batch_out = scrub(&batch_out);
1865 match read_pip_audit(exit_ok, &batch_out) {
1866 Report::Vulnerabilities(found) => {
1867 vulnerabilities.extend(found);
1868 full.push_str(&batch_out);
1869 answered.extend(batch.keys().map(String::as_str));
1870 }
1871 Report::Clean | Report::Advisories(_) => {
1873 answered.extend(batch.keys().map(String::as_str));
1874 }
1875 Report::CouldNotCheck => {
1876 let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
1877 say(&format!(
1878 "pip-audit could not answer — NOT fully checked\n {}\n {}",
1879 clip(&why, WARNING_COLUMNS - 2),
1880 pip_audit_next(&why)
1881 ));
1882 gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
1883 }
1884 }
1885 out.push_str(&batch_out);
1886 }
1887 let skipped = pip_skipped_names(&out);
1888 let audited = answered
1889 .iter()
1890 .filter(|name| !skipped.iter().any(|s| s == *name))
1891 .count();
1892 if audited > 0 {
1893 common::ok(
1894 settings,
1895 &format!(
1896 "audit-python: audited {} ({}, {} skipped)",
1897 requirements_path(rel),
1898 plural(audited, "package version"),
1899 answered.len() - audited
1900 ),
1901 );
1902 }
1903 let report = if !vulnerabilities.is_empty() {
1904 Report::Vulnerabilities(vulnerabilities)
1905 } else if gap.is_some() {
1906 Report::CouldNotCheck
1907 } else {
1908 Report::Clean
1909 };
1910 DirAnswer::Read {
1911 report,
1912 out,
1913 full,
1914 gap,
1915 }
1916}
1917
1918#[derive(Debug, Default, PartialEq, Eq)]
1920struct HashedPins {
1921 pairs: std::collections::BTreeSet<(String, String)>,
1923 marked: bool,
1925}
1926
1927impl HashedPins {
1928 fn names(&self) -> usize {
1930 let names: std::collections::BTreeSet<&str> =
1931 self.pairs.iter().map(|(name, _)| name.as_str()).collect();
1932 names.len()
1933 }
1934}
1935
1936fn hashed_pins(dir: &std::path::Path) -> Option<HashedPins> {
1946 let text = std::fs::read_to_string(dir.join("requirements.txt")).ok()?;
1947 hashed_pins_in(&text)
1948}
1949
1950fn hashed_pins_in(text: &str) -> Option<HashedPins> {
1951 let mut logical = Vec::new();
1952 let mut current = String::new();
1953 for line in text.lines() {
1954 match line.strip_suffix('\\') {
1955 Some(head) => {
1956 current.push_str(head);
1957 current.push(' ');
1958 }
1959 None => {
1960 current.push_str(line);
1961 logical.push(std::mem::take(&mut current));
1962 }
1963 }
1964 }
1965 logical.push(current);
1966 let mut pins = HashedPins::default();
1967 for line in &logical {
1968 let line = match line.find(" #") {
1970 Some(cut) => &line[..cut],
1971 None => line.as_str(),
1972 };
1973 let line = line.trim();
1974 if line.is_empty() || line.starts_with('#') {
1975 continue;
1976 }
1977 if line.starts_with('-') {
1978 return None;
1979 }
1980 let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
1981 let hashed = options
1982 .split_whitespace()
1983 .any(|option| option.starts_with("--hash"));
1984 if !hashed {
1985 return None;
1986 }
1987 pins.pairs.insert(exact_pin(spec)?);
1988 pins.marked |= spec.contains(';');
1989 }
1990 (!pins.pairs.is_empty()).then_some(pins)
1991}
1992
1993fn pip_skipped_names(out: &str) -> Vec<String> {
1996 let mut lines = out.lines().map(str::trim);
1997 let mut names = Vec::new();
1998 while let Some(line) = lines.next() {
1999 if !(line.starts_with("Name") && line.contains("Skip Reason")) {
2000 continue;
2001 }
2002 let rows = lines
2003 .by_ref()
2004 .skip_while(|l| l.starts_with('-'))
2005 .take_while(|l| !l.is_empty());
2006 names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
2007 }
2008 names.sort();
2009 names.dedup();
2010 names
2011}
2012
2013fn plural(count: usize, noun: &str) -> String {
2014 if count == 1 {
2015 format!("{count} {noun}")
2016 } else {
2017 format!("{count} {noun}s")
2018 }
2019}
2020
2021fn skipped_line(prefix: &str, names: &[&str]) -> String {
2025 let head = format!(
2026 "audit-python: {prefix}{} skipped",
2027 plural(names.len(), "private/non-PyPI package")
2028 );
2029 let fewest = names.len().min(1);
2030 for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
2031 let list: Vec<&str> = names.iter().take(shown).copied().collect();
2032 let more = names.len() - shown;
2033 let detail = match (list.is_empty(), more) {
2034 (true, 0) => String::new(),
2035 (true, _) => format!(" (+{more} more)"),
2036 (false, 0) => format!(" ({})", list.join(", ")),
2037 (false, _) => format!(" ({} +{more} more)", list.join(", ")),
2038 };
2039 let line = format!("{head}{detail}");
2040 if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
2041 return line;
2042 }
2043 }
2044 head
2045}
2046
2047fn clip(text: &str, columns: usize) -> String {
2049 text.chars().take(columns).collect()
2050}
2051
2052fn scrub_private(
2057 text: &str,
2058 private: &std::path::Path,
2059 canonical: Option<&std::path::Path>,
2060) -> String {
2061 let plain = private.to_string_lossy();
2062 let mut scrubbed = text.to_string();
2063 if let Some(canonical) = canonical.filter(|c| *c != private) {
2064 scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
2065 }
2066 scrubbed.replace(plain.as_ref(), "<tmp>")
2067}
2068
2069struct LockDirAudit {
2071 vulnerabilities: Vec<String>,
2072 advisories: Vec<String>,
2073 full: String,
2074 complete: bool,
2077 waivable: bool,
2078}
2079
2080impl LockDirAudit {
2081 fn unchecked() -> LockDirAudit {
2082 LockDirAudit {
2083 vulnerabilities: Vec::new(),
2084 advisories: Vec::new(),
2085 full: String::new(),
2086 complete: false,
2087 waivable: false,
2088 }
2089 }
2090}
2091
2092fn audit_uv_lock(
2098 settings: &crate::config::Settings,
2099 mut production: Production,
2100 dir: &str,
2101 budget: &Budget,
2102) -> LockDirAudit {
2103 let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
2104 let lock_path = if dir.is_empty() {
2105 "uv.lock".to_string()
2106 } else {
2107 format!("{dir}/uv.lock")
2108 };
2109 let prefix = if dir.is_empty() {
2110 String::new()
2111 } else {
2112 format!("{lock_path}: ")
2113 };
2114 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2115 let private = match PrivateDir::create() {
2116 Ok(private) => private,
2117 Err(why) => {
2118 say(&format!(
2119 "no private directory ({}) — did NOT run\n {TMPDIR_NEXT}",
2120 why.kind()
2121 ));
2122 return LockDirAudit::unchecked();
2123 }
2124 };
2125 let canonical = std::fs::canonicalize(private.path()).ok();
2127 let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2128 let export = private.path().join("export.txt");
2129 if budget.spent() {
2130 say(&format!(
2131 "out of time before the export — the audit did NOT run\n {TIMEOUT_NEXT}"
2132 ));
2133 return LockDirAudit::unchecked();
2134 }
2135 let argv = vec![
2136 common::program("uv"),
2137 "export".into(),
2138 "--frozen".into(),
2139 "--all-packages".into(),
2140 "--all-groups".into(),
2141 "--all-extras".into(),
2142 "--no-hashes".into(),
2143 "--no-emit-workspace".into(),
2144 "--format".into(),
2145 "requirements-txt".into(),
2146 "-o".into(),
2147 export.to_string_lossy().into_owned(),
2148 ];
2149 let exported = audited_in(settings, &argv, &dir_path);
2150 if !matches!(exported, Some((true, _))) {
2151 let why = exported
2152 .and_then(|(_, out)| failure_line(&scrub(&out)))
2153 .unwrap_or_else(|| "uv did not answer".to_string());
2154 let place = if dir.is_empty() {
2155 "at the repo root".to_string()
2156 } else {
2157 format!("in {dir}")
2158 };
2159 say(&format!(
2160 "uv export failed — the audit did NOT run\n {}\n Next: `uv export --frozen` {place}",
2161 clip(&why, WARNING_COLUMNS - 2)
2162 ));
2163 return LockDirAudit::unchecked();
2164 }
2165 let raw = std::fs::read_to_string(&export);
2166 let _ = std::fs::remove_file(&export); let raw = match raw {
2169 Ok(raw) => raw,
2170 Err(why) => {
2171 say(&format!(
2172 "could not read export.txt ({}) — the audit did NOT run\n {TMPDIR_NEXT}",
2173 why.kind()
2174 ));
2175 return LockDirAudit::unchecked();
2176 }
2177 };
2178 let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
2179 Ok(lock) => lock,
2180 Err(why) => {
2181 say(&format!(
2182 "could not read uv.lock ({}) — the audit did NOT run\n \
2183 Next: check that {lock_path} is readable, then push again",
2184 why.kind()
2185 ));
2186 return LockDirAudit::unchecked();
2187 }
2188 };
2189 let sources = scan_uv_lock(&lock);
2190 let pins = filter_export(&raw, &sources.pypi);
2191 if !pins.skipped.is_empty() {
2192 let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
2193 common::warn(&skipped_line(&prefix, &names));
2194 }
2195 let unclassified = pins.unclassified.len() + sources.nameless;
2196 if unclassified > 0 {
2197 let source = if prefix.is_empty() {
2198 " from uv.lock"
2199 } else {
2200 ""
2201 };
2202 say(&format!(
2203 "{} could not be classified{source}; not audited\n \
2204 Next: check that each [[package]] in {lock_path} has a name and source",
2205 plural(unclassified, "package")
2206 ));
2207 }
2208 if pins.batches.is_empty() {
2209 say(&format!(
2210 "no PyPI package to audit — the audit did NOT run\n \
2211 Next: none if every package is private; else check {lock_path} sources"
2212 ));
2213 return LockDirAudit::unchecked();
2214 }
2215 let mut audit = LockDirAudit {
2216 vulnerabilities: Vec::new(),
2217 advisories: Vec::new(),
2218 full: String::new(),
2219 complete: true,
2220 waivable: true,
2221 };
2222 let mut audited = 0;
2223 for (index, batch) in pins.batches.iter().enumerate() {
2224 let file = private.path().join(format!("batch-{index}.txt"));
2225 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2226 if budget.spent() {
2227 say(&format!(
2228 "out of time; unaudited versions remain — NOT fully checked\n {TIMEOUT_NEXT}"
2229 ));
2230 audit.complete = false;
2231 break;
2232 }
2233 if let Err(why) = std::fs::write(&file, body) {
2234 say(&format!(
2235 "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n {TMPDIR_NEXT}",
2236 why.kind()
2237 ));
2238 audit.complete = false;
2239 break;
2240 }
2241 let argv = vec![
2242 common::program("pip-audit"),
2243 "-r".into(),
2244 file.to_string_lossy().into_owned(),
2245 "--no-deps".into(),
2246 "--disable-pip".into(),
2247 ];
2248 let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
2249 audit.complete = false;
2250 break;
2251 };
2252 let out = scrub(&out);
2253 let report = read_pip_audit(exit_ok, &out);
2254 let names = if has_rows_to_split(&report, &out) {
2255 production.names(settings, budget, &say)
2256 } else {
2257 None
2258 };
2259 let (report, waivable) = shipped_only(report, &out, names);
2260 audit.waivable &= waivable;
2261 match report {
2262 Report::Vulnerabilities(found) => {
2263 audit.vulnerabilities.extend(found);
2264 audit.full.push_str(&out);
2265 audited += batch.len();
2266 }
2267 Report::Advisories(found) => {
2268 audit.advisories.extend(found);
2269 audited += batch.len();
2270 }
2271 Report::Clean => audited += batch.len(),
2272 Report::CouldNotCheck => {
2273 audit.complete = false;
2274 let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
2275 say(&format!(
2276 "pip-audit could not answer — NOT fully checked\n {}\n {}",
2277 clip(&why, WARNING_COLUMNS - 2),
2278 pip_audit_next(&why)
2279 ));
2280 }
2281 }
2282 }
2283 if !audit.complete {
2284 audit.waivable = false;
2285 }
2286 if audited > 0 {
2287 common::ok(
2288 settings,
2289 &format!(
2290 "audit-python: audited {lock_path} ({}, {} skipped)",
2291 plural(audited, "package version"),
2292 pins.skipped.len()
2293 ),
2294 );
2295 }
2296 audit
2297}
2298
2299fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
2303 let (settings, refs) = (ctx.settings, ctx.push.get());
2304 let release = releasing(refs);
2305 let budget = Budget::new(settings);
2306 let root = std::path::PathBuf::from(common::repo_root());
2307 let dirs = lockfile_dirs("uv.lock");
2308 let only_root = dirs.len() == 1 && dirs[0].is_empty();
2309 let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
2310 let mut full = String::new();
2311 let (mut complete, mut waivable) = (true, true);
2312 for dir in &dirs {
2313 let production = if release {
2314 Production::Unasked(root.join(dir))
2315 } else {
2316 Production::Never
2317 };
2318 let audit = audit_uv_lock(settings, production, dir, &budget);
2319 let label = |ids: Vec<String>| -> Vec<String> {
2320 if dir.is_empty() {
2321 ids
2322 } else {
2323 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
2324 }
2325 };
2326 vulnerabilities.extend(label(audit.vulnerabilities));
2327 advisories.extend(label(audit.advisories));
2328 if !audit.full.is_empty() {
2329 if only_root {
2330 full.push_str(&audit.full);
2331 } else {
2332 full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
2333 }
2334 }
2335 complete &= audit.complete;
2336 waivable &= audit.waivable;
2337 }
2338 let report = if !vulnerabilities.is_empty() {
2339 Report::Vulnerabilities(vulnerabilities)
2340 } else if !complete {
2341 return Ran::Unavailable;
2342 } else if !advisories.is_empty() {
2343 Report::Advisories(advisories)
2344 } else {
2345 Report::Clean
2346 };
2347 Ran::Concluded(Concluded {
2348 tool: "audit-python".to_string(),
2349 report,
2350 full,
2351 waivable: waivable && complete,
2352 complete,
2353 })
2354}
2355
2356fn source_is_this_commit(source: &std::path::Path) -> bool {
2360 let src = source.to_string_lossy();
2361 let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
2362 let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
2363 let unmodified = crate::git::stdout(&[
2364 "-C",
2365 &src,
2366 "status",
2367 "--porcelain",
2368 "--untracked-files=no",
2369 "--",
2370 "*pyproject.toml",
2371 "*uv.lock",
2372 "*requirements*.txt",
2373 ])
2374 .is_some_and(|out| out.trim().is_empty());
2375 here.is_some() && here == there && unmodified
2376}
2377
2378fn normalise(name: &str) -> String {
2380 name.to_ascii_lowercase()
2381 .split(['-', '_', '.'])
2382 .filter(|p| !p.is_empty())
2383 .collect::<Vec<_>>()
2384 .join("-")
2385}
2386
2387fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
2391 let mut rows: Vec<(String, String)> = out
2392 .lines()
2393 .filter_map(|l| {
2394 let cols: Vec<&str> = l.split_whitespace().collect();
2395 let id = cols.get(2)?;
2396 ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
2397 .iter()
2398 .any(|p| id.starts_with(p))
2399 .then(|| (normalise(cols[0]), (*id).to_string()))
2400 })
2401 .collect();
2402 rows.sort();
2403 rows.dedup();
2404 rows
2405}
2406
2407fn pip_rows_all_named(out: &str) -> bool {
2411 out.lines().all(|l| {
2412 let cols: Vec<&str> = l.split_whitespace().collect();
2413 let is_row = cols.len() >= 3
2414 && cols[1].starts_with(|c: char| c.is_ascii_digit())
2415 && cols[2].contains('-')
2416 && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
2417 !is_row || !advisory_ids(cols[2]).is_empty()
2418 })
2419}
2420
2421fn uv_production_names(
2425 settings: &crate::config::Settings,
2426 dir: &std::path::Path,
2427) -> Option<std::collections::HashSet<String>> {
2428 if !has_lockfile("uv.lock") || common::which("uv").is_none() {
2429 return None;
2430 }
2431 let argv = vec![
2432 common::program("uv"),
2433 "export".into(),
2434 "--frozen".into(),
2435 "--all-packages".into(),
2438 "--no-dev".into(),
2439 "--no-default-groups".into(),
2440 "--all-extras".into(),
2442 "--no-hashes".into(),
2443 "--no-emit-workspace".into(),
2444 "--format".into(),
2445 "requirements-txt".into(),
2446 ];
2447 let (ok, out) = audited_in(settings, &argv, dir)?;
2448 if !ok {
2449 return None;
2450 }
2451 Some(
2452 out.lines()
2453 .map(str::trim)
2454 .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
2455 .filter_map(|l| {
2456 l.split(|c: char| "=<>!~;[ ".contains(c))
2457 .next()
2458 .map(normalise)
2459 })
2460 .collect(),
2461 )
2462}
2463
2464pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
2466const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
2467const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
2469const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
2472const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");
2476
2477pub fn is_audit(check: &str) -> bool {
2479 check.starts_with("pre-push-audit-")
2480}
2481
2482fn inputs_of(check: &str) -> &'static [&'static str] {
2486 match check {
2487 "pre-push-audit-rust" => &["Cargo.lock"],
2488 "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
2489 "pre-push-audit-go" => &["go.sum", "go.mod"],
2490 "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
2491 _ => &[],
2492 }
2493}
2494
2495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2497enum AuditMode {
2498 Branch,
2500 Release,
2502}
2503
2504impl AuditMode {
2505 fn of(refs: &[PushRef]) -> AuditMode {
2506 if releasing(refs) {
2507 AuditMode::Release
2508 } else {
2509 AuditMode::Branch
2510 }
2511 }
2512}
2513
2514#[derive(Debug, Clone, PartialEq, Eq)]
2518struct Concluded {
2519 tool: String,
2520 report: Report,
2521 full: String,
2522 waivable: bool,
2523 complete: bool,
2527}
2528
2529enum Ran {
2532 Concluded(Concluded),
2533 Inert,
2535 Unavailable,
2537}
2538
2539#[derive(Debug, Clone)]
2542pub struct Pending {
2543 pub tip: String,
2544 material: String,
2545 body: String,
2546}
2547
2548#[derive(Default)]
2553pub struct Ledger {
2554 pending: std::sync::Mutex<Vec<Pending>>,
2555 peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
2556 fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
2557}
2558
2559impl Ledger {
2560 pub fn take_pending(&self) -> Vec<Pending> {
2562 std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
2563 }
2564
2565 fn peel(&self, oid: &str) -> Option<String> {
2567 if let Some(known) = self
2568 .peeled
2569 .lock()
2570 .unwrap_or_else(|e| e.into_inner())
2571 .get(oid)
2572 {
2573 return known.clone();
2574 }
2575 let commit =
2576 crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
2577 self.peeled
2578 .lock()
2579 .unwrap_or_else(|e| e.into_inner())
2580 .insert(oid.to_string(), commit.clone());
2581 commit
2582 }
2583
2584 fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
2586 let mut commits: Vec<String> = refs
2587 .iter()
2588 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
2589 .filter_map(|r| self.peel(&r.local_oid))
2590 .collect();
2591 commits.sort();
2592 commits.dedup();
2593 commits
2594 }
2595}
2596
2597pub fn write_pending(pending: &Pending) -> Result<(), String> {
2600 let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
2603 .map(|k| k.trim().to_string())
2604 .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
2605 let written = crate::git::succeeds(&[
2606 "notes",
2607 "--ref",
2608 AUDIT_REF,
2609 "add",
2610 "-f",
2611 "-m",
2612 &pending.body,
2613 &key,
2614 ]);
2615 if written {
2616 Ok(())
2617 } else {
2618 Err(format!("git refused to write the audit record {key}"))
2619 }
2620}
2621
2622fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
2624 match mode {
2625 AuditMode::Release => {
2626 let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
2627 Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
2628 }
2629 AuditMode::Branch => {
2630 let names = inputs_of(check);
2631 let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
2632 let mut lines: Vec<String> = listing
2633 .lines()
2634 .filter_map(|entry| {
2635 let (meta, path) = entry.split_once('\t')?;
2636 let blob = meta.split_whitespace().nth(2)?;
2637 let base = path.rsplit('/').next().unwrap_or(path);
2638 names.contains(&base).then(|| format!("{path} {blob}"))
2639 })
2640 .collect();
2641 lines.sort();
2642 Some(format!(
2643 "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
2644 lines.join("\n")
2645 ))
2646 }
2647 }
2648}
2649
2650fn now_secs() -> i64 {
2651 std::time::SystemTime::now()
2652 .duration_since(std::time::UNIX_EPOCH)
2653 .map(|d| d.as_secs() as i64)
2654 .unwrap_or(0)
2655}
2656
2657fn class_of(report: &Report) -> &'static str {
2658 match report {
2659 Report::Clean => "clean",
2660 Report::Advisories(_) => "advisories",
2661 Report::Vulnerabilities(_) => "vulnerabilities",
2662 Report::CouldNotCheck => "unchecked",
2663 }
2664}
2665
2666fn render(concluded: &Concluded, at: i64) -> String {
2667 let items: &[String] = match &concluded.report {
2668 Report::Advisories(v) | Report::Vulnerabilities(v) => v,
2669 Report::Clean | Report::CouldNotCheck => &[],
2670 };
2671 let mut body = format!(
2672 "{AUDIT_FORMAT} {at} {} {} {} {WRITER_VERSION}",
2673 class_of(&concluded.report),
2674 u8::from(concluded.waivable),
2675 concluded.tool
2676 );
2677 for item in items {
2678 body.push_str("\nitem ");
2679 body.push_str(item);
2680 }
2681 body.push_str("\n---\n");
2682 body.push_str(&concluded.full);
2683 body
2684}
2685
2686fn parse(body: &str) -> Option<(i64, Option<String>, Concluded)> {
2689 let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
2690 let mut fields = head.split_whitespace();
2691 if fields.next()? != AUDIT_FORMAT {
2692 return None;
2693 }
2694 let at: i64 = fields.next()?.parse().ok()?;
2695 let class = fields.next()?;
2696 let waivable = fields.next()? == "1";
2697 let tool = fields.next()?.to_string();
2698 let writer = fields.next().map(str::to_string);
2699 let (items_part, full) = match rest.split_once("---\n") {
2700 Some((i, full)) => (i, full.to_string()),
2701 None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
2702 };
2703 let items: Vec<String> = items_part
2704 .lines()
2705 .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
2706 .collect();
2707 let report = match class {
2708 "clean" => Report::Clean,
2709 "advisories" => Report::Advisories(items),
2710 "vulnerabilities" => Report::Vulnerabilities(items),
2711 "unchecked" => Report::CouldNotCheck,
2712 _ => return None,
2713 };
2714 Some((
2715 at,
2716 writer,
2717 Concluded {
2718 tool,
2719 report,
2720 full,
2721 waivable,
2722 complete: true,
2723 },
2724 ))
2725}
2726
2727fn fresh_record(
2729 settings: &crate::config::Settings,
2730 check: &str,
2731 mode: AuditMode,
2732 commit: &str,
2733) -> Option<Concluded> {
2734 let material = key_material(check, mode, commit)?;
2735 let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
2736 .trim()
2737 .to_string();
2738 let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
2739 let (at, writer, concluded) = parse(&body)?;
2740 let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
2741 if writer.as_deref() != Some(WRITER_VERSION) {
2742 return None;
2743 }
2744 UNCHECKED_MAX_AGE_SECS
2745 } else {
2746 crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
2747 };
2748 let age = now_secs() - at;
2749 (0..=max_age).contains(&age).then_some(concluded)
2750}
2751
2752fn fresh_for_refs(
2757 settings: &crate::config::Settings,
2758 ledger: &Ledger,
2759 check: &str,
2760 refs: &[PushRef],
2761) -> Option<Concluded> {
2762 if !crate::gate_stamp::push_stamps_enabled(settings) {
2763 return None;
2764 }
2765 let memo_key = format!(
2766 "{check} {}",
2767 refs.iter()
2768 .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
2769 .collect::<Vec<_>>()
2770 .join(" ")
2771 );
2772 if let Some(known) = ledger
2773 .fresh
2774 .lock()
2775 .unwrap_or_else(|e| e.into_inner())
2776 .get(&memo_key)
2777 {
2778 return known.clone();
2779 }
2780 let mode = AuditMode::of(refs);
2781 let mut found: Option<Concluded> = None;
2782 for commit in ledger.pushed_commits(refs) {
2783 let Some(record) = fresh_record(settings, check, mode, &commit) else {
2784 found = None;
2785 break;
2786 };
2787 if found.as_ref().is_some_and(|prev| *prev != record) {
2788 found = None;
2789 break;
2790 }
2791 found = Some(record);
2792 }
2793 ledger
2794 .fresh
2795 .lock()
2796 .unwrap_or_else(|e| e.into_inner())
2797 .insert(memo_key, found.clone());
2798 found
2799}
2800
2801pub fn owed(
2803 settings: &crate::config::Settings,
2804 ledger: &Ledger,
2805 check: &str,
2806 refs: &[PushRef],
2807) -> bool {
2808 !ledger.pushed_commits(refs).is_empty()
2809 && fresh_for_refs(settings, ledger, check, refs).is_none()
2810}
2811
2812fn recorded(
2816 check: &str,
2817 tool: &str,
2818 ctx: &crate::registry::Ctx,
2819 run: fn(&crate::registry::Ctx) -> Ran,
2820) -> Outcome {
2821 let (settings, refs) = (ctx.settings, ctx.push.get());
2822 let mode = AuditMode::of(refs);
2823 let releasing = mode == AuditMode::Release;
2824 if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
2825 common::ok(
2826 settings,
2827 &format!("{tool}: replaying the audit recorded for this push"),
2828 );
2829 return conclude_waivable(
2830 settings,
2831 &record.tool,
2832 record.report,
2833 releasing,
2834 &record.full,
2835 record.waivable,
2836 );
2837 }
2838 let (outcome, concluded) = match run(ctx) {
2839 Ran::Concluded(concluded) => (
2840 conclude_waivable(
2841 settings,
2842 &concluded.tool,
2843 concluded.report.clone(),
2844 releasing,
2845 &concluded.full,
2846 concluded.waivable,
2847 ),
2848 Some(concluded),
2849 ),
2850 Ran::Unavailable => (
2851 Outcome::Unavailable,
2852 Some(Concluded {
2853 tool: tool.to_string(),
2854 report: Report::CouldNotCheck,
2855 full: String::new(),
2856 waivable: false,
2857 complete: true,
2858 }),
2859 ),
2860 Ran::Inert => (Outcome::Inert, None),
2861 };
2862 let concluded = concluded.filter(|concluded| {
2864 concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
2865 });
2866 if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
2867 let body = render(&concluded, now_secs());
2868 let records: Vec<Pending> = ctx
2869 .audits
2870 .pushed_commits(refs)
2871 .into_iter()
2872 .filter_map(|commit| {
2873 key_material(check, mode, &commit).map(|material| Pending {
2874 tip: commit,
2875 material,
2876 body: body.clone(),
2877 })
2878 })
2879 .collect();
2880 ctx.audits
2881 .pending
2882 .lock()
2883 .unwrap_or_else(|e| e.into_inner())
2884 .extend(records);
2885 }
2886 outcome
2887}
2888
2889pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
2890 recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
2891}
2892
2893pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
2894 recorded("pre-push-audit-js", "audit-js", ctx, js_run)
2895}
2896
2897pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
2898 recorded("pre-push-audit-go", "audit-go", ctx, go_run)
2899}
2900
2901pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
2902 recorded("pre-push-audit-python", "audit-python", ctx, python_run)
2903}
2904
2905#[cfg(test)]
2906mod tests {
2907 use super::*;
2908
2909 #[test]
2915 fn a_uv_project_is_audited_through_its_venv() {
2916 let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
2917 let _ = std::fs::remove_dir_all(&root);
2918
2919 std::fs::create_dir_all(&root).unwrap();
2922 assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
2923
2924 let sp = root
2931 .join(".venv")
2932 .join("lib")
2933 .join("python3.13")
2934 .join("site-packages");
2935 std::fs::create_dir_all(&sp).unwrap();
2936 assert_eq!(
2937 venv_site_packages(root.to_str().unwrap(), None),
2938 Some(sp.to_string_lossy().into_owned())
2939 );
2940
2941 let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
2943 let _ = std::fs::remove_dir_all(&win);
2944 let wsp = win.join(".venv").join("Lib").join("site-packages");
2945 std::fs::create_dir_all(&wsp).unwrap();
2946 assert_eq!(
2947 venv_site_packages(win.to_str().unwrap(), None),
2948 Some(wsp.to_string_lossy().into_owned())
2949 );
2950
2951 let _ = std::fs::remove_dir_all(&root);
2952 let _ = std::fs::remove_dir_all(&win);
2953 }
2954
2955 fn tag(name: &str) -> PushRef {
2956 PushRef {
2957 local_ref: name.to_string(),
2958 local_oid: "a".repeat(40),
2959 remote_ref: name.to_string(),
2960 remote_oid: "0".repeat(40),
2961 }
2962 }
2963
2964 #[test]
2967 fn pip_audit_rows_name_their_packages_normalised() {
2968 let out = "Name Version ID Fix Versions\n\
2969 ---------- ------- ------------------- ------------\n\
2970 Pytest_Cov 4.0.0 GHSA-aaaa-bbbb-cccc 4.1.0\n\
2971 requests 2.31.0 PYSEC-2023-74 2.31.1\n\
2972 requests 2.31.0 CVE-2024-35195 2.32.0\n\
2973 Found 3 known vulnerabilities in 2 packages\n";
2974 let names: Vec<String> = pip_vulnerable_rows(out)
2975 .into_iter()
2976 .map(|(n, _)| n)
2977 .collect();
2978 assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
2979 assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
2980 }
2981
2982 #[test]
2983 fn advisory_ids_are_found_wherever_they_sit() {
2984 let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
2985 ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
2986 assert_eq!(
2987 advisory_ids(text),
2988 vec![
2989 "CVE-2024-35195",
2990 "GHSA-h3mg-xc3c-68pw",
2991 "GO-2024-2687",
2992 "OSV-2024-12",
2993 "PYSEC-2023-74",
2994 "RUSTSEC-2025-0001"
2995 ]
2996 );
2997 }
2998
2999 #[test]
3000 fn a_waiver_is_reasoned_dated_and_bounded() {
3001 let today = days_from_date("2026-10-05").unwrap();
3002 let w = Waivers::parse(
3003 "# id expires reason\n\
3004 GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
3005 GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
3006 GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
3007 GHSA-jjjj-kkkk-llll 2026-11-01\n\
3008 GHSA-mmmm-nnnn-oooo soon no date\n",
3009 today,
3010 );
3011 assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
3012 assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
3013 assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
3014 assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
3015 assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
3016 assert_eq!(w.problems().len(), 4);
3017 assert_eq!(days_from_date("1970-01-01"), Some(0));
3018 assert_eq!(days_from_date("2026-02-30"), None);
3019 assert!(days_from_date("2028-02-29").is_some());
3020 assert_eq!(days_from_date("2026-13-01"), None);
3021 }
3022
3023 #[test]
3024 fn two_locked_versions_are_two_answers() {
3025 let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
3026 Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
3027 let ids = vec![
3028 "RUSTSEC-2025-0010".to_string(),
3029 "RUSTSEC-2025-0011".to_string(),
3030 ];
3031 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3032 "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
3033 "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
3034 _ => None,
3035 });
3036 assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
3037 assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
3038 }
3039
3040 #[test]
3041 fn a_pip_row_without_a_nameable_id_is_unwaivable() {
3042 let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
3043 let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
3044 assert!(pip_rows_all_named(named));
3045 assert!(!pip_rows_all_named(unnamed));
3046 }
3047
3048 #[test]
3049 fn a_crate_ships_unless_its_tree_says_otherwise() {
3050 let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
3051 Crate: app\nID: RUSTSEC-2025-0002\n\
3052 Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
3053 let ids = vec![
3054 "RUSTSEC-2025-0001".to_string(),
3055 "RUSTSEC-2025-0002".to_string(),
3056 "RUSTSEC-2025-0003".to_string(),
3057 "RUSTSEC-2025-0004".to_string(),
3058 ];
3059 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3060 "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
3062 "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
3063 "odd" => Some("odd v1.0.0\n".into()),
3065 _ => None,
3066 });
3067 assert_eq!(
3069 shipped,
3070 vec![
3071 "RUSTSEC-2025-0002",
3072 "RUSTSEC-2025-0003",
3073 "RUSTSEC-2025-0004"
3074 ]
3075 );
3076 assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
3077 }
3078
3079 #[test]
3080 fn a_release_is_a_v_number_tag() {
3081 assert!(releasing(&[tag("refs/tags/v1.6.6")]));
3082 assert!(releasing(&[tag("refs/tags/v2")]));
3083 assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
3084 assert!(!releasing(&[tag("refs/tags/release")]));
3085 assert!(!releasing(&[tag("refs/heads/v1-styles")]));
3086 assert!(!releasing(&[tag("refs/heads/main")]));
3087 assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
3089 }
3090
3091 #[test]
3094 fn cargo_audit_ids_decide_not_the_exit_code() {
3095 assert_eq!(
3096 read_cargo_audit(true, "ok, 312 crates checked"),
3097 Report::Clean
3098 );
3099 assert_eq!(
3100 read_cargo_audit(false, "error: couldn't fetch advisory database"),
3101 Report::CouldNotCheck
3102 );
3103 let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
3104 assert_eq!(
3105 read_cargo_audit(true, warn),
3106 Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
3107 );
3108 let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
3109 assert_eq!(
3110 read_cargo_audit(false, vuln),
3111 Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
3112 );
3113 assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
3115 }
3116
3117 fn real_report() -> String {
3120 [
3121 "Crate: paste",
3122 "Version: 1.0.15",
3123 "Warning: unmaintained",
3124 "ID: RUSTSEC-2024-0436",
3125 "URL: https://rustsec.org/advisories/RUSTSEC-2024-0436",
3126 "",
3127 "Crate: lru",
3128 "Version: 0.12.5",
3129 "Warning: unsound",
3130 "ID: RUSTSEC-2026-0253",
3131 "",
3132 "Crate: lru",
3133 "Version: 0.12.5",
3134 "ID: RUSTSEC-2026-0002",
3135 "",
3136 "warning: 3 allowed warnings found",
3137 ]
3138 .join("\n")
3139 }
3140
3141 #[test]
3142 fn an_advisory_is_paired_with_its_crate() {
3143 let pairs = ids_with_crates(&real_report());
3144 assert_eq!(
3145 pairs,
3146 vec![
3147 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3148 ("RUSTSEC-2026-0253".into(), Some("lru".into())),
3149 ("RUSTSEC-2026-0002".into(), Some("lru".into())),
3150 ]
3151 );
3152 }
3153
3154 #[test]
3157 fn a_loose_id_borrows_no_crate() {
3158 let out = "Crate: paste\nID: RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
3159 assert_eq!(
3160 ids_with_crates(out),
3161 vec![
3162 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3163 ("RUSTSEC-2025-0001".into(), None),
3164 ]
3165 );
3166 }
3167
3168 #[test]
3171 fn only_local_crates_are_named_as_reached() {
3172 let tree =
3173 "lru v0.12.5\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
3174 assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
3175 assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
3176 }
3177
3178 #[test]
3182 fn the_warning_names_the_crate_and_what_reaches_it() {
3183 let calls = std::cell::RefCell::new(Vec::new());
3184 let fake = |k: &str| {
3185 calls.borrow_mut().push(k.to_string());
3186 Some(format!(
3187 "{k} v1\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
3188 ))
3189 };
3190 let out = real_report();
3191 let got = attribute(read_cargo_audit(true, &out), &out, fake);
3192 assert_eq!(
3193 got,
3194 Report::Advisories(vec![
3195 "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
3196 "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
3197 "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
3198 ])
3199 );
3200 assert_eq!(
3201 calls.into_inner(),
3202 vec!["paste", "lru"],
3203 "one call per crate"
3204 );
3205 }
3206
3207 #[test]
3211 fn a_crate_outside_the_build_graph_says_so() {
3212 let out = "Crate: wezterm-input-types\nID: RUSTSEC-2025-0001";
3213 let got = attribute(read_cargo_audit(true, out), out, |_| {
3214 Some("warning: nothing to print.".into())
3215 });
3216 assert_eq!(
3217 got,
3218 Report::Advisories(vec![
3219 "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
3220 ])
3221 );
3222 }
3223
3224 #[test]
3227 fn attribution_never_changes_the_verdict() {
3228 let spawned = std::cell::Cell::new(false);
3229 let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
3230 spawned.set(true);
3231 None
3232 });
3233 assert_eq!(clean, Report::Clean);
3234 assert!(!spawned.get(), "a clean report must spawn nothing");
3235
3236 let out = "Crate: paste\nID: RUSTSEC-2024-0436";
3237 let blind = attribute(read_cargo_audit(false, out), out, |_| None);
3238 assert_eq!(
3239 blind,
3240 Report::Vulnerabilities(vec![
3241 "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
3242 ])
3243 );
3244 }
3245
3246 #[test]
3247 fn npm_audit_summary_decides() {
3248 assert_eq!(
3249 read_npm_audit(true, "found 0 vulnerabilities\n"),
3250 Report::Clean
3251 );
3252 assert_eq!(
3253 read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
3254 Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
3255 );
3256 assert_eq!(
3259 read_npm_audit(
3260 false,
3261 "# npm audit report\n\nvite 6.0.0 - 6.1.5\nSeverity: high\n\n\
3262 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n npm audit fix\n"
3263 ),
3264 Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
3265 );
3266 assert_eq!(
3267 read_npm_audit(false, "1 vulnerability (1 high)\n"),
3268 Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
3269 );
3270 assert_eq!(
3271 read_npm_audit(true, "up to date, audited 100 packages\n"),
3272 Report::Clean
3273 );
3274 assert_eq!(
3275 read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
3276 Report::CouldNotCheck
3277 );
3278 }
3279
3280 #[test]
3281 fn pnpm_audit_summary_decides() {
3282 assert_eq!(
3283 read_pnpm_audit(true, "No known vulnerabilities found\n"),
3284 Report::Clean
3285 );
3286 assert_eq!(
3289 read_pnpm_audit(
3290 false,
3291 "│ More info │ https://github.com/advisories/GHSA-395f │\n\
3292 └───────────┴──────────────────────────────────────────┘\n\
3293 107 vulnerabilities found\n\
3294 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
3295 ),
3296 Report::Vulnerabilities(vec![
3297 "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
3298 ])
3299 );
3300 assert_eq!(
3301 read_pnpm_audit(false, "1 vulnerabilities found\n"),
3302 Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
3303 );
3304 assert_eq!(
3305 read_pnpm_audit(
3306 false,
3307 " ERR_PNPM_AUDIT_BAD_RESPONSE The audit endpoint responded with 503\n"
3308 ),
3309 Report::CouldNotCheck
3310 );
3311 }
3312
3313 #[test]
3316 fn govulncheck_ids_decide_not_the_exit_code() {
3317 assert_eq!(
3318 read_govulncheck(true, "No vulnerabilities found.\n"),
3319 Report::Clean
3320 );
3321 assert_eq!(
3322 read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
3323 Report::CouldNotCheck
3324 );
3325 assert_eq!(
3328 read_govulncheck(
3329 true,
3330 "=== Informational ===\nVulnerability #1: GO-2023-1840\n More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
3331 ),
3332 Report::Advisories(vec!["GO-2023-1840".into()])
3333 );
3334 assert_eq!(
3335 read_govulncheck(
3336 false,
3337 "Vulnerability #1: GO-2022-0969\n Your code calls it.\nGO-2022-0969 again\n"
3338 ),
3339 Report::Vulnerabilities(vec!["GO-2022-0969".into()])
3340 );
3341 assert_eq!(
3343 read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
3344 Report::Clean
3345 );
3346 }
3347
3348 #[test]
3349 fn pip_audit_sentence_decides() {
3350 assert_eq!(
3351 read_pip_audit(true, "No known vulnerabilities found\n"),
3352 Report::Clean
3353 );
3354 assert_eq!(
3355 read_pip_audit(
3356 false,
3357 "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
3358 ),
3359 Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
3360 );
3361 assert_eq!(
3362 read_pip_audit(false, "ERROR: could not resolve\n"),
3363 Report::CouldNotCheck
3364 );
3365 }
3366
3367 fn lock_block(name: Option<&str>, source: &str) -> String {
3368 let mut block = String::from("[[package]]\n");
3369 if let Some(name) = name {
3370 block.push_str(&format!("name = \"{name}\"\n"));
3371 }
3372 block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
3373 block
3374 }
3375
3376 #[test]
3377 fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
3378 let pypi = "{ registry = \"https://pypi.org/simple\" }";
3379 let lock = [
3380 lock_block(Some("Requests"), pypi),
3381 lock_block(
3382 Some("slashed"),
3383 "{ registry = \"https://pypi.org/simple/\" }",
3384 ),
3385 lock_block(
3386 Some("mirror"),
3387 "{ registry = \"https://mirror.example/simple\" }",
3388 ),
3389 lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
3390 lock_block(Some("pathdep"), "{ path = \"../x\" }"),
3391 lock_block(Some("edit"), "{ editable = \".\" }"),
3392 lock_block(Some("virt"), "{ virtual = \".\" }"),
3393 lock_block(Some("twice"), pypi),
3394 lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
3395 lock_block(None, pypi),
3396 "[package.metadata]\nname = \"ignored\"\n".to_string(),
3397 ]
3398 .concat();
3399 let sources = scan_uv_lock(&lock);
3400 let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
3401 assert_eq!(admitted, ["requests", "slashed"]);
3402 assert_eq!(sources.nameless, 1);
3403 }
3404
3405 #[test]
3406 fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
3407 let pypi: std::collections::BTreeSet<String> =
3408 ["numpy", "idna", "requests"].map(String::from).into();
3409 let raw = "\
3410# generated
3411numpy==1.26.4 ; python_full_version < '3.12'
3412numpy==2.1.0 ; python_full_version >= '3.12'
3413numpy==2.1.0 ; sys_platform == 'win32'
3414idna==3.7
3415platform-kernel==0.1.0
3416requests @ https://example.com/r.whl
3417";
3418 let pins = filter_export(raw, &pypi);
3419 assert_eq!(pins.versions, 3);
3420 assert_eq!(pins.batches.len(), 2);
3421 assert_eq!(
3422 pins.batches[0].get("numpy").map(String::as_str),
3423 Some("1.26.4")
3424 );
3425 assert_eq!(
3426 pins.batches[1].get("numpy").map(String::as_str),
3427 Some("2.1.0")
3428 );
3429 assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
3430 assert!(pins.skipped.contains("platform-kernel"));
3431 assert!(pins.unclassified.contains("requests"));
3432 }
3433
3434 const HASHED: &str = "\
3436# This file was autogenerated by uv via the following command:
3437# ./compile-requirements.sh
3438anyio==4.15.1 \\
3439 --hash=sha256:6152 \\
3440 --hash=sha256:9f28
3441 # via
3442 # starlette
3443idna==3.7 \\
3444 --hash=sha256:aaaa
3445torch==2.14.0+cpu \\
3446 --hash=sha256:bbbb
3447 # via -r requirements.in
3448";
3449
3450 #[test]
3451 fn only_a_fully_hashed_file_skips_the_resolve() {
3452 let pins = hashed_pins_in(HASHED).expect("hashed");
3453 assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
3454 assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
3456 let one_unhashed = format!("{HASHED}idna==3.7\n");
3457 assert_eq!(hashed_pins_in(&one_unhashed), None);
3458 let ranged = "requests>=2.0 \\\n --hash=sha256:cccc\n";
3459 assert_eq!(hashed_pins_in(ranged), None);
3460 let included = format!("-r requirements-upload.txt\n{HASHED}");
3461 assert_eq!(hashed_pins_in(&included), None);
3462 let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
3463 assert_eq!(hashed_pins_in(&indexed), None);
3464 let marked =
3466 format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n --hash=sha256:dddd\n");
3467 assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
3468 assert_eq!(
3469 hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
3470 None
3471 );
3472 assert_eq!(hashed_pins_in("# fixture\n"), None);
3473 assert_eq!(hashed_pins_in(""), None);
3474 }
3475
3476 #[test]
3477 fn marked_pins_are_stripped_and_their_versions_batched_apart() {
3478 let text = "\
3479six==1.16.0 \\
3480 --hash=sha256:aaaa
3481numpy==1.26.4 ; python_version == '3.9' \\
3482 --hash=sha256:bbbb
3483numpy==2.1.0 ; python_version == '3.12' \\
3484 --hash=sha256:cccc
3485";
3486 let pins = hashed_pins_in(text).expect("hashed");
3487 assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
3488 let batches = batches_of(pins.pairs);
3489 assert_eq!(batches.len(), 2);
3490 assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
3491 assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
3492 assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
3493 }
3494
3495 const SKIPPING: &str = "\
3498Found 2 known vulnerabilities in 1 package
3499Name Version ID Fix Versions
3500--------- ------- --------------- ------------
3501starlette 0.41.3 PYSEC-2026-1941 0.47.2
3502starlette 0.41.3 PYSEC-2026-1942 0.49.1
3503
3504Name Skip Reason
3505----- -------------------------------------------------------------------------
3506torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
3507";
3508
3509 #[test]
3510 fn the_skip_table_names_its_packages_and_is_no_finding() {
3511 assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
3512 assert_eq!(
3513 pip_vulnerable_rows(SKIPPING),
3514 vec![
3515 ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
3516 ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
3517 ]
3518 );
3519 assert!(pip_rows_all_named(SKIPPING));
3520 let clean = "No known vulnerabilities found\nName Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
3521 assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
3522 assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
3523 }
3524
3525 #[test]
3526 fn the_skipped_line_names_three_and_counts_the_rest() {
3527 let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
3528 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
3529 assert_eq!(
3530 skipped_line("", &refs),
3531 "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
3532 );
3533 assert_eq!(
3534 skipped_line("", &refs[..1]),
3535 "audit-python: 1 private/non-PyPI package skipped (a)"
3536 );
3537 let long = "services/laya-decisions/requirements.txt: ";
3538 assert_eq!(
3539 skipped_line(long, &["torch", "triton"]),
3540 format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
3541 );
3542 }
3543
3544 #[test]
3545 fn scrub_names_the_canonical_private_path_too() {
3546 let plain = std::path::Path::new("/var/folders/a/audit-1");
3547 let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
3548 assert_eq!(
3549 scrub_private(
3550 "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
3551 plain,
3552 canonical
3553 ),
3554 "x <tmp>/b and <tmp>/c"
3555 );
3556 }
3557
3558 #[test]
3559 fn production_names_are_never_asked_off_a_release_or_out_of_time() {
3560 let settings = crate::config::Settings::default();
3561 let spent = Budget {
3562 started: std::time::Instant::now(),
3563 limit: Some(std::time::Duration::ZERO),
3564 };
3565 let said = std::cell::RefCell::new(Vec::<String>::new());
3566 let say = |m: &str| said.borrow_mut().push(m.to_string());
3567 let dir = std::env::temp_dir();
3568
3569 let mut off = Production::Never;
3570 assert!(off.names(&settings, &spent, &say).is_none());
3571 assert!(matches!(off, Production::Never), "no release never asks");
3572 assert!(said.borrow().is_empty());
3573
3574 let mut late = Production::Unasked(dir.clone());
3575 assert!(late.names(&settings, &spent, &say).is_none());
3576 assert!(late.names(&settings, &spent, &say).is_none());
3577 assert!(
3578 matches!(late, Production::Asked(None)),
3579 "spent is remembered as unknown"
3580 );
3581
3582 let fresh = Budget {
3585 started: std::time::Instant::now(),
3586 limit: None,
3587 };
3588 let mut asked = Production::Unasked(dir);
3589 assert!(asked.names(&settings, &fresh, &say).is_none());
3590 assert!(matches!(asked, Production::Asked(None)));
3591 let said = said.borrow();
3592 assert_eq!(said.len(), 1, "warned once: {said:?}");
3593 assert!(said[0].contains("every finding counts"), "{said:?}");
3594 assert!(said[0].contains("greengate.timeout"), "{said:?}");
3595 }
3596
3597 #[test]
3598 fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
3599 for why in [
3600 "ConnectionError: Max retries exceeded",
3601 "error: request timed out",
3602 "SSL: CERTIFICATE_VERIFY_FAILED",
3603 "Temporary failure in name resolution",
3604 ] {
3605 assert!(pip_audit_next(why).contains("the network"), "{why}");
3606 }
3607 for why in [
3608 "(no output)",
3609 "ModuleNotFoundError: No module named 'pip_audit'",
3610 ] {
3611 assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
3612 }
3613 }
3614
3615 #[test]
3616 fn only_readable_vulnerability_rows_need_the_split() {
3617 let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
3618 assert!(has_rows_to_split(
3619 &Report::Vulnerabilities(vec!["certifi".into()]),
3620 rows
3621 ));
3622 assert!(!has_rows_to_split(
3623 &Report::Vulnerabilities(vec!["x".into()]),
3624 "Found 1\n"
3625 ));
3626 assert!(!has_rows_to_split(&Report::Clean, rows));
3627 assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
3628 }
3629
3630 #[test]
3631 fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
3632 let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
3633 let guard = PrivateDir::create_at(path.clone()).unwrap();
3634 #[cfg(unix)]
3635 {
3636 use std::os::unix::fs::PermissionsExt;
3637 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
3638 assert_eq!(mode & 0o777, 0o700);
3639 }
3640 assert!(PrivateDir::create_at(path.clone()).is_err());
3641 assert!(path.is_dir(), "the refused attempt must leave it alone");
3642 drop(guard);
3643 assert!(!path.exists());
3644 }
3645}