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