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 if matches!(tool, "audit-rust" | "audit-python") {
150 common::warn(&format!(
151 "{tool}: this list is the whole tree; a tag judges only what ships"
152 ));
153 }
154 Outcome::Warned
155 }
156 }
157 Report::CouldNotCheck => {
158 common::warn(&format!(
159 "{tool} could not complete — the dependency tree was NOT checked. \
160 This is not a clean result."
161 ));
162 Outcome::Unavailable
163 }
164 }
165}
166
167const WAIVERS_FILE: &str = crate::names::AUDIT_WAIVERS;
169
170const OLD_WAIVERS_FILE: &str = crate::names::old::AUDIT_WAIVERS;
173
174const MAX_WAIVER_DAYS: i64 = 90;
178
179#[derive(Debug)]
181struct Waiver {
182 id: String,
183 expires: String,
184 reason: String,
185 valid: bool,
186}
187
188#[derive(Debug, Default)]
197struct Waivers {
198 entries: Vec<Waiver>,
199 problems: Vec<String>,
200 file: Option<&'static str>,
203}
204
205impl Waivers {
206 fn load(root: &str, today: i64) -> Self {
207 let root = std::path::Path::new(root);
208 let read = |file: &'static str| (file, std::fs::read_to_string(root.join(file)));
209 let (mut file, mut got) = read(WAIVERS_FILE);
210 if matches!(&got, Err(e) if e.kind() == std::io::ErrorKind::NotFound) {
211 (file, got) = read(OLD_WAIVERS_FILE);
212 } else if root.join(OLD_WAIVERS_FILE).exists() {
213 common::warn(&format!(
214 "{OLD_WAIVERS_FILE} is ignored: {WAIVERS_FILE} exists — \
215 delete the old file"
216 ));
217 }
218 match got {
219 Ok(text) => Self {
220 file: Some(file),
221 ..Self::parse(&text, today)
222 },
223 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
224 Err(e) => Self {
225 entries: Vec::new(),
226 problems: vec![format!(
227 "{file} could not be read ({e}) — it waives nothing"
228 )],
229 file: Some(file),
230 },
231 }
232 }
233
234 fn parse(text: &str, today: i64) -> Self {
235 let mut w = Self::default();
236 for line in text.lines().map(str::trim) {
237 if line.is_empty() || line.starts_with('#') {
238 continue;
239 }
240 let mut parts = line.splitn(3, char::is_whitespace);
241 let id = parts.next().unwrap_or_default().to_string();
242 let expires = parts.next().unwrap_or_default().trim().to_string();
243 let reason = parts.next().unwrap_or_default().trim().to_string();
244 let valid = match days_from_date(&expires) {
245 None => {
246 w.problems.push(format!(
247 "waiver for {id} has no readable expiry date (YYYY-MM-DD) — it waives nothing"
248 ));
249 false
250 }
251 Some(_) if reason.is_empty() => {
252 w.problems.push(format!(
253 "waiver for {id} gives no reason — it waives nothing"
254 ));
255 false
256 }
257 Some(d) if d < today => {
258 w.problems
259 .push(format!("waiver for {id} expired on {expires}"));
260 false
261 }
262 Some(d) if d - today > MAX_WAIVER_DAYS => {
263 w.problems.push(format!(
264 "waiver for {id} runs to {expires}, more than {MAX_WAIVER_DAYS} days \
265 ahead — it waives nothing; date it sooner and revisit"
266 ));
267 false
268 }
269 Some(_) => true,
270 };
271 w.entries.push(Waiver {
272 id,
273 expires,
274 reason,
275 valid,
276 });
277 }
278 w
279 }
280
281 fn covers(&self, id: &str) -> bool {
282 self.entries.iter().any(|w| w.valid && w.id == id)
283 }
284
285 fn describe(&self, id: &str) -> String {
286 match self.entries.iter().find(|w| w.valid && w.id == id) {
287 Some(w) => format!("{id} until {} ({})", w.expires, w.reason),
288 None => id.to_string(),
289 }
290 }
291
292 fn problems(&self) -> &[String] {
293 &self.problems
294 }
295}
296
297fn days_from_date(date: &str) -> Option<i64> {
299 let mut it = date.split('-');
300 let (y, m, d): (i64, i64, i64) = (
301 it.next()?.parse().ok()?,
302 it.next()?.parse().ok()?,
303 it.next()?.parse().ok()?,
304 );
305 let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
306 let month_days = [
307 31,
308 if leap { 29 } else { 28 },
309 31,
310 30,
311 31,
312 30,
313 31,
314 31,
315 30,
316 31,
317 30,
318 31,
319 ];
320 if it.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > month_days[(m - 1) as usize] {
321 return None;
322 }
323 let y = if m <= 2 { y - 1 } else { y };
325 let era = if y >= 0 { y } else { y - 399 } / 400;
326 let yoe = y - era * 400;
327 let mp = (m + 9) % 12;
328 let doy = (153 * mp + 2) / 5 + d - 1;
329 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
330 Some(era * 146_097 + doe - 719_468)
331}
332
333fn today() -> i64 {
335 std::time::SystemTime::now()
336 .duration_since(std::time::UNIX_EPOCH)
337 .map(|d| (d.as_secs() / 86_400) as i64)
338 .unwrap_or(0)
339}
340
341fn advisory_ids(text: &str) -> Vec<String> {
344 let mut ids: Vec<String> = text
345 .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
346 .filter(|w| {
347 let parts: Vec<&str> = w.split('-').collect();
348 match parts.as_slice() {
349 ["GHSA", a, b, c] => [a, b, c]
350 .iter()
351 .all(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphanumeric())),
352 ["RUSTSEC" | "GO" | "PYSEC" | "CVE" | "OSV", year, num] => {
353 year.len() == 4
354 && year.bytes().all(|b| b.is_ascii_digit())
355 && !num.is_empty()
356 && num.bytes().all(|b| b.is_ascii_digit())
357 }
358 _ => false,
359 }
360 })
361 .map(str::to_string)
362 .collect();
363 ids.sort();
364 ids.dedup();
365 ids
366}
367
368fn is_advisory_id(w: &str) -> bool {
370 w.len() == 17
371 && w.starts_with("RUSTSEC-")
372 && w[8..12].bytes().all(|b| b.is_ascii_digit())
373 && w.as_bytes()[12] == b'-'
374 && w[13..17].bytes().all(|b| b.is_ascii_digit())
375}
376
377fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
388 let mut pairs: Vec<(String, Option<String>)> = Vec::new();
389 let mut pending: Option<String> = None;
390 for line in out.lines() {
391 let t = line.trim();
392 if let Some(rest) = t.strip_prefix("Crate:") {
393 pending = rest.split_whitespace().next().map(str::to_string);
394 continue;
395 }
396 if let Some(rest) = t.strip_prefix("ID:") {
397 if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
398 pairs.push((id.to_string(), pending.take()));
399 continue;
400 }
401 }
402 for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
405 pairs.push((w.to_string(), None));
406 }
407 }
408 pairs
409}
410
411fn local_dependents(tree_out: &str) -> Vec<String> {
423 let mut names: Vec<String> = tree_out
424 .lines()
425 .filter(|l| l.contains(" (/"))
426 .filter_map(|l| {
427 l.split_whitespace()
428 .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
429 .map(str::to_string)
430 })
431 .collect();
432 names.sort();
433 names.dedup();
434 names
435}
436
437fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
440 match (krate, reaches.is_empty()) {
441 (None, _) => id.to_string(),
442 (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
443 (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
444 }
445}
446
447fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
450 let mut ids: Vec<String> = out
451 .split_whitespace()
452 .filter(|w| {
453 w.len() == 17
454 && w.starts_with("RUSTSEC-")
455 && w[8..12].bytes().all(|b| b.is_ascii_digit())
456 && w.as_bytes()[12] == b'-'
457 && w[13..17].bytes().all(|b| b.is_ascii_digit())
458 })
459 .map(|w| w.to_string())
460 .collect();
461 ids.sort();
462 ids.dedup();
463 match (ids.is_empty(), exit_ok) {
464 (true, true) => Report::Clean,
465 (true, false) => Report::CouldNotCheck,
466 (false, true) => Report::Advisories(ids),
467 (false, false) => Report::Vulnerabilities(ids),
468 }
469}
470
471fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
478 let summary = out.lines().rev().map(str::trim).find(|l| {
479 l.contains("vulnerabilit")
480 && (l.starts_with("found ")
481 || l.split_whitespace()
482 .next()
483 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
484 });
485 match summary {
486 Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
487 Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
488 None if exit_ok => Report::Clean,
489 None => Report::CouldNotCheck,
490 }
491}
492
493fn read_pnpm_audit(exit_ok: bool, out: &str) -> Report {
499 let lines: Vec<&str> = out.lines().map(str::trim).collect();
500 if lines
501 .iter()
502 .any(|l| l.starts_with("No known vulnerabilities found"))
503 {
504 return Report::Clean;
505 }
506 let found = lines.iter().enumerate().rev().find(|(_, l)| {
507 let mut w = l.split_whitespace();
508 w.next()
509 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
510 && w.next().is_some_and(|v| v.starts_with("vulnerabilit"))
511 && w.next() == Some("found")
512 });
513 match found {
514 Some((_, l)) if l.starts_with("0 ") => Report::Clean,
515 Some((i, l)) => {
516 let severity = lines
517 .get(i + 1)
518 .and_then(|n| n.strip_prefix("Severity:"))
519 .map(str::trim);
520 Report::Vulnerabilities(vec![match severity {
521 Some(sev) => format!("{l} ({sev})"),
522 None => l.to_string(),
523 }])
524 }
525 None if exit_ok => Report::Clean,
526 None => Report::CouldNotCheck,
527 }
528}
529
530fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
537 let mut ids: Vec<String> = out
538 .split_whitespace()
539 .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
540 .filter(|w| {
541 w.len() >= 12
542 && w.starts_with("GO-")
543 && w[3..7].bytes().all(|b| b.is_ascii_digit())
544 && w.as_bytes()[7] == b'-'
545 && w[8..].bytes().all(|b| b.is_ascii_digit())
546 })
547 .map(|w| w.to_string())
548 .collect();
549 ids.sort();
550 ids.dedup();
551 match (ids.is_empty(), exit_ok) {
552 (true, true) => Report::Clean,
553 (true, false) => Report::CouldNotCheck,
554 (false, true) => Report::Advisories(ids),
555 (false, false) => Report::Vulnerabilities(ids),
556 }
557}
558
559fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
561 if out.contains("No known vulnerabilities found") {
562 return Report::Clean;
563 }
564 if let Some(line) = out
565 .lines()
566 .map(str::trim)
567 .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
568 {
569 return Report::Vulnerabilities(vec![line.to_string()]);
570 }
571 if exit_ok {
572 Report::Clean
573 } else {
574 Report::CouldNotCheck
575 }
576}
577
578fn venv_site_packages(root: &str, source: Option<&std::path::Path>) -> Option<String> {
587 let source_venv = source
593 .filter(|src| {
594 let answers = source_is_this_commit(src);
595 if !answers {
596 common::warn(
597 "audit-python: the source worktree's virtualenv is not this commit's \
598 (another HEAD, or modified Python manifests) — not auditing it",
599 );
600 }
601 answers
602 })
603 .map(|src| src.join(".venv"));
604 let candidates = std::env::var_os("VIRTUAL_ENV")
605 .map(std::path::PathBuf::from)
606 .into_iter()
607 .chain(std::iter::once(std::path::Path::new(root).join(".venv")))
608 .chain(source_venv);
609 for venv in candidates {
610 let windows = venv.join("Lib").join("site-packages");
611 if windows.is_dir() {
612 return Some(windows.to_string_lossy().into_owned());
613 }
614 let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
615 continue;
616 };
617 for e in entries.flatten() {
618 if !e.file_name().to_string_lossy().starts_with("python") {
619 continue;
620 }
621 let sp = e.path().join("site-packages");
622 if sp.is_dir() {
623 return Some(sp.to_string_lossy().into_owned());
624 }
625 }
626 }
627 None
628}
629
630fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
632 audited_in(settings, argv, std::path::Path::new(&common::repo_root()))
633}
634
635fn audited_in(
637 settings: &crate::config::Settings,
638 argv: &[String],
639 dir: &std::path::Path,
640) -> Option<(bool, String)> {
641 let mut cmd = std::process::Command::new(&argv[0]);
642 cmd.args(&argv[1..])
643 .current_dir(dir)
644 .stdin(std::process::Stdio::null());
645 common::strip_git_env(&mut cmd);
646 let (ran, out) = common::capture_within(settings, &mut cmd)?;
647 match ran {
648 common::Ran::Status(s) => Some((s.success(), out)),
649 common::Ran::TimedOut(budget) => {
650 common::say_timed_out(&argv[0], budget);
651 None
652 }
653 }
654}
655
656fn failure_line(out: &str) -> Option<String> {
662 let lines: Vec<&str> = out
663 .lines()
664 .map(str::trim)
665 .filter(|l| !l.is_empty())
666 .collect();
667 let line = lines
668 .iter()
669 .rev()
670 .find(|l| l.to_ascii_lowercase().contains("error"))
671 .or(lines.last())?;
672 let mut s: String = line.chars().take(200).collect();
673 if line.chars().count() > 200 {
674 s.push('…');
675 }
676 Some(s)
677}
678
679struct Merged {
681 report: Report,
682 full: String,
685 waivable: bool,
686 complete: bool,
688}
689
690fn audit_each_dir(
704 settings: &crate::config::Settings,
705 tool: &str,
706 lockfile: &str,
707 argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
708 read: fn(bool, &str) -> Report,
709 refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
710) -> Merged {
711 let answer_in = |path: &std::path::Path| match argv_in(path) {
712 None => DirAnswer::Nothing,
713 Some(argv) => answer_of(settings, &argv, path, read),
714 };
715 audit_each_dir_answered(tool, lockfile, answer_in, refine)
716}
717
718fn answer_of(
720 settings: &crate::config::Settings,
721 argv: &[String],
722 dir: &std::path::Path,
723 read: fn(bool, &str) -> Report,
724) -> DirAnswer {
725 match audited_in(settings, argv, dir) {
726 None => DirAnswer::TimedOut,
727 Some((exit_ok, out)) => DirAnswer::Read {
728 report: read(exit_ok, &out),
729 full: out.clone(),
730 out,
731 gap: None,
732 },
733 }
734}
735
736enum DirAnswer {
738 Nothing,
740 TimedOut,
743 Read {
749 report: Report,
750 out: String,
751 full: String,
752 gap: Option<String>,
753 },
754}
755
756fn audit_each_dir_answered(
759 tool: &str,
760 lockfile: &str,
761 mut answer_in: impl FnMut(&std::path::Path) -> DirAnswer,
762 mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
763) -> Merged {
764 let root = std::path::PathBuf::from(common::repo_root());
765 let dirs = lockfile_dirs(lockfile);
766 let only_root = dirs.len() == 1 && dirs[0].is_empty();
767 let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
768 let mut partial = Vec::new();
769 let mut full = String::new();
770 for dir in &dirs {
771 let path = root.join(dir);
772 let label = if dir.is_empty() { "." } else { dir.as_str() };
773 let label_ids = |ids: Vec<String>| -> Vec<String> {
774 if dir.is_empty() {
775 ids
776 } else {
777 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
778 }
779 };
780 let (report, out, dir_full, gap) = match answer_in(&path) {
781 DirAnswer::Nothing => {
782 unchecked.push(format!("{label} (nothing to audit there)"));
783 continue;
784 }
785 DirAnswer::TimedOut => {
788 unchecked.push(format!("{label} (timed out)"));
789 continue;
790 }
791 DirAnswer::Read {
792 report,
793 out,
794 full,
795 gap,
796 } => (report, out, full, gap),
797 };
798 let report = refine(&path, report, &out);
799 if gap.is_some() && !matches!(report, Report::CouldNotCheck) {
800 partial.push(label.to_string());
801 }
802 match report {
803 Report::Vulnerabilities(ids) => {
804 vulns.extend(label_ids(ids));
805 if only_root {
806 full.push_str(&dir_full);
807 } else {
808 full.push_str(&format!("── {tool} in {label}\n{dir_full}\n"));
809 }
810 }
811 Report::Advisories(ids) => advisories.extend(label_ids(ids)),
812 Report::CouldNotCheck => unchecked.push(match gap.or_else(|| failure_line(&out)) {
813 Some(why) => format!("{label} ({why})"),
814 None => label.to_string(),
815 }),
816 Report::Clean => {}
817 }
818 }
819 if !unchecked.is_empty() {
820 common::warn(&format!(
821 "{tool}: the audit could not answer in {} — NOT checked there",
822 unchecked.join(", ")
823 ));
824 }
825 if !partial.is_empty() {
827 common::warn(&format!(
828 "{tool}: NOT fully checked in {} (part of the audit did not answer)",
829 partial.join(", ")
830 ));
831 }
832 let report = if !vulns.is_empty() {
833 Report::Vulnerabilities(vulns)
834 } else if !unchecked.is_empty() || !partial.is_empty() {
835 Report::CouldNotCheck
836 } else if !advisories.is_empty() {
837 Report::Advisories(advisories)
838 } else {
839 Report::Clean
840 };
841 Merged {
842 report,
843 full,
844 waivable: unchecked.is_empty() && partial.is_empty(),
845 complete: unchecked.is_empty() && partial.is_empty(),
846 }
847}
848
849fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
850 let (settings, refs) = (ctx.settings, ctx.push.get());
851 if !has_lockfile("Cargo.lock") {
852 return Ran::Inert;
853 }
854 if common::which("cargo-audit").is_none() {
855 common::warn(
856 "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
857 the audit did NOT run",
858 );
859 return Ran::Unavailable;
860 }
861 let argv = vec![
862 common::program("cargo"),
863 "audit".into(),
864 "--color".into(),
865 "never".into(),
866 ];
867 let release = releasing(refs);
868 let merged = audit_each_dir(
869 settings,
870 "audit-rust",
871 "Cargo.lock",
872 |_| Some(argv.clone()),
873 read_cargo_audit,
874 |dir, mut report, out| {
875 if release {
876 if let Report::Vulnerabilities(ids) = report {
877 let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
878 cargo_tree_shipped(settings, dir, krate)
879 });
880 warn_dev_only("audit-rust", &dev_only);
881 report = if shipped.is_empty() {
882 Report::Clean
883 } else {
884 Report::Vulnerabilities(shipped)
885 };
886 }
887 }
888 attribute(report, out, |krate| {
889 cargo_tree_inverse(settings, dir, krate)
890 })
891 },
892 );
893 Ran::Concluded(Concluded {
894 tool: "audit-rust".to_string(),
895 report: merged.report,
896 full: merged.full,
897 waivable: merged.waivable,
898 complete: merged.complete,
899 })
900}
901
902fn cargo_tree_shipped(
907 settings: &crate::config::Settings,
908 dir: &std::path::Path,
909 spec: &str,
910) -> Option<String> {
911 let argv = vec![
912 common::program("cargo"),
913 "tree".into(),
914 "--invert".into(),
915 spec.into(),
916 "--edges".into(),
917 "normal,build".into(),
918 "--target".into(),
919 "all".into(),
920 "--all-features".into(),
921 "--color".into(),
922 "never".into(),
923 ];
924 audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
927}
928
929fn tree_says_dev_only(tree: &str) -> bool {
933 local_dependents(tree).is_empty() && tree.contains("nothing to print")
934}
935
936fn split_shipped_crates(
940 ids: Vec<String>,
941 out: &str,
942 shipped_tree: impl Fn(&str) -> Option<String>,
943) -> (Vec<String>, Vec<String>) {
944 let specs = ids_with_specs(out);
945 let mut verdicts: Vec<(String, bool)> = Vec::new();
946 let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
947 for id in ids {
948 let spec = specs
949 .iter()
950 .find(|(pid, spec)| *pid == id && spec.is_some())
951 .and_then(|(_, spec)| spec.clone());
952 let ships = match spec {
953 None => true,
954 Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
957 Some((_, v)) => *v,
958 None => {
959 let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
960 verdicts.push((spec, v));
961 v
962 }
963 },
964 };
965 if ships {
966 shipped.push(id);
967 } else {
968 dev_only.push(id);
969 }
970 }
971 (shipped, dev_only)
972}
973
974fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
978 let mut pairs = Vec::new();
979 let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
980 for line in out.lines().map(str::trim) {
981 if let Some(rest) = line.strip_prefix("Crate:") {
982 krate = rest.split_whitespace().next().map(str::to_string);
983 version = None;
984 } else if let Some(rest) = line.strip_prefix("Version:") {
985 version = rest.split_whitespace().next().map(str::to_string);
986 } else if let Some(rest) = line.strip_prefix("ID:") {
987 if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
988 let spec = krate.take().map(|k| match version.take() {
989 Some(v) => format!("{k}@{v}"),
990 None => k,
991 });
992 pairs.push((id.to_string(), spec));
993 }
994 }
995 }
996 pairs
997}
998
999fn warn_dev_only(tool: &str, dev_only: &[String]) {
1001 if !dev_only.is_empty() {
1002 common::warn(&format!(
1003 "{tool}: dev-only, only in development dependencies, which the release does not ship — not blocking: {}",
1004 dev_only.join("; ")
1005 ));
1006 }
1007}
1008
1009fn cargo_tree_inverse(
1013 settings: &crate::config::Settings,
1014 dir: &std::path::Path,
1015 krate: &str,
1016) -> Option<String> {
1017 let argv = vec![
1018 common::program("cargo"),
1019 "tree".into(),
1020 "--invert".into(),
1021 krate.into(),
1022 "--edges".into(),
1023 "normal".into(),
1024 "--color".into(),
1025 "never".into(),
1026 ];
1027 audited_in(settings, &argv, dir).map(|(_, out)| out)
1028}
1029
1030fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
1038 match report {
1039 Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
1040 Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
1041 other => other,
1044 }
1045}
1046
1047fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
1051 let pairs = ids_with_crates(out);
1052 let mut seen: Vec<(String, Vec<String>)> = Vec::new();
1053 ids.iter()
1054 .map(|id| {
1055 let krate = pairs
1056 .iter()
1057 .find(|(pid, k)| pid == id && k.is_some())
1058 .and_then(|(_, k)| k.clone());
1059 let Some(k) = krate else {
1060 return id.clone();
1061 };
1062 if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
1063 return describe(id, Some(&k), reaches);
1064 }
1065 let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
1066 seen.push((k.clone(), reaches.clone()));
1067 describe(id, Some(&k), &reaches)
1068 })
1069 .collect()
1070}
1071
1072fn has_lockfile(lockfile: &str) -> bool {
1079 crate::tracked_paths()
1080 .iter()
1081 .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1082}
1083
1084fn lockfile_dirs(lockfile: &str) -> Vec<String> {
1089 let mut dirs: Vec<String> = crate::tracked_paths()
1090 .iter()
1091 .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
1092 .map(|p| {
1093 p.rsplit_once('/')
1094 .map(|(d, _)| d.to_string())
1095 .unwrap_or_default()
1096 })
1097 .collect();
1098 dirs.sort();
1099 dirs.dedup();
1100 dirs
1101}
1102
1103struct JsAuditor {
1106 lockfile: &'static str,
1107 tool: &'static str,
1108 read: fn(bool, &str) -> Report,
1109 args: fn(&str) -> Vec<String>,
1111 prod_only: &'static str,
1114}
1115
1116fn pnpm_args(dir: &str) -> Vec<String> {
1123 let manifest = if dir.is_empty() {
1124 "pnpm-workspace.yaml".to_string()
1125 } else {
1126 format!("{dir}/pnpm-workspace.yaml")
1127 };
1128 if crate::tracked_paths().contains(&manifest) {
1129 vec![]
1130 } else {
1131 vec!["--ignore-workspace".into()]
1132 }
1133}
1134
1135const JS_AUDITORS: [JsAuditor; 2] = [
1136 JsAuditor {
1137 lockfile: "package-lock.json",
1138 tool: "npm",
1139 read: read_npm_audit,
1140 args: |_| vec![],
1141 prod_only: "--omit=dev",
1142 },
1143 JsAuditor {
1144 lockfile: "pnpm-lock.yaml",
1145 tool: "pnpm",
1146 read: read_pnpm_audit,
1147 args: pnpm_args,
1148 prod_only: "--prod",
1149 },
1150];
1151
1152fn js_run(ctx: &crate::registry::Ctx) -> Ran {
1180 let settings = ctx.settings;
1181 let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
1182 .iter()
1183 .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
1184 .collect();
1185 if projects.is_empty() {
1186 return Ran::Inert;
1187 }
1188 let root = std::path::PathBuf::from(common::repo_root());
1189 let mut found = Vec::new();
1190 let mut dev_only = Vec::new();
1191 let mut unchecked = Vec::new();
1192 let mut unsplit = false;
1193 let mut full = String::new();
1194 for (auditor, dir) in &projects {
1195 let label = if dir.is_empty() {
1196 ".".to_string()
1197 } else {
1198 dir.clone()
1199 };
1200 let mut argv = vec![common::program(auditor.tool), "audit".into()];
1201 argv.extend((auditor.args)(dir));
1202 let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
1203 common::warn(&format!(
1204 "audit-js: {} could not run in {label} — the audit did NOT run",
1205 auditor.tool
1206 ));
1207 return Ran::Unavailable;
1208 };
1209 match (auditor.read)(exit_ok, &out) {
1210 Report::Vulnerabilities(what) => {
1211 let mut prod = argv.clone();
1212 prod.push(auditor.prod_only.into());
1213 match audited_in(settings, &prod, &root.join(dir))
1214 .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
1215 {
1216 Some((Report::Clean | Report::Advisories(_), _)) => {
1217 dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1218 }
1219 Some((Report::Vulnerabilities(shipped), pout)) => {
1220 let prod_ids = advisory_ids(&pout);
1226 let dev: Vec<String> = if prod_ids.is_empty() {
1227 Vec::new()
1228 } else {
1229 advisory_ids(&out)
1230 .into_iter()
1231 .filter(|id| !prod_ids.contains(id))
1232 .collect()
1233 };
1234 if !dev.is_empty() {
1235 dev_only.push(format!("{label}: {}", dev.join(", ")));
1236 }
1237 found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
1238 full.push_str(&format!(
1239 "── {} audit {} in {label}\n{pout}\n",
1240 auditor.tool, auditor.prod_only
1241 ));
1242 }
1243 Some((Report::CouldNotCheck, _)) | None => {
1244 common::warn(&format!(
1245 "audit-js: could not audit production dependencies in {label}; \
1246 judged the whole tree"
1247 ));
1248 unsplit = true;
1249 found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
1250 full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
1251 }
1252 }
1253 }
1254 Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
1255 Report::Clean | Report::Advisories(_) => {}
1256 }
1257 }
1258 if !unchecked.is_empty() {
1259 common::warn(&format!(
1260 "audit-js: the audit could not answer in {} — those projects were NOT checked",
1261 unchecked.join(", ")
1262 ));
1263 }
1264 warn_dev_only("audit-js", &dev_only);
1265 let waivable = unchecked.is_empty();
1266 let report = if !found.is_empty() {
1267 Report::Vulnerabilities(found)
1268 } else if !unchecked.is_empty() {
1269 Report::CouldNotCheck
1270 } else {
1271 Report::Clean
1272 };
1273 Ran::Concluded(Concluded {
1274 tool: "audit-js".to_string(),
1275 report,
1276 full,
1277 waivable,
1278 complete: !unsplit,
1281 })
1282}
1283
1284fn go_run(ctx: &crate::registry::Ctx) -> Ran {
1292 let settings = ctx.settings;
1293 if !has_lockfile("go.sum") {
1294 return Ran::Inert;
1295 }
1296 if common::which("govulncheck").is_none() {
1297 common::warn(
1298 "audit-go: govulncheck is not installed \
1299 (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
1300 );
1301 return Ran::Unavailable;
1302 }
1303 let tool_dirs = std::cell::RefCell::new(std::collections::HashSet::new());
1306 let argv_in = |dir: &std::path::Path| {
1307 let tools_only =
1308 !super::go_tools::has_go_package(dir) && super::go_tools::declares_tool(dir);
1309 if tools_only {
1310 tool_dirs.borrow_mut().insert(dir.to_path_buf());
1311 }
1312 let pattern = if tools_only { "tool" } else { "./..." };
1313 Some(vec![common::program("govulncheck"), pattern.into()])
1314 };
1315 let root = std::path::PathBuf::from(common::repo_root());
1318 let mut in_tools = Vec::new();
1319 let refine = |dir: &std::path::Path, report: Report, _: &str| match report {
1320 Report::Vulnerabilities(ids) if tool_dirs.borrow().contains(dir) => {
1321 let label = dir
1322 .strip_prefix(&root)
1323 .ok()
1324 .map(|d| d.display().to_string())
1325 .filter(|d| !d.is_empty())
1326 .unwrap_or_else(|| ".".into());
1327 in_tools.push(format!("{label} (govulncheck tool): {}", ids.join(", ")));
1328 Report::Clean
1329 }
1330 other => other,
1331 };
1332 let merged = audit_each_dir(
1333 settings,
1334 "audit-go",
1335 "go.sum",
1336 argv_in,
1337 read_govulncheck,
1338 refine,
1339 );
1340 if !in_tools.is_empty() {
1341 common::warn(&format!(
1342 "audit-go: in a tools module, whose tools the release does not ship — not blocking: {}",
1343 in_tools.join("; ")
1344 ));
1345 }
1346 Ran::Concluded(Concluded {
1347 tool: "audit-go".to_string(),
1348 report: merged.report,
1349 full: merged.full,
1350 waivable: merged.waivable,
1351 complete: merged.complete,
1352 })
1353}
1354
1355fn python_run(ctx: &crate::registry::Ctx) -> Ran {
1356 let (settings, refs) = (ctx.settings, ctx.push.get());
1357 if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
1358 return Ran::Inert;
1359 }
1360 if common::which("pip-audit").is_none() {
1361 common::warn(
1362 "audit-python: pip-audit is not installed (pip install pip-audit) — \
1363 the audit did NOT run",
1364 );
1365 return Ran::Unavailable;
1366 }
1367 let root = common::repo_root();
1368 if !lockfile_dirs("requirements.txt").is_empty() {
1371 let root_path = std::path::PathBuf::from(&root);
1372 let rel_of = |dir: &std::path::Path| {
1373 dir.strip_prefix(&root_path)
1374 .map(|p| p.to_string_lossy().into_owned())
1375 .unwrap_or_default()
1376 };
1377 let host = host_sources(
1381 &|var| std::env::var_os(var).map(|value| value.to_string_lossy().into_owned()),
1382 &read_config,
1383 );
1384 let budget = Budget::new(settings);
1386 let answer_in = |dir: &std::path::Path| {
1387 requirements_answer(settings, dir, &rel_of(dir), &host, &budget)
1388 };
1389 let merged = audit_each_dir_answered(
1390 "audit-python",
1391 "requirements.txt",
1392 answer_in,
1393 |_, report, _| report,
1394 );
1395 let waivable = merged.waivable && pip_rows_all_named(&merged.full);
1398 return Ran::Concluded(Concluded {
1399 tool: "audit-python".to_string(),
1400 report: merged.report,
1401 full: merged.full,
1402 waivable,
1403 complete: merged.complete,
1404 });
1405 }
1406 let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
1407 vec![
1415 common::program("pip-audit"),
1416 "--path".into(),
1417 site_packages,
1418 "--skip-editable".into(),
1421 ]
1422 } else if has_lockfile("uv.lock") && common::which("uv").is_some() {
1423 return python_lock_run(ctx);
1425 } else {
1426 common::warn(
1427 "audit-python: the audit did NOT run — found no requirements.txt,\n \
1428 no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n \
1429 Next: `uv sync`, or install uv so uv.lock can be audited.",
1430 );
1431 return Ran::Unavailable;
1432 };
1433 let Some((exit_ok, out)) = audited(settings, &argv) else {
1434 return Ran::Unavailable;
1435 };
1436 let report = read_pip_audit(exit_ok, &out);
1441 let production = if releasing(refs) && has_rows_to_split(&report, &out) {
1442 uv_production_names(settings, std::path::Path::new(&root))
1443 } else {
1444 None
1445 };
1446 let (report, waivable) = shipped_only(report, &out, production.as_ref());
1447 Ran::Concluded(Concluded {
1448 tool: "audit-python".to_string(),
1449 report,
1450 full: out,
1451 waivable,
1452 complete: true,
1453 })
1454}
1455
1456struct SentAnswer {
1458 answer: DirAnswer,
1459 sent_names: Option<usize>,
1462 private: std::collections::BTreeSet<String>,
1464 unproven: bool,
1466}
1467
1468fn requirements_answer(
1472 settings: &crate::config::Settings,
1473 dir: &std::path::Path,
1474 rel: &str,
1475 host: &[IndexSource],
1476 budget: &Budget,
1477) -> DirAnswer {
1478 let prefix = requirements_prefix(rel);
1479 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
1480 let held_back = |why: &str| DirAnswer::Read {
1481 report: Report::CouldNotCheck,
1482 out: String::new(),
1483 full: String::new(),
1484 gap: Some(why.to_string()),
1485 };
1486 if budget.spent() {
1489 say(&format!(
1490 "out of time before this directory was reached — NOT checked\n {TIMEOUT_NEXT}"
1491 ));
1492 return held_back("out of time");
1493 }
1494 let path = dir.join("requirements.txt");
1495 let text = std::fs::read_to_string(&path).ok();
1496 let mut sources = match text.as_deref() {
1497 Some(text) => file_sources(text, "requirements.txt", dir, &read_include),
1498 None if path.exists() => vec![IndexSource::unread_include("requirements.txt")],
1501 None => Vec::new(),
1502 };
1503 sources.extend(host.iter().cloned());
1504 let argv_of = |closed: &[&str]| -> Vec<String> {
1505 let mut argv = vec![
1506 common::program("pip-audit"),
1507 "-r".into(),
1508 "requirements.txt".into(),
1509 ];
1510 argv.extend(closed.iter().map(|flag| flag.to_string()));
1511 argv
1512 };
1513 let resolve_file = || answer_of(settings, &argv_of(&[]), dir, read_pip_audit);
1514 let audit_closed_file = || {
1518 answer_of(
1519 settings,
1520 &argv_of(&["--no-deps", "--disable-pip"]),
1521 dir,
1522 read_pip_audit,
1523 )
1524 };
1525 let sent = match text.as_deref().and_then(hashed_pins_in) {
1526 None if !sources.is_empty() => {
1528 say(&format!(
1529 "not sent: {} is not PyPI, and a resolve sends every dependency — did NOT run\n {ANNOTATE_NEXT}",
1530 sources_phrase(&sources)
1531 ));
1532 return held_back("names not shown public");
1533 }
1534 None => SentAnswer {
1535 answer: resolve_file(),
1536 sent_names: None,
1537 private: std::collections::BTreeSet::new(),
1538 unproven: false,
1539 },
1540 Some(pins) => {
1541 let held = provenance(&pins, &sources);
1542 if sources.is_empty() && held.private.is_empty() {
1543 let names = pins.names();
1544 let answer = if pins.marked {
1545 audit_hashed_pins(settings, dir, rel, pins.pairs, 0, budget)
1546 } else {
1547 audit_closed_file()
1548 };
1549 SentAnswer {
1550 answer,
1551 sent_names: Some(names),
1552 private: held.private,
1553 unproven: false,
1554 }
1555 } else {
1556 if !held.unproven.is_empty() {
1557 say(&format!(
1558 "{} not sent {}: no index shown for them, and {} is not PyPI — NOT fully checked\n {ANNOTATE_NEXT}",
1559 plural(held.unproven.len(), "package"),
1560 names_phrase(&held.unproven),
1561 sources_phrase(&sources)
1562 ));
1563 }
1564 if held.sent.is_empty() {
1565 if !held.private.is_empty() {
1566 let names: Vec<String> =
1567 held.private.iter().map(|n| printable(n)).collect();
1568 let names: Vec<&str> = names.iter().map(String::as_str).collect();
1569 common::warn(&skipped_line(&prefix, &names));
1570 }
1571 if held.unproven.is_empty() {
1572 say(
1573 "no PyPI package to audit — the audit did NOT run\n \
1574 Next: none if every package is private; else check its `# from` lines",
1575 );
1576 } else {
1577 say("no PyPI package to audit — the audit did NOT run");
1578 }
1579 return held_back("no PyPI package to audit");
1580 }
1581 let sent: std::collections::BTreeSet<&str> =
1582 held.sent.iter().map(|(name, _)| name.as_str()).collect();
1583 let sent_names = sent.len();
1584 let held_count = held.private.len() + held.unproven.len();
1585 SentAnswer {
1589 answer: audit_hashed_pins(settings, dir, rel, held.sent, held_count, budget),
1590 sent_names: Some(sent_names),
1591 private: held.private,
1592 unproven: !held.unproven.is_empty(),
1593 }
1594 }
1595 }
1596 };
1597 let DirAnswer::Read {
1598 report,
1599 out,
1600 full,
1601 gap,
1602 } = sent.answer
1603 else {
1604 return sent.answer;
1605 };
1606 let skipped = pip_skipped_names(&out);
1607 let all_skipped = !skipped.is_empty() && sent.sent_names.is_some_and(|n| skipped.len() >= n);
1609 let mut named: Vec<String> = sent.private.iter().map(|n| printable(n)).collect();
1610 named.extend(skipped);
1611 named.sort();
1612 named.dedup();
1613 if !named.is_empty() {
1614 let names: Vec<&str> = named.iter().map(String::as_str).collect();
1615 common::warn(&skipped_line(&prefix, &names));
1616 }
1617 let gap = if sent.unproven {
1618 gap.or_else(|| Some("names not shown public".to_string()))
1619 } else {
1620 gap
1621 };
1622 let report = match report {
1623 Report::Vulnerabilities(found) => Report::Vulnerabilities(found),
1624 Report::CouldNotCheck => Report::CouldNotCheck,
1625 Report::Clean | Report::Advisories(_) if all_skipped || gap.is_some() => {
1626 Report::CouldNotCheck
1627 }
1628 Report::Clean => Report::Clean,
1629 Report::Advisories(found) => Report::Advisories(found),
1630 };
1631 DirAnswer::Read {
1632 report,
1633 out,
1634 full,
1635 gap,
1636 }
1637}
1638
1639fn shipped_only(
1645 mut report: Report,
1646 out: &str,
1647 production: Option<&std::collections::HashSet<String>>,
1648) -> (Report, bool) {
1649 let mut waivable = pip_rows_all_named(out);
1650 if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
1651 let rows = pip_vulnerable_rows(out);
1652 if !rows.is_empty() {
1653 let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
1654 .into_iter()
1655 .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
1656 .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
1657 if ships {
1658 s.push(row);
1659 } else {
1660 d.push(row);
1661 }
1662 (s, d)
1663 });
1664 warn_dev_only("audit-python", &dev_only);
1665 waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
1666 report = if shipped.is_empty() {
1667 Report::Clean
1668 } else {
1669 Report::Vulnerabilities(shipped)
1670 };
1671 }
1672 }
1673 (report, waivable)
1674}
1675
1676fn has_rows_to_split(report: &Report, out: &str) -> bool {
1680 matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
1681}
1682
1683enum Production {
1686 Never,
1688 Unasked(std::path::PathBuf),
1690 Asked(Option<std::collections::HashSet<String>>),
1692}
1693
1694impl Production {
1695 fn names(
1699 &mut self,
1700 settings: &crate::config::Settings,
1701 budget: &Budget,
1702 say: &dyn Fn(&str),
1703 ) -> Option<&std::collections::HashSet<String>> {
1704 if let Production::Unasked(dir) = self {
1705 *self = Production::Asked(if budget.spent() {
1706 say(&format!(
1707 "out of time before the dev-only split — every finding counts\n {TIMEOUT_NEXT}"
1708 ));
1709 None
1710 } else {
1711 uv_production_names(settings, dir)
1712 });
1713 }
1714 match self {
1715 Production::Asked(names) => names.as_ref(),
1716 Production::Never | Production::Unasked(_) => None,
1717 }
1718 }
1719}
1720
1721const TIMEOUT_NEXT: &str =
1723 "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";
1724
1725const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";
1727
1728fn pip_audit_next(why: &str) -> &'static str {
1731 let why = why.to_ascii_lowercase();
1735 let network = [
1736 "network",
1737 "connect",
1738 "timed out",
1739 "timeout",
1740 "resolve",
1741 "dns",
1742 "ssl",
1743 "certificate",
1744 "unreachable",
1745 "temporary failure",
1746 ]
1747 .iter()
1748 .any(|word| why.contains(word));
1749 if network {
1750 "Next: check the network, then push again"
1751 } else {
1752 "Next: `pip-audit --version` to check the install, then push again"
1753 }
1754}
1755
1756const PYPI_REGISTRY: &str = "https://pypi.org/simple";
1759
1760const WARNING_COLUMNS: usize = 80;
1762
1763const NAMES_SHOWN: usize = 3;
1765
1766struct PrivateDir {
1769 path: std::path::PathBuf,
1770}
1771
1772impl PrivateDir {
1773 fn create() -> std::io::Result<PrivateDir> {
1775 Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
1776 }
1777
1778 fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
1781 #[cfg(unix)]
1782 let builder = {
1783 let mut unix_builder = std::fs::DirBuilder::new();
1784 std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
1785 unix_builder
1786 };
1787 #[cfg(not(unix))]
1788 let builder = std::fs::DirBuilder::new();
1789 builder.create(&path)?;
1790 Ok(PrivateDir { path })
1791 }
1792
1793 fn path(&self) -> &std::path::Path {
1794 &self.path
1795 }
1796}
1797
1798impl Drop for PrivateDir {
1799 fn drop(&mut self) {
1800 let _ = std::fs::remove_dir_all(&self.path); }
1802}
1803
1804struct Budget {
1807 started: std::time::Instant,
1808 limit: Option<std::time::Duration>,
1810}
1811
1812impl Budget {
1813 fn new(settings: &crate::config::Settings) -> Budget {
1814 Budget {
1815 started: std::time::Instant::now(),
1816 limit: Some(common::check_timeout(settings))
1817 .filter(|secs| *secs > 0)
1818 .map(std::time::Duration::from_secs),
1819 }
1820 }
1821
1822 fn spent(&self) -> bool {
1823 self.limit
1824 .is_some_and(|limit| self.started.elapsed() >= limit)
1825 }
1826}
1827
1828#[derive(Debug, Default, PartialEq, Eq)]
1830struct LockSources {
1831 pypi: std::collections::BTreeSet<String>,
1833 nameless: usize,
1835}
1836
1837fn is_pypi_url(url: &str) -> bool {
1840 url.trim_end_matches('/') == PYPI_REGISTRY
1841}
1842
1843fn is_pypi_source(source_field: &str) -> bool {
1845 source_field
1846 .split_once("registry = \"")
1847 .and_then(|(_, rest)| rest.split('"').next())
1848 .is_some_and(is_pypi_url)
1849}
1850
1851fn scan_uv_lock(text: &str) -> LockSources {
1855 struct Block {
1856 name: Option<String>,
1857 pypi: bool,
1858 }
1859 let mut blocks: Vec<Block> = Vec::new();
1860 let mut top_level = false;
1861 for line in text.lines() {
1862 if line.starts_with('[') {
1863 top_level = line.trim() == "[[package]]";
1864 if top_level {
1865 blocks.push(Block {
1866 name: None,
1867 pypi: false,
1868 });
1869 }
1870 continue;
1871 }
1872 let (true, Some(block)) = (top_level, blocks.last_mut()) else {
1873 continue;
1874 };
1875 if let Some(value) = line.strip_prefix("name = ") {
1876 if block.name.is_none() {
1877 block.name = value.split('"').nth(1).map(normalise);
1878 }
1879 } else if let Some(value) = line.strip_prefix("source = ") {
1880 block.pypi = is_pypi_source(value);
1881 }
1882 }
1883 let mut sources = LockSources::default();
1884 let mut rejected = std::collections::BTreeSet::new();
1885 for block in blocks {
1886 match block.name.filter(|n| !n.is_empty()) {
1887 None => sources.nameless += 1,
1888 Some(name) if block.pypi => {
1889 sources.pypi.insert(name);
1890 }
1891 Some(name) => {
1892 rejected.insert(name);
1893 }
1894 }
1895 }
1896 sources.pypi.retain(|name| !rejected.contains(name));
1897 sources
1898}
1899
1900#[derive(Debug, Default, PartialEq, Eq)]
1902struct ExportPins {
1903 batches: Vec<std::collections::BTreeMap<String, String>>,
1906 versions: usize,
1908 skipped: std::collections::BTreeSet<String>,
1910 unclassified: std::collections::BTreeSet<String>,
1912}
1913
1914fn exact_pin(line: &str) -> Option<(String, String)> {
1917 let spec = line.split(';').next()?.trim();
1918 let (name, version) = spec.split_once("==")?;
1919 let name = name.split('[').next()?.trim();
1920 let version = version.trim();
1921 let name_ok = !name.is_empty()
1922 && name
1923 .chars()
1924 .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
1925 let version_ok = !version.is_empty()
1926 && version
1927 .chars()
1928 .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
1929 (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
1930}
1931
1932fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
1933 let mut pins = ExportPins::default();
1934 let mut pairs = std::collections::BTreeSet::new();
1935 for line in raw.lines().map(str::trim) {
1936 if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
1937 continue;
1938 }
1939 let name = normalise(
1940 line.split(|c: char| "=<>!~;[ @".contains(c))
1941 .next()
1942 .unwrap_or_default(),
1943 );
1944 if name.is_empty() {
1945 continue;
1946 }
1947 if !pypi.contains(&name) {
1948 pins.skipped.insert(name);
1949 continue;
1950 }
1951 match exact_pin(line) {
1952 Some(pair) => {
1953 pairs.insert(pair);
1954 }
1955 None => {
1956 pins.unclassified.insert(name);
1957 }
1958 }
1959 }
1960 pins.versions = pairs.len();
1961 pins.batches = batches_of(pairs);
1962 pins
1963}
1964
1965fn batches_of(
1969 pairs: std::collections::BTreeSet<(String, String)>,
1970) -> Vec<std::collections::BTreeMap<String, String>> {
1971 let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
1972 for (name, version) in pairs {
1973 match batches.iter().position(|batch| !batch.contains_key(&name)) {
1974 Some(index) => {
1975 batches[index].insert(name, version);
1976 }
1977 None => batches.push(std::collections::BTreeMap::from([(name, version)])),
1978 }
1979 }
1980 batches
1981}
1982
1983fn requirements_path(rel: &str) -> String {
1985 if rel.is_empty() {
1986 "requirements.txt".to_string()
1987 } else {
1988 format!("{rel}/requirements.txt")
1989 }
1990}
1991
1992fn requirements_prefix(rel: &str) -> String {
1995 if rel.is_empty() {
1996 String::new()
1997 } else {
1998 format!("{}: ", requirements_path(rel))
1999 }
2000}
2001
2002fn audit_hashed_pins(
2015 settings: &crate::config::Settings,
2016 dir: &std::path::Path,
2017 rel: &str,
2018 pairs: std::collections::BTreeSet<(String, String)>,
2019 held: usize,
2020 budget: &Budget,
2021) -> DirAnswer {
2022 let prefix = requirements_prefix(rel);
2023 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2024 let unchecked = |why: &str| DirAnswer::Read {
2025 report: Report::CouldNotCheck,
2026 out: String::new(),
2027 full: String::new(),
2028 gap: Some(why.to_string()),
2029 };
2030 let private = match PrivateDir::create() {
2031 Ok(private) => private,
2032 Err(why) => {
2033 say(&format!(
2034 "no private directory ({}) — did NOT run\n {TMPDIR_NEXT}",
2035 why.kind()
2036 ));
2037 return unchecked("no private directory");
2038 }
2039 };
2040 let canonical = std::fs::canonicalize(private.path()).ok();
2042 let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2043 let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
2044 let mut gap: Option<String> = None;
2045 let (mut answered, mut skipped_pins) = (0usize, 0usize);
2049 let batches = batches_of(pairs);
2050 for (index, batch) in batches.iter().enumerate() {
2051 if budget.spent() {
2052 say(&format!(
2053 "out of time; unaudited versions remain — NOT fully checked\n {TIMEOUT_NEXT}"
2054 ));
2055 gap.get_or_insert_with(|| "out of time".to_string());
2056 break;
2057 }
2058 let file = private.path().join(format!("batch-{index}.txt"));
2059 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2060 if let Err(why) = std::fs::write(&file, body) {
2061 say(&format!(
2062 "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n {TMPDIR_NEXT}",
2063 why.kind()
2064 ));
2065 gap.get_or_insert_with(|| "could not write a batch file".to_string());
2066 break;
2067 }
2068 let argv = vec![
2069 common::program("pip-audit"),
2070 "-r".into(),
2071 file.to_string_lossy().into_owned(),
2072 "--no-deps".into(),
2073 "--disable-pip".into(),
2074 ];
2075 let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
2077 if answered == 0 && gap.is_none() {
2078 return DirAnswer::TimedOut;
2079 }
2080 say("timed out; unaudited versions remain — NOT fully checked");
2082 gap.get_or_insert_with(|| "timed out".to_string());
2083 break;
2084 };
2085 let batch_out = scrub(&batch_out);
2086 match read_pip_audit(exit_ok, &batch_out) {
2087 Report::Vulnerabilities(found) => {
2088 vulnerabilities.extend(found);
2089 full.push_str(&batch_out);
2090 answered += batch.len();
2091 skipped_pins += skipped_in(batch, &batch_out);
2092 }
2093 Report::Clean | Report::Advisories(_) => {
2095 answered += batch.len();
2096 skipped_pins += skipped_in(batch, &batch_out);
2097 }
2098 Report::CouldNotCheck => {
2099 let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
2100 say(&format!(
2101 "pip-audit could not answer — NOT fully checked\n {}\n {}",
2102 clip(&why, WARNING_COLUMNS - 2),
2103 pip_audit_next(&why)
2104 ));
2105 gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
2106 }
2107 }
2108 out.push_str(&batch_out);
2109 }
2110 let audited = answered - skipped_pins;
2111 if audited > 0 {
2112 common::ok(
2113 settings,
2114 &format!(
2115 "audit-python: audited {} ({}, {} skipped)",
2116 requirements_path(rel),
2117 plural(audited, "package version"),
2118 skipped_pins + held
2119 ),
2120 );
2121 }
2122 let report = if !vulnerabilities.is_empty() {
2123 Report::Vulnerabilities(vulnerabilities)
2124 } else if gap.is_some() {
2125 Report::CouldNotCheck
2126 } else {
2127 Report::Clean
2128 };
2129 DirAnswer::Read {
2130 report,
2131 out,
2132 full,
2133 gap,
2134 }
2135}
2136
2137fn skipped_in(batch: &std::collections::BTreeMap<String, String>, batch_out: &str) -> usize {
2141 let skipped = pip_skipped_names(batch_out);
2142 batch.keys().filter(|name| skipped.contains(name)).count()
2143}
2144
2145#[derive(Debug, Default, PartialEq, Eq)]
2147struct HashedPins {
2148 pairs: std::collections::BTreeSet<(String, String)>,
2150 marked: bool,
2152 from: std::collections::BTreeMap<String, Vec<Option<String>>>,
2156}
2157
2158impl HashedPins {
2159 fn names(&self) -> usize {
2161 let names: std::collections::BTreeSet<&str> =
2162 self.pairs.iter().map(|(name, _)| name.as_str()).collect();
2163 names.len()
2164 }
2165}
2166
2167fn logical_lines(text: &str) -> Vec<(usize, String)> {
2170 let mut logical = Vec::new();
2171 let mut current = String::new();
2172 let mut open: Option<usize> = None;
2175 for (index, line) in text.lines().enumerate() {
2176 let first = *open.get_or_insert(index + 1);
2177 match line.strip_suffix('\\') {
2178 Some(head) => {
2179 current.push_str(head);
2180 current.push(' ');
2181 }
2182 None => {
2183 current.push_str(line);
2184 logical.push((first, std::mem::take(&mut current)));
2185 open = None;
2186 }
2187 }
2188 }
2189 if let Some(first) = open {
2190 logical.push((first, current));
2191 }
2192 logical
2193}
2194
2195fn uncommented(line: &str) -> &str {
2198 if line.trim_start().starts_with('#') {
2199 return "";
2200 }
2201 match line.find(" #") {
2202 Some(cut) => line[..cut].trim(),
2203 None => line.trim(),
2204 }
2205}
2206
2207fn index_annotation(line: &str) -> Option<&str> {
2209 let url = line.trim().strip_prefix("# from ")?.trim();
2210 (url.contains("://") && !url.contains(char::is_whitespace)).then_some(url)
2211}
2212
2213fn hashed_pins_in(text: &str) -> Option<HashedPins> {
2226 let mut pins = HashedPins::default();
2227 let mut last: Option<String> = None;
2228 for (_, raw) in logical_lines(text) {
2229 if let Some(url) = index_annotation(&raw) {
2230 if let Some(slot) = last
2231 .as_ref()
2232 .and_then(|name| pins.from.get_mut(name))
2233 .and_then(|pins_of| pins_of.last_mut())
2234 {
2235 *slot = Some(url.to_string());
2236 }
2237 continue;
2238 }
2239 let line = uncommented(&raw);
2240 if line.is_empty() {
2241 continue;
2242 }
2243 if line.starts_with('-') {
2244 match option_line(line) {
2245 OptionLine::Index(_)
2246 | OptionLine::FindLinks(_)
2247 | OptionLine::NoIndex
2248 | OptionLine::TrustedHost => continue,
2249 OptionLine::Include(_) | OptionLine::Editable | OptionLine::Other => return None,
2250 }
2251 }
2252 let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
2253 let hashed = options
2254 .split_whitespace()
2255 .any(|option| option.starts_with("--hash"));
2256 if !hashed {
2257 return None;
2258 }
2259 let pair = exact_pin(spec)?;
2260 pins.from.entry(pair.0.clone()).or_default().push(None);
2261 last = Some(pair.0.clone());
2262 pins.pairs.insert(pair);
2263 pins.marked |= spec.contains(';');
2264 }
2265 (!pins.pairs.is_empty()).then_some(pins)
2266}
2267
2268#[derive(Debug, PartialEq, Eq)]
2270enum OptionLine<'a> {
2271 Index(&'a str),
2273 FindLinks(&'a str),
2275 NoIndex,
2276 Include(&'a str),
2278 TrustedHost,
2280 Editable,
2282 Other,
2283}
2284
2285const PIP_FILE_OPTIONS: &[&str] = &[
2288 "--index-url",
2289 "--extra-index-url",
2290 "--no-index",
2291 "--find-links",
2292 "--requirement",
2293 "--constraint",
2294 "--editable",
2295 "--trusted-host",
2296 "--pre",
2297 "--prefer-binary",
2298 "--require-hashes",
2299 "--only-binary",
2300 "--no-binary",
2301 "--use-feature",
2302 "--hash",
2303 "--config-settings",
2304 "--global-option",
2305];
2306
2307fn long_option(name: &str) -> &str {
2310 if PIP_FILE_OPTIONS.contains(&name) {
2311 return name;
2312 }
2313 let mut matches = PIP_FILE_OPTIONS
2314 .iter()
2315 .filter(|full| full.starts_with(name));
2316 match (matches.next(), matches.next()) {
2317 (Some(full), None) => full,
2318 _ => name,
2319 }
2320}
2321
2322fn option_line(line: &str) -> OptionLine<'_> {
2326 let mut words = line.split_whitespace();
2327 let first = words.next().unwrap_or_default();
2328 let (name, glued) = if first.starts_with("--") {
2329 match first.split_once('=') {
2330 Some((name, value)) => (long_option(name), Some(value)),
2331 None => (long_option(first), None),
2332 }
2333 } else if first.len() > 2 && first.is_char_boundary(2) {
2334 (&first[..2], Some(&first[2..]))
2335 } else {
2336 (first, None)
2337 };
2338 let value = glued.or_else(|| words.next()).unwrap_or_default();
2339 match name {
2340 "-i" | "--index-url" | "--extra-index-url" => OptionLine::Index(value),
2341 "-f" | "--find-links" => OptionLine::FindLinks(value),
2342 "--no-index" => OptionLine::NoIndex,
2343 "-r" | "--requirement" | "-c" | "--constraint" => OptionLine::Include(value),
2344 "--trusted-host" => OptionLine::TrustedHost,
2345 "-e" | "--editable" => OptionLine::Editable,
2346 _ => OptionLine::Other,
2347 }
2348}
2349
2350#[derive(Debug, Clone, PartialEq, Eq)]
2354struct IndexSource {
2355 label: String,
2357 what: String,
2359}
2360
2361impl IndexSource {
2362 fn new(label: &str, what: &str) -> IndexSource {
2363 IndexSource {
2364 label: printable(label),
2365 what: printable(what),
2366 }
2367 }
2368
2369 fn index(label: &str, url: &str) -> Option<IndexSource> {
2371 (!is_pypi_url(url)).then(|| IndexSource::new(label, &host_of(url)))
2372 }
2373
2374 fn find_links(label: &str, location: &str) -> IndexSource {
2376 let remote = location
2377 .split_once("://")
2378 .is_some_and(|(scheme, _)| !scheme.eq_ignore_ascii_case("file"));
2379 if remote {
2380 IndexSource::new(label, &host_of(location))
2381 } else {
2382 IndexSource::new(label, "a local path")
2383 }
2384 }
2385
2386 fn no_index(label: &str) -> IndexSource {
2387 IndexSource::new(label, "--no-index")
2388 }
2389
2390 fn unread_include(label: &str) -> IndexSource {
2391 IndexSource::new(label, "an unread include")
2392 }
2393
2394 fn unread_config(label: &str) -> IndexSource {
2395 IndexSource::new(label, "an unread config file")
2396 }
2397
2398 fn direct_reference(label: &str) -> IndexSource {
2399 IndexSource::new(label, "a direct reference")
2400 }
2401}
2402
2403fn is_direct_reference(line: &str) -> bool {
2407 let spec = line.split(" --").next().unwrap_or_default();
2408 let spec = spec.split(';').next().unwrap_or_default().trim();
2409 let archive = [".whl", ".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz"]
2410 .iter()
2411 .any(|ext| spec.to_ascii_lowercase().ends_with(ext));
2412 spec.contains(['@', '/', '\\']) || spec.starts_with('.') || archive
2413}
2414
2415fn host_of(url: &str) -> String {
2419 let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
2420 let rest = rest.rsplit('@').next().unwrap_or_default();
2421 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
2422 if host.is_empty() {
2423 "an index with no host".to_string()
2424 } else {
2425 host.to_string()
2426 }
2427}
2428
2429fn printable(text: &str) -> String {
2432 let mut shown = String::with_capacity(text.len());
2433 for c in text.chars() {
2434 if c.is_control() {
2435 shown.extend(c.escape_default());
2436 } else {
2437 shown.push(c);
2438 }
2439 }
2440 shown
2441}
2442
2443const INCLUDE_DEPTH: usize = 8;
2445
2446fn read_include(path: &std::path::Path) -> Option<String> {
2450 let meta = std::fs::metadata(path).ok()?;
2451 if !meta.is_file() {
2452 return None;
2453 }
2454 std::fs::read_to_string(path).ok()
2455}
2456
2457fn file_sources(
2462 text: &str,
2463 label: &str,
2464 dir: &std::path::Path,
2465 read: &dyn Fn(&std::path::Path) -> Option<String>,
2466) -> Vec<IndexSource> {
2467 let mut sources = Vec::new();
2468 let mut seen = std::collections::BTreeSet::new();
2469 let mut pending = vec![(text.to_string(), label.to_string(), dir.to_path_buf(), 0)];
2471 while let Some((text, label, dir, depth)) = pending.pop() {
2472 for (number, raw) in logical_lines(&text) {
2473 let line = uncommented(&raw);
2474 if line.is_empty() {
2475 continue;
2476 }
2477 let at = format!("{label} line {number}");
2478 if !line.starts_with('-') {
2479 if is_direct_reference(line) {
2480 sources.push(IndexSource::direct_reference(&at));
2481 }
2482 continue;
2483 }
2484 match option_line(line) {
2485 OptionLine::Index(url) => sources.extend(IndexSource::index(&at, url)),
2486 OptionLine::FindLinks(location) => {
2487 sources.push(IndexSource::find_links(&at, location));
2488 }
2489 OptionLine::NoIndex => sources.push(IndexSource::no_index(&at)),
2490 OptionLine::Include(target) => {
2491 if target.is_empty() || target.contains("://") || depth + 1 > INCLUDE_DEPTH {
2492 sources.push(IndexSource::unread_include(&at));
2493 continue;
2494 }
2495 let path = dir.join(target);
2496 let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
2497 if !seen.insert(key) {
2498 continue;
2499 }
2500 match read(&path) {
2501 Some(included) => {
2502 let parent = path.parent().unwrap_or(&dir).to_path_buf();
2503 pending.push((included, target.to_string(), parent, depth + 1));
2504 }
2505 None => sources.push(IndexSource::unread_include(&at)),
2506 }
2507 }
2508 OptionLine::Editable => sources.push(IndexSource::direct_reference(&at)),
2509 OptionLine::Other if line.contains("://") => {
2512 sources.push(IndexSource::new(&at, "an unparsed option"));
2513 }
2514 OptionLine::TrustedHost | OptionLine::Other => {}
2515 }
2516 }
2517 }
2518 sources
2519}
2520
2521fn pip_true(value: &str) -> bool {
2523 matches!(
2524 value.trim().to_ascii_lowercase().as_str(),
2525 "1" | "true" | "yes" | "on"
2526 )
2527}
2528
2529fn env_sources(get: &dyn Fn(&str) -> Option<String>) -> Vec<IndexSource> {
2531 let mut sources = Vec::new();
2532 for var in ["PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL"] {
2533 for url in get(var).unwrap_or_default().split_whitespace() {
2534 sources.extend(IndexSource::index(var, url));
2535 }
2536 }
2537 for location in get("PIP_FIND_LINKS").unwrap_or_default().split_whitespace() {
2538 sources.push(IndexSource::find_links("PIP_FIND_LINKS", location));
2539 }
2540 if get("PIP_NO_INDEX").is_some_and(|value| pip_true(&value)) {
2541 sources.push(IndexSource::no_index("PIP_NO_INDEX"));
2542 }
2543 sources
2544}
2545
2546fn config_sources(text: &str, label: &str) -> Vec<IndexSource> {
2549 let mut sources = Vec::new();
2550 let mut key: Option<String> = None;
2551 let take = |key: &str, value: &str| -> Vec<IndexSource> {
2552 match key {
2553 "index-url" | "extra-index-url" => value
2554 .split_whitespace()
2555 .filter_map(|url| IndexSource::index(label, url))
2556 .collect(),
2557 "find-links" => value
2558 .split_whitespace()
2559 .map(|location| IndexSource::find_links(label, location))
2560 .collect(),
2561 "no-index" if pip_true(value) => vec![IndexSource::no_index(label)],
2562 _ => Vec::new(),
2563 }
2564 };
2565 for line in text.lines() {
2566 let trimmed = line.trim();
2567 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
2568 continue;
2569 }
2570 if line.starts_with([' ', '\t']) {
2571 if let Some(key) = key.as_deref() {
2573 sources.extend(take(key, trimmed));
2574 }
2575 continue;
2576 }
2577 if trimmed.starts_with('[') {
2578 key = None;
2579 continue;
2580 }
2581 let Some(cut) = trimmed.find(['=', ':']) else {
2582 key = None;
2583 continue;
2584 };
2585 let name = trimmed[..cut].trim().to_ascii_lowercase().replace('_', "-");
2586 sources.extend(take(&name, trimmed[cut + 1..].trim()));
2587 key = Some(name);
2588 }
2589 sources
2590}
2591
2592fn config_paths(get: &dyn Fn(&str) -> Option<String>) -> Vec<(std::path::PathBuf, String)> {
2598 let named = get("PIP_CONFIG_FILE").filter(|path| !path.is_empty());
2599 if named.as_deref() == Some("/dev/null") {
2600 return Vec::new();
2601 }
2602 let home = get("HOME").filter(|home| !home.is_empty());
2603 let mut paths: Vec<std::path::PathBuf> =
2604 ["/etc/pip.conf", "/Library/Application Support/pip/pip.conf"]
2605 .iter()
2606 .map(std::path::PathBuf::from)
2607 .collect();
2608 let xdg_dirs = get("XDG_CONFIG_DIRS").filter(|dirs| !dirs.is_empty());
2609 for dir in xdg_dirs.as_deref().unwrap_or("/etc/xdg").split(':') {
2610 if !dir.is_empty() {
2611 paths.push(std::path::Path::new(dir).join("pip/pip.conf"));
2612 }
2613 }
2614 if let Some(home) = home.as_deref() {
2615 let home = std::path::Path::new(home);
2616 paths.push(home.join(".pip/pip.conf"));
2617 paths.push(home.join("Library/Application Support/pip/pip.conf"));
2618 if get("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).is_none() {
2619 paths.push(home.join(".config/pip/pip.conf"));
2620 }
2621 }
2622 if let Some(xdg) = get("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
2623 paths.push(std::path::Path::new(&xdg).join("pip/pip.conf"));
2624 }
2625 if let Some(venv) = get("VIRTUAL_ENV").filter(|v| !v.is_empty()) {
2626 paths.push(std::path::Path::new(&venv).join("pip.conf"));
2627 }
2628 if let Some(named) = named {
2629 paths.push(std::path::PathBuf::from(named));
2630 }
2631 paths
2632 .into_iter()
2633 .map(|path| {
2634 let shown = path.to_string_lossy();
2635 let label = match home.as_deref().and_then(|h| shown.strip_prefix(h)) {
2636 Some(rest) if rest.starts_with('/') => format!("~{rest}"),
2637 _ => shown.into_owned(),
2638 };
2639 (path, label)
2640 })
2641 .collect()
2642}
2643
2644#[derive(Debug, PartialEq, Eq)]
2646enum ConfigFile {
2647 Absent,
2648 Text(String),
2649 Unread,
2650}
2651
2652fn read_config(path: &std::path::Path) -> ConfigFile {
2653 let parent_is_dir = path.parent().is_some_and(std::path::Path::is_dir);
2655 match std::fs::metadata(path) {
2656 Err(why) if why.kind() == std::io::ErrorKind::NotFound => ConfigFile::Absent,
2657 Err(_) if !parent_is_dir => ConfigFile::Absent,
2659 Ok(meta) if meta.is_file() => match std::fs::read_to_string(path) {
2660 Ok(text) => ConfigFile::Text(text),
2661 Err(_) => ConfigFile::Unread,
2662 },
2663 _ => ConfigFile::Unread,
2665 }
2666}
2667
2668fn host_sources(
2672 get: &dyn Fn(&str) -> Option<String>,
2673 read: &dyn Fn(&std::path::Path) -> ConfigFile,
2674) -> Vec<IndexSource> {
2675 let mut sources = env_sources(get);
2676 for (path, label) in config_paths(get) {
2677 match read(&path) {
2678 ConfigFile::Absent => {}
2679 ConfigFile::Text(text) => sources.extend(config_sources(&text, &label)),
2680 ConfigFile::Unread => sources.push(IndexSource::unread_config(&label)),
2681 }
2682 }
2683 sources
2684}
2685
2686#[derive(Debug, Default, PartialEq, Eq)]
2688struct Provenance {
2689 sent: std::collections::BTreeSet<(String, String)>,
2691 private: std::collections::BTreeSet<String>,
2693 unproven: std::collections::BTreeSet<String>,
2695}
2696
2697fn provenance(pins: &HashedPins, sources: &[IndexSource]) -> Provenance {
2701 let mut held = Provenance::default();
2702 for (name, from) in &pins.from {
2703 if from
2704 .iter()
2705 .any(|url| url.as_deref().is_some_and(|url| !is_pypi_url(url)))
2706 {
2707 held.private.insert(name.clone());
2708 } else if !sources.is_empty() && from.iter().any(Option::is_none) {
2709 held.unproven.insert(name.clone());
2710 }
2711 }
2712 held.sent = pins
2713 .pairs
2714 .iter()
2715 .filter(|(name, _)| !held.private.contains(name) && !held.unproven.contains(name))
2716 .cloned()
2717 .collect();
2718 held
2719}
2720
2721fn sources_phrase(sources: &[IndexSource]) -> String {
2723 let Some(first) = sources.first() else {
2724 return String::new();
2725 };
2726 let more = match sources.len() - 1 {
2727 0 => String::new(),
2728 1 => " +1 more source".to_string(),
2729 n => format!(" +{n} more sources"),
2730 };
2731 format!("{} ({}){more}", first.what, first.label)
2732}
2733
2734fn names_phrase<'a>(names: impl IntoIterator<Item = &'a String>) -> String {
2736 let names: Vec<&String> = names.into_iter().collect();
2737 let shown: Vec<String> = names
2738 .iter()
2739 .take(NAMES_SHOWN)
2740 .map(|n| printable(n))
2741 .collect();
2742 let more = names.len().saturating_sub(NAMES_SHOWN);
2743 if more == 0 {
2744 format!("({})", shown.join(", "))
2745 } else {
2746 format!("({} +{more} more)", shown.join(", "))
2747 }
2748}
2749
2750const ANNOTATE_NEXT: &str = "Next: `uv pip compile --generate-hashes --emit-index-annotation` \
2752 (so each pin names its index)";
2753
2754fn pip_skipped_names(out: &str) -> Vec<String> {
2757 let mut lines = out.lines().map(str::trim);
2758 let mut names = Vec::new();
2759 while let Some(line) = lines.next() {
2760 if !(line.starts_with("Name") && line.contains("Skip Reason")) {
2761 continue;
2762 }
2763 let rows = lines
2764 .by_ref()
2765 .skip_while(|l| l.starts_with('-'))
2766 .take_while(|l| !l.is_empty());
2767 names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
2768 }
2769 names.sort();
2770 names.dedup();
2771 names
2772}
2773
2774fn plural(count: usize, noun: &str) -> String {
2775 if count == 1 {
2776 format!("{count} {noun}")
2777 } else {
2778 format!("{count} {noun}s")
2779 }
2780}
2781
2782fn skipped_line(prefix: &str, names: &[&str]) -> String {
2786 let head = format!(
2787 "audit-python: {prefix}{} skipped",
2788 plural(names.len(), "private/non-PyPI package")
2789 );
2790 let fewest = names.len().min(1);
2791 for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
2792 let list: Vec<&str> = names.iter().take(shown).copied().collect();
2793 let more = names.len() - shown;
2794 let detail = match (list.is_empty(), more) {
2795 (true, 0) => String::new(),
2796 (true, _) => format!(" (+{more} more)"),
2797 (false, 0) => format!(" ({})", list.join(", ")),
2798 (false, _) => format!(" ({} +{more} more)", list.join(", ")),
2799 };
2800 let line = format!("{head}{detail}");
2801 if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
2802 return line;
2803 }
2804 }
2805 head
2806}
2807
2808fn clip(text: &str, columns: usize) -> String {
2810 text.chars().take(columns).collect()
2811}
2812
2813fn scrub_private(
2818 text: &str,
2819 private: &std::path::Path,
2820 canonical: Option<&std::path::Path>,
2821) -> String {
2822 let plain = private.to_string_lossy();
2823 let mut scrubbed = text.to_string();
2824 if let Some(canonical) = canonical.filter(|c| *c != private) {
2825 scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
2826 }
2827 scrubbed.replace(plain.as_ref(), "<tmp>")
2828}
2829
2830struct LockDirAudit {
2832 vulnerabilities: Vec<String>,
2833 advisories: Vec<String>,
2834 full: String,
2835 complete: bool,
2838 waivable: bool,
2839}
2840
2841impl LockDirAudit {
2842 fn unchecked() -> LockDirAudit {
2843 LockDirAudit {
2844 vulnerabilities: Vec::new(),
2845 advisories: Vec::new(),
2846 full: String::new(),
2847 complete: false,
2848 waivable: false,
2849 }
2850 }
2851}
2852
2853fn audit_uv_lock(
2859 settings: &crate::config::Settings,
2860 mut production: Production,
2861 dir: &str,
2862 budget: &Budget,
2863) -> LockDirAudit {
2864 let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
2865 let lock_path = if dir.is_empty() {
2866 "uv.lock".to_string()
2867 } else {
2868 format!("{dir}/uv.lock")
2869 };
2870 let prefix = if dir.is_empty() {
2871 String::new()
2872 } else {
2873 format!("{lock_path}: ")
2874 };
2875 let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
2876 let private = match PrivateDir::create() {
2877 Ok(private) => private,
2878 Err(why) => {
2879 say(&format!(
2880 "no private directory ({}) — did NOT run\n {TMPDIR_NEXT}",
2881 why.kind()
2882 ));
2883 return LockDirAudit::unchecked();
2884 }
2885 };
2886 let canonical = std::fs::canonicalize(private.path()).ok();
2888 let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
2889 let export = private.path().join("export.txt");
2890 if budget.spent() {
2891 say(&format!(
2892 "out of time before the export — the audit did NOT run\n {TIMEOUT_NEXT}"
2893 ));
2894 return LockDirAudit::unchecked();
2895 }
2896 let argv = vec![
2897 common::program("uv"),
2898 "export".into(),
2899 "--frozen".into(),
2900 "--all-packages".into(),
2901 "--all-groups".into(),
2902 "--all-extras".into(),
2903 "--no-hashes".into(),
2904 "--no-emit-workspace".into(),
2905 "--format".into(),
2906 "requirements-txt".into(),
2907 "-o".into(),
2908 export.to_string_lossy().into_owned(),
2909 ];
2910 let exported = audited_in(settings, &argv, &dir_path);
2911 if !matches!(exported, Some((true, _))) {
2912 let why = exported
2913 .and_then(|(_, out)| failure_line(&scrub(&out)))
2914 .unwrap_or_else(|| "uv did not answer".to_string());
2915 let place = if dir.is_empty() {
2916 "at the repo root".to_string()
2917 } else {
2918 format!("in {dir}")
2919 };
2920 say(&format!(
2921 "uv export failed — the audit did NOT run\n {}\n Next: `uv export --frozen` {place}",
2922 clip(&why, WARNING_COLUMNS - 2)
2923 ));
2924 return LockDirAudit::unchecked();
2925 }
2926 let raw = std::fs::read_to_string(&export);
2927 let _ = std::fs::remove_file(&export); let raw = match raw {
2930 Ok(raw) => raw,
2931 Err(why) => {
2932 say(&format!(
2933 "could not read export.txt ({}) — the audit did NOT run\n {TMPDIR_NEXT}",
2934 why.kind()
2935 ));
2936 return LockDirAudit::unchecked();
2937 }
2938 };
2939 let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
2940 Ok(lock) => lock,
2941 Err(why) => {
2942 say(&format!(
2943 "could not read uv.lock ({}) — the audit did NOT run\n \
2944 Next: check that {lock_path} is readable, then push again",
2945 why.kind()
2946 ));
2947 return LockDirAudit::unchecked();
2948 }
2949 };
2950 let sources = scan_uv_lock(&lock);
2951 let pins = filter_export(&raw, &sources.pypi);
2952 if !pins.skipped.is_empty() {
2953 let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
2954 common::warn(&skipped_line(&prefix, &names));
2955 }
2956 let unclassified = pins.unclassified.len() + sources.nameless;
2957 if unclassified > 0 {
2958 let source = if prefix.is_empty() {
2959 " from uv.lock"
2960 } else {
2961 ""
2962 };
2963 say(&format!(
2964 "{} could not be classified{source}; not audited\n \
2965 Next: check that each [[package]] in {lock_path} has a name and source",
2966 plural(unclassified, "package")
2967 ));
2968 }
2969 if pins.batches.is_empty() {
2970 say(&format!(
2971 "no PyPI package to audit — the audit did NOT run\n \
2972 Next: none if every package is private; else check {lock_path} sources"
2973 ));
2974 return LockDirAudit::unchecked();
2975 }
2976 let mut audit = LockDirAudit {
2977 vulnerabilities: Vec::new(),
2978 advisories: Vec::new(),
2979 full: String::new(),
2980 complete: true,
2981 waivable: true,
2982 };
2983 let mut audited = 0;
2984 for (index, batch) in pins.batches.iter().enumerate() {
2985 let file = private.path().join(format!("batch-{index}.txt"));
2986 let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
2987 if budget.spent() {
2988 say(&format!(
2989 "out of time; unaudited versions remain — NOT fully checked\n {TIMEOUT_NEXT}"
2990 ));
2991 audit.complete = false;
2992 break;
2993 }
2994 if let Err(why) = std::fs::write(&file, body) {
2995 say(&format!(
2996 "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n {TMPDIR_NEXT}",
2997 why.kind()
2998 ));
2999 audit.complete = false;
3000 break;
3001 }
3002 let argv = vec![
3003 common::program("pip-audit"),
3004 "-r".into(),
3005 file.to_string_lossy().into_owned(),
3006 "--no-deps".into(),
3007 "--disable-pip".into(),
3008 ];
3009 let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
3010 audit.complete = false;
3011 break;
3012 };
3013 let out = scrub(&out);
3014 let report = read_pip_audit(exit_ok, &out);
3015 let names = if has_rows_to_split(&report, &out) {
3016 production.names(settings, budget, &say)
3017 } else {
3018 None
3019 };
3020 let (report, waivable) = shipped_only(report, &out, names);
3021 audit.waivable &= waivable;
3022 match report {
3023 Report::Vulnerabilities(found) => {
3024 audit.vulnerabilities.extend(found);
3025 audit.full.push_str(&out);
3026 audited += batch.len();
3027 }
3028 Report::Advisories(found) => {
3029 audit.advisories.extend(found);
3030 audited += batch.len();
3031 }
3032 Report::Clean => audited += batch.len(),
3033 Report::CouldNotCheck => {
3034 audit.complete = false;
3035 let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
3036 say(&format!(
3037 "pip-audit could not answer — NOT fully checked\n {}\n {}",
3038 clip(&why, WARNING_COLUMNS - 2),
3039 pip_audit_next(&why)
3040 ));
3041 }
3042 }
3043 }
3044 if !audit.complete {
3045 audit.waivable = false;
3046 }
3047 if audited > 0 {
3048 common::ok(
3049 settings,
3050 &format!(
3051 "audit-python: audited {lock_path} ({}, {} skipped)",
3052 plural(audited, "package version"),
3053 pins.skipped.len()
3054 ),
3055 );
3056 }
3057 audit
3058}
3059
3060fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
3064 let (settings, refs) = (ctx.settings, ctx.push.get());
3065 let release = releasing(refs);
3066 let budget = Budget::new(settings);
3067 let root = std::path::PathBuf::from(common::repo_root());
3068 let dirs = lockfile_dirs("uv.lock");
3069 let only_root = dirs.len() == 1 && dirs[0].is_empty();
3070 let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
3071 let mut full = String::new();
3072 let (mut complete, mut waivable) = (true, true);
3073 for dir in &dirs {
3074 let production = if release {
3075 Production::Unasked(root.join(dir))
3076 } else {
3077 Production::Never
3078 };
3079 let audit = audit_uv_lock(settings, production, dir, &budget);
3080 let label = |ids: Vec<String>| -> Vec<String> {
3081 if dir.is_empty() {
3082 ids
3083 } else {
3084 ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
3085 }
3086 };
3087 vulnerabilities.extend(label(audit.vulnerabilities));
3088 advisories.extend(label(audit.advisories));
3089 if !audit.full.is_empty() {
3090 if only_root {
3091 full.push_str(&audit.full);
3092 } else {
3093 full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
3094 }
3095 }
3096 complete &= audit.complete;
3097 waivable &= audit.waivable;
3098 }
3099 let report = if !vulnerabilities.is_empty() {
3100 Report::Vulnerabilities(vulnerabilities)
3101 } else if !complete {
3102 return Ran::Unavailable;
3103 } else if !advisories.is_empty() {
3104 Report::Advisories(advisories)
3105 } else {
3106 Report::Clean
3107 };
3108 Ran::Concluded(Concluded {
3109 tool: "audit-python".to_string(),
3110 report,
3111 full,
3112 waivable: waivable && complete,
3113 complete,
3114 })
3115}
3116
3117fn source_is_this_commit(source: &std::path::Path) -> bool {
3121 let src = source.to_string_lossy();
3122 let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
3123 let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
3124 let unmodified = crate::git::stdout(&[
3125 "-C",
3126 &src,
3127 "status",
3128 "--porcelain",
3129 "--untracked-files=no",
3130 "--",
3131 "*pyproject.toml",
3132 "*uv.lock",
3133 "*requirements*.txt",
3134 ])
3135 .is_some_and(|out| out.trim().is_empty());
3136 here.is_some() && here == there && unmodified
3137}
3138
3139fn normalise(name: &str) -> String {
3141 name.to_ascii_lowercase()
3142 .split(['-', '_', '.'])
3143 .filter(|p| !p.is_empty())
3144 .collect::<Vec<_>>()
3145 .join("-")
3146}
3147
3148fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
3152 let mut rows: Vec<(String, String)> = out
3153 .lines()
3154 .filter_map(|l| {
3155 let cols: Vec<&str> = l.split_whitespace().collect();
3156 let id = cols.get(2)?;
3157 ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
3158 .iter()
3159 .any(|p| id.starts_with(p))
3160 .then(|| (normalise(cols[0]), (*id).to_string()))
3161 })
3162 .collect();
3163 rows.sort();
3164 rows.dedup();
3165 rows
3166}
3167
3168fn pip_rows_all_named(out: &str) -> bool {
3172 out.lines().all(|l| {
3173 let cols: Vec<&str> = l.split_whitespace().collect();
3174 let is_row = cols.len() >= 3
3175 && cols[1].starts_with(|c: char| c.is_ascii_digit())
3176 && cols[2].contains('-')
3177 && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
3178 !is_row || !advisory_ids(cols[2]).is_empty()
3179 })
3180}
3181
3182fn uv_production_names(
3186 settings: &crate::config::Settings,
3187 dir: &std::path::Path,
3188) -> Option<std::collections::HashSet<String>> {
3189 if !has_lockfile("uv.lock") || common::which("uv").is_none() {
3190 return None;
3191 }
3192 let argv = vec![
3193 common::program("uv"),
3194 "export".into(),
3195 "--frozen".into(),
3196 "--all-packages".into(),
3199 "--no-dev".into(),
3200 "--no-default-groups".into(),
3201 "--all-extras".into(),
3203 "--no-hashes".into(),
3204 "--no-emit-workspace".into(),
3205 "--format".into(),
3206 "requirements-txt".into(),
3207 ];
3208 let (ok, out) = audited_in(settings, &argv, dir)?;
3209 if !ok {
3210 return None;
3211 }
3212 Some(
3213 out.lines()
3214 .map(str::trim)
3215 .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
3216 .filter_map(|l| {
3217 l.split(|c: char| "=<>!~;[ ".contains(c))
3218 .next()
3219 .map(normalise)
3220 })
3221 .collect(),
3222 )
3223}
3224
3225pub const AUDIT_REF: &str = crate::names::AUDIT_REF;
3227const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
3228const AUDIT_MAX_AGE: &str = "greengate.auditMaxAge";
3230const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;
3233const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");
3237
3238pub fn is_audit(check: &str) -> bool {
3240 check.starts_with("pre-push-audit-")
3241}
3242
3243fn inputs_of(check: &str) -> &'static [&'static str] {
3248 match check {
3249 "pre-push-audit-rust" => &["Cargo.lock"],
3250 "pre-push-audit-js" => &[
3251 "package-lock.json",
3252 "pnpm-lock.yaml",
3253 "pnpm-workspace.yaml",
3254 "package.json",
3256 ],
3257 "pre-push-audit-go" => &["go.sum", "go.mod"],
3258 "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
3259 _ => &[],
3260 }
3261}
3262
3263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3265enum AuditMode {
3266 Branch,
3268 Release,
3270}
3271
3272impl AuditMode {
3273 fn of(refs: &[PushRef]) -> AuditMode {
3274 if releasing(refs) {
3275 AuditMode::Release
3276 } else {
3277 AuditMode::Branch
3278 }
3279 }
3280}
3281
3282#[derive(Debug, Clone, PartialEq, Eq)]
3286struct Concluded {
3287 tool: String,
3288 report: Report,
3289 full: String,
3290 waivable: bool,
3291 complete: bool,
3295}
3296
3297enum Ran {
3300 Concluded(Concluded),
3301 Inert,
3303 Unavailable,
3305}
3306
3307#[derive(Debug, Clone)]
3310pub struct Pending {
3311 pub tip: String,
3312 material: String,
3313 body: String,
3314}
3315
3316#[derive(Default)]
3321pub struct Ledger {
3322 pending: std::sync::Mutex<Vec<Pending>>,
3323 peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
3324 fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
3325}
3326
3327impl Ledger {
3328 pub fn take_pending(&self) -> Vec<Pending> {
3330 std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
3331 }
3332
3333 fn peel(&self, oid: &str) -> Option<String> {
3335 if let Some(known) = self
3336 .peeled
3337 .lock()
3338 .unwrap_or_else(|e| e.into_inner())
3339 .get(oid)
3340 {
3341 return known.clone();
3342 }
3343 let commit =
3344 crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
3345 self.peeled
3346 .lock()
3347 .unwrap_or_else(|e| e.into_inner())
3348 .insert(oid.to_string(), commit.clone());
3349 commit
3350 }
3351
3352 fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
3354 let mut commits: Vec<String> = refs
3355 .iter()
3356 .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
3357 .filter_map(|r| self.peel(&r.local_oid))
3358 .collect();
3359 commits.sort();
3360 commits.dedup();
3361 commits
3362 }
3363}
3364
3365pub fn write_pending(pending: &Pending) -> Result<(), String> {
3368 let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
3371 .map(|k| k.trim().to_string())
3372 .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
3373 let written = crate::git::succeeds(&[
3374 "notes",
3375 "--ref",
3376 AUDIT_REF,
3377 "add",
3378 "-f",
3379 "-m",
3380 &pending.body,
3381 &key,
3382 ]);
3383 if written {
3384 Ok(())
3385 } else {
3386 Err(format!("git refused to write the audit record {key}"))
3387 }
3388}
3389
3390fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
3392 let split = if check == "pre-push-audit-js" {
3396 "split\n"
3397 } else {
3398 ""
3399 };
3400 match mode {
3401 AuditMode::Release => {
3402 let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
3403 Some(format!("{AUDIT_FORMAT}\n{check}\n{split}release\n{tree}\n"))
3404 }
3405 AuditMode::Branch => {
3406 let names = inputs_of(check);
3407 let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
3408 let mut lines: Vec<String> = listing
3409 .lines()
3410 .filter_map(|entry| {
3411 let (meta, path) = entry.split_once('\t')?;
3412 let blob = meta.split_whitespace().nth(2)?;
3413 let base = path.rsplit('/').next().unwrap_or(path);
3414 names.contains(&base).then(|| format!("{path} {blob}"))
3415 })
3416 .collect();
3417 lines.sort();
3418 Some(format!(
3419 "{AUDIT_FORMAT}\n{check}\n{split}branch\n{}\n",
3420 lines.join("\n")
3421 ))
3422 }
3423 }
3424}
3425
3426fn now_secs() -> i64 {
3427 std::time::SystemTime::now()
3428 .duration_since(std::time::UNIX_EPOCH)
3429 .map(|d| d.as_secs() as i64)
3430 .unwrap_or(0)
3431}
3432
3433fn class_of(report: &Report) -> &'static str {
3434 match report {
3435 Report::Clean => "clean",
3436 Report::Advisories(_) => "advisories",
3437 Report::Vulnerabilities(_) => "vulnerabilities",
3438 Report::CouldNotCheck => "unchecked",
3439 }
3440}
3441
3442fn render(concluded: &Concluded, at: i64) -> String {
3443 let items: &[String] = match &concluded.report {
3444 Report::Advisories(v) | Report::Vulnerabilities(v) => v,
3445 Report::Clean | Report::CouldNotCheck => &[],
3446 };
3447 let mut body = format!(
3448 "{AUDIT_FORMAT} {at} {} {} {} {WRITER_VERSION}",
3449 class_of(&concluded.report),
3450 u8::from(concluded.waivable),
3451 concluded.tool
3452 );
3453 for item in items {
3454 body.push_str("\nitem ");
3455 body.push_str(item);
3456 }
3457 body.push_str("\n---\n");
3458 body.push_str(&concluded.full);
3459 body
3460}
3461
3462fn parse(body: &str) -> Option<(i64, Option<String>, Concluded)> {
3465 let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
3466 let mut fields = head.split_whitespace();
3467 if fields.next()? != AUDIT_FORMAT {
3468 return None;
3469 }
3470 let at: i64 = fields.next()?.parse().ok()?;
3471 let class = fields.next()?;
3472 let waivable = fields.next()? == "1";
3473 let tool = fields.next()?.to_string();
3474 let writer = fields.next().map(str::to_string);
3475 let (items_part, full) = match rest.split_once("---\n") {
3476 Some((i, full)) => (i, full.to_string()),
3477 None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
3478 };
3479 let items: Vec<String> = items_part
3480 .lines()
3481 .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
3482 .collect();
3483 let report = match class {
3484 "clean" => Report::Clean,
3485 "advisories" => Report::Advisories(items),
3486 "vulnerabilities" => Report::Vulnerabilities(items),
3487 "unchecked" => Report::CouldNotCheck,
3488 _ => return None,
3489 };
3490 Some((
3491 at,
3492 writer,
3493 Concluded {
3494 tool,
3495 report,
3496 full,
3497 waivable,
3498 complete: true,
3499 },
3500 ))
3501}
3502
3503fn fresh_record(
3505 settings: &crate::config::Settings,
3506 check: &str,
3507 mode: AuditMode,
3508 commit: &str,
3509) -> Option<Concluded> {
3510 let material = key_material(check, mode, commit)?;
3511 let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
3512 .trim()
3513 .to_string();
3514 let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
3515 let (at, writer, concluded) = parse(&body)?;
3516 let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
3517 if writer.as_deref() != Some(WRITER_VERSION) {
3518 return None;
3519 }
3520 UNCHECKED_MAX_AGE_SECS
3521 } else {
3522 crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
3523 };
3524 let age = now_secs() - at;
3525 (0..=max_age).contains(&age).then_some(concluded)
3526}
3527
3528fn fresh_for_refs(
3533 settings: &crate::config::Settings,
3534 ledger: &Ledger,
3535 check: &str,
3536 refs: &[PushRef],
3537) -> Option<Concluded> {
3538 if !crate::gate_stamp::push_stamps_enabled(settings) {
3539 return None;
3540 }
3541 let memo_key = format!(
3542 "{check} {}",
3543 refs.iter()
3544 .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
3545 .collect::<Vec<_>>()
3546 .join(" ")
3547 );
3548 if let Some(known) = ledger
3549 .fresh
3550 .lock()
3551 .unwrap_or_else(|e| e.into_inner())
3552 .get(&memo_key)
3553 {
3554 return known.clone();
3555 }
3556 let mode = AuditMode::of(refs);
3557 let mut found: Option<Concluded> = None;
3558 for commit in ledger.pushed_commits(refs) {
3559 let Some(record) = fresh_record(settings, check, mode, &commit) else {
3560 found = None;
3561 break;
3562 };
3563 if found.as_ref().is_some_and(|prev| *prev != record) {
3564 found = None;
3565 break;
3566 }
3567 found = Some(record);
3568 }
3569 ledger
3570 .fresh
3571 .lock()
3572 .unwrap_or_else(|e| e.into_inner())
3573 .insert(memo_key, found.clone());
3574 found
3575}
3576
3577pub fn owed(
3579 settings: &crate::config::Settings,
3580 ledger: &Ledger,
3581 check: &str,
3582 refs: &[PushRef],
3583) -> bool {
3584 !ledger.pushed_commits(refs).is_empty()
3585 && fresh_for_refs(settings, ledger, check, refs).is_none()
3586}
3587
3588fn recorded(
3592 check: &str,
3593 tool: &str,
3594 ctx: &crate::registry::Ctx,
3595 run: fn(&crate::registry::Ctx) -> Ran,
3596) -> Outcome {
3597 let (settings, refs) = (ctx.settings, ctx.push.get());
3598 let mode = AuditMode::of(refs);
3599 let releasing = mode == AuditMode::Release;
3600 if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
3601 common::ok(
3602 settings,
3603 &format!("{tool}: replaying the audit recorded for this push"),
3604 );
3605 return conclude_waivable(
3606 settings,
3607 &record.tool,
3608 record.report,
3609 releasing,
3610 &record.full,
3611 record.waivable,
3612 );
3613 }
3614 let (outcome, concluded) = match run(ctx) {
3615 Ran::Concluded(concluded) => (
3616 conclude_waivable(
3617 settings,
3618 &concluded.tool,
3619 concluded.report.clone(),
3620 releasing,
3621 &concluded.full,
3622 concluded.waivable,
3623 ),
3624 Some(concluded),
3625 ),
3626 Ran::Unavailable => (
3627 Outcome::Unavailable,
3628 Some(Concluded {
3629 tool: tool.to_string(),
3630 report: Report::CouldNotCheck,
3631 full: String::new(),
3632 waivable: false,
3633 complete: true,
3634 }),
3635 ),
3636 Ran::Inert => (Outcome::Inert, None),
3637 };
3638 let concluded = concluded.filter(|concluded| {
3640 concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
3641 });
3642 if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
3643 let body = render(&concluded, now_secs());
3644 let records: Vec<Pending> = ctx
3645 .audits
3646 .pushed_commits(refs)
3647 .into_iter()
3648 .filter_map(|commit| {
3649 key_material(check, mode, &commit).map(|material| Pending {
3650 tip: commit,
3651 material,
3652 body: body.clone(),
3653 })
3654 })
3655 .collect();
3656 ctx.audits
3657 .pending
3658 .lock()
3659 .unwrap_or_else(|e| e.into_inner())
3660 .extend(records);
3661 }
3662 outcome
3663}
3664
3665pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
3666 recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
3667}
3668
3669pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
3670 recorded("pre-push-audit-js", "audit-js", ctx, js_run)
3671}
3672
3673pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
3674 recorded("pre-push-audit-go", "audit-go", ctx, go_run)
3675}
3676
3677pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
3678 recorded("pre-push-audit-python", "audit-python", ctx, python_run)
3679}
3680
3681#[cfg(test)]
3682mod tests {
3683 use super::*;
3684
3685 #[test]
3691 fn a_uv_project_is_audited_through_its_venv() {
3692 let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
3693 let _ = std::fs::remove_dir_all(&root);
3694
3695 std::fs::create_dir_all(&root).unwrap();
3698 assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);
3699
3700 let sp = root
3707 .join(".venv")
3708 .join("lib")
3709 .join("python3.13")
3710 .join("site-packages");
3711 std::fs::create_dir_all(&sp).unwrap();
3712 assert_eq!(
3713 venv_site_packages(root.to_str().unwrap(), None),
3714 Some(sp.to_string_lossy().into_owned())
3715 );
3716
3717 let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
3719 let _ = std::fs::remove_dir_all(&win);
3720 let wsp = win.join(".venv").join("Lib").join("site-packages");
3721 std::fs::create_dir_all(&wsp).unwrap();
3722 assert_eq!(
3723 venv_site_packages(win.to_str().unwrap(), None),
3724 Some(wsp.to_string_lossy().into_owned())
3725 );
3726
3727 let _ = std::fs::remove_dir_all(&root);
3728 let _ = std::fs::remove_dir_all(&win);
3729 }
3730
3731 fn tag(name: &str) -> PushRef {
3732 PushRef {
3733 local_ref: name.to_string(),
3734 local_oid: "a".repeat(40),
3735 remote_ref: name.to_string(),
3736 remote_oid: "0".repeat(40),
3737 }
3738 }
3739
3740 #[test]
3743 fn pip_audit_rows_name_their_packages_normalised() {
3744 let out = "Name Version ID Fix Versions\n\
3745 ---------- ------- ------------------- ------------\n\
3746 Pytest_Cov 4.0.0 GHSA-aaaa-bbbb-cccc 4.1.0\n\
3747 requests 2.31.0 PYSEC-2023-74 2.31.1\n\
3748 requests 2.31.0 CVE-2024-35195 2.32.0\n\
3749 Found 3 known vulnerabilities in 2 packages\n";
3750 let names: Vec<String> = pip_vulnerable_rows(out)
3751 .into_iter()
3752 .map(|(n, _)| n)
3753 .collect();
3754 assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
3755 assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
3756 }
3757
3758 #[test]
3759 fn advisory_ids_are_found_wherever_they_sit() {
3760 let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
3761 ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
3762 assert_eq!(
3763 advisory_ids(text),
3764 vec![
3765 "CVE-2024-35195",
3766 "GHSA-h3mg-xc3c-68pw",
3767 "GO-2024-2687",
3768 "OSV-2024-12",
3769 "PYSEC-2023-74",
3770 "RUSTSEC-2025-0001"
3771 ]
3772 );
3773 }
3774
3775 #[test]
3776 fn a_waiver_is_reasoned_dated_and_bounded() {
3777 let today = days_from_date("2026-10-05").unwrap();
3778 let w = Waivers::parse(
3779 "# id expires reason\n\
3780 GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
3781 GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
3782 GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
3783 GHSA-jjjj-kkkk-llll 2026-11-01\n\
3784 GHSA-mmmm-nnnn-oooo soon no date\n",
3785 today,
3786 );
3787 assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
3788 assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
3789 assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
3790 assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
3791 assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
3792 assert_eq!(w.problems().len(), 4);
3793 assert_eq!(days_from_date("1970-01-01"), Some(0));
3794 assert_eq!(days_from_date("2026-02-30"), None);
3795 assert!(days_from_date("2028-02-29").is_some());
3796 assert_eq!(days_from_date("2026-13-01"), None);
3797 }
3798
3799 #[test]
3800 fn two_locked_versions_are_two_answers() {
3801 let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
3802 Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
3803 let ids = vec![
3804 "RUSTSEC-2025-0010".to_string(),
3805 "RUSTSEC-2025-0011".to_string(),
3806 ];
3807 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3808 "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
3809 "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
3810 _ => None,
3811 });
3812 assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
3813 assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
3814 }
3815
3816 #[test]
3817 fn a_pip_row_without_a_nameable_id_is_unwaivable() {
3818 let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
3819 let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
3820 assert!(pip_rows_all_named(named));
3821 assert!(!pip_rows_all_named(unnamed));
3822 }
3823
3824 #[test]
3825 fn a_crate_ships_unless_its_tree_says_otherwise() {
3826 let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
3827 Crate: app\nID: RUSTSEC-2025-0002\n\
3828 Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
3829 let ids = vec![
3830 "RUSTSEC-2025-0001".to_string(),
3831 "RUSTSEC-2025-0002".to_string(),
3832 "RUSTSEC-2025-0003".to_string(),
3833 "RUSTSEC-2025-0004".to_string(),
3834 ];
3835 let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
3836 "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
3838 "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
3839 "odd" => Some("odd v1.0.0\n".into()),
3841 _ => None,
3842 });
3843 assert_eq!(
3845 shipped,
3846 vec![
3847 "RUSTSEC-2025-0002",
3848 "RUSTSEC-2025-0003",
3849 "RUSTSEC-2025-0004"
3850 ]
3851 );
3852 assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
3853 }
3854
3855 #[test]
3856 fn a_release_is_a_v_number_tag() {
3857 assert!(releasing(&[tag("refs/tags/v1.6.6")]));
3858 assert!(releasing(&[tag("refs/tags/v2")]));
3859 assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
3860 assert!(!releasing(&[tag("refs/tags/release")]));
3861 assert!(!releasing(&[tag("refs/heads/v1-styles")]));
3862 assert!(!releasing(&[tag("refs/heads/main")]));
3863 assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
3865 }
3866
3867 #[test]
3870 fn cargo_audit_ids_decide_not_the_exit_code() {
3871 assert_eq!(
3872 read_cargo_audit(true, "ok, 312 crates checked"),
3873 Report::Clean
3874 );
3875 assert_eq!(
3876 read_cargo_audit(false, "error: couldn't fetch advisory database"),
3877 Report::CouldNotCheck
3878 );
3879 let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
3880 assert_eq!(
3881 read_cargo_audit(true, warn),
3882 Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
3883 );
3884 let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
3885 assert_eq!(
3886 read_cargo_audit(false, vuln),
3887 Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
3888 );
3889 assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
3891 }
3892
3893 fn real_report() -> String {
3896 [
3897 "Crate: paste",
3898 "Version: 1.0.15",
3899 "Warning: unmaintained",
3900 "ID: RUSTSEC-2024-0436",
3901 "URL: https://rustsec.org/advisories/RUSTSEC-2024-0436",
3902 "",
3903 "Crate: lru",
3904 "Version: 0.12.5",
3905 "Warning: unsound",
3906 "ID: RUSTSEC-2026-0253",
3907 "",
3908 "Crate: lru",
3909 "Version: 0.12.5",
3910 "ID: RUSTSEC-2026-0002",
3911 "",
3912 "warning: 3 allowed warnings found",
3913 ]
3914 .join("\n")
3915 }
3916
3917 #[test]
3918 fn an_advisory_is_paired_with_its_crate() {
3919 let pairs = ids_with_crates(&real_report());
3920 assert_eq!(
3921 pairs,
3922 vec![
3923 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3924 ("RUSTSEC-2026-0253".into(), Some("lru".into())),
3925 ("RUSTSEC-2026-0002".into(), Some("lru".into())),
3926 ]
3927 );
3928 }
3929
3930 #[test]
3933 fn a_loose_id_borrows_no_crate() {
3934 let out = "Crate: paste\nID: RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
3935 assert_eq!(
3936 ids_with_crates(out),
3937 vec![
3938 ("RUSTSEC-2024-0436".into(), Some("paste".into())),
3939 ("RUSTSEC-2025-0001".into(), None),
3940 ]
3941 );
3942 }
3943
3944 #[test]
3947 fn only_local_crates_are_named_as_reached() {
3948 let tree =
3949 "lru v0.12.5\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
3950 assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
3951 assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
3952 }
3953
3954 #[test]
3958 fn the_warning_names_the_crate_and_what_reaches_it() {
3959 let calls = std::cell::RefCell::new(Vec::new());
3960 let fake = |k: &str| {
3961 calls.borrow_mut().push(k.to_string());
3962 Some(format!(
3963 "{k} v1\n└── ratatui v0.29.0\n └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
3964 ))
3965 };
3966 let out = real_report();
3967 let got = attribute(read_cargo_audit(true, &out), &out, fake);
3968 assert_eq!(
3969 got,
3970 Report::Advisories(vec![
3971 "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
3972 "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
3973 "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
3974 ])
3975 );
3976 assert_eq!(
3977 calls.into_inner(),
3978 vec!["paste", "lru"],
3979 "one call per crate"
3980 );
3981 }
3982
3983 #[test]
3987 fn a_crate_outside_the_build_graph_says_so() {
3988 let out = "Crate: wezterm-input-types\nID: RUSTSEC-2025-0001";
3989 let got = attribute(read_cargo_audit(true, out), out, |_| {
3990 Some("warning: nothing to print.".into())
3991 });
3992 assert_eq!(
3993 got,
3994 Report::Advisories(vec![
3995 "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
3996 ])
3997 );
3998 }
3999
4000 #[test]
4003 fn attribution_never_changes_the_verdict() {
4004 let spawned = std::cell::Cell::new(false);
4005 let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
4006 spawned.set(true);
4007 None
4008 });
4009 assert_eq!(clean, Report::Clean);
4010 assert!(!spawned.get(), "a clean report must spawn nothing");
4011
4012 let out = "Crate: paste\nID: RUSTSEC-2024-0436";
4013 let blind = attribute(read_cargo_audit(false, out), out, |_| None);
4014 assert_eq!(
4015 blind,
4016 Report::Vulnerabilities(vec![
4017 "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
4018 ])
4019 );
4020 }
4021
4022 #[test]
4023 fn npm_audit_summary_decides() {
4024 assert_eq!(
4025 read_npm_audit(true, "found 0 vulnerabilities\n"),
4026 Report::Clean
4027 );
4028 assert_eq!(
4029 read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
4030 Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
4031 );
4032 assert_eq!(
4035 read_npm_audit(
4036 false,
4037 "# npm audit report\n\nvite 6.0.0 - 6.1.5\nSeverity: high\n\n\
4038 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n npm audit fix\n"
4039 ),
4040 Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
4041 );
4042 assert_eq!(
4043 read_npm_audit(false, "1 vulnerability (1 high)\n"),
4044 Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
4045 );
4046 assert_eq!(
4047 read_npm_audit(true, "up to date, audited 100 packages\n"),
4048 Report::Clean
4049 );
4050 assert_eq!(
4051 read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
4052 Report::CouldNotCheck
4053 );
4054 }
4055
4056 #[test]
4057 fn pnpm_audit_summary_decides() {
4058 assert_eq!(
4059 read_pnpm_audit(true, "No known vulnerabilities found\n"),
4060 Report::Clean
4061 );
4062 assert_eq!(
4065 read_pnpm_audit(
4066 false,
4067 "│ More info │ https://github.com/advisories/GHSA-395f │\n\
4068 └───────────┴──────────────────────────────────────────┘\n\
4069 107 vulnerabilities found\n\
4070 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
4071 ),
4072 Report::Vulnerabilities(vec![
4073 "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
4074 ])
4075 );
4076 assert_eq!(
4077 read_pnpm_audit(false, "1 vulnerabilities found\n"),
4078 Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
4079 );
4080 assert_eq!(
4081 read_pnpm_audit(
4082 false,
4083 " ERR_PNPM_AUDIT_BAD_RESPONSE The audit endpoint responded with 503\n"
4084 ),
4085 Report::CouldNotCheck
4086 );
4087 }
4088
4089 #[test]
4092 fn govulncheck_ids_decide_not_the_exit_code() {
4093 assert_eq!(
4094 read_govulncheck(true, "No vulnerabilities found.\n"),
4095 Report::Clean
4096 );
4097 assert_eq!(
4098 read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
4099 Report::CouldNotCheck
4100 );
4101 assert_eq!(
4104 read_govulncheck(
4105 true,
4106 "=== Informational ===\nVulnerability #1: GO-2023-1840\n More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
4107 ),
4108 Report::Advisories(vec!["GO-2023-1840".into()])
4109 );
4110 assert_eq!(
4111 read_govulncheck(
4112 false,
4113 "Vulnerability #1: GO-2022-0969\n Your code calls it.\nGO-2022-0969 again\n"
4114 ),
4115 Report::Vulnerabilities(vec!["GO-2022-0969".into()])
4116 );
4117 assert_eq!(
4119 read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
4120 Report::Clean
4121 );
4122 }
4123
4124 #[test]
4125 fn pip_audit_sentence_decides() {
4126 assert_eq!(
4127 read_pip_audit(true, "No known vulnerabilities found\n"),
4128 Report::Clean
4129 );
4130 assert_eq!(
4131 read_pip_audit(
4132 false,
4133 "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
4134 ),
4135 Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
4136 );
4137 assert_eq!(
4138 read_pip_audit(false, "ERROR: could not resolve\n"),
4139 Report::CouldNotCheck
4140 );
4141 }
4142
4143 fn lock_block(name: Option<&str>, source: &str) -> String {
4144 let mut block = String::from("[[package]]\n");
4145 if let Some(name) = name {
4146 block.push_str(&format!("name = \"{name}\"\n"));
4147 }
4148 block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
4149 block
4150 }
4151
4152 #[test]
4153 fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
4154 let pypi = "{ registry = \"https://pypi.org/simple\" }";
4155 let lock = [
4156 lock_block(Some("Requests"), pypi),
4157 lock_block(
4158 Some("slashed"),
4159 "{ registry = \"https://pypi.org/simple/\" }",
4160 ),
4161 lock_block(
4162 Some("mirror"),
4163 "{ registry = \"https://mirror.example/simple\" }",
4164 ),
4165 lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
4166 lock_block(Some("pathdep"), "{ path = \"../x\" }"),
4167 lock_block(Some("edit"), "{ editable = \".\" }"),
4168 lock_block(Some("virt"), "{ virtual = \".\" }"),
4169 lock_block(Some("twice"), pypi),
4170 lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
4171 lock_block(None, pypi),
4172 "[package.metadata]\nname = \"ignored\"\n".to_string(),
4173 ]
4174 .concat();
4175 let sources = scan_uv_lock(&lock);
4176 let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
4177 assert_eq!(admitted, ["requests", "slashed"]);
4178 assert_eq!(sources.nameless, 1);
4179 }
4180
4181 #[test]
4182 fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
4183 let pypi: std::collections::BTreeSet<String> =
4184 ["numpy", "idna", "requests"].map(String::from).into();
4185 let raw = "\
4186# generated
4187numpy==1.26.4 ; python_full_version < '3.12'
4188numpy==2.1.0 ; python_full_version >= '3.12'
4189numpy==2.1.0 ; sys_platform == 'win32'
4190idna==3.7
4191platform-kernel==0.1.0
4192requests @ https://example.com/r.whl
4193";
4194 let pins = filter_export(raw, &pypi);
4195 assert_eq!(pins.versions, 3);
4196 assert_eq!(pins.batches.len(), 2);
4197 assert_eq!(
4198 pins.batches[0].get("numpy").map(String::as_str),
4199 Some("1.26.4")
4200 );
4201 assert_eq!(
4202 pins.batches[1].get("numpy").map(String::as_str),
4203 Some("2.1.0")
4204 );
4205 assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
4206 assert!(pins.skipped.contains("platform-kernel"));
4207 assert!(pins.unclassified.contains("requests"));
4208 }
4209
4210 const HASHED: &str = "\
4212# This file was autogenerated by uv via the following command:
4213# ./compile-requirements.sh
4214anyio==4.15.1 \\
4215 --hash=sha256:6152 \\
4216 --hash=sha256:9f28
4217 # via
4218 # starlette
4219idna==3.7 \\
4220 --hash=sha256:aaaa
4221torch==2.14.0+cpu \\
4222 --hash=sha256:bbbb
4223 # via -r requirements.in
4224";
4225
4226 #[test]
4227 fn only_a_fully_hashed_file_skips_the_resolve() {
4228 let pins = hashed_pins_in(HASHED).expect("hashed");
4229 assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
4230 assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
4232 let one_unhashed = format!("{HASHED}idna==3.7\n");
4233 assert_eq!(hashed_pins_in(&one_unhashed), None);
4234 let ranged = "requests>=2.0 \\\n --hash=sha256:cccc\n";
4235 assert_eq!(hashed_pins_in(ranged), None);
4236 let included = format!("-r requirements-upload.txt\n{HASHED}");
4237 assert_eq!(hashed_pins_in(&included), None);
4238 let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
4241 assert!(hashed_pins_in(&indexed).is_some());
4242 let editable = format!("-e .\n{HASHED}");
4243 assert_eq!(hashed_pins_in(&editable), None);
4244 let marked =
4246 format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n --hash=sha256:dddd\n");
4247 assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
4248 assert_eq!(
4249 hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
4250 None
4251 );
4252 assert_eq!(hashed_pins_in("# fixture\n"), None);
4253 assert_eq!(hashed_pins_in(""), None);
4254 }
4255
4256 #[test]
4257 fn marked_pins_are_stripped_and_their_versions_batched_apart() {
4258 let text = "\
4259six==1.16.0 \\
4260 --hash=sha256:aaaa
4261numpy==1.26.4 ; python_version == '3.9' \\
4262 --hash=sha256:bbbb
4263numpy==2.1.0 ; python_version == '3.12' \\
4264 --hash=sha256:cccc
4265";
4266 let pins = hashed_pins_in(text).expect("hashed");
4267 assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
4268 let batches = batches_of(pins.pairs);
4269 assert_eq!(batches.len(), 2);
4270 assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
4271 assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
4272 assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
4273 }
4274
4275 const SKIPPING: &str = "\
4278Found 2 known vulnerabilities in 1 package
4279Name Version ID Fix Versions
4280--------- ------- --------------- ------------
4281starlette 0.41.3 PYSEC-2026-1941 0.47.2
4282starlette 0.41.3 PYSEC-2026-1942 0.49.1
4283
4284Name Skip Reason
4285----- -------------------------------------------------------------------------
4286torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
4287";
4288
4289 #[test]
4290 fn the_skip_table_names_its_packages_and_is_no_finding() {
4291 assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
4292 assert_eq!(
4293 pip_vulnerable_rows(SKIPPING),
4294 vec![
4295 ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
4296 ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
4297 ]
4298 );
4299 assert!(pip_rows_all_named(SKIPPING));
4300 let clean = "No known vulnerabilities found\nName Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
4301 assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
4302 assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
4303 }
4304
4305 #[test]
4306 fn the_skipped_line_names_three_and_counts_the_rest() {
4307 let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
4308 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
4309 assert_eq!(
4310 skipped_line("", &refs),
4311 "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
4312 );
4313 assert_eq!(
4314 skipped_line("", &refs[..1]),
4315 "audit-python: 1 private/non-PyPI package skipped (a)"
4316 );
4317 let long = "services/laya-decisions/requirements.txt: ";
4318 assert_eq!(
4319 skipped_line(long, &["torch", "triton"]),
4320 format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
4321 );
4322 }
4323
4324 #[test]
4325 fn scrub_names_the_canonical_private_path_too() {
4326 let plain = std::path::Path::new("/var/folders/a/audit-1");
4327 let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
4328 assert_eq!(
4329 scrub_private(
4330 "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
4331 plain,
4332 canonical
4333 ),
4334 "x <tmp>/b and <tmp>/c"
4335 );
4336 }
4337
4338 #[test]
4339 fn production_names_are_never_asked_off_a_release_or_out_of_time() {
4340 let settings = crate::config::Settings::default();
4341 let spent = Budget {
4342 started: std::time::Instant::now(),
4343 limit: Some(std::time::Duration::ZERO),
4344 };
4345 let said = std::cell::RefCell::new(Vec::<String>::new());
4346 let say = |m: &str| said.borrow_mut().push(m.to_string());
4347 let dir = std::env::temp_dir();
4348
4349 let mut off = Production::Never;
4350 assert!(off.names(&settings, &spent, &say).is_none());
4351 assert!(matches!(off, Production::Never), "no release never asks");
4352 assert!(said.borrow().is_empty());
4353
4354 let mut late = Production::Unasked(dir.clone());
4355 assert!(late.names(&settings, &spent, &say).is_none());
4356 assert!(late.names(&settings, &spent, &say).is_none());
4357 assert!(
4358 matches!(late, Production::Asked(None)),
4359 "spent is remembered as unknown"
4360 );
4361
4362 let fresh = Budget {
4365 started: std::time::Instant::now(),
4366 limit: None,
4367 };
4368 let mut asked = Production::Unasked(dir);
4369 assert!(asked.names(&settings, &fresh, &say).is_none());
4370 assert!(matches!(asked, Production::Asked(None)));
4371 let said = said.borrow();
4372 assert_eq!(said.len(), 1, "warned once: {said:?}");
4373 assert!(said[0].contains("every finding counts"), "{said:?}");
4374 assert!(said[0].contains("greengate.timeout"), "{said:?}");
4375 }
4376
4377 #[test]
4378 fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
4379 for why in [
4380 "ConnectionError: Max retries exceeded",
4381 "error: request timed out",
4382 "SSL: CERTIFICATE_VERIFY_FAILED",
4383 "Temporary failure in name resolution",
4384 ] {
4385 assert!(pip_audit_next(why).contains("the network"), "{why}");
4386 }
4387 for why in [
4388 "(no output)",
4389 "ModuleNotFoundError: No module named 'pip_audit'",
4390 ] {
4391 assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
4392 }
4393 }
4394
4395 #[test]
4396 fn only_readable_vulnerability_rows_need_the_split() {
4397 let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
4398 assert!(has_rows_to_split(
4399 &Report::Vulnerabilities(vec!["certifi".into()]),
4400 rows
4401 ));
4402 assert!(!has_rows_to_split(
4403 &Report::Vulnerabilities(vec!["x".into()]),
4404 "Found 1\n"
4405 ));
4406 assert!(!has_rows_to_split(&Report::Clean, rows));
4407 assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
4408 }
4409
4410 #[test]
4411 fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
4412 let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
4413 let guard = PrivateDir::create_at(path.clone()).unwrap();
4414 #[cfg(unix)]
4415 {
4416 use std::os::unix::fs::PermissionsExt;
4417 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
4418 assert_eq!(mode & 0o777, 0o700);
4419 }
4420 assert!(PrivateDir::create_at(path.clone()).is_err());
4421 assert!(path.is_dir(), "the refused attempt must leave it alone");
4422 drop(guard);
4423 assert!(!path.exists());
4424 }
4425
4426 fn no_include(_: &std::path::Path) -> Option<String> {
4429 None
4430 }
4431
4432 fn whats(sources: &[IndexSource]) -> Vec<(String, String)> {
4433 sources
4434 .iter()
4435 .map(|s| (s.label.clone(), s.what.clone()))
4436 .collect()
4437 }
4438
4439 #[test]
4440 fn a_file_names_its_non_pypi_sources_by_label_and_host() {
4441 let text = "\
4442--extra-index-url https://u:tok@pkgs.example/simple
4443--index-url=https://pypi.org/simple/
4444-f ./wheels
4445--find-links https://wheels.example/list
4446--no-index
4447--trusted-host pkgs.example
4448six==1.16.0
4449";
4450 let sources = file_sources(
4451 text,
4452 "requirements.txt",
4453 std::path::Path::new("."),
4454 &no_include,
4455 );
4456 assert_eq!(
4457 whats(&sources),
4458 [
4459 ("requirements.txt line 1", "pkgs.example"),
4460 ("requirements.txt line 3", "a local path"),
4461 ("requirements.txt line 4", "wheels.example"),
4462 ("requirements.txt line 5", "--no-index"),
4463 ]
4464 .map(|(l, w)| (l.to_string(), w.to_string()))
4465 );
4466 assert!(!format!("{sources:?}").contains("tok"));
4467 }
4468
4469 #[test]
4470 fn a_host_never_carries_its_userinfo() {
4471 assert_eq!(host_of("https://u:p@ss@h.example/simple"), "h.example");
4472 assert_eq!(host_of("u:tok@h.example/x"), "h.example");
4473 assert_eq!(host_of("https://h.example:8443/simple/"), "h.example:8443");
4474 assert_eq!(host_of("https:///simple"), "an index with no host");
4475 assert!(!host_of("https://u:secret@h.example/simple/@x").contains("secret"));
4477 let escaped = IndexSource::new("a\u{1b}[31mb", "h\nx");
4478 assert_eq!(
4479 (escaped.label.as_str(), escaped.what.as_str()),
4480 ("a\\u{1b}[31mb", "h\\nx")
4481 );
4482 }
4483
4484 #[test]
4485 fn pypi_is_the_lock_routes_registry_with_or_without_its_slash() {
4486 assert!(is_pypi_url("https://pypi.org/simple"));
4487 assert!(is_pypi_url("https://pypi.org/simple/"));
4488 assert!(!is_pypi_url("https://download.pytorch.org/whl/cpu"));
4489 assert!(!is_pypi_url("https://u:tok@pypi.org/simple"));
4490 assert!(is_pypi_source(
4491 "{ registry = \"https://pypi.org/simple/\" }"
4492 ));
4493 }
4494
4495 #[test]
4496 fn includes_are_followed_and_an_unread_one_is_a_source() {
4497 let dir = std::env::temp_dir().join(common::unique_name("f142-includes"));
4498 std::fs::create_dir_all(dir.join("sub")).expect("mkdir");
4499 std::fs::write(dir.join("base.txt"), "-r sub/more.txt\n").expect("write");
4500 std::fs::write(
4501 dir.join("sub/more.txt"),
4502 "--extra-index-url https://private.example/simple\n-c ../base.txt\n",
4503 )
4504 .expect("write");
4505 let text = "-r base.txt\n-r missing.txt\n-r https://example.com/r.txt\nsix==1.16.0\n";
4506 let sources = file_sources(text, "requirements.txt", &dir, &read_include);
4507 assert_eq!(
4508 whats(&sources),
4509 [
4510 ("requirements.txt line 2", "an unread include"),
4512 ("requirements.txt line 3", "an unread include"),
4513 ("sub/more.txt line 1", "private.example"),
4514 ]
4515 .map(|(l, w)| (l.to_string(), w.to_string()))
4516 );
4517 #[cfg(unix)]
4519 {
4520 let fifo = dir.join("fifo.txt");
4521 let made = std::process::Command::new(common::program("mkfifo"))
4522 .arg(&fifo)
4523 .status()
4524 .is_ok_and(|s| s.success());
4525 assert!(made, "mkfifo failed: the FIFO case would go unchecked");
4526 assert_eq!(read_include(&fifo), None);
4527 let sources = file_sources("-r fifo.txt\n", "requirements.txt", &dir, &read_include);
4528 assert_eq!(sources.len(), 1);
4529 assert_eq!(read_config(&fifo), ConfigFile::Unread);
4530 }
4531 let _ = std::fs::remove_dir_all(&dir); }
4533
4534 #[test]
4535 fn a_direct_reference_is_a_source() {
4536 let text = "-e .\nlib @ git+https://git.example/lib.git\n./pkg.tar.gz\nsix==1.16.0\nnumpy>=1.0 ; python_version < '3.12'\n";
4537 let sources = file_sources(
4538 text,
4539 "requirements.txt",
4540 std::path::Path::new("."),
4541 &no_include,
4542 );
4543 assert_eq!(
4544 whats(&sources),
4545 [
4546 ("requirements.txt line 1", "a direct reference"),
4547 ("requirements.txt line 2", "a direct reference"),
4548 ("requirements.txt line 3", "a direct reference"),
4549 ]
4550 .map(|(l, w)| (l.to_string(), w.to_string()))
4551 );
4552 assert!(!format!("{sources:?}").contains("git.example"));
4553 }
4554
4555 #[cfg(unix)]
4558 #[test]
4559 fn the_environment_and_config_files_are_sources() {
4560 let env = |vars: &'static [(&'static str, &'static str)]| {
4561 move |var: &str| {
4562 vars.iter()
4563 .find(|(k, _)| *k == var)
4564 .map(|(_, v)| v.to_string())
4565 }
4566 };
4567 let get = env(&[
4568 (
4569 "PIP_EXTRA_INDEX_URL",
4570 "https://pypi.org/simple https://x.example/simple",
4571 ),
4572 ("PIP_NO_INDEX", "0"),
4573 ]);
4574 assert_eq!(
4575 whats(&env_sources(&get)),
4576 [("PIP_EXTRA_INDEX_URL".to_string(), "x.example".to_string())]
4577 );
4578 for on in ["1", "TRUE", "yes", "On"] {
4579 assert!(pip_true(on), "{on}");
4580 }
4581 for off in ["0", "false", "no", "off", ""] {
4582 assert!(!pip_true(off), "{off}");
4583 }
4584 let conf = "[global]\ntimeout = 5\n[install]\nextra_index_url =\n https://pypi.org/simple\n https://u:tok@conf.example/simple\nfind-links: /opt/wheels\n";
4585 assert_eq!(
4586 whats(&config_sources(conf, "~/.pip/pip.conf")),
4587 [
4588 ("~/.pip/pip.conf", "conf.example"),
4589 ("~/.pip/pip.conf", "a local path"),
4590 ]
4591 .map(|(l, w)| (l.to_string(), w.to_string()))
4592 );
4593 let devnull = env(&[("PIP_CONFIG_FILE", "/dev/null"), ("HOME", "/home/me")]);
4595 assert!(config_paths(&devnull).is_empty());
4596 let home = env(&[
4597 ("HOME", "/home/me"),
4598 ("XDG_CONFIG_DIRS", "/opt/xdg:/etc/xdg"),
4599 ]);
4600 let labels: Vec<String> = config_paths(&home).into_iter().map(|(_, l)| l).collect();
4601 assert!(
4602 labels.contains(&"~/.config/pip/pip.conf".to_string()),
4603 "{labels:?}"
4604 );
4605 assert!(
4606 labels.contains(&"~/.pip/pip.conf".to_string()),
4607 "{labels:?}"
4608 );
4609 assert!(
4610 labels.contains(&"/opt/xdg/pip/pip.conf".to_string()),
4611 "{labels:?}"
4612 );
4613 let read = |path: &std::path::Path| match path.to_str() {
4616 Some("/opt/xdg/pip/pip.conf") => {
4617 ConfigFile::Text("[global]\nindex-url = https://xdg.example/simple\n".into())
4618 }
4619 Some("/home/me/.pip/pip.conf") => ConfigFile::Unread,
4620 _ => ConfigFile::Absent,
4621 };
4622 assert_eq!(
4623 whats(&host_sources(&home, &read)),
4624 [
4625 ("/opt/xdg/pip/pip.conf", "xdg.example"),
4626 ("~/.pip/pip.conf", "an unread config file"),
4627 ]
4628 .map(|(l, w)| (l.to_string(), w.to_string()))
4629 );
4630 }
4631
4632 const ANNOTATED: &str = "\
4634# This file was autogenerated by uv via the following command:
4635# ./compile-requirements.sh
4636anyio==4.15.1 \\
4637 --hash=sha256:6152
4638 # via
4639 # starlette
4640 # from https://pypi.org/simple
4641six==1.16.0 \\
4642 --hash=sha256:aaaa
4643 # from https://pypi.org/simple/
4644torch==2.14.0+cpu \\
4645 --hash=sha256:bbbb
4646 # via -r requirements.in
4647 # from https://download.pytorch.org/whl/cpu
4648internal-lib==1.0 \\
4649 --hash=sha256:cccc
4650";
4651
4652 #[test]
4653 fn an_annotation_holds_its_name_and_an_unannotated_one_needs_no_source() {
4654 let pins = hashed_pins_in(ANNOTATED).expect("hashed");
4655 assert_eq!(
4656 pins.from.get("torch"),
4657 Some(&vec![Some(
4658 "https://download.pytorch.org/whl/cpu".to_string()
4659 )])
4660 );
4661 assert_eq!(pins.from.get("internal-lib"), Some(&vec![None]));
4662 let held = provenance(&pins, &[]);
4664 assert_eq!(held.private, set(&["torch"]));
4665 assert!(held.unproven.is_empty());
4666 let sent: Vec<&str> = held.sent.iter().map(|(n, _)| n.as_str()).collect();
4667 assert_eq!(sent, ["anyio", "internal-lib", "six"]);
4668 let held = provenance(&pins, &[IndexSource::no_index("PIP_NO_INDEX")]);
4670 assert_eq!(
4671 (held.private, held.unproven),
4672 (set(&["torch"]), set(&["internal-lib"]))
4673 );
4674 let twice = "numpy==1.26.4 ; python_version == '3.9' \\\n --hash=sha256:a\n # from https://pypi.org/simple\nnumpy==2.1.0 ; python_version == '3.12' \\\n --hash=sha256:b\n # from https://mirror.example/simple\n";
4676 let held = provenance(&hashed_pins_in(twice).expect("hashed"), &[]);
4677 assert_eq!(held.private, set(&["numpy"]));
4678 assert!(held.sent.is_empty());
4679 }
4680
4681 #[test]
4682 fn held_names_are_named_three_at_a_time() {
4683 let names: Vec<String> = ["a", "b", "c", "d\u{7}"].map(String::from).into();
4684 assert_eq!(names_phrase(&names), "(a, b, c +1 more)");
4685 assert_eq!(names_phrase(&names[3..]), "(d\\u{7})");
4686 assert_eq!(names_phrase(&set(&["b", "a"])), "(a, b)");
4687 let sources = [
4688 IndexSource::new("PIP_INDEX_URL", "x.example"),
4689 IndexSource::no_index("pip.conf"),
4690 ];
4691 assert_eq!(
4692 sources_phrase(&sources),
4693 "x.example (PIP_INDEX_URL) +1 more source"
4694 );
4695 assert_eq!(sources_phrase(&sources[1..]), "--no-index (pip.conf)");
4696 }
4697
4698 fn set(names: &[&str]) -> std::collections::BTreeSet<String> {
4699 names.iter().map(|n| n.to_string()).collect()
4700 }
4701
4702 const LAYA_EXCERPT: &str = "\
4705# This file was autogenerated by uv via the following command:
4706# ./compile-requirements.sh
4707annotated-doc==0.0.5 \\
4708 --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \\
4709 --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb
4710 # via
4711 # fastapi
4712 # typer
4713 # from https://pypi.org/simple
4714torch==2.14.0+cpu \\
4715 --hash=sha256:019463a7566401db8b1ed142026086db8fa680abda49ec41a60a8718d88e891d \\
4716 --hash=sha256:ff2e3a049e4c6d406d2f87acad9b2907d5052a3fa6d0e658b5f6e48d46bae11b
4717 # via
4718 # laya-decisions (pyproject.toml)
4719 # laya
4720 # from https://download.pytorch.org/whl/cpu
4721";
4722
4723 #[test]
4724 fn laya_decisions_holds_torch_and_sends_the_rest() {
4725 let pins = hashed_pins_in(LAYA_EXCERPT).expect("hashed");
4726 for sources in [vec![], vec![IndexSource::no_index("PIP_NO_INDEX")]] {
4727 let held = provenance(&pins, &sources);
4728 assert_eq!(held.private, set(&["torch"]));
4729 assert!(held.unproven.is_empty(), "every pin is annotated");
4730 let sent: Vec<&str> = held.sent.iter().map(|(n, _)| n.as_str()).collect();
4731 assert_eq!(sent, ["annotated-doc"]);
4732 }
4733 }
4734
4735 #[test]
4736 fn glued_and_abbreviated_options_are_read_as_pip_reads_them() {
4737 assert_eq!(
4738 option_line("-ihttps://u:tok@h.example/s"),
4739 OptionLine::Index("https://u:tok@h.example/s")
4740 );
4741 assert_eq!(option_line("-rbase.txt"), OptionLine::Include("base.txt"));
4742 assert_eq!(option_line("-fwheels"), OptionLine::FindLinks("wheels"));
4743 assert_eq!(option_line("-e."), OptionLine::Editable);
4744 assert_eq!(
4745 option_line("--extra-index https://x.example/simple"),
4746 OptionLine::Index("https://x.example/simple")
4747 );
4748 assert_eq!(
4749 option_line("--extra=https://x.example/simple"),
4750 OptionLine::Index("https://x.example/simple")
4751 );
4752 assert_eq!(option_line("--no"), OptionLine::Other);
4754 let text = "-ihttps://u:tok@h.example/s\n--mystery-index=https://m.example/simple\n--pre\n";
4755 let sources = file_sources(
4756 text,
4757 "requirements.txt",
4758 std::path::Path::new("."),
4759 &no_include,
4760 );
4761 assert_eq!(
4762 whats(&sources),
4763 [
4764 ("requirements.txt line 1", "h.example"),
4765 ("requirements.txt line 2", "an unparsed option"),
4766 ]
4767 .map(|(l, w)| (l.to_string(), w.to_string()))
4768 );
4769 }
4770
4771 #[test]
4772 fn an_include_chain_past_the_depth_is_unproven_and_its_references_count() {
4773 let files: std::collections::BTreeMap<String, String> = (0..=INCLUDE_DEPTH + 1)
4774 .map(|n| (format!("r{n}.txt"), format!("-r r{}.txt\n", n + 1)))
4775 .chain([(
4776 "refs.txt".to_string(),
4777 "lib @ git+https://git.example/lib\n".to_string(),
4778 )])
4779 .collect();
4780 let read = |path: &std::path::Path| {
4781 let name = path.file_name()?.to_str()?;
4782 files.get(name).cloned()
4783 };
4784 let sources = file_sources(
4785 "-r r0.txt\n-r refs.txt\n",
4786 "requirements.txt",
4787 std::path::Path::new("/x"),
4788 &read,
4789 );
4790 assert_eq!(
4791 whats(&sources),
4792 [
4793 ("refs.txt line 1", "a direct reference"),
4794 (
4795 &*format!("r{}.txt line 1", INCLUDE_DEPTH - 1),
4796 "an unread include"
4797 ),
4798 ]
4799 .map(|(l, w)| (l.to_string(), w.to_string()))
4800 );
4801 }
4802
4803 #[test]
4804 fn a_lone_continuation_keeps_the_next_lines_number() {
4805 assert_eq!(
4806 logical_lines("\\\nsix==1\nidna==3\n"),
4807 [(1, " six==1".to_string()), (3, "idna==3".to_string())]
4808 );
4809 }
4810}