diff --git a/docs/incidents.md b/docs/incidents.md index b644a5fae..7cf4c6cd3 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -74,6 +74,7 @@ pipeline still calls it there. | ar. `ar_description_stamped_to_the_head` | A dependency run's pull request was described from a head, and the head then moved on without it. A feedback round changed an override in the manifest and the description was rebuilt on that commit, where the lockfile still resolved the old version ("not moved on the head"); the lockfile was regenerated in the commits after it and the run completed. The description still said not moved, still counted the advisory as not fixed, still listed the package under open findings and "the lockfile is out of sync" under Open items, and CoderHelm's own review of the final head left that as a note. The checks step on an open pull request never rebuilt the computed sections, a regenerated lockfile was pushed with nothing after it, a review wrote its findings into the copy of the description it had read when it started (undoing a rebuild made meanwhile), and nits on CoderHelm's own pull request ended the loop. | The description names the head it was built for, and whenever that is not the pull request's head it is rebuilt: after every message in which CoderHelm moved the branch (seen in the one place every request leaves the GitHub client), in the checks and settle step, before a review of its own pull request, in the pull request watch, and at the end of the run, which never completes while the two differ. A review writes on the description as it is now and only for the head it reviewed. An item that says a lockfile is out of sync is checked on the head, never carried. A finding that the description is behind the code is settled by the rebuild, and every finding on CoderHelm's own pull request that is not pure style is its own to act on. | | as. `as_infra_closed_pr_keeps_record` | The same gap as `ap` in the other store. An infrastructure finding keeps its own record and nothing released it: after a person closed its fix pull request the record stayed `pr_open`, so the Infrastructure tab kept the closed pull request and never offered "Open fix PR" again; a cancelled or failed fix run left the record `fixing` for good; a reopened pull request was never noticed. | Infrastructure records go through the same reconciliation as dependency findings (one `reconcile` over `common::security_release::Claim`, not a copy): the same reads of GitHub and the run records, events, sweep bounds, person-closed record, holds and Retry. What is this store's own stays: a merge never closes a finding (only a read of the account does), a pull request the replacement guard made a draft is not closed and is left as it is, a finding on its runbook stays there until its code or target changes, a pull request is recorded only after the guard read it, and a fix round that ends without settling its pull request becomes the guard's second step (a draft), never a ready pull request. | | at. `at_round_scope` | A feature run opened its draft pull request and the proof check found three gaps. The fix round went to edit the existing file that builds a page's metadata, which the pull request had not touched yet: two edits were "rejected: outside the ticket's files" and a third failed. The guard held every fix round to the files the pull request already changed and gave way after two refusals of one path, so the round started for work the branch had not done was refused the file that work lives in. A planned task stayed not done, planned-work rounds went on for about an hour on a pull request whose checks passed, and one that hit GitHub's hourly limit was read as "it met an error": its work branch was deleted during the limit, an attempt was spent and the next try started five seconds later. | A round may edit what it was started for (`write_guard`): the pull request's files, the plan's task files (done or not) and listed dependents, and the files its gap, finding or failing check names; a check's output names the files that fail, never the ones it only warns about. Any other existing file is refused every time, however often it is tried, with one message that says how to justify the edit (`outside_plan`, one sentence); a justified edit is made and listed on the pull request under "Changed outside the plan's files". A round that ends with an edit refused and no task finished made no progress whatever it pushed: the next round is told what was refused, and a second one stops and names the file once. GitHub's limit inside a round on the pull request is a wait: the round is parked as it stands (its work branch, its attempt) and goes on after the reset. | +| au. `au_upgrade_decided_and_proven` | An outside reviewer checked a dependency security pull request of about fifty packages, four across a major version. The code was sound and the account of it was not: its count of advisories left was CoderHelm's own and disagreed with the package manager's production audit of the same head; one package of a framework was raised while its siblings from the same source repository stayed behind; no type check was recorded, because the repository's CI has none and CoderHelm's checks mirrored CI; it said "contract unchanged" although a validation library's major changed the 400 error bodies of an endpoint; and each override across a major lacked why it is safe. | A dependency update is decided and proven by the pipeline (`common::upgrade_quality`). Packages released together are found from the registry's source repository and the base branch's lockfile, move as one bump, and a lockfile that splits them fails the set like any check. The set a dependency change is verified with (frozen install with the manifest's package manager version and the deployment image's, type check when the project is typed, build, lint, tests, production audit) is found in the project whatever CI runs, budgeted to the sandbox's time, compared with the base branch, and recorded against the head; the settle stage cites the record, so "check not run" never stays open for a check of the set. Advisories are counted once: the base branch and the head read the same way and laid beside the package manager's audit, each disagreement with its cause, each remaining advisory with its package, whether the change touches it and why it stays. Each major carries its dependency paths, where they run, whether the repository uses it, the reachability verdict with its limit, and how it is fixed (a parent release that declares the fixed range before an override). A major the repository calls is probed through its call sites on the base branch's build and the head's; a changed answer is a known behaviour change, and a sentence that calls the contract or the behaviour unchanged without a probe that shows it is taken out. The record is of one commit, and a head that has moved since is said to have. | | aw. `aw_quarantine_dead_end` | Sixteen end-to-end tests of one team sat in quarantine, some for over three weeks, each with one button (release) and nothing happening. The week's two automatic fixes went to whichever flaky test a default-branch run listed first and only to tests that cost CI time that week, which a quarantined test never does; a test whose fix failed once was never looked at again; a person's "Fix this test" was dropped by the worker as a duplicate of the gateway's own mark, and refused for a quarantined test whose health had gone back to healthy. One test had failed three times and then passed about thirty-five runs in a row on several pull requests; it stayed quarantined under a cause sentence its history had disproved. | A quarantined test always shows where it stands and what happens next (`common::e2e::quarantine`): its fix pull request with its state, the run that is working, or the actions (fix, remove) with the one reason nothing happened by itself. A test that proved healthy (20 clean passes in a row, on more than one pull request or branch, over two hours) leaves by itself with the evidence and its ticket is closed; one that bounces back twice in 30 days is called unstable and needs a quiet week. A cause the runs disprove is marked out of date and worked out again on the next failure. Automatic fixes go to the longest quarantined first, a fix that did not hold is tried again after a week, and the weekly number is said with the day it starts again; a person's request is never counted and never dropped. A removal is a pull request for the team with why it is reasonable: CoderHelm proposes one only when the test was quarantined 30 days, two fixes did not hold and another healthy test covers it, and never merges it. | | ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | | bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | diff --git a/services/common/src/dep_audit.rs b/services/common/src/dep_audit.rs index 26244e068..e1b3b2ab9 100644 --- a/services/common/src/dep_audit.rs +++ b/services/common/src/dep_audit.rs @@ -468,6 +468,181 @@ pub fn read(audits: &[Audit], output: &str) -> Vec { .collect() } +// ── The production-scoped audit and the advisories it lists ───────────── + +/// The audit of production dependencies only, for the managers whose own +/// documentation names the flag: what people read, and what runs. `None` +/// for a manager CoderHelm has no production-scoped audit for (its audit +/// of every dependency is [`audits`]). +pub fn production(manager: &str) -> Option<(&'static str, String)> { + use crate::e2e::test_package::{ensure_manager, Manager}; + match manager { + "npm" => Some(( + "npm audit --omit=dev --json", + "npm audit --omit=dev --json".to_string(), + )), + "pnpm" => Some(( + "pnpm audit --prod --json", + format!("{}pnpm audit --prod --json", ensure_manager(Manager::Pnpm)), + )), + _ => None, + } +} + +/// One advisory an audit lists. +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct Listed { + /// The advisory's id as the audit names it (a GHSA id), upper case. + pub id: String, + pub severity: String, + pub package: String, +} + +/// What one audit listed. +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct Listing { + /// What ran, as people read it. + pub shown: String, + /// Distinct advisory and package pairs the report holds. + pub total: usize, + /// The first [`MAX_LISTED`] of them. + pub listed: Vec, +} + +impl Listing { + /// The report held more than is listed here. + pub fn cut(&self) -> bool { + self.total > self.listed.len() + } +} + +/// The production audit's listing and the listing of every dependency. +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct Listings { + pub production: Option, + pub all: Option, + /// Why a listing is missing; empty when both were read. + pub why: String, +} + +/// Advisories one listing carries at most: the sandbox keeps only the end +/// of a build's output. +pub const MAX_LISTED: usize = 30; +const LIST_ADV: &str = "CODERHELM_AUDIT_ADV"; +const LIST_END: &str = "CODERHELM_AUDIT_LIST"; + +/// Reduces an audit's JSON report (npm 7 and later, pnpm, yarn, bun) to +/// one line per advisory and package: any object that names a GHSA id (a +/// `github_advisory_id`, or an advisory URL) is an advisory, its package +/// the name beside it. It then prints how many it found and whether the +/// file was a report at all. +const LIST_JS: &str = r#" +const fs=require('fs');const [file,scope,max]=process.argv.slice(2); +let text='';try{text=fs.readFileSync(file,'utf8')}catch(e){} +let docs=[]; +try{docs=[JSON.parse(text.slice(text.indexOf('{')))]}catch(e){ + for(const l of text.split('\n')){try{const d=JSON.parse(l);if(d&&typeof d==='object')docs.push(d)}catch(e){}}} +const report=docs.some(d=>d.auditReportVersion||d.vulnerabilities||d.advisories||d.metadata||d.type==='auditSummary'||d.type==='auditAdvisory'||d.children); +const seen=new Map(); +function ghsa(o){const g=String(o.github_advisory_id||o.ghsa||'');if(/^GHSA-/i.test(g))return g; + for(const k of['url','URL']){const m=String(o[k]==null?'':o[k]).match(/GHSA(-[0-9a-z]{4}){3}/i);if(m)return m[0]}return ''} +function walk(o,key){ + if(Array.isArray(o)){for(const x of o)walk(x,key);return} + if(!o||typeof o!=='object')return; + const g=ghsa(o); + if(g){const pkg=String(o.module_name||o.name||o.dependency||o.package||key||'-').replace(/\s/g,''); + const sev=String(o.severity||o.Severity||'-').toLowerCase().replace(/\s/g,''); + const k=g.toUpperCase()+' '+pkg;if(!seen.has(k))seen.set(k,sev)} + const own=(typeof o.value==='string'&&o.children)?o.value:null; + for(const [k,v] of Object.entries(o))walk(v,own||k)} +for(const d of docs)walk(d,''); +let n=0;for(const [k,sev] of seen){if(n++>=Number(max))break;const [g,pkg]=k.split(' ');console.log(['CODERHELM_AUDIT_ADV',scope,g,sev,pkg].join(' '))} +console.log(['CODERHELM_AUDIT_LIST',scope,seen.size,report?1:0].join(' ')); +"#; + +/// The shell lines that list what a manager's audits found, for the +/// managers with a [`production`] audit: `{out}` is the file the +/// production audit's report was written to; the audit of every +/// dependency is run here, in `dir`, and listed beside it. `None` for a +/// manager with no production audit. +pub fn listing(manager: &str, dir: &str) -> Option { + production(manager)?; + let all = tool(manager, false)?; + let cd = if dir.is_empty() { + String::new() + } else { + format!("cd '{dir}' && ") + }; + Some(format!( + "echo '{}' | base64 -d > /tmp/coderhelm-audit-list.js; \ + node /tmp/coderhelm-audit-list.js {{out}} production {MAX_LISTED}; \ + ( {cd}{} ) > /tmp/coderhelm-audit-all.out 2>/dev/null; \ + node /tmp/coderhelm-audit-list.js /tmp/coderhelm-audit-all.out all {MAX_LISTED}", + crate::dep_fix::b64(LIST_JS.as_bytes()), + all.run + )) +} + +/// The listings in a build's output. A scope whose end line is missing, or +/// whose file was no audit report, has no listing, and `why` says so. +pub fn listings(manager: &str, output: &str) -> Listings { + let mut out = Listings::default(); + let shown_all = tool(manager, false).map(|t| t.shown).unwrap_or("the audit"); + let shown_prod = production(manager) + .map(|(s, _)| s) + .unwrap_or("the production audit"); + let mut missing: Vec = vec![]; + for (scope, shown) in [("production", shown_prod), ("all", shown_all)] { + let mut listed: Vec = vec![]; + let mut end: Option<(usize, bool)> = None; + for line in output.lines() { + let mut p = line.split_whitespace(); + match (p.next(), p.next()) { + (Some(LIST_ADV), Some(s)) if s == scope => { + if let (Some(id), Some(sev), Some(pkg)) = (p.next(), p.next(), p.next()) { + listed.push(Listed { + id: id.to_ascii_uppercase(), + severity: sev.to_string(), + package: pkg.to_string(), + }); + } + } + (Some(LIST_END), Some(s)) if s == scope => { + if let (Some(n), Some(ok)) = (p.next().and_then(|n| n.parse().ok()), p.next()) { + end = Some((n, ok == "1")); + } + } + _ => {} + } + } + let listing = match end { + Some((total, true)) => Some(Listing { + shown: shown.to_string(), + total, + listed, + }), + Some((_, false)) => { + missing.push(format!("`{shown}` gave no report")); + None + } + None => { + missing.push(format!("`{shown}` did not report before the build ended")); + None + } + }; + if scope == "production" { + out.production = listing; + } else { + out.all = listing; + } + } + out.why = missing.join("; "); + out +} + #[cfg(test)] mod tests { use super::*; @@ -708,4 +883,37 @@ mod tests { ); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn the_production_audit_is_listed_beside_the_audit_of_everything() { + // Only the managers whose documentation names the flag. + assert_eq!(production("pnpm").unwrap().0, "pnpm audit --prod --json"); + assert_eq!(production("npm").unwrap().0, "npm audit --omit=dev --json"); + assert!(production("cargo").is_none()); + assert!(listing("cargo", "").is_none()); + let cmd = listing("pnpm", "apps/api").unwrap(); + assert!(cmd.contains("{out} production 30")); + assert!(cmd.contains("cd 'apps/api' && ")); + assert!(cmd.contains("pnpm audit --json")); + let out = "CODERHELM_AUDIT_LIST production 0 1\n\ + CODERHELM_AUDIT_ADV all GHSA-AAAA-BBBB-CCCC high dev-tool\n\ + CODERHELM_AUDIT_ADV all GHSA-DDDD-EEEE-FFFF moderate @scope/lint-kit\n\ + CODERHELM_AUDIT_LIST all 2 1\n"; + let l = listings("pnpm", out); + assert!(l.why.is_empty()); + let prod = l.production.unwrap(); + assert_eq!((prod.total, prod.listed.len()), (0, 0)); + assert_eq!(prod.shown, "pnpm audit --prod --json"); + let all = l.all.unwrap(); + assert_eq!(all.listed[1].package, "@scope/lint-kit"); + assert!(!all.cut()); + // A file that was no report, and a build cut short, give no + // listing: never an empty one. + let l = listings("npm", "CODERHELM_AUDIT_LIST production 0 0\n"); + assert!(l.production.is_none() && l.all.is_none()); + assert_eq!( + l.why, + "`npm audit --omit=dev --json` gave no report; `npm audit --json` did not report before the build ended" + ); + } } diff --git a/services/common/src/dep_fix.rs b/services/common/src/dep_fix.rs index 59964a52b..4c67c77bf 100644 --- a/services/common/src/dep_fix.rs +++ b/services/common/src/dep_fix.rs @@ -62,6 +62,7 @@ use crate::security_fixes::{ compare_versions, is_major_bump, version_line, Finding, FindingState, MajorBumps, SecurityConfig, Status, Tier, Verdict, }; +use crate::upgrade_quality::{family, verify as vq}; // ── Limits ────────────────────────────────────────────────────────────── @@ -82,6 +83,10 @@ pub const DEFAULT_RUN_BUDGET_CENTS: u32 = 300; /// Sandbox builds one run's runtime proof may start (the base branch's, the /// branch's, and one more for each commit of bumps the proof takes out). pub const MAX_PROOF_RUNS: u32 = 6; +/// Sandbox builds one run's verification set may start (the branch's, the +/// base branch's where the branch fails something, and again after a set +/// of bumps is taken out). +pub const MAX_VERIFY_RUNS: u32 = 5; // ── The plan ──────────────────────────────────────────────────────────── @@ -136,6 +141,31 @@ pub struct PlanBump { /// lists no patched release on the line, with the releases it does list. /// Empty for a bump that stays on its line; never empty for a major. pub major_reason: String, + /// The packages released with it that move in the same step + /// (`upgrade_quality::family`): applied, probed, committed and deferred + /// with it, never apart. + pub companions: Vec, + /// Its family's key (the source repository), when it has one. + pub family: String, + /// What the family does in this run, in words: who moves with it, or + /// why it goes alone. + pub family_note: String, + /// The parent raised instead of writing an override for this package: + /// its release declares the fixed range + /// (`upgrade_quality::safety::parent_route`). The probe checks that + /// raising it moved the package; when it did not, this is cleared and + /// the override is written. + pub via_parent: Option, +} + +/// A package that moves with a bump because the two are released together. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Companion { + pub package: String, + pub from: String, + pub to: String, + pub line: String, } impl PlanBump { @@ -691,6 +721,7 @@ pub fn plan(members: &[(&Finding, &FindingState)], cfg: &SecurityConfig) -> DepP g.line ), }, + ..Default::default() }); } } @@ -808,11 +839,28 @@ pub fn specs(bumps: &[&PlanBump]) -> Vec { root: dir_of(&b.manifest), bumps: vec![], }); - spec.bumps.push(ApplyBump { - name: b.package.clone(), - line: b.line.clone(), - to: b.to.clone(), - }); + match &b.via_parent { + // The parent's release brings the fixed version in: raise it, + // and write no override for the package. + Some(p) => spec.bumps.push(ApplyBump { + name: p.package.clone(), + line: p.line.clone(), + to: p.to.clone(), + }), + None => spec.bumps.push(ApplyBump { + name: b.package.clone(), + line: b.line.clone(), + to: b.to.clone(), + }), + } + // Its family moves in the same step. + for c in &b.companions { + spec.bumps.push(ApplyBump { + name: c.package.clone(), + line: c.line.clone(), + to: c.to.clone(), + }); + } } by.into_values().collect() } @@ -998,6 +1046,41 @@ pub fn apply_skipped(output: &str) -> Vec { .unwrap_or_default() } +/// What the lockfiles a probe wrote say against the run's families and the +/// parents it raised: each family the lockfile installs at more than one +/// version, as a sentence, and each package whose parent was raised +/// instead of an override and that the lockfile still installs below its +/// fixed version (the parent's release did not move it). +pub fn lockfile_violations( + families: &[family::Family], + bumps: &[&PlanBump], + files: &[(String, String)], +) -> (Vec, Vec) { + let mut split: Vec = vec![]; + let mut unmoved: Vec = vec![]; + for (path, text) in files { + let Some(copies) = crate::reachability::lock_copies(path, text) else { + continue; + }; + split.extend( + family::splits(families, path, &copies) + .iter() + .map(family::Split::line), + ); + for b in bumps.iter().filter(|b| b.via_parent.is_some()) { + let behind = copies.iter().any(|(n, v)| { + n.eq_ignore_ascii_case(&b.package) + && version_line(v) == b.line + && compare_versions(v, &b.to) == std::cmp::Ordering::Less + }); + if b.manifest == *path && behind && !unmoved.contains(&b.package) { + unmoved.push(b.package.clone()); + } + } + } + (split, unmoved) +} + /// The files a probe may hand back to commit: manifests and lockfiles, /// never what a build or test wrote. pub fn commit_path(path: &str) -> bool { @@ -1051,6 +1134,10 @@ impl ProbeResult { pub const LOCKFILE_CHECK: &str = "lockfile"; /// The install step's name. pub const INSTALL_CHECK: &str = "install"; +/// The check name for "the lockfile the bumps wrote installs a family +/// released together at more than one version, or leaves a declared peer +/// range unmet" (`upgrade_quality::family`). +pub const FAMILY_CHECK: &str = "family"; /// One set of bumps being verified together. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -1120,10 +1207,66 @@ pub enum Action { /// ([`DepRun::take_out_last_commit`]) with this reason, then prove the /// branch again. ProofTakeOut { why: String }, + /// Find what the verification set runs: the project's own install, + /// type check, build, lint, tests and production audit + /// (`upgrade_quality::verify::discover`). + VerifyPlan, + /// Run the verification set in a sandbox build of its own: on the + /// branch with the committed bumps, or on the base branch (`base`) when + /// the branch fails something, so a failure the base has too is never + /// blamed. + Verify { base: bool }, + /// A check of the set fails with the bumps and passes without them: + /// take out the newest commit of verified bumps with this reason, then + /// verify the branch again. + VerifyTakeOut { why: String }, /// Nothing left: open the pull request with what is committed. Done, } +/// The verification set of one run (`upgrade_quality::verify`): what a +/// dependency change is verified with whatever CI runs, on the branch with +/// the bumps, and on the base branch where the branch fails something. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Verification { + /// What runs, found once. + pub plan: Option, + /// The branch's results; they are of the commit they name. + pub head: Option, + pub base: Option, + /// Sandbox builds started for it. + pub runs: u32, + /// Builds in a row that gave no result. + pub broken: u32, + /// The run already moved to a fresh step for the next build. + pub waited: bool, + /// The sets of bumps it took out, as where their deferrals start in + /// the run's `deferred` and how many they are. + pub taken_out: Vec<(usize, usize)>, + /// What still fails with the bumps and passes without them, when no + /// further set could be taken out. + pub unresolved: Vec, + /// Why the set did not run; empty when it did. + pub skipped: String, + pub done: bool, + /// What the package manager's audit listed on the branch (the + /// production audit and the audit of every dependency), read in the + /// same build as the branch's results. + pub audit: Option, +} + +/// Why a bump the probes passed is deferred after all: a check of the +/// verification set fails with it. `failing`: what fails. +pub fn verify_deferral_reason(failing: &[String]) -> String { + format!( + "with it applied {} fail{}, which pass{} on the base branch; taken out so the bumps before it ship", + crate::truncate_str(&failing.join(", "), 300), + if failing.len() == 1 { "s" } else { "" }, + if failing.len() == 1 { "es" } else { "" } + ) +} + /// The runtime proof of one run: the repository's real build and its start /// command, run on the base branch and on the branch with the bumps. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -1211,6 +1354,21 @@ pub struct DepRun { pub commits: Vec, /// The build and the start, proven after the batches settle. pub proof: RuntimeProof, + /// The families of the plan's packages: released together, moved + /// together, and checked on every lockfile a probe writes. + pub families: Vec, + /// The peer ranges the plan's new releases declare. + pub peers: Vec, + /// The verification set, run after the runtime proof. + pub verify: Verification, + /// The majors whose behaviour the runtime proof probes, each with its + /// requests (indices into the proof plan's `probes`), and the majors + /// it does not probe, each with why (`upgrade_quality::behaviour`). + pub probed: Vec<(String, Vec)>, + pub not_probed: Vec<(String, String)>, + /// The commit the run's upgrade evidence was last recorded on + /// (`upgrade_quality::UpgradeFacts`). + pub facts_sha: String, } /// One commit of verified bumps. @@ -1292,8 +1450,13 @@ impl DepRun { self.applied.len(), self.probes, self.dropped.len() + self.deferred.len(), - self.proof.runs + u32::from(self.proof.waited) + u32::from(self.proof.plan.is_some()), - self.proof.taken_out.len() + self.proof.runs + + u32::from(self.proof.waited) + + u32::from(self.proof.plan.is_some()) + + self.verify.runs + + u32::from(self.verify.waited) + + u32::from(self.verify.plan.is_some()), + self.proof.taken_out.len() + self.verify.taken_out.len() ) } @@ -1348,6 +1511,9 @@ impl DepRun { if let Some(a) = self.proof_action() { return a; } + if let Some(a) = self.verify_action() { + return a; + } self.done = true; return Action::Done; } @@ -1413,7 +1579,16 @@ impl DepRun { error, }; let only_lock = checks.iter().all(|c| c == LOCKFILE_CHECK); - if b.major && b.risk() == Risk::UrgentMajor && !only_lock { + if checks.iter().any(|c| c == FAMILY_CHECK) { + // Not a call site the coder can change: the versions the + // lockfile resolves do not go together. + self.drop_bump( + d, + "the lockfile written with it installs packages released together at different versions", + false, + Cause::Parent, + ); + } else if b.major && b.risk() == Risk::UrgentMajor && !only_lock { self.code_queue.push(d); } else if only_lock { self.drop_bump( @@ -1573,7 +1748,7 @@ impl DepRun { // Only the apply and the lockfile can fail without a base. r.failing() .into_iter() - .filter(|c| c == LOCKFILE_CHECK) + .filter(|c| c == LOCKFILE_CHECK || c == FAMILY_CHECK) .collect() } else { r.failing() @@ -1938,6 +2113,171 @@ impl DepRun { self.proof.done = true; } + /// The verification set's next action, once the runtime proof is over; + /// `None` when the set is over (or has nothing to verify). + fn verify_action(&mut self) -> Option { + if self.verify.done { + return None; + } + let skip = |v: &mut Verification, why: String| -> Option { + v.skipped = why; + v.done = true; + None + }; + if self.applied.is_empty() { + self.verify.done = true; + return None; + } + if self.unverified { + return skip( + &mut self.verify, + "the sandbox could not run the repository's commands on the base branch".into(), + ); + } + let Some(plan) = self.verify.plan.clone() else { + return Some(Action::VerifyPlan); + }; + if plan.is_empty() { + return skip(&mut self.verify, plan.none); + } + let spent = self.verify.runs >= MAX_VERIFY_RUNS; + let head = match &self.verify.head { + Some(h) if h.sha == self.head => h.clone(), + _ if spent => { + return skip( + &mut self.verify, + "the run's sandbox builds for it were used up before the branch's last commit was verified".into(), + ) + } + _ => return Some(Action::Verify { base: false }), + }; + if !head.ran || !vq::needs_base(&head) { + // No result (said as none), or nothing a change can be blamed + // for: over. + self.verify.done = true; + return None; + } + let base = match &self.verify.base { + Some(b) => b.clone(), + None if spent => { + self.verify.done = true; + return None; + } + None => return Some(Action::Verify { base: true }), + }; + let blamed: Vec = vq::blamed(&head, base.ran.then_some(&base)) + .iter() + .map(|o| format!("the {} (`{}`)", o.kind.name(), o.shown)) + .collect(); + if blamed.is_empty() { + self.verify.done = true; + return None; + } + if self.commits.len() >= 2 && !spent { + return Some(Action::VerifyTakeOut { + why: verify_deferral_reason(&blamed), + }); + } + // One commit left (the pull request is never emptied) or the + // builds are used up: what fails is said, and CI decides. + self.verify.unresolved = blamed; + self.verify.done = true; + None + } + + /// What the verification set runs was found. + pub fn on_verify_plan(&mut self, plan: vq::Plan) { + self.verify.plan = Some(plan); + } + + /// The set was not permitted or could not be set up: said, never a + /// claim. + pub fn skip_verify(&mut self, why: &str) { + self.verify.skipped = why.to_string(); + self.verify.done = true; + } + + /// The result of `Action::Verify`. A build that gave no result is run + /// once more before it stands as "no result". + pub fn on_verify(&mut self, base: bool, v: vq::Verified) { + self.verify.runs += 1; + self.verify.waited = false; + if !v.ran { + self.verify.broken += 1; + if self.verify.broken < MAX_BROKEN_PROBES && self.verify.runs < MAX_VERIFY_RUNS { + return; + } + } + self.verify.broken = 0; + if base { + self.verify.base = Some(v); + } else { + self.verify.head = Some(v); + } + } + + /// The run moved to a fresh step so the next verification build has a + /// full time window. + pub fn on_verify_wait(&mut self) { + self.verify.waited = true; + } + + /// `Action::VerifyTakeOut` was written to the branch, now at `head`: + /// the bumps it took out are deferred, and the branch is verified + /// again. The runtime proof stays of the commit it proved, and says so. + pub fn on_verify_taken_out(&mut self, out: &TakenOut, head: &str) { + let n = out.lines.len(); + self.verify + .taken_out + .push((self.deferred.len().saturating_sub(n), n)); + self.head = head.to_string(); + self.verify.head = None; + } + + /// `Action::VerifyTakeOut` could not be written: what fails is said, + /// and the pull request's own CI decides. + pub fn on_verify_take_out_failed(&mut self) { + let v = &self.verify; + self.verify.unresolved = match (&v.head, &v.base) { + (Some(head), Some(base)) => vq::blamed(head, base.ran.then_some(base)) + .iter() + .map(|o| format!("the {} (`{}`)", o.kind.name(), o.shown)) + .collect(), + _ => vec![], + }; + self.verify.done = true; + } + + /// The report's account of what the verification set took out or + /// could not settle. Its results are in the upgrade evidence. + fn verify_md(&self) -> String { + let v = &self.verify; + let mut s = String::new(); + if !v.skipped.is_empty() { + s.push_str(&format!( + "\n**Verification set (the project's own install, type check, build, lint, tests and production audit):**\n- Not run: {}. Nothing here claims those checks pass; CI on this pull request is the check.\n", + v.skipped + )); + return s; + } + if v.taken_out.is_empty() && v.unresolved.is_empty() { + return s; + } + s.push_str("\n**Verification set:**\n"); + for &(start, len) in &v.taken_out { + for d in self.deferred.iter().skip(start).take(len) { + s.push_str(&format!("- Taken out by it: {}\n", d.line())); + } + } + if !v.unresolved.is_empty() { + s.push_str(&format!( + "- Still failing with the bumps in this pull request: {}. It passes on the base branch, and no further set of bumps could be taken out here, so the pull request's CI decides.\n", + v.unresolved.join("; ") + )); + } + s + } + /// The report's account of the runtime proof. fn proof_md(&self) -> String { let p = &self.proof; @@ -1980,6 +2320,10 @@ impl DepRun { self.proof.skipped = "the run had no step left for it".into(); self.proof.done = true; } + if !self.verify.done { + self.verify.skipped = "the run had no step left for it".into(); + self.verify.done = true; + } self.done = true; } @@ -2040,6 +2384,15 @@ impl DepRun { (false, _) => "same version line".to_string(), } )); + if !b.family_note.is_empty() { + s.push_str(&format!(" - Its family: {}\n", b.family_note)); + } + if let Some(p) = &b.via_parent { + s.push_str(&format!( + " - Fixed by raising its parent `{}` {} to {}, whose release declares the fixed range: no override.\n", + p.package, p.from, p.to + )); + } } if applied.len() > 80 { s.push_str(&format!("- and {} more\n", applied.len() - 80)); @@ -2076,6 +2429,7 @@ impl DepRun { } if !self.applied.is_empty() { s.push_str(&self.proof_md()); + s.push_str(&self.verify_md()); } s.push_str(&format!( "\n**Cost:** {} sandbox probe(s){}; model ${:.2}", diff --git a/services/common/src/dep_fix/tests.rs b/services/common/src/dep_fix/tests.rs index f5f05dfc1..a42da3697 100644 --- a/services/common/src/dep_fix/tests.rs +++ b/services/common/src/dep_fix/tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::security_fixes::{same_line, Relation, Scope, SecurityConfig}; +use crate::upgrade_quality::verify as vq; fn finding( id: &str, @@ -568,6 +569,13 @@ struct FakeSandbox { /// The build fails on the base branch too. base_build_fails: bool, proof_runs: u32, + /// What the verification set runs (`None`: nothing to verify with). + verify_plan: Option, + /// Packages a check of the set fails with, by the check's kind. + verify_breaks: Vec<(String, vq::Kind)>, + /// Kinds that fail on the base branch too. + verify_base_fails: Vec, + verify_runs: u32, } const CHECKS: [&str; 4] = ["install", "lint", "typecheck", "tests"]; @@ -651,6 +659,40 @@ impl FakeSandbox { self.commits += 1; run.on_proof_taken_out(&out, &format!("sha{}", self.commits)); } + Action::VerifyPlan => { + run.on_verify_plan(self.verify_plan.clone().unwrap_or_default()) + } + Action::Verify { base } => { + self.verify_runs += 1; + let plan = run.verify.plan.clone().unwrap(); + let all: Vec = (0..plan.checks.len()).collect(); + let out: String = plan + .checks + .iter() + .enumerate() + .map(|(i, c)| { + let broken = self.verify_base_fails.contains(&c.kind) + || (!base + && run.applied_bumps().iter().any(|b| { + self.verify_breaks + .iter() + .any(|(p, k)| *p == b.package && *k == c.kind) + })); + format!("{} {i} {}\n", vq::MARK, u8::from(broken)) + }) + .collect(); + let sha = if base { + "base".to_string() + } else { + run.head.clone() + }; + run.on_verify(base, vq::read(&plan, &sha, &all, &[], &out)); + } + Action::VerifyTakeOut { why } => { + let out = run.take_out_last_commit(&why).expect("a set to take out"); + self.commits += 1; + run.on_verify_taken_out(&out, &format!("sha{}", self.commits)); + } Action::Done => return, } } @@ -672,6 +714,10 @@ fn sandbox(breaks: &[(&str, &str)]) -> FakeSandbox { build_breaks: vec![], base_build_fails: false, proof_runs: 0, + verify_plan: None, + verify_breaks: vec![], + verify_base_fails: vec![], + verify_runs: 0, } } @@ -1007,6 +1053,9 @@ fn a_version_that_cannot_be_installed_is_deferred_without_the_coder() { // The batches are settled: the runtime proof, here with nothing to run. assert_eq!(run.next_action(), Action::ProofPlan); run.on_proof_plan(rp::ProofPlan::default()); + // Then the verification set, here with nothing to verify with. + assert_eq!(run.next_action(), Action::VerifyPlan); + run.on_verify_plan(vq::Plan::default()); assert_eq!(run.next_action(), Action::Done); assert_eq!(run.code_fixes, 0); assert_eq!(run.deferred[0].cause, Cause::Parent); @@ -1707,6 +1756,7 @@ fn step(sb: &mut FakeSandbox, run: &mut DepRun) { run.on_commit(g, &head); } Action::ProofPlan => run.on_proof_plan(sb.proof_plan.clone().unwrap_or_default()), + Action::VerifyPlan => run.on_verify_plan(sb.verify_plan.clone().unwrap_or_default()), other => panic!("unexpected {other:?}"), } } @@ -1867,3 +1917,180 @@ fn a_take_out_that_could_not_be_written_leaves_the_bumps_and_says_what_fails() { vec!["the build `pnpm build` fails (exit 1)"] ); } + +/// The verification set of a typed project with a build, tests and a +/// production audit, as `upgrade_quality::verify` finds it. +fn typed_verify_plan() -> vq::Plan { + let tree: Vec = ["package.json", "pnpm-lock.yaml", "tsconfig.json"] + .iter() + .map(|s| s.to_string()) + .collect(); + vq::discover( + "pnpm-lock.yaml", + &tree, + &[( + "package.json".to_string(), + r#"{"scripts":{"build":"tsc -p .","test":"vitest run"}}"#.to_string(), + )], + Some(("pnpm audit --prod --json", "pnpm audit --prod --json")), + ) +} + +#[test] +fn the_verification_set_runs_once_on_a_green_branch() { + let mut run = DepRun::new(mixed_plan(), "base", 3.0); + let mut sb = sandbox(&[]); + sb.verify_plan = Some(typed_verify_plan()); + sb.drive(&mut run); + // One build, on the branch: nothing failed, so the base is not run. + assert_eq!((sb.verify_runs, run.verify.runs), (1, 1)); + assert!(run.verify.done && run.verify.base.is_none()); + let head = run.verify.head.as_ref().unwrap(); + // The record is of the branch's last commit, and every check of the + // set has a result on it: none is left as not run. + assert_eq!(head.sha, run.head); + assert!(head.not_run().is_empty()); + assert!(head.outcome(vq::Kind::Typecheck).unwrap().passed()); + assert!(run.verify.taken_out.is_empty() && run.verify.unresolved.is_empty()); +} + +#[test] +fn a_check_of_the_set_that_fails_on_the_base_too_is_never_blamed() { + let mut run = DepRun::new(mixed_plan(), "base", 3.0); + let mut sb = sandbox(&[]); + sb.verify_plan = Some(typed_verify_plan()); + sb.verify_base_fails = vec![vq::Kind::Tests]; + sb.drive(&mut run); + // The branch, then the base branch because the branch failed a check. + assert_eq!(run.verify.runs, 2); + assert_eq!(run.applied.len(), 10); + assert!(run.verify.taken_out.is_empty() && run.verify.unresolved.is_empty()); + let text = vq::section(run.verify.head.as_ref().unwrap(), run.verify.base.as_ref()); + assert!( + text.contains("it fails on the base branch too, so not caused by this change"), + "{text}" + ); +} + +#[test] +fn a_type_check_the_bumps_break_takes_out_the_set_that_breaks_it() { + // The probes and CI's mirrored checks pass: the repository's CI has no + // type check. The set finds it in the project and runs it. + let mut run = DepRun::new(mixed_plan(), "base", 3.0); + let mut sb = sandbox(&[]); + sb.verify_plan = Some(typed_verify_plan()); + sb.verify_breaks = vec![("route-kit".into(), vq::Kind::Typecheck)]; + sb.drive(&mut run); + assert!(!run.verify.taken_out.is_empty()); + let applied: Vec<&str> = run + .applied_bumps() + .iter() + .map(|b| b.package.as_str()) + .collect(); + assert!(!applied.contains(&"route-kit"), "{applied:?}"); + let d = run + .deferred + .iter() + .find(|d| d.package == "route-kit") + .expect("route-kit deferred"); + assert!( + d.reason + .contains("the type check (`npx --no-install tsc --noEmit`) fails, which passes on the base branch"), + "{}", + d.reason + ); + // What is left was verified again, on the commit it is on, and passes. + let head = run.verify.head.as_ref().unwrap(); + assert_eq!(head.sha, run.head); + assert!(head.outcome(vq::Kind::Typecheck).unwrap().passed()); + assert!(run.verify.unresolved.is_empty()); + assert!(run.report_md().contains("- Taken out by it: `route-kit`")); + // The run reads as moving through each build of the set. + assert!(run.progress().starts_with("dep:")); +} + +#[test] +fn a_set_with_no_result_claims_nothing_and_a_single_commit_is_never_emptied() { + // The sandbox gives no result, twice: recorded as none. + let mut run = DepRun::new(ten_bumps(), "base", 3.0); + let mut sb = sandbox(&[]); + let plan = typed_verify_plan(); + loop { + match run.next_action() { + Action::VerifyPlan => run.on_verify_plan(plan.clone()), + Action::Verify { base } => { + assert!(!base); + run.on_verify( + false, + vq::no_result(&plan, &run.head.clone(), "the sandbox build timed out"), + ); + } + Action::Done => break, + _ => step(&mut sb, &mut run), + } + } + assert_eq!(run.verify.runs, MAX_BROKEN_PROBES); + let head = run.verify.head.as_ref().unwrap(); + assert!(!head.ran); + assert!(vq::section(head, None).contains("Nothing here claims a check passed")); + // One commit of bumps and a blamed check: nothing is taken out (the + // pull request is never emptied); what fails is said. + let mut run = DepRun::new(ten_bumps(), "base", 3.0); + let mut sb = sandbox(&[]); + sb.verify_plan = Some(typed_verify_plan()); + sb.verify_breaks = vec![("lib-03".into(), vq::Kind::Build)]; + sb.drive(&mut run); + assert_eq!(run.commits.len(), 1); + assert_eq!(run.applied.len(), 10); + assert_eq!( + run.verify.unresolved, + vec!["the build (`pnpm run build`)".to_string()] + ); + assert!(run.report_md().contains( + "Still failing with the bumps in this pull request: the build (`pnpm run build`)" + )); + // A run with no step left says the set did not run. + let mut run = DepRun::new(ten_bumps(), "base", 3.0); + run.on_base(&FakeSandbox::result(&sandbox(&[]), &[])); + run.finish_now("the run had no step left"); + assert_eq!(run.verify.skipped, "the run had no step left for it"); +} + +#[test] +fn a_split_family_fails_the_probe_and_is_deferred_with_the_reason() { + let fs = vec![finding( + "f1", + "@lattice/common", + "10.4.15", + &["10.4.22"], + Tier::P2, + Verdict::Unknown, + )]; + let mut run = DepRun::new(plan(&pairs(&fs), &cfg()), "base", 3.0); + run.on_base(&FakeSandbox::result(&sandbox(&[]), &[])); + let Action::Probe(g) = run.next_action() else { + panic!() + }; + // Every check of the repository passes; the lockfile the bump wrote + // has its family at two versions. + let mut r = FakeSandbox::result(&sandbox(&[]), &[]); + r.checks.push((FAMILY_CHECK.to_string(), false)); + r.tail = "the family `lattice-js/lattice` is split on the head: `@lattice/common` at 10.4.22, `@lattice/core` at 10.4.15".into(); + run.on_probes(&[(g[0], r)]); + while run.next_action() != Action::Done { + if let Some(v) = run.verify.plan.is_none().then(vq::Plan::default) { + run.on_verify_plan(v); + } + } + assert!(run.applied.is_empty()); + assert_eq!(run.deferred.len(), 1); + assert_eq!(run.deferred[0].cause, Cause::Parent); + assert!( + run.deferred[0] + .reason + .starts_with("the lockfile written with it installs packages released together at different versions"), + "{}", + run.deferred[0].reason + ); + assert!(run.deferred[0].reason.contains("is split on the head")); +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 92e79c006..a43c06196 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -109,6 +109,7 @@ pub mod settings_index; /// Setup: the settings registry, the repo analysis, runs, apply and undo. pub mod setup; pub mod upgrade_notes; +pub mod upgrade_quality; // Which repo a log group's or alarm's code lives in, from evidence. /// Sealed credentials for a team's MCP servers (KMS, bound to team and server). pub mod envelope; diff --git a/services/common/src/pr_body_fit.rs b/services/common/src/pr_body_fit.rs index e8d7098e0..32cc73a3e 100644 --- a/services/common/src/pr_body_fit.rs +++ b/services/common/src/pr_body_fit.rs @@ -13,7 +13,9 @@ //! failing, Not yet verified, Verification, Open items, Proof, Risk), a //! dependency fix run's account (its `### Dependency fix run` block under //! What to check: the bumps applied, the ones deferred with why, the -//! sandbox's checks and the cost), every `## ` heading (so a section rewritten in place later is still found), and +//! sandbox's checks and the cost) and its `### Upgrade evidence` block (what +//! the run recorded for the head: the advisory count, the families, the +//! verification set, each major and its behaviour probe), every `## ` heading (so a section rewritten in place later is still found), and //! every line holding an HTML comment (the markers CoderHelm parses later). //! Shrunk, largest section first and a step at a time: nested detail under //! a list item, then long lists (capped, with "and N more"), then a whole @@ -34,7 +36,7 @@ pub const BODY_TARGET: usize = 64_000; pub const GITHUB_TITLE_MAX: usize = 256; /// The sections kept as written, by the start of their heading. -const KEPT: [&str; 11] = [ +const KEPT: [&str; 12] = [ "summary", "not finished", "ci failing", @@ -46,6 +48,7 @@ const KEPT: [&str; 11] = [ "why it stopped", "what you can do", "dependency fix run", + "upgrade evidence", ]; /// The notice a shortened body ends with. diff --git a/services/common/src/reachability.rs b/services/common/src/reachability.rs index 81c462e42..387a74010 100644 --- a/services/common/src/reachability.rs +++ b/services/common/src/reachability.rs @@ -108,7 +108,7 @@ pub fn is_test_path(path: &str) -> bool { /// Build and lint configuration (`vite.config.ts`, `.eslintrc.js`, /// `babel.config.js`): what it imports runs at build time. Counted as a /// mention, so the model reads it, never as a runtime import. -fn is_tooling_config(path: &str) -> bool { +pub fn is_tooling_config(path: &str) -> bool { let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase(); let stem = name.split('.').next().unwrap_or(""); name.starts_with('.') diff --git a/services/common/src/runtime_proof.rs b/services/common/src/runtime_proof.rs index c6fe045ec..d6aae05e2 100644 --- a/services/common/src/runtime_proof.rs +++ b/services/common/src/runtime_proof.rs @@ -52,6 +52,10 @@ pub const MARK: &str = "CODERHELM_PROOF"; pub const STEP_MARK: &str = "CODERHELM_PROOF_STEP"; /// One requested path's status: `CODERHELM_PROOF_PAGE `. pub const PAGE_MARK: &str = "CODERHELM_PROOF_PAGE"; +/// Each before-and-after request's answer. +pub const PROBE_MARK: &str = "CODERHELM_PROOF_PROBE"; +/// Bytes of an answer's body kept to show what changed. +pub const PROBE_EXCERPT: usize = 120; /// The port the start command is given as `PORT`. pub const PORT: u16 = 38411; /// Ports asked when the application ignores `PORT` and the sandbox image @@ -193,6 +197,56 @@ pub struct ProofPlan { /// Why the workspace projects that take the changed packages could not /// be worked out; empty when they were (or the project is no workspace). pub projects_unknown: String, + /// The requests sent to the started application, on the base branch + /// and on the head alike, so what a major changes in its answers shows + /// (`upgrade_quality::behaviour`). + pub probes: Vec, +} + +/// One request of a before-and-after probe. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ProbeRequest { + pub method: String, + pub path: String, + /// Empty for a request with no body. + pub content_type: String, + pub body: String, + /// Zero bytes sent after `body` and before `tail`, in KiB (an upload + /// over a size limit). + pub pad_kb: u32, + pub tail: String, + /// What the request exercises, in words. + pub what: String, +} + +impl ProbeRequest { + /// It can be sent by the proof's shell command as it is. + pub fn sendable(&self) -> bool { + let ok = |s: &str, extra: &[char]| { + s.chars() + .all(|c| c.is_ascii_alphanumeric() || extra.contains(&c)) + }; + !self.method.is_empty() + && self.method.chars().all(|c| c.is_ascii_uppercase()) + && self.path.starts_with('/') + && ok(&self.path, &['/', '_', '-', '.', '~']) + && ok(&self.content_type, &['/', ';', '=', '+', '.', '-', ' ']) + } +} + +/// One answer to a [`ProbeRequest`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ProbeAnswer { + pub status: u16, + pub content_type: String, + /// The start of the body's SHA-256. + pub sha: String, + /// The start of the body. + pub excerpt: String, + /// The same request sent twice to this build was answered the same. + pub stable: bool, } /// One project the bumps can break, beside the main one. @@ -678,6 +732,9 @@ pub fn script(plan: &ProofPlan) -> String { s.push_str(&format!( " echo \"{PAGE_MARK} $ch_path ${{ch_code:-000}}\"\n done\n" )); + for (i, q) in plan.probes.iter().enumerate().filter(|(_, q)| q.sendable()) { + s.push_str(&probe_lines(i + 1, q)); + } s.push_str(" else\n echo \"--- start did not answer ($ch_start), last output ---\"; tail -c 1200 /tmp/coderhelm-proof-start.log; echo\n fi\n"); s.push_str(" ch_killtree $ch_pid\nfi\n"); } @@ -687,6 +744,57 @@ pub fn script(plan: &ProofPlan) -> String { s } +/// The shell lines that send request `n` twice and print each answer as +/// `CODERHELM_PROOF_PROBE ` +/// (the excerpt base64, on the first try only). The body travels encoded, +/// so nothing in it meets the shell. +fn probe_lines(n: usize, q: &ProbeRequest) -> String { + let file = format!("/tmp/coderhelm-probe-{n}.in"); + let mut s = String::new(); + let has_body = !q.body.is_empty() || q.pad_kb > 0 || !q.tail.is_empty(); + if has_body { + s.push_str(&format!( + " echo '{}' | base64 -d > {file}\n", + crate::dep_fix::b64(q.body.as_bytes()) + )); + if q.pad_kb > 0 { + s.push_str(&format!( + " head -c {} /dev/zero >> {file}\n", + u64::from(q.pad_kb) * 1024 + )); + } + if !q.tail.is_empty() { + s.push_str(&format!( + " echo '{}' | base64 -d >> {file}\n", + crate::dep_fix::b64(q.tail.as_bytes()) + )); + } + } + let header = if q.content_type.is_empty() { + String::new() + } else { + format!(" -H 'Content-Type: {}'", q.content_type) + }; + let data = if has_body { + format!(" --data-binary @{file}") + } else { + String::new() + }; + s.push_str(" for ch_t in 1 2; do\n"); + s.push_str(&format!( + " ch_o=$(curl -s -m 30 --noproxy '*' -X {}{header}{data} -o /tmp/coderhelm-probe.out -w '%{{http_code}} %{{content_type}}' \"http://127.0.0.1:$ch_port{}\" 2>/dev/null)\n", + q.method, q.path + )); + s.push_str(" ch_ct=$(printf %s \"${ch_o#* }\" | tr -d ' ' | cut -c1-48); ch_sha=$( (sha256sum /tmp/coderhelm-probe.out 2>/dev/null || shasum -a 256 /tmp/coderhelm-probe.out 2>/dev/null) | cut -c1-16)\n"); + s.push_str(&format!( + " ch_ex=; if [ $ch_t = 1 ]; then ch_ex=$(head -c {PROBE_EXCERPT} /tmp/coderhelm-probe.out 2>/dev/null | base64 | tr -d '\\n'); fi\n" + )); + s.push_str(&format!( + " echo \"{PROBE_MARK} {n} $ch_t ${{ch_o%% *}} ${{ch_ct:--}} ${{ch_sha:--}} $ch_ex\"\n done\n" + )); + s +} + /// What one proof run came to. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(default)] @@ -704,6 +812,9 @@ pub struct ProofResult { pub port: u16, /// Each requested path and the status it answered (0: no answer). pub pages: Vec<(String, u16)>, + /// The answer to each of the plan's probes, in its order (`None`: no + /// answer, or the request was not sent). + pub probes: Vec>, /// The output's tail, for a reason. pub tail: String, } @@ -733,6 +844,9 @@ pub fn page_ok(status: u16) -> bool { /// A proof's result from its output; `ran` is false without the last line. pub fn parse(output: &str, plan: &ProofPlan) -> ProofResult { + // Each probe's two answers: (status, content type, sha, excerpt). + type Try = Option<(u16, String, String, String)>; + let mut tries: Vec<[Try; 2]> = vec![[None, None]; plan.probes.len()]; let mut r = ProofResult { builds: vec![None; plan.builds.len()], start: "skipped".into(), @@ -764,6 +878,29 @@ pub fn parse(output: &str, plan: &ProofPlan) -> ProofResult { r.pages.retain(|(p, _)| p != path); r.pages.push((path.to_string(), code)); } + Some(PROBE_MARK) => { + let (Some(n), Some(t), Some(status)) = ( + parts.next().and_then(|n| n.parse::().ok()), + parts.next().and_then(|n| n.parse::().ok()), + parts.next().and_then(|c| c.parse::().ok()), + ) else { + continue; + }; + if !(1..=tries.len()).contains(&n) || !(1..=2).contains(&t) { + continue; + } + let ct = parts.next().unwrap_or("-").to_string(); + let sha = parts.next().unwrap_or("-").to_string(); + let excerpt = parts + .next() + .and_then(|b| { + use base64::Engine; + base64::engine::general_purpose::STANDARD.decode(b).ok() + }) + .map(|b| String::from_utf8_lossy(&b).to_string()) + .unwrap_or_default(); + tries[n - 1][t - 1] = Some((status, ct, sha, excerpt)); + } Some(MARK) => { let mut install = None; for p in parts { @@ -783,6 +920,22 @@ pub fn parse(output: &str, plan: &ProofPlan) -> ProofResult { _ => {} } } + r.probes = tries + .into_iter() + .map(|[first, second]| { + let (status, content_type, sha, excerpt) = first.filter(|(s, ..)| *s != 0)?; + let stable = second + .as_ref() + .is_some_and(|(s, c, h, _)| *s == status && *c == content_type && *h == sha); + Some(ProbeAnswer { + status, + content_type, + sha, + excerpt, + stable, + }) + }) + .collect(); r } diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index 2b750032b..16564f3c1 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -3222,6 +3222,22 @@ fn body_linked( // two heads; everything shown comes from the head when it was read. let short = uses_short_body(unit, members); let plan = unit; + // The upgrade evidence is of one commit: it is shown against the head + // this body is written for, and the run's own words may call the + // contract or the behaviour unchanged only when a probe recorded on + // that head shows it. + let head_sha = head.map(|h| h.sha.clone()).unwrap_or_default(); + let shown = check + .upgrade_facts + .as_ref() + .is_some_and(|f| f.of_head(&head_sha) && f.unchanged_shown()); + let guarded = crate::upgrade_quality::behaviour::guard(change, shown); + let change = guarded.as_str(); + let with_head = crate::upgrade_notes::WhatToCheck { + head_sha, + ..check.clone() + }; + let check = &with_head; let at_head = head.map(|h| h.unit_at_head(unit)); let unit = at_head.as_ref().unwrap_or(unit); let headline = head.map(|h| h.headline(plan, members)); diff --git a/services/common/src/upgrade_notes.rs b/services/common/src/upgrade_notes.rs index 47cb374d1..b20fb9f84 100644 --- a/services/common/src/upgrade_notes.rs +++ b/services/common/src/upgrade_notes.rs @@ -1312,6 +1312,14 @@ pub struct WhatToCheck { /// bumps applied, the ones deferred with why, and the checks run in the /// sandbox. Empty for a run without one. pub dep_report: String, + /// What the dependency run recorded for its head commit + /// (`upgrade_quality::UpgradeFacts`): the reconciled advisory count, + /// the families, the verification set's results, why each major is + /// safe and what its behaviour probe showed. + pub upgrade_facts: Option, + /// The head the description is written for: facts recorded on another + /// commit are shown as that commit's. + pub head_sha: String, } impl WhatToCheck { @@ -1381,6 +1389,10 @@ pub fn what_to_check(bumps: &[Bump], w: &WhatToCheck) -> String { s.push_str(w.dep_report.trim()); s.push_str("\n\n"); } + if let Some(facts) = &w.upgrade_facts { + s.push_str(facts.section(&w.head_sha).trim()); + s.push_str("\n\n"); + } for b in bumps { s.push_str(&package_check(b, w, usize::MAX)); } @@ -1434,6 +1446,10 @@ pub fn what_to_check_short( s.push_str(w.dep_report.trim()); s.push_str("\n\n"); } + if let Some(facts) = &w.upgrade_facts { + s.push_str(facts.section(&w.head_sha).trim()); + s.push_str("\n\n"); + } if !intro.trim().is_empty() { s.push_str(intro.trim()); s.push_str("\n\n"); diff --git a/services/common/src/upgrade_quality/advisories.rs b/services/common/src/upgrade_quality/advisories.rs new file mode 100644 index 000000000..6b1e4ae47 --- /dev/null +++ b/services/common/src/upgrade_quality/advisories.rs @@ -0,0 +1,1177 @@ +//! One count of advisories: fixed, remaining and introduced. +//! +//! A dependency pull request said "N high advisories left". The package +//! manager's production audit of the same head showed fewer, every one in a +//! package the pull request does not touch. The first number was counted +//! from CoderHelm's own findings, and nothing compared it with the audit. +//! +//! Here the base branch and the head are read the same way, and the result +//! is compared with the package manager's audit before a number is written: +//! +//! - [`reconcile`] evaluates every advisory CoderHelm holds for the +//! repository against the copies the base branch's lockfile installs and +//! against the copies the head's lockfile installs. Withdrawn advisories +//! are dropped and ids that are aliases of one advisory are counted once. +//! Fixed is in the base and not in the head, remaining is in both, +//! introduced is in the head only. +//! - The package manager's audit of the head (production dependencies, and +//! every dependency) is then laid beside it. Where the two agree nothing +//! is said. Where they differ the difference has a [`Cause`] and a +//! sentence: an advisory the audit lists that CoderHelm did not hold is +//! taken in; one CoderHelm holds that the audit does not list is shown +//! with where CoderHelm has it from; a finding recorded for a version the +//! lockfile never installed is set aside with the override or the stale +//! record that explains it; an advisory only the audit of every +//! dependency lists is development only. +//! - Every remaining advisory names its package, whether this change +//! touches it, whether it is in production, and why it stays. +//! - Without an audit result the numbers are CoderHelm's own and are said +//! to be: never the audit's. +//! +//! Everything here is pure; the lockfile reads and the audit are the +//! worker's. + +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::dep_audit::{Listed, Listings}; +use crate::security_fixes::{ + clusters, compare_versions, in_range, primary_id, same_line, Finding, FindingState, Scope, + Status, +}; + +/// An advisory CoderHelm holds for one package of the repository. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Held { + /// The id it is shown by. + pub id: String, + /// Every id it is known by, the shown one included. + pub ids: Vec, + pub package: String, + /// `critical`, `high`, `moderate`, `low`, or empty. + pub severity: String, + /// The vulnerable ranges, as the sources wrote them. + pub ranges: Vec, + /// The patched versions the sources name. + pub fixed: Vec, + /// The version the finding was recorded against. + pub recorded: String, + pub scope: Scope, + pub withdrawn: bool, + /// Where CoderHelm has it from (`dependabot`, `osv`, `github_advisory`). + pub source: String, + pub finding: String, +} + +impl Held { + pub fn of(f: &Finding, st: &FindingState) -> Held { + let mut ids = f.advisory.ids.clone(); + if !f.advisory.primary.is_empty() && !ids.contains(&f.advisory.primary) { + ids.push(f.advisory.primary.clone()); + } + let known = |id: &String| st.withdrawn.iter().any(|w| w.eq_ignore_ascii_case(id)); + let mut fixed = st.fixed.clone(); + if let Some(v) = f.fixed_version.as_ref().filter(|v| !v.is_empty()) { + if !fixed.contains(v) { + fixed.push(v.clone()); + } + } + Held { + id: f.advisory.primary.clone(), + withdrawn: f.status == Status::Withdrawn || (!ids.is_empty() && ids.iter().all(known)), + ids, + package: f.package.clone(), + severity: st + .severity + .clone() + .unwrap_or_else(|| match f.advisory.cvss { + Some(c) if c >= 9.0 => "critical".into(), + Some(c) if c >= 7.0 => "high".into(), + Some(c) if c >= 4.0 => "moderate".into(), + Some(_) => "low".into(), + None => String::new(), + }) + .to_ascii_lowercase(), + ranges: st.ranges.clone(), + fixed, + recorded: f.version.clone(), + scope: f.scope, + source: f.advisory.source.clone(), + finding: f.id.clone(), + } + } + + /// Whether one installed version is vulnerable to it: inside a range + /// the sources wrote; or, with no range, below the patched version of + /// its line (or below every patched version, when its line has none). + /// With neither, only the version the finding was recorded against. + pub fn affects(&self, version: &str) -> bool { + if !self.ranges.is_empty() { + return self.ranges.iter().any(|r| in_range(version, r)); + } + if self.fixed.is_empty() { + return compare_versions(version, &self.recorded) == Ordering::Equal; + } + match self.fixed.iter().find(|f| same_line(version, f)) { + Some(f) => compare_versions(version, f) == Ordering::Less, + None => self + .fixed + .iter() + .all(|f| compare_versions(version, f) == Ordering::Less), + } + } +} + +/// Why CoderHelm's read of the lockfile and the package manager's audit +/// differ on one advisory. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Cause { + /// The audit lists it and CoderHelm did not hold it: taken in. + NotHeld, + /// CoderHelm holds it and the audit does not list it. + NotInAudit, + /// The repository's audit configuration ignores it. + Ignored, + /// The audit lists it for a version CoderHelm's ranges put outside it. + RangeDiffers, + /// The finding was recorded for a version the lockfile never + /// installed, and the manifest overrides the package. + Override, + /// The same, with no override: the record is behind the lockfile. + StaleRecord, + /// Only the audit of every dependency lists it, not the production + /// one. + DevelopmentOnly, +} + +/// One difference, with how it was settled. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Difference { + pub id: String, + pub package: String, + pub cause: Cause, + /// The difference in one sentence, with what was done about it. + pub text: String, +} + +/// Where a remaining advisory's package is installed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum Where { + Production, + Development, + #[default] + NotKnown, +} + +impl Where { + fn words(self) -> &'static str { + match self { + Where::Production => "production", + Where::Development => "development only", + Where::NotKnown => "production or development not known", + } + } +} + +/// One advisory with the package it is in. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Entry { + pub id: String, + pub package: String, + pub severity: String, + /// The vulnerable versions installed (the base's for a fixed one, the + /// head's otherwise); empty when only the audit names it. + pub versions: Vec, + pub scope: Where, + /// This change moves the package (a remaining or introduced one). + pub touched: bool, + /// Why it stays (a remaining one). + pub why: String, +} + +/// How the audit stands beside the count. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct AuditState { + /// The production audit and the audit of every dependency, as people + /// read them; empty for one that gave no listing. + pub production: String, + pub all: String, + /// Why a listing is missing; empty when both were read. + pub missing: String, + /// A listing held more advisories than the sandbox's output carries. + pub cut: bool, +} + +/// The advisories of one head, counted once. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Reconciled { + pub sha: String, + pub lockfile: String, + pub fixed: Vec, + pub remaining: Vec, + pub introduced: Vec, + pub differences: Vec, + pub audit: AuditState, + /// Advisories CoderHelm held that were withdrawn: dropped. + pub withdrawn: usize, + /// Ids that were aliases of an advisory already counted. + pub aliases: usize, +} + +/// What [`reconcile`] reads. +#[derive(Debug, Clone, Default)] +pub struct Input<'a> { + pub sha: &'a str, + pub lockfile: &'a str, + pub held: &'a [Held], + /// The copies the base branch's lockfile and the head's install. + pub base: &'a [(String, String)], + pub head: &'a [(String, String)], + /// The package manager's audit of the head; `None` when none ran. + pub audit: Option<&'a Listings>, + /// Why no audit ran, when none did. + pub no_audit: &'a str, + /// Advisory ids the repository's audit configuration ignores. + pub ignored: &'a [String], + /// Packages the manifest overrides. + pub overrides: &'a [String], + /// Why a finding stays, by finding id (a deferral's reason). + pub stays: &'a [(String, String)], +} + +fn versions_of<'a>(copies: &'a [(String, String)], package: &str) -> Vec<&'a str> { + let mut v: Vec<&str> = copies + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(package)) + .map(|(_, v)| v.as_str()) + .collect(); + v.sort_by(|a, b| compare_versions(a, b)); + v.dedup(); + v +} + +fn key(id: &str, package: &str) -> (String, String) { + (id.to_ascii_uppercase(), package.to_ascii_lowercase()) +} + +/// Counts the advisories of a head once (see the module notes). +pub fn reconcile(i: &Input<'_>) -> Reconciled { + let mut out = Reconciled { + sha: i.sha.to_string(), + lockfile: i.lockfile.to_string(), + ..Default::default() + }; + // One id per advisory: aliases collapse. + let mut records: Vec> = i.held.iter().map(|h| h.ids.clone()).collect(); + let listed: Vec<&Listed> = i + .audit + .into_iter() + .flat_map(|a| a.production.iter().chain(a.all.iter())) + .flat_map(|l| l.listed.iter()) + .collect(); + records.extend(listed.iter().map(|l| vec![l.id.clone()])); + let canon: BTreeMap = clusters(&records) + .into_iter() + .flat_map(|c| { + let p = primary_id(&c); + c.into_iter().map(move |id| (id, p.clone())) + }) + .collect(); + let canonical = |id: &str| -> String { + let u = id.trim().to_ascii_uppercase(); + canon.get(&u).cloned().unwrap_or(u) + }; + // CoderHelm's own read, base and head the same way. + type Seen = BTreeMap<(String, String), (Vec, Vec, usize)>; + let mut own: Seen = BTreeMap::new(); + let mut counted: BTreeSet<(String, String)> = BTreeSet::new(); + for (n, h) in i.held.iter().enumerate() { + if h.withdrawn { + out.withdrawn += 1; + continue; + } + let k = key(&canonical(&h.id), &h.package); + if !counted.insert(k.clone()) { + out.aliases += 1; + } + let hit = |copies: &[(String, String)]| -> Vec { + versions_of(copies, &h.package) + .into_iter() + .filter(|v| h.affects(v)) + .map(String::from) + .collect() + }; + let (b, hd) = (hit(i.base), hit(i.head)); + // A finding recorded for a version neither lockfile installs. + let recorded_installed = versions_of(i.base, &h.package) + .iter() + .any(|v| compare_versions(v, &h.recorded) == Ordering::Equal); + if b.is_empty() && hd.is_empty() && !recorded_installed && !h.recorded.is_empty() { + let installed = versions_of(i.head, &h.package); + let overridden = i + .overrides + .iter() + .any(|o| o.eq_ignore_ascii_case(&h.package)); + let at = if installed.is_empty() { + "the lockfile does not install it".to_string() + } else { + format!("the lockfile installs {}", installed.join(", ")) + }; + out.differences.push(Difference { + id: h.id.clone(), + package: h.package.clone(), + cause: if overridden { + Cause::Override + } else { + Cause::StaleRecord + }, + text: if overridden { + format!( + "CoderHelm's finding was recorded for `{}` {}, and {at}: the manifest overrides the package, which the source of the finding does not read. Not counted.", + h.package, h.recorded + ) + } else { + format!( + "CoderHelm's finding was recorded for `{}` {}, and {at}: the record is behind the lockfile. Not counted.", + h.package, h.recorded + ) + }, + }); + continue; + } + let e = own.entry(k).or_insert((vec![], vec![], n)); + for v in b { + if !e.0.contains(&v) { + e.0.push(v); + } + } + for v in hd { + if !e.1.contains(&v) { + e.1.push(v); + } + } + } + // The audit of the head. + let (prod, all) = match i.audit { + Some(a) => (a.production.as_ref(), a.all.as_ref()), + None => (None, None), + }; + out.audit = AuditState { + production: prod.map(|l| l.shown.clone()).unwrap_or_default(), + all: all.map(|l| l.shown.clone()).unwrap_or_default(), + missing: match i.audit { + Some(a) => a.why.clone(), + None if i.no_audit.is_empty() => "no audit ran on this head".to_string(), + None => i.no_audit.to_string(), + }, + cut: prod.is_some_and(|l| l.cut()) || all.is_some_and(|l| l.cut()), + }; + let set_of = |l: Option<&crate::dep_audit::Listing>| -> BTreeMap<(String, String), String> { + l.into_iter() + .flat_map(|l| l.listed.iter()) + .map(|a| (key(&canonical(&a.id), &a.package), a.severity.clone())) + .collect() + }; + let (in_prod, in_all) = (set_of(prod), set_of(all)); + let audited = |k: &(String, String)| in_prod.contains_key(k) || in_all.contains_key(k); + let scope_of = |k: &(String, String), held: Option<&Held>| -> Where { + if in_prod.contains_key(k) { + Where::Production + } else if in_all.contains_key(k) && prod.is_some() { + Where::Development + } else { + match held.map(|h| h.scope) { + Some(Scope::Runtime) => Where::Production, + Some(Scope::Dev) => Where::Development, + _ => Where::NotKnown, + } + } + }; + let touched = |package: &str| versions_of(i.base, package) != versions_of(i.head, package); + let why_stays = |h: &Held, moved: bool| -> String { + if let Some((_, why)) = i.stays.iter().find(|(id, _)| *id == h.finding) { + return why.clone(); + } + if h.fixed.is_empty() { + "no patched release exists".to_string() + } else if moved { + "this change moves the package and the version installed is still below the patched one" + .to_string() + } else { + "this change does not touch the package".to_string() + } + }; + // Whether the audit can speak for an advisory: its listing of every + // dependency was read whole. + let audit_complete = all.is_some_and(|l| !l.cut()); + for (k, (b, hd, n)) in &own { + let h = &i.held[*n]; + let entry = |versions: &[String], why: String| Entry { + id: h.id.clone(), + package: h.package.clone(), + severity: h.severity.clone(), + versions: versions.to_vec(), + scope: scope_of(k, Some(h)), + touched: touched(&h.package), + why, + }; + match (b.is_empty(), hd.is_empty()) { + (true, true) => {} + (false, true) => { + if audited(k) { + // CoderHelm's ranges say fixed; the audit still lists it. + out.differences.push(Difference { + id: h.id.clone(), + package: h.package.clone(), + cause: Cause::RangeDiffers, + text: format!( + "`{}` lists `{}` for {} on the head, and by the ranges CoderHelm holds the versions installed there ({}) are patched. Counted as remaining until the two agree.", + if in_prod.contains_key(k) { &out.audit.production } else { &out.audit.all }, + h.package, + h.id, + versions_of(i.head, &h.package).join(", ") + ), + }); + let head_versions: Vec = versions_of(i.head, &h.package) + .into_iter() + .map(String::from) + .collect(); + out.remaining.push(entry( + &head_versions, + "the package manager's audit still lists it on the head".to_string(), + )); + } else { + out.fixed.push(entry(b, String::new())); + } + } + (_, false) => { + if audit_complete && !audited(k) { + let ignored = h + .ids + .iter() + .any(|id| i.ignored.iter().any(|g| g.eq_ignore_ascii_case(id))); + out.differences.push(Difference { + id: h.id.clone(), + package: h.package.clone(), + cause: if ignored { Cause::Ignored } else { Cause::NotInAudit }, + text: if ignored { + format!( + "`{}` does not list {} in `{}` because the repository's audit configuration ignores it. CoderHelm counts it.", + out.audit.all, h.id, h.package + ) + } else { + format!( + "CoderHelm holds {} for `{}` {} (from {}), and `{}` does not list it. CoderHelm counts it; the registry's audit does not serve every advisory.", + h.id, + h.package, + hd.join(", "), + if h.source.is_empty() { "its advisory sources" } else { &h.source }, + out.audit.all + ) + }, + }); + } + let e = entry(hd, why_stays(h, touched(&h.package))); + if b.is_empty() { + out.introduced.push(Entry { + why: String::new(), + ..e + }); + } else { + out.remaining.push(e); + } + } + } + } + // What only the audit names. + let mut audit_only: BTreeMap<(String, String), String> = in_all.clone(); + for (k, sev) in &in_prod { + audit_only.entry(k.clone()).or_insert_with(|| sev.clone()); + } + for (k, sev) in audit_only { + if own.contains_key(&k) { + continue; + } + let listed_as = listed + .iter() + .find(|l| key(&canonical(&l.id), &l.package) == k) + .map(|l| (canonical(&l.id), l.package.clone())) + .unwrap_or((k.0.clone(), k.1.clone())); + let (id, package) = listed_as; + let head_versions: Vec = versions_of(i.head, &package) + .into_iter() + .map(String::from) + .collect(); + let base_versions = versions_of(i.base, &package); + // New on the head: every copy the head has is one the base lacks. + let new_here = !head_versions.is_empty() + && head_versions + .iter() + .all(|v| !base_versions.iter().any(|b| b == v)); + let scope = scope_of(&k, None); + out.differences.push(Difference { + id: id.clone(), + package: package.clone(), + cause: Cause::NotHeld, + text: format!( + "`{}` lists {id} in `{package}`, which CoderHelm did not hold. Taken in and counted as {}.", + if in_prod.contains_key(&k) { &out.audit.production } else { &out.audit.all }, + if new_here { "introduced by this change" } else { "remaining" } + ), + }); + let e = Entry { + id, + touched: touched(&package), + package, + severity: sev, + versions: head_versions, + scope, + why: if new_here { + String::new() + } else { + "this change does not touch the package".to_string() + }, + }; + if new_here { + out.introduced.push(e); + } else { + out.remaining.push(e); + } + } + // What the production audit leaves out is development only: said once. + if prod.is_some() { + for e in out.remaining.iter().chain(out.introduced.iter()) { + if e.scope == Where::Development { + out.differences.push(Difference { + id: e.id.clone(), + package: e.package.clone(), + cause: Cause::DevelopmentOnly, + text: format!( + "`{}` lists {} in `{}` and `{}` does not: it is installed for development only.", + out.audit.all, e.id, e.package, out.audit.production + ), + }); + } + } + } + let order = |a: &Entry, b: &Entry| { + (rank(&b.severity), &a.package, &a.id).cmp(&(rank(&a.severity), &b.package, &b.id)) + }; + out.fixed.sort_by(order); + out.remaining.sort_by(order); + out.introduced.sort_by(order); + out.differences + .sort_by(|a, b| (a.cause, &a.package, &a.id).cmp(&(b.cause, &b.package, &b.id))); + out +} + +/// The package an override's key is for: its parent chain and its version +/// selector are dropped (`web-kit>glob-walk@2` and `**/glob-walk` are +/// `glob-walk`, `@scope/kit@1` is `@scope/kit`). +fn override_name(key: &str) -> &str { + let last = key.rsplit('>').next().unwrap_or(key).trim(); + let last = last.trim_start_matches("**/"); + let last = match last.rfind("/@") { + Some(i) => &last[i + 1..], + None if last.starts_with('@') => last, + None => last.rsplit('/').next().unwrap_or(last), + }; + match last.strip_prefix('@') { + Some(rest) => match rest.find('@') { + Some(i) => &last[..i + 1], + None => last, + }, + None => last.split('@').next().unwrap_or(last), + } +} + +fn override_names(table: &serde_json::Value, out: &mut Vec) { + let Some(map) = table.as_object() else { + return; + }; + for (key, value) in map { + let name = override_name(key); + if !name.is_empty() && name != "." { + out.push(name.to_string()); + } + // npm nests a parent's children under it. + override_names(value, out); + } +} + +/// The packages a JavaScript manifest overrides (`overrides`, +/// `pnpm.overrides`, `resolutions`), by name, sorted. +pub fn overrides_of(manifest: &str) -> Vec { + let Ok(v) = serde_json::from_str::(manifest) else { + return vec![]; + }; + let mut out: Vec = vec![]; + for table in [&v["overrides"], &v["pnpm"]["overrides"], &v["resolutions"]] { + override_names(table, &mut out); + } + out.sort(); + out.dedup(); + out +} + +/// The advisory ids a repository's audit configuration ignores: pnpm's +/// `auditConfig.ignoreGhsas` and `ignoreCves` in the manifest, and +/// `audit.ignore` in `pnpm-workspace.yaml`. +pub fn ignored_of(manifest: &str, workspace_yaml: &str) -> Vec { + let mut out: Vec = vec![]; + let mut add = |id: &str| { + let id = id.trim().to_string(); + if !id.is_empty() && !out.contains(&id) { + out.push(id); + } + }; + if let Ok(v) = serde_json::from_str::(manifest) { + for key in ["ignoreGhsas", "ignoreCves"] { + for id in v["pnpm"]["auditConfig"][key] + .as_array() + .into_iter() + .flatten() + .filter_map(|x| x.as_str()) + { + add(id); + } + } + } + if let Ok(y) = serde_yaml::from_str::(workspace_yaml) { + for key in ["audit", "auditConfig"] { + for list in ["ignore", "ignoreGhsas", "ignoreCves"] { + for id in y[key][list] + .as_sequence() + .into_iter() + .flatten() + .filter_map(|x| x.as_str()) + { + add(id); + } + } + } + } + out +} + +fn rank(severity: &str) -> u8 { + match severity { + "critical" => 4, + "high" => 3, + "moderate" | "medium" => 2, + "low" => 1, + _ => 0, + } +} + +fn plural(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +impl Reconciled { + /// How many remaining advisories are in production, development only, + /// or not known. + pub fn remaining_by_scope(&self) -> (usize, usize, usize) { + let n = |w: Where| self.remaining.iter().filter(|e| e.scope == w).count(); + ( + n(Where::Production), + n(Where::Development), + n(Where::NotKnown), + ) + } + + /// The count in one sentence, with what it was read from. + pub fn headline(&self) -> String { + let sha = &self.sha[..self.sha.len().min(7)]; + let from = if self.audit.all.is_empty() && self.audit.production.is_empty() { + format!( + "from the advisories CoderHelm holds against `{}` only ({}; the package manager's audit is not part of this count)", + self.lockfile, self.audit.missing + ) + } else { + let audits: Vec = [&self.audit.production, &self.audit.all] + .into_iter() + .filter(|a| !a.is_empty()) + .map(|a| format!("`{a}`")) + .collect(); + format!( + "from the advisories CoderHelm holds against `{}`, compared with {}", + self.lockfile, + audits.join(" and ") + ) + }; + let (p, d, u) = self.remaining_by_scope(); + let mut parts: Vec = vec![]; + if p > 0 { + parts.push(format!("{p} in production")); + } + if d > 0 { + parts.push(format!("{d} development only")); + } + if u > 0 { + parts.push(format!("{u} not known which")); + } + format!( + "Advisories on commit `{sha}`, the base branch and the head read the same way ({from}): {} fixed, {} remaining{}, {} introduced.", + self.fixed.len(), + self.remaining.len(), + if parts.is_empty() { + String::new() + } else { + format!(" ({})", parts.join(", ")) + }, + self.introduced.len() + ) + } + + /// The count as the pull request states it. + pub fn section(&self) -> String { + let mut s = format!("**{}**\n", self.headline()); + let line = |e: &Entry, with_why: bool| { + format!( + "- {}{} in `{}`{} ({}; {}){}\n", + e.id, + if e.severity.is_empty() { + String::new() + } else { + format!(" ({})", e.severity) + }, + e.package, + if e.versions.is_empty() { + String::new() + } else { + format!(" {}", e.versions.join(", ")) + }, + e.scope.words(), + if e.touched { + "this change moves the package" + } else { + "this change does not touch the package" + }, + if with_why && !e.why.is_empty() { + format!(": {}", e.why) + } else { + String::new() + } + ) + }; + if !self.remaining.is_empty() { + s.push_str("Remaining:\n"); + for e in self.remaining.iter().take(25) { + s.push_str(&line(e, true)); + } + if self.remaining.len() > 25 { + s.push_str(&format!("- and {} more\n", self.remaining.len() - 25)); + } + } + if !self.introduced.is_empty() { + s.push_str("Introduced by this change:\n"); + for e in self.introduced.iter().take(15) { + s.push_str(&line(e, false)); + } + } + if !self.differences.is_empty() { + s.push_str(&format!( + "Where CoderHelm's read and the package manager's audit differ ({}), each with its cause:\n", + plural(self.differences.len(), "advisory", "advisories") + )); + for d in self.differences.iter().take(15) { + s.push_str(&format!("- {}\n", d.text)); + } + if self.differences.len() > 15 { + s.push_str(&format!("- and {} more\n", self.differences.len() - 15)); + } + } + if self.audit.cut { + s.push_str("- The audit listed more advisories than the sandbox's output carries; the ones not carried are not part of the comparison.\n"); + } + if !self.audit.missing.is_empty() + && !(self.audit.all.is_empty() && self.audit.production.is_empty()) + { + s.push_str(&format!("- Not read: {}.\n", self.audit.missing)); + } + if self.withdrawn > 0 || self.aliases > 0 { + s.push_str(&format!( + "- Left out of the count: {} withdrawn, {} that {} another id of an advisory already counted.\n", + plural(self.withdrawn, "advisory", "advisories"), + self.aliases, + if self.aliases == 1 { "is" } else { "are" } + )); + } + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dep_audit::Listing; + + fn copies(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + pairs + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect() + } + + fn held(id: &str, package: &str, recorded: &str, fixed: &str) -> Held { + Held { + id: id.into(), + ids: vec![id.into()], + package: package.into(), + severity: "high".into(), + fixed: if fixed.is_empty() { + vec![] + } else { + vec![fixed.into()] + }, + recorded: recorded.into(), + source: "dependabot".into(), + finding: format!("f-{id}"), + ..Default::default() + } + } + + fn listing(shown: &str, items: &[(&str, &str, &str)]) -> Listing { + Listing { + shown: shown.into(), + total: items.len(), + listed: items + .iter() + .map(|(id, sev, pkg)| Listed { + id: id.to_string(), + severity: sev.to_string(), + package: pkg.to_string(), + }) + .collect(), + } + } + + fn audit(prod: &[(&str, &str, &str)], all: &[(&str, &str, &str)]) -> Listings { + Listings { + production: Some(listing("pnpm audit --prod --json", prod)), + all: Some(listing("pnpm audit --json", all)), + why: String::new(), + } + } + + #[test] + fn base_and_head_are_read_the_same_way() { + let h = [ + held("GHSA-1111-1111-1111", "body-kit", "1.2.0", "1.2.9"), + held("GHSA-2222-2222-2222", "left-pad-x", "3.0.0", "3.0.4"), + ]; + let base = copies(&[("body-kit", "1.2.0"), ("left-pad-x", "3.0.0")]); + let head = copies(&[("body-kit", "1.2.9"), ("left-pad-x", "3.0.0")]); + let a = audit( + &[("GHSA-2222-2222-2222", "high", "left-pad-x")], + &[("GHSA-2222-2222-2222", "high", "left-pad-x")], + ); + let r = reconcile(&Input { + sha: "abcdef1234", + lockfile: "pnpm-lock.yaml", + held: &h, + base: &base, + head: &head, + audit: Some(&a), + ..Default::default() + }); + assert_eq!(r.fixed.len(), 1); + assert_eq!(r.fixed[0].package, "body-kit"); + assert_eq!(r.remaining.len(), 1); + let left = &r.remaining[0]; + assert_eq!(left.package, "left-pad-x"); + assert_eq!(left.scope, Where::Production); + assert!(!left.touched); + assert_eq!(left.why, "this change does not touch the package"); + // The two agree: nothing to explain. + assert!(r.differences.is_empty()); + assert_eq!( + r.headline(), + "Advisories on commit `abcdef1`, the base branch and the head read the same way (from the advisories CoderHelm holds against `pnpm-lock.yaml`, compared with `pnpm audit --prod --json` and `pnpm audit --json`): 1 fixed, 1 remaining (1 in production), 0 introduced." + ); + } + + #[test] + fn the_review_case_fewer_in_production_and_none_in_a_touched_package() { + // CoderHelm's findings said three high advisories were left. One is + // recorded for a version an override never installs, one sits in a + // development tool, one is in a production package the change does + // not touch. + let h = [ + held("GHSA-AAAA-AAAA-AAAA", "glob-walk", "2.3.1", "2.3.9"), + held("GHSA-BBBB-BBBB-BBBB", "lint-kit", "8.0.0", "9.0.0"), + held("GHSA-CCCC-CCCC-CCCC", "xml-read", "1.1.0", ""), + ]; + let base = copies(&[ + ("glob-walk", "2.4.0"), + ("lint-kit", "8.0.0"), + ("xml-read", "1.1.0"), + ]); + let head = base.clone(); + let a = audit( + &[("GHSA-CCCC-CCCC-CCCC", "high", "xml-read")], + &[ + ("GHSA-CCCC-CCCC-CCCC", "high", "xml-read"), + ("GHSA-BBBB-BBBB-BBBB", "high", "lint-kit"), + ], + ); + let overrides = vec!["glob-walk".to_string()]; + let r = reconcile(&Input { + sha: "abcdef1", + lockfile: "pnpm-lock.yaml", + held: &h, + base: &base, + head: &head, + audit: Some(&a), + overrides: &overrides, + ..Default::default() + }); + assert_eq!(r.remaining.len(), 2); + assert_eq!(r.remaining_by_scope(), (1, 1, 0)); + assert!(r.remaining.iter().all(|e| !e.touched)); + let xml = r + .remaining + .iter() + .find(|e| e.package == "xml-read") + .unwrap(); + assert_eq!(xml.why, "no patched release exists"); + // Each disagreement has its cause. + let causes: Vec = r.differences.iter().map(|d| d.cause).collect(); + assert_eq!(causes, vec![Cause::Override, Cause::DevelopmentOnly]); + assert!(r.differences[0].text.contains( + "recorded for `glob-walk` 2.3.1, and the lockfile installs 2.4.0: the manifest overrides the package" + )); + assert!(r.differences[1] + .text + .contains("it is installed for development only")); + let text = r.section(); + assert!(text.contains("2 remaining (1 in production, 1 development only)")); + assert!(text.contains( + "- GHSA-CCCC-CCCC-CCCC (high) in `xml-read` 1.1.0 (production; this change does not touch the package): no patched release exists" + )); + } + + #[test] + fn each_disagreement_is_settled_or_shown_with_its_cause() { + let h = [ + // Held, and the audit does not list it. + held("OSV-2026-77", "odd-parser", "0.4.0", "0.5.0"), + // Held, ignored by the repository's audit configuration. + held("GHSA-DDDD-DDDD-DDDD", "old-tool", "1.0.0", "2.0.0"), + // CoderHelm's range says patched; the audit still lists it. + Held { + ranges: vec![">= 4.0.0, < 4.2.0".into()], + ..held("GHSA-EEEE-EEEE-EEEE", "net-kit", "4.1.0", "4.2.0") + }, + // Recorded for a version the lockfile never had, no override. + held("GHSA-FFFF-FFFF-FFFF", "ghost", "0.1.0", "0.1.5"), + ]; + let base = copies(&[ + ("odd-parser", "0.4.0"), + ("old-tool", "1.0.0"), + ("net-kit", "4.1.0"), + ("ghost", "0.2.0"), + ("fresh", "1.0.0"), + ("quiet", "7.0.0"), + ]); + let head = copies(&[ + ("odd-parser", "0.4.0"), + ("old-tool", "1.0.0"), + ("net-kit", "4.2.0"), + ("ghost", "0.2.0"), + ("fresh", "2.0.0"), + ("quiet", "7.0.0"), + ]); + let a = audit( + &[ + ("GHSA-EEEE-EEEE-EEEE", "high", "net-kit"), + // In a version this change brought in: introduced. + ("GHSA-9999-9999-9999", "critical", "fresh"), + // There before, never held: taken in as remaining. + ("GHSA-8888-8888-8888", "low", "quiet"), + ], + &[ + ("GHSA-EEEE-EEEE-EEEE", "high", "net-kit"), + ("GHSA-9999-9999-9999", "critical", "fresh"), + ("GHSA-8888-8888-8888", "low", "quiet"), + ], + ); + let ignored = vec!["GHSA-dddd-dddd-dddd".to_string()]; + let r = reconcile(&Input { + sha: "abc", + lockfile: "pnpm-lock.yaml", + held: &h, + base: &base, + head: &head, + audit: Some(&a), + ignored: &ignored, + ..Default::default() + }); + let cause_of = |pkg: &str| -> Vec { + r.differences + .iter() + .filter(|d| d.package == pkg) + .map(|d| d.cause) + .collect() + }; + assert_eq!(cause_of("odd-parser"), vec![Cause::NotInAudit]); + assert_eq!(cause_of("old-tool"), vec![Cause::Ignored]); + assert_eq!(cause_of("net-kit"), vec![Cause::RangeDiffers]); + assert_eq!(cause_of("ghost"), vec![Cause::StaleRecord]); + assert_eq!(cause_of("fresh"), vec![Cause::NotHeld]); + assert_eq!(cause_of("quiet"), vec![Cause::NotHeld]); + // Nothing is silently one number: what the audit names and + // CoderHelm did not hold is counted, what the audit still lists is + // not called fixed, and the stale record is not counted at all. + assert!(r.fixed.is_empty()); + let names = |v: &[Entry]| -> Vec { v.iter().map(|e| e.package.clone()).collect() }; + assert_eq!(names(&r.introduced), vec!["fresh"]); + assert_eq!( + names(&r.remaining), + vec!["net-kit", "odd-parser", "old-tool", "quiet"] + ); + assert!(r + .section() + .contains("Where CoderHelm's read and the package manager's audit differ (6 advisories), each with its cause:")); + } + + #[test] + fn withdrawn_advisories_are_dropped_and_aliases_count_once() { + let h = [ + Held { + withdrawn: true, + ..held("GHSA-1111-2222-3333", "pkg-a", "1.0.0", "1.0.1") + }, + Held { + ids: vec!["CVE-2026-0001".into(), "GHSA-4444-5555-6666".into()], + ..held("CVE-2026-0001", "pkg-b", "2.0.0", "2.0.3") + }, + // The same advisory under its other id, from another source. + held("GHSA-4444-5555-6666", "pkg-b", "2.0.0", "2.0.3"), + ]; + let base = copies(&[("pkg-a", "1.0.0"), ("pkg-b", "2.0.0")]); + let a = audit( + &[("GHSA-4444-5555-6666", "high", "pkg-b")], + &[("GHSA-4444-5555-6666", "high", "pkg-b")], + ); + let r = reconcile(&Input { + sha: "abc", + lockfile: "package-lock.json", + held: &h, + base: &base, + head: &base, + audit: Some(&a), + ..Default::default() + }); + assert_eq!((r.withdrawn, r.aliases), (1, 1)); + assert_eq!(r.remaining.len(), 1); + // The audit's GHSA id is the held CVE's alias: they agree. + assert!(r.differences.is_empty()); + assert!(r.section().contains( + "Left out of the count: 1 advisory withdrawn, 1 that is another id of an advisory already counted." + )); + // A finding whose advisory was withdrawn is read as withdrawn. + let f = Finding { + status: Status::Withdrawn, + ..Default::default() + }; + assert!(Held::of(&f, &FindingState::default()).withdrawn); + } + + #[test] + fn without_an_audit_the_numbers_are_said_to_be_coderhelms_own() { + let h = [held("GHSA-1111-1111-1111", "body-kit", "1.2.0", "1.2.9")]; + let base = copies(&[("body-kit", "1.2.0")]); + let r = reconcile(&Input { + sha: "abcdef1", + lockfile: "poetry.lock", + held: &h, + base: &base, + head: &base, + no_audit: "CoderHelm has no production-scoped audit for poetry", + ..Default::default() + }); + assert_eq!(r.remaining.len(), 1); + assert_eq!(r.remaining[0].scope, Where::NotKnown); + // Never a disagreement invented from an audit that did not run. + assert!(r.differences.is_empty()); + assert!(r.headline().contains( + "from the advisories CoderHelm holds against `poetry.lock` only (CoderHelm has no production-scoped audit for poetry; the package manager's audit is not part of this count)" + )); + // A listing cut short can't speak for what it does not carry. + let mut a = audit(&[], &[]); + a.all.as_mut().unwrap().total = 60; + let r = reconcile(&Input { + sha: "abc", + lockfile: "pnpm-lock.yaml", + held: &h, + base: &base, + head: &base, + audit: Some(&a), + ..Default::default() + }); + assert!(r.differences.is_empty()); + assert!(r.audit.cut); + } + + #[test] + fn a_version_is_judged_by_the_range_or_the_patched_version_of_its_line() { + let h = Held { + fixed: vec!["1.2.5".into(), "2.0.3".into()], + ..held("X", "p", "1.0.0", "") + }; + assert!(h.affects("1.1.0")); + assert!(!h.affects("1.2.5")); + assert!(h.affects("2.0.1")); + assert!(!h.affects("2.0.4")); + assert!(!h.affects("3.0.0")); + assert!(h.affects("0.9.0")); + let ranged = Held { + ranges: vec![">= 2.0.0, < 2.0.3".into()], + ..h.clone() + }; + assert!(!ranged.affects("1.1.0")); + assert!(ranged.affects("2.0.2")); + // Neither a range nor a patched version: only the recorded one. + let bare = held("Y", "p", "1.0.0", ""); + assert!(bare.affects("1.0.0")); + assert!(!bare.affects("1.0.1")); + } + + #[test] + fn overrides_and_ignores_are_read_from_the_repository() { + let manifest = r#"{ + "overrides": {"glob-walk@2": "^2.3.9", "web-kit": {"upload-kit": "2.0.2"}}, + "pnpm": { + "overrides": {"web-kit>path-match@3": "^3.1.4", "@scope/kit@1": "1.2.3", "@scope/plain": "2.0.0"}, + "auditConfig": {"ignoreGhsas": ["GHSA-aaaa-bbbb-cccc"], "ignoreCves": ["CVE-2026-1"]} + }, + "resolutions": {"**/deep-kit": "1.0.1"} + }"#; + assert_eq!( + overrides_of(manifest), + vec![ + "@scope/kit", + "@scope/plain", + "deep-kit", + "glob-walk", + "path-match", + "upload-kit", + "web-kit" + ] + ); + assert!(overrides_of("not json").is_empty()); + assert_eq!( + ignored_of(manifest, "audit:\n ignore:\n - GHSA-dddd-eeee-ffff\n"), + vec!["GHSA-aaaa-bbbb-cccc", "CVE-2026-1", "GHSA-dddd-eeee-ffff"] + ); + } +} diff --git a/services/common/src/upgrade_quality/behaviour.rs b/services/common/src/upgrade_quality/behaviour.rs new file mode 100644 index 000000000..38b063e66 --- /dev/null +++ b/services/common/src/upgrade_quality/behaviour.rs @@ -0,0 +1,1051 @@ +//! Behaviour changes of a major bump are found, never assumed. +//! +//! A dependency pull request said "contract unchanged". A validation +//! library's major had changed the text and the shape of the 400 error +//! bodies of two endpoints. The type check passed, as it does on such a +//! change: the signatures were the same and the answers were not. +//! +//! For a major whose package the repository calls: +//! +//! - [`used_breaking`] takes the breaking changes of its release notes +//! that name an API the repository calls (`upgrade_notes` read both). +//! - [`plan`] finds the requests that go through those call sites: the +//! routes declared in the files that call the package ([`routes`], one +//! table of route syntaxes), each asked the way that reaches the error +//! paths a major changes: an empty body, a malformed one, and for an +//! upload a small file and one over the size limit. +//! - The runtime proof sends each request to the application built from +//! the base branch and from the head (`runtime_proof`, twice each, so an +//! answer that varies by itself is known). [`compare`] sets the answers +//! side by side: status, content type and body. +//! - A difference is a known behaviour change, recorded with the request +//! that shows it and the other repositories of the team that name the +//! endpoint. +//! - [`Behaviour::unchanged_shown`] is the only thing that lets the word +//! "unchanged" stand: every request answered the same on both builds, +//! and at least one reached the code. [`guard`] takes the sentence out of +//! any text that says it without that, and the section then says what +//! was and was not checked. +//! +//! Everything here is pure; the requests are sent by the worker's runtime +//! proof. + +use std::sync::LazyLock; + +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use crate::runtime_proof::{ProbeAnswer, ProbeRequest}; +use crate::upgrade_notes::PackageNotes; + +/// Requests one proof sends at most: the sandbox keeps only the end of a +/// build's output. +pub const MAX_PROBES: usize = 6; +/// The upload size sent to reach a size limit the code does not state. +const DEFAULT_LIMIT: u64 = 16 * 1024 * 1024; +/// The largest upload a probe sends. +const MAX_UPLOAD: u64 = 64 * 1024 * 1024; + +/// A route a file declares. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Route { + pub method: String, + pub path: String, + pub file: String, + /// The file takes uploads. + pub upload: bool, + /// The form field an upload is read from. + pub field: String, + /// The size limit the file states, in bytes. + pub limit: Option, +} + +/// How routes are written. One row per syntax; the first group is the +/// method (or empty for a row whose method is in the third), the second +/// the path. +struct Syntax { + re: &'static LazyLock, + /// A prefix every route of the file gets, when the file declares one. + prefix: Option<&'static LazyLock>, +} + +static DECORATOR: LazyLock = LazyLock::new(|| { + Regex::new(r#"@(Get|Post|Put|Patch)(?:Mapping)?\(\s*(?:value\s*=\s*)?(?:['"]([^'"]*)['"])?"#) + .unwrap() +}); +static DECORATOR_PREFIX: LazyLock = LazyLock::new(|| { + Regex::new(r#"@(?:Controller|RequestMapping)\(\s*(?:value\s*=\s*)?['"]([^'"]*)['"]"#).unwrap() +}); +static CALL: LazyLock = LazyLock::new(|| { + Regex::new(r#"(?i)\b[A-Za-z_]\w*\.(get|post|put|patch)\(\s*['"`](/[^'"`\s]*)['"`]"#).unwrap() +}); +static ROUTE_CALL: LazyLock = LazyLock::new(|| { + Regex::new( + r#"\.route\(\s*['"](/[^'"\s]*)['"](?:[^)\n]*methods\s*=\s*\[\s*['"]([A-Za-z]+)['"])?"#, + ) + .unwrap() +}); +static UPLOAD_FIELD: LazyLock = LazyLock::new(|| { + Regex::new(r#"(?:single|FileInterceptor|FormFile|array)\(\s*['"](\w+)['"]"#).unwrap() +}); +static LIMIT_PRODUCT: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)(?:fileSize|max_?(?:file_?|upload_?|content_?)?(?:size|length)|limit)\s*[:=]\s*([0-9][0-9_ *]*)") + .unwrap() +}); +static LIMIT_WORD: LazyLock = + LazyLock::new(|| Regex::new(r#"(?i)['"](\d+)\s*(kb|mb)['"]"#).unwrap()); + +const SYNTAXES: &[Syntax] = &[ + // `@Post('upload')` under `@Controller('files')`, `@PostMapping("/x")`. + Syntax { + re: &DECORATOR, + prefix: Some(&DECORATOR_PREFIX), + }, + // `app.post('/x', ...)`, `router.GET("/x", ...)`, `@app.get("/x")`. + Syntax { + re: &CALL, + prefix: None, + }, +]; + +/// Words that say a file takes uploads. +const UPLOAD_SIGNS: &[&str] = &[ + "multipart", + "fileinterceptor", + "uploadfile", + "formfile", + "upload.single", + "upload.array", + "uploadedfile", +]; + +/// A path with its parameters filled in (`/files/:id` is `/files/1`). +fn concrete(path: &str) -> String { + let mut out: Vec = vec![]; + for seg in path.split('/').filter(|s| !s.is_empty()) { + let param = seg.starts_with(':') + || (seg.starts_with('{') && seg.ends_with('}')) + || (seg.starts_with('<') && seg.ends_with('>')); + out.push(if param { + "1".to_string() + } else if seg == "*" { + "x".to_string() + } else { + seg.to_string() + }); + } + format!("/{}", out.join("/")) +} + +/// A path a shell command and a URL can carry as it is. +fn plain_path(p: &str) -> bool { + p.starts_with('/') + && p.len() <= 120 + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '-' | '.' | '~')) +} + +fn limit_of(text: &str) -> Option { + if let Some(c) = LIMIT_PRODUCT.captures(text) { + let product: Option = c[1] + .split('*') + .map(|n| n.replace(['_', ' '], "").parse::().ok()) + .try_fold(1u64, |acc, n| n.and_then(|n| acc.checked_mul(n))); + if let Some(p) = product.filter(|p| *p >= 1024) { + return Some(p); + } + } + LIMIT_WORD.captures(text).and_then(|c| { + let n: u64 = c[1].parse().ok()?; + Some(match c[2].to_ascii_lowercase().as_str() { + "kb" => n * 1024, + _ => n * 1024 * 1024, + }) + }) +} + +/// The routes `text` declares, in the order it declares them. Routes that +/// remove something are never probed, so they are not read. +pub fn routes(file: &str, text: &str) -> Vec { + let lower = text.to_ascii_lowercase(); + let upload = UPLOAD_SIGNS.iter().any(|s| lower.contains(s)); + let field = UPLOAD_FIELD + .captures(text) + .map(|c| c[1].to_string()) + .unwrap_or_else(|| "file".to_string()); + let limit = limit_of(text); + let mut found: Vec<(usize, String, String)> = vec![]; + for syn in SYNTAXES { + let prefix = syn + .prefix + .and_then(|p| p.captures(text)) + .map(|c| c[1].to_string()) + .unwrap_or_default(); + for c in syn.re.captures_iter(text) { + let at = c.get(0).map(|m| m.start()).unwrap_or(0); + let method = c[1].to_ascii_uppercase(); + let path = c.get(2).map(|m| m.as_str()).unwrap_or(""); + found.push((at, method, concrete(&format!("{prefix}/{path}")))); + } + } + for c in ROUTE_CALL.captures_iter(text) { + let at = c.get(0).map(|m| m.start()).unwrap_or(0); + let method = c + .get(2) + .map(|m| m.as_str().to_ascii_uppercase()) + .unwrap_or_else(|| "GET".to_string()); + if matches!(method.as_str(), "GET" | "POST" | "PUT" | "PATCH") { + found.push((at, method, concrete(&c[1]))); + } + } + found.sort(); + let mut out: Vec = vec![]; + for (_, method, path) in found { + if !plain_path(&path) || out.iter().any(|r| r.method == method && r.path == path) { + continue; + } + out.push(Route { + method, + path, + file: file.to_string(), + upload, + field: field.clone(), + limit, + }); + } + out +} + +const BOUNDARY: &str = "coderhelmprobe"; + +/// The requests that exercise one route: as it is for a read; for a +/// write, the bodies that reach the paths a major changes. +pub fn requests_for(r: &Route) -> Vec { + let req = + |what: String, content_type: &str, body: String, pad_kb: u32, tail: &str| ProbeRequest { + method: r.method.clone(), + path: r.path.clone(), + content_type: content_type.to_string(), + body, + pad_kb, + tail: tail.to_string(), + what, + }; + if r.method == "GET" { + return vec![req("a plain request".into(), "", String::new(), 0, "")]; + } + if r.upload { + let head = format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{}\"; filename=\"probe.txt\"\r\nContent-Type: text/plain\r\n\r\nprobe", + r.field + ); + let tail = format!("\r\n--{BOUNDARY}--\r\n"); + let ct = format!("multipart/form-data; boundary={BOUNDARY}"); + let limit = r.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_UPLOAD); + let over_kb = (limit / 1024 + 64) as u32; + return vec![ + req( + format!("a small upload in the field `{}`", r.field), + &ct, + head.clone(), + 0, + &tail, + ), + req( + match r.limit { + Some(l) => format!( + "an upload over the size limit the file states ({} KiB)", + l / 1024 + ), + None => format!( + "an upload of {} MiB (the file states no size limit)", + over_kb / 1024 + ), + }, + &ct, + head, + over_kb, + &tail, + ), + ]; + } + vec![ + req( + "an empty JSON object (the validation error)".into(), + "application/json", + "{}".into(), + 0, + "", + ), + req( + "a malformed JSON body (the parser error)".into(), + "application/json", + "{\"probe\":".into(), + 0, + "", + ), + ] +} + +/// The breaking changes of a package's notes that name an API the +/// repository calls. +pub fn used_breaking(n: &PackageNotes) -> Vec { + let called: Vec<&str> = n + .call_sites + .iter() + .map(|c| c.api.trim_end_matches("()")) + .filter(|a| !a.is_empty()) + .collect(); + n.breaking + .iter() + .filter(|line| called.iter().any(|api| line.contains(api))) + .cloned() + .collect() +} + +/// What a proof probes for the majors of a run. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Planned { + pub requests: Vec, + /// Each probed package with its requests, by index. + pub of: Vec<(String, Vec)>, + /// Each major that is not probed, with why. + pub not_probed: Vec<(String, String)>, +} + +fn files_named(files: &[&str]) -> String { + let shown: Vec = files.iter().take(3).map(|f| format!("`{f}`")).collect(); + shown.join(", ") +} + +/// The requests for the majors among `notes`, through the files that call +/// them. `files`: those call-site files with their text. A major with no +/// call site, or none behind a route, is named as not probed with why. +pub fn plan(notes: &[PackageNotes], files: &[(String, String)]) -> Planned { + let mut out = Planned::default(); + let mut per: Vec<(String, Vec)> = vec![]; + for n in notes.iter().filter(|n| n.major) { + let mut sites: Vec<&str> = n.call_sites.iter().map(|c| c.file.as_str()).collect(); + sites.sort(); + sites.dedup(); + if sites.is_empty() { + out.not_probed.push(( + n.package.clone(), + if !n.read() { + format!( + "its release notes were not read ({}), so the APIs it changes are not known", + if n.missing.is_empty() { "none were found" } else { &n.missing } + ) + } else { + "no call of an API its notes name was found in the repository".to_string() + }, + )); + continue; + } + let mut reqs: Vec = vec![]; + for site in &sites { + let Some((_, text)) = files.iter().find(|(p, _)| p == site) else { + continue; + }; + for r in routes(site, text) { + for q in requests_for(&r) { + if !reqs + .iter() + .any(|x| x.method == q.method && x.path == q.path && x.what == q.what) + { + reqs.push(q); + } + } + } + } + if reqs.is_empty() { + out.not_probed.push(( + n.package.clone(), + format!( + "no route is declared in the files that call it ({}), so its callers are not behind a request CoderHelm can send; a job or a library function has no before-and-after probe here, and the repository's tests are the check", + files_named(&sites) + ), + )); + } else { + per.push((n.package.clone(), reqs)); + } + } + // One request of each package in turn, so a package with many routes + // never takes every place. + let mut round = 0; + while out.requests.len() < MAX_PROBES && per.iter().any(|(_, r)| r.len() > round) { + for (package, reqs) in &per { + if out.requests.len() >= MAX_PROBES { + break; + } + let Some(q) = reqs.get(round) else { + continue; + }; + let idx = out.requests.len(); + out.requests.push(q.clone()); + match out.of.iter_mut().find(|(p, _)| p == package) { + Some((_, v)) => v.push(idx), + None => out.of.push((package.clone(), vec![idx])), + } + } + round += 1; + } + out +} + +/// How one request's answers compare. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Same, + Changed, + /// A build gave no answer. + #[default] + NoAnswer, +} + +/// One request with its answers on the base branch's build and the head's. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Compared { + /// `POST /files/upload` + pub request: String, + pub what: String, + /// `413 application/json`, or empty for no answer. + pub base: String, + pub head: String, + pub outcome: Outcome, + /// What differs, in words. + pub detail: String, + /// Both answers came from the route (not a 401, 403 or 404). + pub reached: bool, + /// The same request was answered differently twice by one build, so + /// only its status and content type are compared. + pub varies: bool, +} + +fn answer_words(a: &ProbeAnswer) -> String { + if a.content_type.is_empty() || a.content_type == "-" { + a.status.to_string() + } else { + format!("{} {}", a.status, a.content_type) + } +} + +fn from_route(status: u16) -> bool { + !matches!(status, 0 | 401 | 403 | 404) +} + +/// The answers of the base branch's build and the head's, request by +/// request. +pub fn compare( + requests: &[ProbeRequest], + base: &[Option], + head: &[Option], +) -> Vec { + requests + .iter() + .enumerate() + .map(|(i, q)| { + let (b, h) = ( + base.get(i).and_then(Option::as_ref), + head.get(i).and_then(Option::as_ref), + ); + let mut c = Compared { + request: format!("{} {}", q.method, q.path), + what: q.what.clone(), + base: b.map(answer_words).unwrap_or_default(), + head: h.map(answer_words).unwrap_or_default(), + ..Default::default() + }; + let (Some(b), Some(h)) = (b, h) else { + c.detail = match (b, h) { + (None, None) => "neither build answered".to_string(), + (None, _) => "the base branch's build did not answer".to_string(), + _ => "the head's build did not answer".to_string(), + }; + return c; + }; + c.reached = from_route(b.status) && from_route(h.status); + c.varies = !b.stable || !h.stable; + let mut diffs: Vec = vec![]; + if b.status != h.status { + diffs.push(format!("status {} to {}", b.status, h.status)); + } + if b.content_type != h.content_type { + diffs.push(format!( + "content type `{}` to `{}`", + b.content_type, h.content_type + )); + } + if !c.varies && b.sha != h.sha { + diffs.push(format!( + "body before `{}`, after `{}`", + crate::truncate_str(&b.excerpt.replace('`', "'"), 120), + crate::truncate_str(&h.excerpt.replace('`', "'"), 120) + )); + } + c.outcome = if diffs.is_empty() { + Outcome::Same + } else { + Outcome::Changed + }; + c.detail = diffs.join("; "); + c + }) + .collect() +} + +/// What is known of one major's behaviour. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Behaviour { + pub package: String, + pub from: String, + pub to: String, + /// The breaking changes of its notes that name an API the repository + /// calls. + pub breaking_used: Vec, + pub compared: Vec, + /// Why no request was sent; empty when some were. + pub not_probed: String, + /// The team's other repositories that name an endpoint whose answer + /// changed. + pub consumers: Vec, + /// The repositories searched for them, in words; empty when none were. + pub consumers_searched: String, +} + +impl Behaviour { + /// The requests whose answers differ between the two builds. + pub fn changes(&self) -> Vec<&Compared> { + self.compared + .iter() + .filter(|c| c.outcome == Outcome::Changed) + .collect() + } + + /// Whether a probe shows its behaviour unchanged: every request was + /// answered by both builds, the same, and at least one answer came + /// from the route itself. + pub fn unchanged_shown(&self) -> bool { + !self.compared.is_empty() + && self.compared.iter().all(|c| c.outcome == Outcome::Same) + && self.compared.iter().any(|c| c.reached) + } + + /// The endpoint paths whose answers changed: what a consumer names. + pub fn changed_paths(&self) -> Vec { + let mut v: Vec = self + .changes() + .iter() + .filter_map(|c| c.request.split_whitespace().nth(1).map(String::from)) + .collect(); + v.sort(); + v.dedup(); + v + } + + /// What is known, as the pull request states it. + pub fn section(&self) -> String { + let mut s = format!("- `{}` {} to {}:\n", self.package, self.from, self.to); + for b in self.breaking_used.iter().take(5) { + s.push_str(&format!( + " - Its notes list a breaking change in an API this repository calls: {}\n", + crate::truncate_str(b, 240) + )); + } + if self.compared.is_empty() { + s.push_str(&format!( + " - Not probed: {}. Nothing here says its behaviour is the same as before.\n", + if self.not_probed.is_empty() { + "no request was sent" + } else { + &self.not_probed + } + )); + return s; + } + let changes = self.changes(); + let same = self + .compared + .iter() + .filter(|c| c.outcome == Outcome::Same) + .count(); + for c in &changes { + s.push_str(&format!( + " - Known behaviour change: `{}` ({}) answered {} on the base branch's build and {} on this head's: {}.\n", + c.request, + c.what, + if c.base.is_empty() { "nothing" } else { &c.base }, + if c.head.is_empty() { "nothing" } else { &c.head }, + c.detail + )); + } + if !changes.is_empty() { + s.push_str(&match (self.consumers.as_slice(), self.consumers_searched.is_empty()) { + ([], true) => " - Who could care: the team's other repositories were not searched for these endpoints.\n".to_string(), + ([], false) => format!( + " - Who could care: no other repository names these endpoints (searched {}).\n", + self.consumers_searched + ), + (found, _) => format!( + " - Who could care: {} name{} these endpoints.\n", + found + .iter() + .map(|r| format!("`{r}`")) + .collect::>() + .join(", "), + if found.len() == 1 { "s" } else { "" } + ), + }); + } + let silent: Vec<&Compared> = self + .compared + .iter() + .filter(|c| c.outcome == Outcome::NoAnswer) + .collect(); + for c in &silent { + s.push_str(&format!( + " - `{}` ({}): {}, so it shows nothing.\n", + c.request, c.what, c.detail + )); + } + if same > 0 { + let reached = self + .compared + .iter() + .filter(|c| c.outcome == Outcome::Same && c.reached) + .count(); + let list: Vec = self + .compared + .iter() + .filter(|c| c.outcome == Outcome::Same) + .map(|c| format!("`{}` ({}: {})", c.request, c.what, c.head)) + .collect(); + s.push_str(&format!( + " - Answered the same by both builds: {}.{}{}\n", + list.join(", "), + if reached == 0 { + " None of these answers came from the route itself (each was a 401, 403 or 404), so they show nothing about the package." + } else if reached < same { + " Some of these were answered before the route (a 401, 403 or 404) and show nothing about the package." + } else { + "" + }, + if self.compared.iter().any(|c| c.varies) { + " A request answered differently twice by one build is compared by status and content type only." + } else { + "" + } + )); + } + if self.unchanged_shown() { + s.push_str(&format!( + " - Unchanged on these {} request{}; nothing is claimed beyond them.\n", + self.compared.len(), + if self.compared.len() == 1 { "" } else { "s" } + )); + } + s + } +} + +/// What replaces a sentence that calls the behaviour unchanged with no +/// probe behind it. +pub const TAKEN_OUT: &str = "(CoderHelm took out a sentence here that called the contract or the behaviour unchanged: no probe or test recorded on this head shows that. This description lists what was checked; what it does not list was not.)"; + +static UNCHANGED: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)\b(unchanged|not changed|unaffected|remains? the same|stays? the same|identical|no (?:behaviou?r(?:al)?|contract|api|functional|breaking|runtime|observable)[a-z ]{0,20}changes?|does(?:n't| not) change|backwards?[- ]compatible|drop-in)\b", + ) + .unwrap() +}); +static SUBJECT: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)\b(contracts?|behaviou?rs?|responses?|apis?|endpoints?|error (?:bodies|body|messages?|shapes?)|interfaces?|outputs?|compatible|drop-in|semantics)\b", + ) + .unwrap() +}); + +/// `text` with every sentence that calls a contract or behaviour +/// unchanged taken out, unless a probe shows it (`shown`). The first one +/// leaves [`TAKEN_OUT`] in its place; the others leave nothing. +pub fn guard(text: &str, shown: bool) -> String { + if shown || !UNCHANGED.is_match(text) { + return text.to_string(); + } + let mut noted = false; + let mut out: Vec = vec![]; + for line in text.split('\n') { + if !(UNCHANGED.is_match(line) && SUBJECT.is_match(line)) { + out.push(line.to_string()); + continue; + } + // Sentence by sentence: the rest of the line stays. + let lead_len = line.len() - line.trim_start().len(); + let (lead, body) = line.split_at(lead_len); + let bullet = body + .strip_prefix("- ") + .or_else(|| body.strip_prefix("* ")) + .map(|rest| (&body[..2], rest)); + let (mark, body) = bullet.unwrap_or(("", body)); + let mut kept: Vec = vec![]; + for sentence in split_sentences(body) { + if UNCHANGED.is_match(&sentence) && SUBJECT.is_match(&sentence) { + if !noted { + kept.push(TAKEN_OUT.to_string()); + noted = true; + } + } else { + kept.push(sentence); + } + } + if !kept.is_empty() { + out.push(format!("{lead}{mark}{}", kept.join(" "))); + } + } + out.join("\n") +} + +/// A line's sentences, each with its final mark. +fn split_sentences(line: &str) -> Vec { + let mut out: Vec = vec![]; + let mut cur = String::new(); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + cur.push(c); + if matches!(c, '.' | '!' | '?') && chars.peek().is_none_or(|n| n.is_whitespace()) { + out.push(cur.trim().to_string()); + cur.clear(); + } + } + if !cur.trim().is_empty() { + out.push(cur.trim().to_string()); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::upgrade_notes::CallSite; + + const UPLOADS: &str = "import { Controller, Post, UseInterceptors } from '@lattice/common';\nimport { FileInterceptor } from '@lattice/platform-http';\n\n@Controller('files')\nexport class FilesController {\n @Post('upload')\n @UseInterceptors(FileInterceptor('document', { limits: { fileSize: 2 * 1024 * 1024 } }))\n upload() {}\n\n @Get(':id')\n one() {}\n\n @Delete(':id')\n remove() {}\n}\n"; + + #[test] + fn routes_are_read_in_every_syntax_and_a_delete_is_never_probed() { + let r = routes("src/files.controller.ts", UPLOADS); + let got: Vec<(&str, &str)> = r + .iter() + .map(|x| (x.method.as_str(), x.path.as_str())) + .collect(); + assert_eq!(got, vec![("POST", "/files/upload"), ("GET", "/files/1")]); + assert!(r[0].upload); + assert_eq!(r[0].field, "document"); + assert_eq!(r[0].limit, Some(2 * 1024 * 1024)); + // Call style, with a parameter in braces. + let r = routes( + "src/api.js", + "router.post('/orders', validate(schema), create);\napp.get(`/orders/{id}`, one);\nrouter.delete('/orders/:id', gone);\n", + ); + let got: Vec<(&str, &str)> = r + .iter() + .map(|x| (x.method.as_str(), x.path.as_str())) + .collect(); + assert_eq!(got, vec![("POST", "/orders"), ("GET", "/orders/1")]); + // Python decorators and a `route` with its methods; Go's upper case. + let r = routes( + "app/main.py", + "@app.post(\"/items\")\ndef make(): ...\n@bp.route('/legacy', methods=['POST'])\ndef old(): ...\n", + ); + assert_eq!(r.len(), 2); + assert_eq!( + (r[1].method.as_str(), r[1].path.as_str()), + ("POST", "/legacy") + ); + let r = routes("main.go", "r.POST(\"/v1/things\", h.Create)\n"); + assert_eq!(r[0].path, "/v1/things"); + // A client call to another host is no route. + assert!(routes("src/client.ts", "http.get('https://example.test/x')").is_empty()); + } + + #[test] + fn an_upload_is_probed_small_and_over_the_limit_and_a_write_on_its_error_paths() { + let r = routes("src/files.controller.ts", UPLOADS); + let q = requests_for(&r[0]); + assert_eq!(q.len(), 2); + assert_eq!(q[0].what, "a small upload in the field `document`"); + assert!(q[0] + .body + .contains("name=\"document\"; filename=\"probe.txt\"")); + assert_eq!( + q[1].what, + "an upload over the size limit the file states (2048 KiB)" + ); + assert_eq!(q[1].pad_kb, 2048 + 64); + assert!(q[1] + .content_type + .starts_with("multipart/form-data; boundary=")); + let post = Route { + method: "POST".into(), + path: "/orders".into(), + ..Default::default() + }; + let whats: Vec = requests_for(&post).into_iter().map(|q| q.what).collect(); + assert_eq!( + whats, + vec![ + "an empty JSON object (the validation error)", + "a malformed JSON body (the parser error)" + ] + ); + } + + fn note(package: &str, api: &str, file: &str) -> PackageNotes { + PackageNotes { + package: package.into(), + from: "3.2.0".into(), + to: "4.0.1".into(), + major: true, + versions: vec!["4.0.0".into()], + breaking: vec![ + format!("`{api}` reports issues in a new format"), + "`otherThing` was removed".into(), + ], + apis: vec![api.into(), "otherThing".into()], + call_sites: vec![CallSite { + api: api.into(), + file: file.into(), + line: 7, + text: format!("{api}(body)"), + }], + ..Default::default() + } + } + + #[test] + fn the_plan_goes_through_the_call_sites_and_names_what_it_cannot_probe() { + let notes = vec![ + note("shape-check", "safeParse", "src/api.js"), + note("queue-kit", "enqueue", "src/jobs/mailer.ts"), + PackageNotes { + call_sites: vec![], + ..note("quiet-kit", "x", "") + }, + PackageNotes { + versions: vec![], + call_sites: vec![], + missing: "the registry answered 404".into(), + ..note("unread-kit", "x", "") + }, + // A bump inside its major is not probed here. + PackageNotes { + major: false, + ..note("minor-kit", "y", "src/api.js") + }, + ]; + let files = vec![ + ( + "src/api.js".to_string(), + "router.post('/orders', (req, res) => safeParse(req.body));\n".to_string(), + ), + ( + "src/jobs/mailer.ts".to_string(), + "export async function run() { await enqueue(job) }\n".to_string(), + ), + ]; + let p = plan(¬es, &files); + assert_eq!(p.requests.len(), 2); + assert_eq!(p.of, vec![("shape-check".to_string(), vec![0, 1])]); + let why = |pkg: &str| { + p.not_probed + .iter() + .find(|(n, _)| n == pkg) + .map(|(_, w)| w.as_str()) + .unwrap() + }; + assert!(why("queue-kit") + .contains("no route is declared in the files that call it (`src/jobs/mailer.ts`)")); + assert!(why("quiet-kit").contains("no call of an API its notes name was found")); + assert!(why("unread-kit") + .contains("its release notes were not read (the registry answered 404)")); + assert_eq!(p.not_probed.len(), 3); + // Only the breaking change whose API is called. + assert_eq!( + used_breaking(¬es[0]), + vec!["`safeParse` reports issues in a new format"] + ); + } + + #[test] + fn many_routes_never_take_every_place() { + let mut text = String::new(); + for i in 0..10 { + text.push_str(&format!("router.post('/r{i}', h);\n")); + } + let notes = vec![ + note("a-kit", "one", "src/a.js"), + note("b-kit", "two", "src/b.js"), + ]; + let files = vec![ + ("src/a.js".to_string(), text), + ("src/b.js".to_string(), "app.get('/b', h);\n".to_string()), + ]; + let p = plan(¬es, &files); + assert_eq!(p.requests.len(), MAX_PROBES); + assert_eq!(p.of[1], ("b-kit".to_string(), vec![1])); + } + + fn answer(status: u16, sha: &str, excerpt: &str) -> Option { + Some(ProbeAnswer { + status, + content_type: "application/json".into(), + sha: sha.into(), + excerpt: excerpt.into(), + stable: true, + }) + } + + fn two_requests() -> Vec { + requests_for(&Route { + method: "POST".into(), + path: "/orders".into(), + ..Default::default() + }) + } + + #[test] + fn a_changed_error_body_is_a_known_behaviour_change() { + // The review's case: the status is the same, the 400 body is not. + let reqs = two_requests(); + let base = vec![ + answer( + 400, + "aaaa", + r#"{"message":["name must be a string"],"error":"Bad Request"}"#, + ), + answer(400, "cccc", r#"{"message":"Unexpected end of JSON input"}"#), + ]; + let head = vec![ + answer( + 400, + "bbbb", + r#"{"issues":[{"path":["name"],"code":"invalid_type"}]}"#, + ), + answer(400, "cccc", r#"{"message":"Unexpected end of JSON input"}"#), + ]; + let c = compare(&reqs, &base, &head); + assert_eq!(c[0].outcome, Outcome::Changed); + assert!(c[0] + .detail + .starts_with("body before `{\"message\":[\"name must be a string\"]")); + assert_eq!(c[1].outcome, Outcome::Same); + assert!(c[0].reached && c[1].reached); + let b = Behaviour { + package: "shape-check".into(), + from: "3.2.0".into(), + to: "4.0.1".into(), + compared: c, + consumers: vec!["acme/mobile".into()], + consumers_searched: "2 other repositories".into(), + ..Default::default() + }; + assert!(!b.unchanged_shown()); + assert_eq!(b.changed_paths(), vec!["/orders"]); + let text = b.section(); + assert!(text.contains( + "Known behaviour change: `POST /orders` (an empty JSON object (the validation error)) answered 400 application/json on the base branch's build and 400 application/json on this head's: body before" + )); + assert!(text.contains("Who could care: `acme/mobile` names these endpoints.")); + assert!(!text.contains("Unchanged on these")); + } + + #[test] + fn unchanged_is_shown_only_by_answers_that_came_from_the_route() { + let reqs = two_requests(); + let same = vec![answer(400, "aaaa", "x"), answer(400, "bbbb", "y")]; + let b = Behaviour { + compared: compare(&reqs, &same, &same), + ..Default::default() + }; + assert!(b.unchanged_shown()); + assert!(b + .section() + .contains("Unchanged on these 2 requests; nothing is claimed beyond them.")); + // The same answers from a sign-in wall show nothing. + let wall = vec![answer(401, "aaaa", "x"), answer(401, "aaaa", "x")]; + let b = Behaviour { + compared: compare(&reqs, &wall, &wall), + ..Default::default() + }; + assert!(!b.unchanged_shown()); + assert!(b + .section() + .contains("None of these answers came from the route itself")); + // A build that did not answer shows nothing either. + let b = Behaviour { + compared: compare(&reqs, &same, &[None, None]), + ..Default::default() + }; + assert!(!b.unchanged_shown()); + assert!(b + .section() + .contains("the head's build did not answer, so it shows nothing")); + // No request at all: said as not probed. + let b = Behaviour { + package: "queue-kit".into(), + not_probed: "no route is declared in the files that call it".into(), + ..Default::default() + }; + assert!(!b.unchanged_shown()); + assert!(b + .section() + .contains("Nothing here says its behaviour is the same as before.")); + } + + #[test] + fn an_answer_that_varies_by_itself_is_compared_by_status_only() { + let reqs = two_requests(); + let vary = |sha: &str| { + Some(ProbeAnswer { + stable: false, + ..answer(200, sha, "{\"at\":1}").unwrap() + }) + }; + let c = compare( + &reqs, + &[vary("aaaa"), answer(400, "x", "")], + &[vary("bbbb"), answer(500, "x", "")], + ); + assert_eq!(c[0].outcome, Outcome::Same); + assert!(c[0].varies); + assert_eq!(c[1].outcome, Outcome::Changed); + assert_eq!(c[1].detail, "status 400 to 500"); + } + + #[test] + fn the_word_unchanged_stands_only_on_a_probe() { + let text = "Bumped 50 packages. Contract unchanged. The build passes.\n- No behaviour changes are expected for the API.\n- `left-trim` is unchanged in the lockfile."; + let guarded = guard(text, false); + assert_eq!( + guarded, + format!("Bumped 50 packages. {TAKEN_OUT} The build passes.\n- `left-trim` is unchanged in the lockfile.") + ); + // With a probe that shows it, the text stands. + assert_eq!(guard(text, true), text); + // Other ways of saying it. + for claim in [ + "The API is backward compatible.", + "This is a drop-in upgrade.", + "Responses remain the same.", + "The upgrade does not change the error bodies.", + "There are no breaking changes to the public interface.", + ] { + assert_eq!(guard(claim, false), TAKEN_OUT, "{claim}"); + } + // A sentence about something else is left alone. + let other = "The lockfile's format is unchanged. Two lines of the table are identical."; + assert_eq!(guard(other, false), other); + } +} diff --git a/services/common/src/upgrade_quality/family.rs b/services/common/src/upgrade_quality/family.rs new file mode 100644 index 000000000..24069a2fe --- /dev/null +++ b/services/common/src/upgrade_quality/family.rs @@ -0,0 +1,1036 @@ +//! Packages released together move together. +//! +//! A dependency pull request raised one package of a framework to 10.4.22 +//! and left its siblings from the same source repository at 10.4.15. Each +//! bump was correct on its own advisory; together they installed a mix of +//! releases the framework never shipped as one. +//! +//! A family is found from what the registry and the lockfile say, never +//! from a list of names kept here: +//! +//! - the registry record of each package names its source repository +//! (`upgrade_notes::source_repo`), and the base branch's lockfile says +//! which of them it installs at the same version. Same repository and the +//! same version on the base branch is a lockstep family; +//! - the release a bump moves to declares peer ranges. A range that holds a +//! sibling to one minor line makes that sibling a member; +//! - a shared scope or name stem is supporting evidence only: it orders +//! which packages are worth a registry read ([`candidates`]) and is shown +//! beside the evidence that decides. +//! +//! Packages of one repository at different versions on the base branch are +//! versioned on their own: named ([`Independent`]), never held together. +//! +//! No grouping data of another project is used. The public grouping tables +//! of dependency update tools are part of projects under licences this +//! codebase does not take data from; everything here is derived from the +//! registry's metadata and the repository's lockfile. +//! +//! Everything here is pure; the registry reads are the worker's +//! (`worker::passes::upgrade_quality`). + +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::dep_fix::{Companion, DepPlan}; +use crate::security_fixes::{compare_versions, is_major_bump, version_line}; +use crate::upgrade_notes::range_admits; + +/// Registry reads one bumped package's family search makes at most. +pub const MAX_CANDIDATES: usize = 12; +/// A version this many packages of a lockfile share says nothing by itself +/// (`1.0.0`): only packages related by name are then read. +const COMMON_VERSION: usize = 25; + +/// Why packages are taken to be one family. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "kind")] +pub enum Evidence { + /// The registry records of the members name one source repository. + SameSource { repo: String }, + /// The base branch's lockfile installs every member at this version. + EqualOnBase { version: String }, + /// The release `from` moves to holds `on` to one minor line. + PeerPin { + from: String, + on: String, + range: String, + }, + /// The members share a scope or a name stem. Supporting only. + NamePattern { pattern: String }, +} + +impl Evidence { + pub fn line(&self) -> String { + match self { + Evidence::SameSource { repo } => { + format!("the registry names `{repo}` as the source repository of each") + } + Evidence::EqualOnBase { version } => { + format!("the base branch's lockfile installs each at {version}") + } + Evidence::PeerPin { from, on, range } => { + format!("`{from}` declares the peer range `{range}` for `{on}`") + } + Evidence::NamePattern { pattern } => format!("the names share `{pattern}`"), + } + } +} + +/// What is known of one package of the lockfile. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Known { + pub name: String, + /// `owner/name` of its source repository, lowercase; `None` when the + /// registry record was not read or names none. + pub source: Option, +} + +/// A package of the bumped one's source repository the base branch has at +/// another version: versioned on its own, not held to the family. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Independent { + pub name: String, + pub version: String, +} + +/// Packages released in lockstep, in one lockfile. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Family { + /// The source repository (`owner/name`), or `peers of `. + pub key: String, + pub lockfile: String, + /// The version every member has on the base branch. + pub base_version: String, + /// Every member, the bumped one included, by name. + pub members: Vec, + pub evidence: Vec, + /// The version the family moves to; empty when it does not move as one. + pub target: String, + /// Why it does not move as one; empty when it does. A family with a + /// reason here is allowed to differ on the head, and the reason is + /// shown. + pub held: String, + /// Packages of the same repository at other versions on the base + /// branch. + pub independent: Vec, +} + +impl Family { + pub fn evidence_line(&self) -> String { + self.evidence + .iter() + .map(Evidence::line) + .collect::>() + .join("; ") + } +} + +/// The scope of a scoped name (`@scope/x` is `@scope`), or the first word +/// of a plain one (`pkg-core` is `pkg`, `pkg.core` is `pkg`). +fn stem(name: &str) -> &str { + if let Some(rest) = name.strip_prefix('@') { + return match rest.find('/') { + Some(i) => &name[..i + 1], + None => name, + }; + } + // A Maven coordinate's group, a Go module's repository. + if let Some((group, _)) = name.split_once(':') { + return group; + } + let end = name.find(['-', '.', '_', '/']).unwrap_or(name.len()); + &name[..end] +} + +/// What two names share, when they share something: `@scope`, or a stem of +/// three letters or more. A scope named after a plain package counts +/// (`runner` and `@runner/coverage`). +pub fn name_pattern(a: &str, b: &str) -> Option { + let (sa, sb) = (stem(a), stem(b)); + let bare = |s: &str| s.trim_start_matches('@').to_ascii_lowercase(); + if a.eq_ignore_ascii_case(b) || bare(sa).len() < 3 { + return None; + } + if bare(sa) != bare(sb) { + return None; + } + Some(if sa.starts_with('@') { + format!("{sa}/") + } else if sb.starts_with('@') { + format!("{sb}/") + } else { + sa.to_string() + }) +} + +/// The packages of the base branch's lockfile worth a registry read to +/// find `package`'s family, at most [`MAX_CANDIDATES`]: the ones it +/// installs at the same version (related names first), then the related +/// names at other versions (they are named as versioned on their own). A +/// version half the lockfile shares brings in related names only. +pub fn candidates(package: &str, from: &str, base: &[(String, String)]) -> Vec { + let mut names: Vec<(&str, bool)> = base + .iter() + .filter(|(n, _)| !n.eq_ignore_ascii_case(package)) + .map(|(n, v)| (n.as_str(), compare_versions(v, from) == Ordering::Equal)) + .collect(); + names.sort(); + names.dedup(); + let same: Vec<&str> = names + .iter() + .filter(|(_, eq)| *eq) + .map(|(n, _)| *n) + .collect(); + let common = same.len() > COMMON_VERSION; + let related = |n: &&str| name_pattern(package, n).is_some(); + let mut out: Vec<&str> = same.iter().copied().filter(related).collect(); + if !common { + out.extend(same.iter().copied().filter(|n| !related(n))); + } + out.extend( + names + .iter() + .filter(|(n, eq)| !*eq && related(n) && !same.contains(n)) + .map(|(n, _)| *n), + ); + out.dedup(); + out.into_iter() + .take(MAX_CANDIDATES) + .map(String::from) + .collect() +} + +/// A peer range that holds its package to one minor line: an exact +/// version, a tilde range, or `1.2.x`. A caret or an open range lets the +/// peer move on its own. +pub fn pins(range: &str) -> bool { + let r = range.trim(); + if r.is_empty() || r.contains("||") || r.contains(' ') || r == "*" { + return false; + } + let body = r.trim_start_matches(['=', 'v']); + if let Some(t) = r.strip_prefix('~') { + return !t.starts_with('>') && t.matches('.').count() >= 1; + } + if r.starts_with(['^', '>', '<']) { + return false; + } + let parts: Vec<&str> = body.split('.').collect(); + match parts.as_slice() { + [a, b, c] => { + let num = |s: &str| !s.is_empty() && s.chars().all(|ch| ch.is_ascii_digit()); + num(a) + && num(b) + && (c.eq_ignore_ascii_case("x") + || *c == "*" + || c.chars().next().is_some_and(|ch| ch.is_ascii_digit())) + } + _ => false, + } +} + +/// The family of `package` (at `from` on the base branch, in `lockfile`): +/// the packages the base branch's lockfile has at the same version whose +/// registry record names the same source repository, and the packages the +/// release it moves to pins as peers (`peers`: peer name and range). +/// `known`: what the registry said of `package` and of each candidate. +/// `None` when it has no family; a package with only independently +/// versioned siblings gets a family of itself, so they are named. +pub fn detect( + package: &str, + from: &str, + lockfile: &str, + base: &[(String, String)], + known: &[Known], + peers: &[(String, String)], +) -> Option { + let source = known + .iter() + .find(|k| k.name.eq_ignore_ascii_case(package)) + .and_then(|k| k.source.clone()); + let installed = |name: &str| -> Vec<&str> { + base.iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + .collect() + }; + let mut members: BTreeSet = BTreeSet::new(); + let mut evidence: Vec = vec![]; + let mut independent: Vec = vec![]; + if let Some(repo) = &source { + for k in known { + if k.name.eq_ignore_ascii_case(package) || k.source.as_ref() != Some(repo) { + continue; + } + let versions = installed(&k.name); + if versions + .iter() + .any(|v| compare_versions(v, from) == Ordering::Equal) + { + members.insert(k.name.clone()); + } else if let Some(v) = versions.first() { + independent.push(Independent { + name: k.name.clone(), + version: v.to_string(), + }); + } + } + if !members.is_empty() { + evidence.push(Evidence::SameSource { repo: repo.clone() }); + evidence.push(Evidence::EqualOnBase { + version: from.to_string(), + }); + } + } + for (peer, range) in peers { + if !pins(range) || installed(peer).is_empty() || peer.eq_ignore_ascii_case(package) { + continue; + } + members.insert(peer.clone()); + evidence.push(Evidence::PeerPin { + from: package.to_string(), + on: peer.clone(), + range: range.clone(), + }); + } + if members.is_empty() && independent.is_empty() { + return None; + } + let mut patterns: Vec = members + .iter() + .filter_map(|m| name_pattern(package, m)) + .collect(); + patterns.sort(); + patterns.dedup(); + for pattern in patterns { + evidence.push(Evidence::NamePattern { pattern }); + } + let key = match (&source, evidence.first()) { + (Some(repo), Some(Evidence::SameSource { .. })) | (Some(repo), None) => repo.clone(), + _ => format!("peers of {package}"), + }; + members.insert(package.to_string()); + independent.sort_by(|a, b| a.name.cmp(&b.name)); + Some(Family { + key, + lockfile: lockfile.to_string(), + base_version: from.to_string(), + members: members.into_iter().collect(), + evidence, + independent, + ..Default::default() + }) +} + +/// The version a family moves to: the lowest of `wanted` (the versions +/// that fix the advisory, lowest first) every member publishes. +/// `published`: per member, which of `wanted` its registry has; a member +/// missing from it was not read. `Err` says why there is none. +pub fn target( + family: &Family, + wanted: &[String], + published: &BTreeMap>, +) -> Result { + if family.members.len() < 2 { + return Err("it has no member released with it".to_string()); + } + let mut wanted: Vec<&String> = wanted.iter().collect(); + wanted.sort_by(|a, b| compare_versions(a, b)); + wanted.dedup(); + let unread: Vec<&String> = family + .members + .iter() + .filter(|m| !published.contains_key(*m)) + .collect(); + if let Some(m) = unread.first() { + return Err(format!( + "the registry could not be read for `{m}`, so no version every member publishes is known" + )); + } + for v in &wanted { + if family + .members + .iter() + .all(|m| published[m].iter().any(|p| p == *v)) + { + return Ok((*v).clone()); + } + } + let lacking: Vec = family + .members + .iter() + .filter(|m| { + wanted + .first() + .is_some_and(|v| !published[*m].iter().any(|p| p == *v)) + }) + .map(|m| format!("`{m}`")) + .collect(); + Err(match wanted.first() { + Some(v) => format!( + "{} publish{} no {v}, the lowest version that fixes the advisory", + lacking.join(", "), + if lacking.len() == 1 { "es" } else { "" } + ), + None => "no fixed version is known for it".to_string(), + }) +} + +/// Brings each family of `families` into the plan: the first bump of a +/// member carries the others as companions at the family's target, so one +/// probe, one commit and one deferral move the family or none of it. A +/// second bump of the same family folds into the first (its findings with +/// it). A target that would newly cross a major version is not taken: the +/// family is held with that reason, and the bump goes alone. +pub fn attach(plan: &mut DepPlan, families: &mut [Family]) { + for fam in families.iter_mut() { + let in_family = |b: &crate::dep_fix::PlanBump| { + b.manifest == fam.lockfile + && fam + .members + .iter() + .any(|m| m.eq_ignore_ascii_case(&b.package)) + && version_line(&b.from) == version_line(&fam.base_version) + }; + let Some(first) = plan.bumps.iter().position(in_family) else { + continue; + }; + if fam.target.is_empty() || !fam.held.is_empty() { + plan.bumps[first].family = fam.key.clone(); + plan.bumps[first].family_note = if fam.held.is_empty() { + "its family has no version to move to together".to_string() + } else { + fam.held.clone() + }; + continue; + } + let crosses = plan + .bumps + .iter() + .filter(|b| in_family(b)) + .any(|b| !b.major && is_major_bump(&b.from, &fam.target)); + if crosses { + fam.held = format!( + "the lowest version every member publishes, {}, is a major version away, and the advisory is fixed inside the current one", + fam.target + ); + fam.target.clear(); + plan.bumps[first].family = fam.key.clone(); + plan.bumps[first].family_note = fam.held.clone(); + continue; + } + // Fold the family's other bumps into the first. + let mut folded: Vec = vec![]; + let mut i = first + 1; + while i < plan.bumps.len() { + if in_family(&plan.bumps[i]) { + folded.push(plan.bumps.remove(i)); + } else { + i += 1; + } + } + let primary = &mut plan.bumps[first]; + primary.family = fam.key.clone(); + if compare_versions(&fam.target, &primary.to) == Ordering::Greater { + primary.to = fam.target.clone(); + } + for other in folded { + for id in other.finding_ids { + if !primary.finding_ids.contains(&id) { + primary.finding_ids.push(id); + } + } + // The family is verified as its riskiest member is. + if other.major && !primary.major { + primary.major = true; + primary.major_reason = other.major_reason; + primary.risk = other.risk; + } else if !other.major + && !primary.major + && primary.risk() > other.risk.unwrap_or(crate::dep_fix::Risk::Safe) + { + primary.risk = other.risk; + } + } + let line = primary.line.clone(); + for m in &fam.members { + if m.eq_ignore_ascii_case(&primary.package) { + continue; + } + primary.companions.push(Companion { + package: m.clone(), + from: fam.base_version.clone(), + to: fam.target.clone(), + line: line.clone(), + }); + } + primary.family_note = format!( + "moves with {} to {} ({})", + primary + .companions + .iter() + .map(|c| format!("`{}`", c.package)) + .collect::>() + .join(", "), + fam.target, + fam.evidence_line() + ); + } +} + +/// A family the head installs at more than one version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Split { + pub family: String, + /// Each member and the version the head has it at. + pub at: Vec<(String, String)>, +} + +impl Split { + pub fn line(&self) -> String { + let at: Vec = self + .at + .iter() + .map(|(m, v)| format!("`{m}` at {v}")) + .collect(); + format!( + "the family `{}` is split on the head: {}", + self.family, + at.join(", ") + ) + } +} + +/// Where a member that was at `base_version` stands on the head: still +/// there, or the lowest version the head has above it. +fn member_at(name: &str, base_version: &str, head: &[(String, String)]) -> Option { + let versions: Vec<&str> = head + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + .collect(); + if versions + .iter() + .any(|v| compare_versions(v, base_version) == Ordering::Equal) + { + return Some(base_version.to_string()); + } + versions + .iter() + .copied() + .filter(|v| compare_versions(v, base_version) == Ordering::Greater) + .min_by(|a, b| compare_versions(a, b)) + .or_else(|| { + versions + .iter() + .copied() + .min_by(|a, b| compare_versions(a, b)) + }) + .map(String::from) +} + +/// The families the head installs at more than one version. A family held +/// for a recorded reason is allowed to differ and is not returned; a member +/// the head no longer installs is not part of the comparison. +pub fn splits(families: &[Family], lockfile: &str, head: &[(String, String)]) -> Vec { + let mut out = vec![]; + for fam in families { + if fam.lockfile != lockfile || !fam.held.is_empty() || fam.members.len() < 2 { + continue; + } + let at: Vec<(String, String)> = fam + .members + .iter() + .filter_map(|m| member_at(m, &fam.base_version, head).map(|v| (m.clone(), v))) + .collect(); + let distinct: BTreeSet<&str> = at.iter().map(|(_, v)| v.as_str()).collect(); + if distinct.len() > 1 { + out.push(Split { + family: fam.key.clone(), + at, + }); + } + } + out +} + +/// One peer range a bumped release declares. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct PeerRange { + pub from: String, + pub on: String, + pub range: String, +} + +/// The peer ranges no copy on the head satisfies, each as a sentence. A +/// peer the head does not install, or a range that can't be evaluated, is +/// not judged. +pub fn peers_unmet(ecosystem: &str, peers: &[PeerRange], head: &[(String, String)]) -> Vec { + let mut out = vec![]; + for p in peers { + let versions: Vec<&str> = head + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(&p.on)) + .map(|(_, v)| v.as_str()) + .collect(); + if versions.is_empty() { + continue; + } + let verdicts: Vec> = versions + .iter() + .map(|v| range_admits(ecosystem, &p.range, v)) + .collect(); + if verdicts.iter().all(|v| *v == Some(false)) { + out.push(format!( + "`{}` declares the peer range `{}` for `{}`, and the head installs it at {}", + p.from, + p.range, + p.on, + versions.join(", ") + )); + } + } + out +} + +/// The families as the pull request states them. +pub fn section(families: &[Family], splits: &[Split], peers: &[String]) -> String { + if families.is_empty() && peers.is_empty() { + return String::new(); + } + let mut s = String::from( + "**Families released together** (from the registry's source repository of each package and the versions in the base branch's lockfile):\n", + ); + for f in families { + let members: Vec = f.members.iter().map(|m| format!("`{m}`")).collect(); + if f.members.len() < 2 { + // Only independently versioned siblings. + } else if !f.target.is_empty() && f.held.is_empty() { + let split = splits.iter().find(|x| x.family == f.key); + s.push_str(&format!( + "- {} move together from {} to {}: {}. {}\n", + members.join(", "), + f.base_version, + f.target, + f.evidence_line(), + match split { + Some(x) => format!("Not coherent: {}.", x.line()), + None => "The head installs every member at one version.".to_string(), + } + )); + } else { + s.push_str(&format!( + "- {} are one family ({}) and do not move together here: {}.\n", + members.join(", "), + f.evidence_line(), + if f.held.is_empty() { + "no version to move to together was found" + } else { + f.held.as_str() + } + )); + } + if !f.independent.is_empty() { + let named: Vec = f + .independent + .iter() + .take(6) + .map(|i| format!("`{}` {}", i.name, i.version)) + .collect(); + s.push_str(&format!( + "- Same source repository `{}`, at other versions on the base branch, so versioned on their own and left where they are: {}{}.\n", + f.key, + named.join(", "), + if f.independent.len() > 6 { + format!(" and {} more", f.independent.len() - 6) + } else { + String::new() + } + )); + } + } + for p in peers { + s.push_str(&format!("- Peer range not met: {p}.\n")); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dep_fix::PlanBump; + + fn copies(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + pairs + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect() + } + + fn known(name: &str, repo: &str) -> Known { + Known { + name: name.into(), + source: (!repo.is_empty()).then(|| repo.to_string()), + } + } + + fn base() -> Vec<(String, String)> { + copies(&[ + ("@lattice/common", "10.4.15"), + ("@lattice/core", "10.4.15"), + ("@lattice/platform-http", "10.4.15"), + ("@lattice/cli", "10.2.0"), + ("left-trim", "10.4.15"), + ("zeta", "1.0.0"), + ]) + } + + fn lattice() -> Family { + detect( + "@lattice/common", + "10.4.15", + "pnpm-lock.yaml", + &base(), + &[ + known("@lattice/common", "lattice-js/lattice"), + known("@lattice/core", "lattice-js/lattice"), + known("@lattice/platform-http", "lattice-js/lattice"), + known("@lattice/cli", "lattice-js/lattice"), + known("left-trim", "someone/left-trim"), + ], + &[], + ) + .unwrap() + } + + #[test] + fn a_family_is_the_same_repository_at_the_same_version_on_the_base() { + let f = lattice(); + assert_eq!(f.key, "lattice-js/lattice"); + assert_eq!( + f.members, + vec!["@lattice/common", "@lattice/core", "@lattice/platform-http"] + ); + // The unrelated package at the same version is not a member: the + // registry names another repository for it. + assert!(!f.members.iter().any(|m| m == "left-trim")); + // The scope is supporting evidence, after the two that decide. + assert_eq!( + f.evidence, + vec![ + Evidence::SameSource { + repo: "lattice-js/lattice".into() + }, + Evidence::EqualOnBase { + version: "10.4.15".into() + }, + Evidence::NamePattern { + pattern: "@lattice/".into() + }, + ] + ); + } + + #[test] + fn a_sibling_at_another_version_is_versioned_on_its_own() { + let f = lattice(); + assert_eq!( + f.independent, + vec![Independent { + name: "@lattice/cli".into(), + version: "10.2.0".into() + }] + ); + // A repository whose packages all differ on the base is no lockstep + // family: one type-definitions repository publishing hundreds of + // packages on their own versions. + let types = detect( + "@defs/alpha", + "18.2.1", + "package-lock.json", + &copies(&[("@defs/alpha", "18.2.1"), ("@defs/beta", "4.17.3")]), + &[ + known("@defs/alpha", "defs/definitions"), + known("@defs/beta", "defs/definitions"), + ], + &[], + ) + .unwrap(); + assert_eq!(types.members, vec!["@defs/alpha"]); + assert_eq!(types.independent.len(), 1); + // Nothing is held together, so nothing can be split. + let head = copies(&[("@defs/alpha", "18.2.5"), ("@defs/beta", "4.17.3")]); + assert!(splits(&[types], "package-lock.json", &head).is_empty()); + } + + #[test] + fn a_name_alone_never_makes_a_family() { + // Same scope, same version, the registry names different + // repositories: no family. + assert!(detect( + "@lattice/common", + "10.4.15", + "pnpm-lock.yaml", + &base(), + &[ + known("@lattice/common", "lattice-js/lattice"), + known("@lattice/core", "elsewhere/core"), + ], + &[], + ) + .is_none()); + // And one whose registry record was not read is not assumed in. + assert!(detect( + "@lattice/common", + "10.4.15", + "pnpm-lock.yaml", + &base(), + &[ + known("@lattice/common", "lattice-js/lattice"), + known("@lattice/core", "") + ], + &[], + ) + .is_none()); + } + + #[test] + fn a_pinning_peer_range_makes_a_member() { + assert!(pins("18.3.1")); + assert!(pins("~2.1.0")); + assert!(pins("2.1.x")); + assert!(!pins("^18.0.0")); + assert!(!pins(">=16")); + assert!(!pins("^17 || ^18")); + assert!(!pins("*")); + let f = detect( + "view-dom", + "18.2.0", + "yarn.lock", + &copies(&[("view-dom", "18.2.0"), ("view", "18.2.0")]), + &[known("view-dom", ""), known("view", "")], + &[("view".to_string(), "18.3.1".to_string())], + ) + .unwrap(); + assert_eq!(f.key, "peers of view-dom"); + assert_eq!(f.members, vec!["view", "view-dom"]); + assert!(matches!(f.evidence[0], Evidence::PeerPin { .. })); + } + + #[test] + fn candidates_are_the_same_version_with_related_names_first() { + let c = candidates("@lattice/common", "10.4.15", &base()); + assert_eq!( + c, + vec![ + "@lattice/core", + "@lattice/platform-http", + "left-trim", + "@lattice/cli" + ] + ); + // A scope named after a plain package is related. + assert_eq!( + name_pattern("runner", "@runner/coverage"), + Some("@runner/".into()) + ); + assert_eq!(name_pattern("view", "view-dom"), Some("view".into())); + assert_eq!(name_pattern("ab", "ab-c"), None); + // A version half the lockfile shares brings related names only. + let mut many = copies(&[("pkg-core", "1.0.0"), ("pkg-extra", "1.0.0")]); + for i in 0..40 { + many.push((format!("other{i}"), "1.0.0".into())); + } + assert_eq!(candidates("pkg-core", "1.0.0", &many), vec!["pkg-extra"]); + } + + fn published(pairs: &[(&str, &[&str])]) -> BTreeMap> { + pairs + .iter() + .map(|(m, v)| (m.to_string(), v.iter().map(|s| s.to_string()).collect())) + .collect() + } + + #[test] + fn the_family_moves_to_the_lowest_fix_every_member_publishes() { + let f = lattice(); + let wanted = vec!["10.4.23".to_string(), "10.4.22".to_string()]; + let all = published(&[ + ("@lattice/common", &["10.4.22", "10.4.23"]), + ("@lattice/core", &["10.4.22", "10.4.23"]), + ("@lattice/platform-http", &["10.4.22", "10.4.23"]), + ]); + assert_eq!(target(&f, &wanted, &all), Ok("10.4.22".into())); + // One member skipped the lowest: the next every member has. + let skipped = published(&[ + ("@lattice/common", &["10.4.22", "10.4.23"]), + ("@lattice/core", &["10.4.23"]), + ("@lattice/platform-http", &["10.4.22", "10.4.23"]), + ]); + assert_eq!(target(&f, &wanted, &skipped), Ok("10.4.23".into())); + // None in common: said, with who lacks it. + let none = published(&[ + ("@lattice/common", &["10.4.22"]), + ("@lattice/core", &[]), + ("@lattice/platform-http", &["10.4.22"]), + ]); + assert_eq!( + target(&f, &wanted, &none).unwrap_err(), + "`@lattice/core` publishes no 10.4.22, the lowest version that fixes the advisory" + ); + // A member the registry could not be read for is never assumed. + let unread = published(&[("@lattice/common", &["10.4.22"])]); + assert!(target(&f, &wanted, &unread) + .unwrap_err() + .contains("could not be read")); + } + + fn bump(package: &str, from: &str, to: &str, id: &str) -> PlanBump { + PlanBump { + package: package.into(), + from: from.into(), + to: to.into(), + line: version_line(from), + manifest: "pnpm-lock.yaml".into(), + finding_ids: vec![id.into()], + ..Default::default() + } + } + + #[test] + fn one_bump_carries_its_family_and_a_second_folds_into_it() { + let mut fam = lattice(); + fam.target = "10.4.22".into(); + let mut plan = DepPlan { + bumps: vec![ + bump("zeta", "1.0.0", "1.0.4", "f-z"), + bump("@lattice/common", "10.4.15", "10.4.22", "f-1"), + bump("@lattice/core", "10.4.15", "10.4.20", "f-2"), + ], + deferred: vec![], + }; + let mut fams = vec![fam]; + attach(&mut plan, &mut fams); + assert_eq!(plan.bumps.len(), 2); + let b = &plan.bumps[1]; + assert_eq!(b.package, "@lattice/common"); + assert_eq!(b.to, "10.4.22"); + assert_eq!(b.finding_ids, vec!["f-1", "f-2"]); + let names: Vec<&str> = b.companions.iter().map(|c| c.package.as_str()).collect(); + assert_eq!(names, vec!["@lattice/core", "@lattice/platform-http"]); + assert!(b.companions.iter().all(|c| c.to == "10.4.22")); + assert!(b.family_note.starts_with("moves with `@lattice/core`")); + // The apply script is told every member. + let specs = crate::dep_fix::specs(&[b]); + let applied: Vec<&str> = specs[0].bumps.iter().map(|a| a.name.as_str()).collect(); + assert_eq!( + applied, + vec!["@lattice/common", "@lattice/core", "@lattice/platform-http"] + ); + } + + #[test] + fn a_family_with_no_common_version_goes_alone_with_the_reason() { + let mut fam = lattice(); + fam.held = + "`@lattice/core` publishes no 10.4.22, the lowest version that fixes the advisory" + .into(); + let mut plan = DepPlan { + bumps: vec![bump("@lattice/common", "10.4.15", "10.4.22", "f-1")], + deferred: vec![], + }; + let mut fams = vec![fam]; + attach(&mut plan, &mut fams); + assert!(plan.bumps[0].companions.is_empty()); + assert!(plan.bumps[0].family_note.contains("publishes no 10.4.22")); + // The head then differs, for a recorded reason: not a split. + let head = copies(&[ + ("@lattice/common", "10.4.22"), + ("@lattice/core", "10.4.15"), + ("@lattice/platform-http", "10.4.15"), + ]); + assert!(splits(&fams, "pnpm-lock.yaml", &head).is_empty()); + assert!(section(&fams, &[], &[]).contains("do not move together here")); + } + + #[test] + fn a_target_that_would_newly_cross_a_major_is_not_taken() { + let mut fam = lattice(); + fam.target = "11.0.0".into(); + let mut plan = DepPlan { + bumps: vec![bump("@lattice/common", "10.4.15", "10.4.22", "f-1")], + deferred: vec![], + }; + let mut fams = vec![fam]; + attach(&mut plan, &mut fams); + assert_eq!(plan.bumps[0].to, "10.4.22"); + assert!(plan.bumps[0].companions.is_empty()); + assert!(fams[0].held.contains("a major version away")); + } + + #[test] + fn a_split_family_is_found_on_the_head() { + let mut fam = lattice(); + fam.target = "10.4.22".into(); + let fams = vec![fam]; + // The review's case: one member raised, its siblings left behind. + let split_head = copies(&[ + ("@lattice/common", "10.4.22"), + ("@lattice/core", "10.4.15"), + ("@lattice/platform-http", "10.4.15"), + ("@lattice/cli", "10.2.0"), + ]); + let found = splits(&fams, "pnpm-lock.yaml", &split_head); + assert_eq!(found.len(), 1); + assert_eq!( + found[0].line(), + "the family `lattice-js/lattice` is split on the head: `@lattice/common` at 10.4.22, `@lattice/core` at 10.4.15, `@lattice/platform-http` at 10.4.15" + ); + // Moved together: coherent. The independent sibling is not judged. + let whole = copies(&[ + ("@lattice/common", "10.4.22"), + ("@lattice/core", "10.4.22"), + ("@lattice/platform-http", "10.4.22"), + ("@lattice/cli", "10.2.0"), + ]); + assert!(splits(&fams, "pnpm-lock.yaml", &whole).is_empty()); + // Untouched: coherent. Another lockfile's copies are not this + // family's. + assert!(splits(&fams, "pnpm-lock.yaml", &base()).is_empty()); + assert!(splits(&fams, "apps/x/pnpm-lock.yaml", &split_head).is_empty()); + let text = section(&fams, &found, &[]); + assert!(text.contains("Not coherent: the family `lattice-js/lattice` is split on the head")); + assert!(text.contains("versioned on their own")); + } + + #[test] + fn an_unmet_peer_range_is_named_and_an_unreadable_one_is_not_judged() { + let peers = vec![ + PeerRange { + from: "view-dom".into(), + on: "view".into(), + range: "^18.3.0".into(), + }, + PeerRange { + from: "view-dom".into(), + on: "absent".into(), + range: "^1.0.0".into(), + }, + ]; + let head = copies(&[("view-dom", "18.3.1"), ("view", "18.2.0")]); + let unmet = peers_unmet("npm", &peers, &head); + assert_eq!( + unmet, + vec!["`view-dom` declares the peer range `^18.3.0` for `view`, and the head installs it at 18.2.0"] + ); + let ok = copies(&[("view-dom", "18.3.1"), ("view", "18.3.1")]); + assert!(peers_unmet("npm", &peers, &ok).is_empty()); + } +} diff --git a/services/common/src/upgrade_quality/mod.rs b/services/common/src/upgrade_quality/mod.rs new file mode 100644 index 000000000..08483a1cd --- /dev/null +++ b/services/common/src/upgrade_quality/mod.rs @@ -0,0 +1,242 @@ +//! A dependency update decided and proven the way a senior engineer would. +//! +//! An outside review of one dependency security pull request (about fifty +//! packages, four across a major version) found the code sound and the +//! account of it wanting in five places: +//! +//! 1. the count of advisories left was CoderHelm's own and disagreed with +//! the package manager's production audit of the same head; +//! 2. one package of a framework was raised and its siblings from the same +//! source repository stayed behind; +//! 3. no type check was recorded, because the repository's CI has none and +//! CoderHelm's checks mirrored CI; +//! 4. it said "contract unchanged" although a validation library's major +//! changed the 400 error bodies of two endpoints; +//! 5. each override across a major lacked the reason it is safe. +//! +//! The mechanisms, one module each, all general across package managers +//! through a table where they differ: +//! +//! - [`family`]: packages released together move together, found from the +//! registry's metadata and the lockfile, and verified on the head. +//! - [`verify`]: the set a dependency change is verified with, found in +//! the project and not in its CI, budgeted to the sandbox's time. +//! - [`advisories`]: fixed, remaining and introduced, the base branch and +//! the head read the same way and laid beside the package manager's +//! audit; every disagreement with its cause. +//! - [`safety`]: why each major is safe, from its dependency paths, where +//! they run, whether the repository uses it, and how it is fixed. +//! - [`behaviour`]: a before-and-after probe through the call sites of a +//! major; "unchanged" stands only on a probe. +//! +//! [`UpgradeFacts`] is what they record for one head commit. The pull +//! request's description and the reviewer cite it; a head that has moved +//! since is said to have, and nothing recorded on an earlier commit is +//! shown as true of the new one. + +pub mod advisories; +pub mod behaviour; +pub mod family; +pub mod safety; +pub mod verify; + +use serde::{Deserialize, Serialize}; + +/// What the dependency run recorded for one head commit. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct UpgradeFacts { + /// The commit every fact below was recorded on. + pub sha: String, + pub families: Vec, + /// The families the head installs at more than one version. + pub splits: Vec, + /// The peer ranges the head leaves unmet, each as a sentence. + pub peers_unmet: Vec, + /// The minimum set's results on the head, and on the base branch where + /// the head failed something. + pub verified: Option, + pub verified_base: Option, + pub advisories: Option, + pub majors: Vec, + pub behaviour: Vec, + /// What did not run, each with why: never shown as a result. + pub not_run: Vec, +} + +fn short(sha: &str) -> &str { + &sha[..sha.len().min(7)] +} + +impl UpgradeFacts { + /// From a ticket record's `dep_facts` (JSON); `None` when it has none. + pub fn from_json(json: &str) -> Option { + if json.trim().is_empty() { + return None; + } + serde_json::from_str(json).ok() + } + + /// The facts were recorded on `head` (a full or short sha). + pub fn of_head(&self, head: &str) -> bool { + !self.sha.is_empty() + && !head.is_empty() + && (self.sha.starts_with(head) || head.starts_with(&self.sha)) + } + + /// Whether a probe shows the behaviour of every probed major + /// unchanged, and no major on a production path went unprobed. Only + /// then may a text call the contract or the behaviour unchanged. + pub fn unchanged_shown(&self) -> bool { + let probed_ok = !self.behaviour.is_empty() + && self + .behaviour + .iter() + .all(behaviour::Behaviour::unchanged_shown); + let all_probed = self.majors.iter().all(|m| { + !matches!(m.probe, safety::ProbeNeed::Needed { .. }) + || self + .behaviour + .iter() + .any(|b| b.package == m.package && b.unchanged_shown()) + }); + probed_ok && all_probed + } + + /// The facts as the pull request states them, under "What to check". + /// `head`: the commit the description is being written for; when the + /// facts are of another commit that is said first, and they are shown + /// as that commit's. + pub fn section(&self, head: &str) -> String { + let mut s = format!( + "### Upgrade evidence\n\nRecorded by CoderHelm on commit `{}`.", + short(&self.sha) + ); + if !head.is_empty() && !self.of_head(head) { + s.push_str(&format!( + " The head is now `{}`: everything in this section is of the earlier commit and has not been run again on the new one.", + short(head) + )); + } + s.push_str("\n\n"); + let mut blocks: Vec = vec![]; + if let Some(a) = &self.advisories { + blocks.push(a.section()); + } + let fam = family::section(&self.families, &self.splits, &self.peers_unmet); + if !fam.is_empty() { + blocks.push(fam); + } + if let Some(v) = &self.verified { + blocks.push(verify::section(v, self.verified_base.as_ref())); + } + if !self.majors.is_empty() { + let mut m = String::from( + "**Why each major version bump is safe, or what is not known about it:**\n", + ); + for major in &self.majors { + m.push_str(&major.section()); + } + blocks.push(m); + } + if !self.behaviour.is_empty() { + let mut b = String::from( + "**Behaviour changes** (the same requests sent to the application built from the base branch and from this commit):\n", + ); + for one in &self.behaviour { + b.push_str(&one.section()); + } + blocks.push(b); + } + if !self.not_run.is_empty() { + let mut n = String::from("**Not run, and not claimed:**\n"); + for line in &self.not_run { + n.push_str(&format!("- {line}\n")); + } + blocks.push(n); + } + s.push_str(&blocks.join("\n")); + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_facts_are_of_one_commit_and_say_so_when_the_head_has_moved() { + let f = UpgradeFacts { + sha: "abc1234def5678".into(), + not_run: vec!["the unit tests: the sandbox build had no time left".into()], + ..Default::default() + }; + assert!(f.of_head("abc1234def5678")); + assert!(f.of_head("abc1234")); + assert!(!f.of_head("fff0000")); + assert!(!f.of_head("")); + let same = f.section("abc1234def5678"); + assert!(same + .starts_with("### Upgrade evidence\n\nRecorded by CoderHelm on commit `abc1234`.\n")); + assert!(same.contains("**Not run, and not claimed:**\n- the unit tests")); + let moved = f.section("fff0000aaaa"); + assert!(moved.contains( + "The head is now `fff0000`: everything in this section is of the earlier commit and has not been run again on the new one." + )); + // It survives the ticket record. + let json = serde_json::to_string(&f).unwrap(); + assert_eq!(UpgradeFacts::from_json(&json), Some(f)); + assert_eq!(UpgradeFacts::from_json(""), None); + assert_eq!(UpgradeFacts::from_json("not json"), None); + } + + #[test] + fn unchanged_needs_every_production_major_probed_and_the_same() { + let same = behaviour::Compared { + outcome: behaviour::Outcome::Same, + reached: true, + ..Default::default() + }; + let shown = behaviour::Behaviour { + package: "shape-check".into(), + compared: vec![same.clone()], + ..Default::default() + }; + let needs = |package: &str| safety::MajorSafety { + package: package.into(), + probe: safety::ProbeNeed::Needed { why: "x".into() }, + ..Default::default() + }; + // Nothing probed: never. + assert!(!UpgradeFacts::default().unchanged_shown()); + // One probed and the same: yes. + let f = UpgradeFacts { + behaviour: vec![shown.clone()], + majors: vec![needs("shape-check")], + ..Default::default() + }; + assert!(f.unchanged_shown()); + // A second production major with no probe: no. + let f = UpgradeFacts { + behaviour: vec![shown.clone()], + majors: vec![needs("shape-check"), needs("upload-kit")], + ..Default::default() + }; + assert!(!f.unchanged_shown()); + // One changed answer: no. + let changed = behaviour::Behaviour { + package: "upload-kit".into(), + compared: vec![behaviour::Compared { + outcome: behaviour::Outcome::Changed, + reached: true, + ..Default::default() + }], + ..Default::default() + }; + let f = UpgradeFacts { + behaviour: vec![shown, changed], + ..Default::default() + }; + assert!(!f.unchanged_shown()); + } +} diff --git a/services/common/src/upgrade_quality/safety.rs b/services/common/src/upgrade_quality/safety.rs new file mode 100644 index 000000000..bb1f24641 --- /dev/null +++ b/services/common/src/upgrade_quality/safety.rs @@ -0,0 +1,884 @@ +//! Why a bump across a major version is safe, from evidence. +//! +//! A dependency pull request moved four packages across a major version, +//! three of them through overrides. The code was sound. The description +//! did not say who depends on each, whether that code runs in production +//! or only when the project installs, builds or lints, whether the feature +//! that uses it is configured at all, or what was run for the one that +//! sits behind a request. +//! +//! For each major, [`evidence`] assembles what a reviewer asks, each part +//! from a recorded fact: +//! +//! - the dependency paths that reach it, each classed ([`classify`]) as +//! production, development, build time or install time, from where the +//! manifest declares the path's root and which of the repository's files +//! import it; +//! - whether the repository uses the package or the feature that needs it, +//! from a search of its files, with what was searched; +//! - the reachability verdict with its limit written beside it: "not +//! reachable" means no path was found, and is never proof of safety; +//! - how it is fixed ([`Route`]): raised in the manifest, through a parent +//! release that declares the fixed range ([`parent_route`], preferred +//! over an override), or by an override scoped to the version line, with +//! every parent the override pushes outside its declared range named; +//! - whether it needs a functional probe: a package on a request or job +//! path in production does, and a development tool does not. +//! +//! Everything here is pure. + +use serde::{Deserialize, Serialize}; + +use crate::dep_fix::Companion; +use crate::reachability::{is_test_path, is_tooling_config}; +use crate::security_fixes::{is_major_bump, version_line, Verdict}; +use crate::upgrade_notes::{range_admits, ParentSupport}; + +/// When the code of a dependency path runs. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, +)] +#[serde(rename_all = "snake_case")] +pub enum PathClass { + /// In the running application. + Production, + /// When the project is built (a bundler, a compiler plugin). + BuildTime, + /// When the project's dependencies are installed (an install script). + InstallTime, + /// In a development tool: tests, lint, local tooling. + Development, + #[default] + NotKnown, +} + +impl PathClass { + pub fn words(self) -> &'static str { + match self { + PathClass::Production => "production", + PathClass::BuildTime => "build time only", + PathClass::InstallTime => "install time only", + PathClass::Development => "development only", + PathClass::NotKnown => "not known", + } + } +} + +/// Where a manifest declares a direct dependency. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum Declared { + Production, + Development, + #[default] + NotKnown, +} + +/// One dependency path that reaches a package: the direct dependency at +/// its root, and what is known of it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PathIn { + /// The direct dependency that brings the package in (the package + /// itself, when it is direct). + pub root: String, + pub declared: Declared, + /// The repository's files that import the root. + pub importers: Vec, + /// A package on the path runs a script when it is installed. + pub install_script: bool, + /// The manifest scripts that run the root (`build`, `lint`). + pub scripts: Vec, +} + +/// One path with its class and the reason for it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct PathFact { + pub root: String, + pub class: PathClass, + pub why: String, +} + +fn name_list(files: &[&String]) -> String { + let shown: Vec = files.iter().take(3).map(|f| format!("`{f}`")).collect(); + format!( + "{}{}", + shown.join(", "), + if files.len() > 3 { + format!(" and {} more", files.len() - 3) + } else { + String::new() + } + ) +} + +/// When the code of one path runs, with why. The files that import the +/// root decide before the manifest's section does: a package declared for +/// development and imported by application code runs in production. +pub fn classify(p: &PathIn) -> PathFact { + let source: Vec<&String> = p + .importers + .iter() + .filter(|f| !is_test_path(f) && !is_tooling_config(f)) + .collect(); + let tooling: Vec<&String> = p + .importers + .iter() + .filter(|f| is_tooling_config(f)) + .collect(); + let tests: Vec<&String> = p.importers.iter().filter(|f| is_test_path(f)).collect(); + let (class, why) = match p.declared { + _ if !source.is_empty() => ( + PathClass::Production, + match p.declared { + Declared::Development => format!( + "`{}` is declared for development and imported by application code ({})", + p.root, + name_list(&source) + ), + _ => format!("`{}` is imported by {}", p.root, name_list(&source)), + }, + ), + Declared::Development => ( + PathClass::Development, + if tests.is_empty() && tooling.is_empty() { + format!( + "`{}` is declared for development, and no application file imports it", + p.root + ) + } else { + let both: Vec<&String> = tooling.iter().chain(tests.iter()).copied().collect(); + format!( + "`{}` is declared for development and imported only by tests or tooling ({})", + p.root, + name_list(&both) + ) + }, + ), + Declared::Production if !tooling.is_empty() || !p.scripts.is_empty() => ( + PathClass::BuildTime, + if tooling.is_empty() { + format!( + "`{}` is run by the manifest's {} script{} and no application file imports it", + p.root, + p.scripts + .iter() + .map(|s| format!("`{s}`")) + .collect::>() + .join(", "), + if p.scripts.len() == 1 { "" } else { "s" } + ) + } else { + format!( + "`{}` is imported only by build configuration ({})", + p.root, + name_list(&tooling) + ) + }, + ), + Declared::Production if p.install_script => ( + PathClass::InstallTime, + format!( + "a package on the path through `{}` runs a script at install, and no file of the repository imports it", + p.root + ), + ), + Declared::Production => ( + PathClass::Production, + format!( + "`{}` is declared as a production dependency; no import of it was found, which is not proof it is unused", + p.root + ), + ), + Declared::NotKnown => ( + PathClass::NotKnown, + format!( + "where the manifest declares `{}` could not be read", + p.root + ), + ), + }; + PathFact { + root: p.root.clone(), + class, + why, + } +} + +/// The reachability verdict as a sentence, with what it does not show. +pub fn reachability_words(v: Verdict) -> &'static str { + match v { + Verdict::Reachable => { + "reachable: a path from the repository's code to the vulnerable code was found (a path is not proof it can be exploited)" + } + Verdict::NotReachable => { + "no path from the repository's code to the vulnerable code was found. That is not proof of safety: calls made by name at runtime, through reflection or from generated code are not seen" + } + Verdict::NotLoaded => { + "the package is not loaded by the repository's code. That is a read of its imports, not proof: a dependency can load it" + } + Verdict::Unknown => "reachability could not be decided from the code", + Verdict::Pending => "reachability has not been read yet", + } +} + +/// How the fixed version gets installed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case", tag = "by")] +pub enum Route { + /// The repository's own manifest declares it: its range is raised. + #[default] + Direct, + /// A parent's release declares the fixed range: the parent is raised. + Parent { + parent: String, + from: String, + to: String, + declares: String, + }, + /// An override scoped to the package's version line. + Override { selector: String }, +} + +/// The parent to raise instead of writing an override, when exactly one +/// parent brings the package in, the repository's manifest declares that +/// parent, the parent's newest release declares a range that admits the +/// fixed version and no longer admits the vulnerable one (so raising it +/// moves the package by itself), and raising the parent stays inside the +/// parent's own major version. `None` otherwise: an override is then the +/// way. +pub fn parent_route( + ecosystem: &str, + parents: &[ParentSupport], + parent_is_direct: bool, + from: &str, +) -> Option { + let [p] = parents else { + return None; + }; + if !parent_is_direct + || p.version.is_empty() + || p.latest.is_empty() + || p.latest == p.version + || p.admits == Some(true) + || p.latest_admits != Some(true) + || is_major_bump(&p.version, &p.latest) + || range_admits(ecosystem, &p.latest_declares, from) != Some(false) + { + return None; + } + Some(Companion { + package: p.parent.clone(), + from: p.version.clone(), + to: p.latest.clone(), + line: version_line(&p.version), + }) +} + +/// Routes each major of `plan` through its parent where [`parent_route`] +/// finds one: the parent is raised and no override is written. `notes`: +/// the upgrade notes read for the unit (each major's parents and what they +/// declare); `findings`: the unit's findings (their dependency paths say +/// whether the parent is in the repository's own manifest). +pub fn route_through_parents( + plan: &mut crate::dep_fix::DepPlan, + notes: &[crate::upgrade_notes::PackageNotes], + findings: &[( + crate::security_fixes::Finding, + crate::security_fixes::FindingState, + )], +) { + for b in plan + .bumps + .iter_mut() + .filter(|b| b.major && b.via_parent.is_none()) + { + let Some(n) = notes.iter().find(|n| { + n.package.eq_ignore_ascii_case(&b.package) && version_line(&n.from) == b.line + }) else { + continue; + }; + if n.direct { + continue; + } + let mine: Vec<&crate::security_fixes::Finding> = findings + .iter() + .map(|(f, _)| f) + .filter(|f| b.finding_ids.contains(&f.id)) + .collect(); + // A path of two is the direct dependency and the package itself. + let parent_is_direct = !mine.is_empty() && mine.iter().all(|f| f.path.len() == 2); + b.via_parent = parent_route(&n.ecosystem, &n.parents, parent_is_direct, &b.from); + } +} + +/// Whether a major needs a functional probe. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case", tag = "probe")] +pub enum ProbeNeed { + /// It runs in production behind the repository's own code. + Needed { why: String }, + /// It does not run in the application. + #[default] + NotNeeded, +} + +/// What [`evidence`] reads for one major. +#[derive(Debug, Clone, Default)] +pub struct MajorIn<'a> { + pub package: &'a str, + pub from: &'a str, + pub to: &'a str, + pub ecosystem: &'a str, + /// Why it leaves its version line. + pub why_major: &'a str, + pub paths: &'a [PathIn], + /// The repository's files that use the package or the feature that + /// needs it, as `path:line`. + pub used_in: &'a [String], + /// What was searched for, in words. + pub searched: &'a str, + pub verdict: Verdict, + pub direct: bool, + pub parents: &'a [ParentSupport], + /// The parent the plan raises instead of an override, when it does. + pub via_parent: Option<&'a Companion>, + /// The override's key, when one is written. + pub selector: &'a str, +} + +/// Why one major is safe, or what is not known about it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct MajorSafety { + pub package: String, + pub from: String, + pub to: String, + pub why_major: String, + pub paths: Vec, + /// The class that decides: production when any path is. + pub class: PathClass, + pub used_in: Vec, + pub searched: String, + pub reachability: String, + pub route: Route, + /// A parent release that would fix it without an override, named when + /// an override is used anyway, with why. + pub parent_available: String, + /// Each parent the fixed version is outside the declared range of. + pub outside_range: Vec, + pub probe: ProbeNeed, +} + +/// The evidence for one major (see the module notes). +pub fn evidence(i: &MajorIn<'_>) -> MajorSafety { + let paths: Vec = i.paths.iter().map(classify).collect(); + // The lowest class is the one that runs closest to production. + let class = paths + .iter() + .map(|p| p.class) + .filter(|c| *c != PathClass::NotKnown) + .min() + .unwrap_or(PathClass::NotKnown); + let route = match (i.direct, i.via_parent) { + (true, _) => Route::Direct, + (false, Some(p)) => Route::Parent { + parent: p.package.clone(), + from: p.from.clone(), + to: p.to.clone(), + declares: i + .parents + .iter() + .find(|s| s.parent == p.package) + .map(|s| s.latest_declares.clone()) + .unwrap_or_default(), + }, + (false, None) => Route::Override { + selector: if i.selector.is_empty() { + format!("{}@{}", i.package, version_line(i.from)) + } else { + i.selector.to_string() + }, + }, + }; + let overridden = matches!(route, Route::Override { .. }); + let outside_range: Vec = if overridden { + i.parents + .iter() + .filter(|p| p.admits == Some(false) && !p.declares.is_empty()) + .map(|p| { + format!( + "`{}`{} declares `{}` for it, and the override installs {}, outside that range", + p.parent, + if p.version.is_empty() { + String::new() + } else { + format!(" {}", p.version) + }, + p.declares, + i.to + ) + }) + .collect() + } else { + vec![] + }; + let parent_available = if overridden { + i.parents + .iter() + .find(|p| p.latest_admits == Some(true) && p.admits != Some(true)) + .map(|p| { + format!( + "`{}` {} declares `{}`, which admits {}. An override is used here because raising the parent would not by itself be enough ({})", + p.parent, + p.latest, + p.latest_declares, + i.to, + if i.parents.len() > 1 { + "more than one parent brings the package in" + } else if is_major_bump(&p.version, &p.latest) { + "the parent's own release is a major version away" + } else if p.version.is_empty() { + "the parent's installed version is not known" + } else { + "the repository's manifest does not declare the parent, or its new range still admits the vulnerable version" + } + ) + }) + .unwrap_or_default() + } else { + String::new() + }; + let probe = match class { + PathClass::Production if !i.used_in.is_empty() => ProbeNeed::Needed { + why: format!( + "it runs in production and the repository uses it ({})", + i.used_in + .iter() + .take(3) + .map(|u| format!("`{u}`")) + .collect::>() + .join(", ") + ), + }, + PathClass::Production => ProbeNeed::Needed { + why: "it is installed for production, and no use of it was found to rule a request or job path out".to_string(), + }, + _ => ProbeNeed::NotNeeded, + }; + MajorSafety { + package: i.package.to_string(), + from: i.from.to_string(), + to: i.to.to_string(), + why_major: i.why_major.to_string(), + paths, + class, + used_in: i.used_in.to_vec(), + searched: i.searched.to_string(), + reachability: reachability_words(i.verdict).to_string(), + route, + parent_available, + outside_range, + probe, + } +} + +impl MajorSafety { + /// The evidence as the pull request states it. + pub fn section(&self) -> String { + let mut s = format!( + "- `{}` {} to {} (major): runs in {}.\n", + self.package, + self.from, + self.to, + match self.class { + PathClass::NotKnown => "a place that could not be worked out", + c => c.words(), + } + ); + if !self.why_major.is_empty() { + s.push_str(&format!(" - Why a major: {}.\n", self.why_major)); + } + for p in self.paths.iter().take(4) { + s.push_str(&format!( + " - Path through `{}` ({}): {}.\n", + p.root, + p.class.words(), + p.why + )); + } + if self.paths.is_empty() { + s.push_str(" - Dependency paths: not read from the lockfile, so who depends on it is not known.\n"); + } else if self.paths.len() > 4 { + s.push_str(&format!(" - and {} more paths.\n", self.paths.len() - 4)); + } + if !self.searched.is_empty() || !self.used_in.is_empty() { + s.push_str(&match self.used_in.as_slice() { + [] => format!( + " - Use in this repository: none found (searched {}).\n", + self.searched + ), + used => format!( + " - Use in this repository: {}{}.\n", + used.iter() + .take(4) + .map(|u| format!("`{u}`")) + .collect::>() + .join(", "), + if used.len() > 4 { + format!(" and {} more", used.len() - 4) + } else { + String::new() + } + ), + }); + } + s.push_str(&format!(" - Reachability: {}.\n", self.reachability)); + s.push_str(&match &self.route { + Route::Direct => { + " - Fixed by raising its range in the repository's own manifest.\n".to_string() + } + Route::Parent { + parent, + from, + to, + declares, + } => format!( + " - Fixed by raising its parent `{parent}` {from} to {to}, which declares `{declares}`: no override.\n" + ), + Route::Override { selector } => format!( + " - Fixed by an override scoped to its version line (`{selector}`); other lines of the package are left alone.\n" + ), + }); + if !self.parent_available.is_empty() { + s.push_str(&format!( + " - A parent release admits it: {}.\n", + self.parent_available + )); + } + for o in &self.outside_range { + s.push_str(&format!(" - Outside a declared range: {o}.\n")); + } + if let ProbeNeed::Needed { why } = &self.probe { + s.push_str(&format!( + " - Needs a functional probe: {why}. See Behaviour changes.\n" + )); + } + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn path(root: &str, declared: Declared, importers: &[&str]) -> PathIn { + PathIn { + root: root.into(), + declared, + importers: importers.iter().map(|s| s.to_string()).collect(), + ..Default::default() + } + } + + #[test] + fn a_path_is_classed_by_who_imports_its_root_then_by_where_it_is_declared() { + // Production: declared for production and imported by the app. + let f = classify(&path( + "web-kit", + Declared::Production, + &["src/uploads/controller.ts"], + )); + assert_eq!(f.class, PathClass::Production); + assert_eq!( + f.why, + "`web-kit` is imported by `src/uploads/controller.ts`" + ); + // Development: declared for development, used by tests only. + let f = classify(&path( + "test-runner", + Declared::Development, + &["src/app.test.ts"], + )); + assert_eq!(f.class, PathClass::Development); + // Declared for development, imported by application code: it runs + // in production, and the mismatch is said. + let f = classify(&path( + "date-kit", + Declared::Development, + &["src/billing/invoice.ts"], + )); + assert_eq!(f.class, PathClass::Production); + assert!(f + .why + .contains("declared for development and imported by application code")); + // Build time: only a build configuration imports it. + let f = classify(&path( + "bundle-kit", + Declared::Production, + &["webpack.config.js"], + )); + assert_eq!(f.class, PathClass::BuildTime); + // Build time: run by a manifest script, imported nowhere. + let f = classify(&PathIn { + scripts: vec!["build".into()], + ..path("compile-kit", Declared::Production, &[]) + }); + assert_eq!(f.class, PathClass::BuildTime); + assert!(f.why.contains("run by the manifest's `build` script")); + // Install time: an install script on the path, imported nowhere. + let f = classify(&PathIn { + install_script: true, + ..path("native-kit", Declared::Production, &[]) + }); + assert_eq!(f.class, PathClass::InstallTime); + // Declared for production with nothing found: production, and the + // absence is not called proof. + let f = classify(&path("quiet-kit", Declared::Production, &[])); + assert_eq!(f.class, PathClass::Production); + assert!(f.why.contains("not proof it is unused")); + let f = classify(&path("lost", Declared::NotKnown, &[])); + assert_eq!(f.class, PathClass::NotKnown); + } + + fn parent(version: &str, admits: Option, latest: &str, declares: &str) -> ParentSupport { + ParentSupport { + parent: "web-kit".into(), + version: version.into(), + declares: "^1.4.0".into(), + admits, + latest: latest.into(), + latest_declares: declares.into(), + latest_admits: Some(true), + missing: String::new(), + } + } + + #[test] + fn a_parent_release_that_declares_the_fixed_range_is_preferred_to_an_override() { + // One direct parent whose newest release moved to the fixed major. + let p = parent("10.4.15", Some(false), "10.4.22", "^2.0.0"); + let route = parent_route("npm", std::slice::from_ref(&p), true, "1.4.5").unwrap(); + assert_eq!( + ( + route.package.as_str(), + route.from.as_str(), + route.to.as_str() + ), + ("web-kit", "10.4.15", "10.4.22") + ); + // Not when the parent is not in the repository's manifest, when its + // own release is a major away, when its new range still admits the + // vulnerable version, or when two parents bring the package in. + assert!(parent_route("npm", std::slice::from_ref(&p), false, "1.4.5").is_none()); + let far = parent("10.4.15", Some(false), "11.0.0", "^2.0.0"); + assert!(parent_route("npm", &[far], true, "1.4.5").is_none()); + let wide = parent("10.4.15", Some(false), "10.4.22", ">=1.4.0"); + assert!(parent_route("npm", &[wide], true, "1.4.5").is_none()); + assert!(parent_route("npm", &[p.clone(), p], true, "1.4.5").is_none()); + } + + #[test] + fn the_evidence_for_a_major_on_a_request_path_asks_for_a_probe() { + let paths = [path( + "web-kit", + Declared::Production, + &["src/uploads/controller.ts"], + )]; + let used = vec!["src/uploads/controller.ts:14".to_string()]; + let parents = [ParentSupport { + latest_admits: None, + ..parent("10.4.15", Some(false), "10.4.15", "") + }]; + let m = evidence(&MajorIn { + package: "upload-kit", + from: "1.4.5", + to: "2.0.2", + ecosystem: "npm", + why_major: "GHSA-1 lists no patched release on the 1 line", + paths: &paths, + used_in: &used, + searched: "`upload-kit` and the APIs its notes name", + verdict: Verdict::NotReachable, + parents: &parents, + ..Default::default() + }); + assert_eq!(m.class, PathClass::Production); + assert!(matches!(m.probe, ProbeNeed::Needed { .. })); + assert_eq!( + m.route, + Route::Override { + selector: "upload-kit@1".into() + } + ); + let text = m.section(); + assert!(text.contains("- `upload-kit` 1.4.5 to 2.0.2 (major): runs in production.")); + assert!(text.contains("Path through `web-kit` (production)")); + // The verdict carries its limit. + assert!(text.contains("That is not proof of safety")); + // The override pushes the parent outside what it declares. + assert!(text.contains( + "Outside a declared range: `web-kit` 10.4.15 declares `^1.4.0` for it, and the override installs 2.0.2, outside that range." + )); + assert!(text.contains("override scoped to its version line (`upload-kit@1`)")); + assert!(text.contains("Needs a functional probe")); + } + + #[test] + fn a_development_tool_or_an_install_helper_needs_no_probe_and_says_why() { + let dev = [path("lint-kit", Declared::Development, &[".eslintrc.js"])]; + let m = evidence(&MajorIn { + package: "glob-walk", + from: "7.2.0", + to: "9.0.1", + paths: &dev, + searched: "`glob-walk`", + verdict: Verdict::NotLoaded, + ..Default::default() + }); + assert_eq!(m.class, PathClass::Development); + assert_eq!(m.probe, ProbeNeed::NotNeeded); + let text = m.section(); + assert!(text.contains("runs in development only")); + assert!(text.contains("Use in this repository: none found (searched `glob-walk`)")); + assert!(!text.contains("Needs a functional probe")); + // Two paths, one of them production: production decides. + let both = [ + path("lint-kit", Declared::Development, &[]), + path("web-kit", Declared::Production, &["src/main.ts"]), + ]; + let m = evidence(&MajorIn { + package: "glob-walk", + from: "7.2.0", + to: "9.0.1", + paths: &both, + ..Default::default() + }); + assert_eq!(m.class, PathClass::Production); + // No path read at all: said as not known, never as safe. + let none = evidence(&MajorIn { + package: "x", + from: "1.0.0", + to: "2.0.0", + direct: true, + ..Default::default() + }); + assert_eq!(none.class, PathClass::NotKnown); + assert!(none.section().contains("who depends on it is not known")); + assert!(none + .section() + .contains("runs in a place that could not be worked out")); + } + + #[test] + fn a_parent_route_is_stated_and_an_unused_one_is_explained() { + let via = Companion { + package: "web-kit".into(), + from: "10.4.15".into(), + to: "10.4.22".into(), + line: "10".into(), + }; + let parents = [parent("10.4.15", Some(false), "10.4.22", "^2.0.0")]; + let m = evidence(&MajorIn { + package: "upload-kit", + from: "1.4.5", + to: "2.0.2", + parents: &parents, + via_parent: Some(&via), + ..Default::default() + }); + assert!(m.section().contains( + "Fixed by raising its parent `web-kit` 10.4.15 to 10.4.22, which declares `^2.0.0`: no override." + )); + assert!(m.outside_range.is_empty()); + // The same parent, not taken: the override says why. + let m = evidence(&MajorIn { + package: "upload-kit", + from: "1.4.5", + to: "2.0.2", + parents: &parents, + ..Default::default() + }); + assert!(m + .parent_available + .contains("`web-kit` 10.4.22 declares `^2.0.0`, which admits 2.0.2")); + } + + #[test] + fn the_plan_raises_the_parent_only_where_the_manifest_declares_it() { + use crate::dep_fix::{DepPlan, PlanBump}; + use crate::security_fixes::{Finding, FindingState}; + use crate::upgrade_notes::PackageNotes; + let bump = |id: &str| PlanBump { + package: "upload-kit".into(), + from: "1.4.5".into(), + to: "2.0.2".into(), + line: "1".into(), + manifest: "pnpm-lock.yaml".into(), + major: true, + finding_ids: vec![id.into()], + ..Default::default() + }; + let notes = vec![PackageNotes { + package: "upload-kit".into(), + ecosystem: "npm".into(), + from: "1.4.5".into(), + to: "2.0.2".into(), + major: true, + parents: vec![parent("10.4.15", Some(false), "10.4.22", "^2.0.0")], + ..Default::default() + }]; + let finding = |id: &str, path: &[&str]| { + ( + Finding { + id: id.into(), + path: path.iter().map(|s| s.to_string()).collect(), + ..Default::default() + }, + FindingState::default(), + ) + }; + let findings = vec![ + finding("f-direct", &["web-kit", "upload-kit"]), + finding("f-deep", &["app-shell", "web-kit", "upload-kit"]), + ]; + let mut plan = DepPlan { + bumps: vec![bump("f-direct"), bump("f-deep")], + deferred: vec![], + }; + route_through_parents(&mut plan, ¬es, &findings); + // The parent is in the manifest: it is raised, and the apply script + // is told the parent, never an override of the package. + let via = plan.bumps[0].via_parent.as_ref().unwrap(); + assert_eq!( + (via.package.as_str(), via.to.as_str()), + ("web-kit", "10.4.22") + ); + let specs = crate::dep_fix::specs(&[&plan.bumps[0]]); + assert_eq!(specs[0].bumps.len(), 1); + assert_eq!(specs[0].bumps[0].name, "web-kit"); + // The parent is itself brought in by another package: an override. + assert!(plan.bumps[1].via_parent.is_none()); + assert_eq!( + crate::dep_fix::specs(&[&plan.bumps[1]])[0].bumps[0].name, + "upload-kit" + ); + // A lockfile where the raised parent left the package behind is + // found, so the run falls back to the override. + let lock = "lockfileVersion: '9.0'\nimporters:\n .:\n dependencies:\n web-kit:\n specifier: ^10.4.22\n version: 10.4.22\npackages:\n upload-kit@1.4.5: {}\n web-kit@10.4.22: {}\nsnapshots:\n upload-kit@1.4.5: {}\n web-kit@10.4.22:\n dependencies:\n upload-kit: 1.4.5\n"; + let (split, unmoved) = crate::dep_fix::lockfile_violations( + &[], + &[&plan.bumps[0]], + &[("pnpm-lock.yaml".to_string(), lock.to_string())], + ); + assert!(split.is_empty()); + assert_eq!(unmoved, vec!["upload-kit"]); + let moved = lock.replace("1.4.5", "2.0.2"); + let (_, unmoved) = crate::dep_fix::lockfile_violations( + &[], + &[&plan.bumps[0]], + &[("pnpm-lock.yaml".to_string(), moved)], + ); + assert!(unmoved.is_empty()); + } +} diff --git a/services/common/src/upgrade_quality/verify.rs b/services/common/src/upgrade_quality/verify.rs new file mode 100644 index 000000000..c38598e81 --- /dev/null +++ b/services/common/src/upgrade_quality/verify.rs @@ -0,0 +1,1653 @@ +//! What a dependency change is verified with, whatever CI happens to run. +//! +//! A dependency pull request recorded no type check because the +//! repository's CI has none, and CoderHelm's checks mirrored CI. The +//! reviewer ran `tsc --noEmit` themselves, and a frozen-lockfile install +//! with the package manager version the manifest declares and again with +//! the one the deployment image installs. +//! +//! The set here is found in the project, never in its CI: +//! +//! - [`ROWS`] has one row per package manager: its frozen-lockfile install +//! with the flag written out (a package manager decides by itself whether +//! it is in CI), how it runs a tool, and how each check is found: a +//! manifest script, a configuration file, a table in a configuration +//! file, or the toolchain's own command. Adding a manager is one row. +//! - [`discover`] reads one project into a [`Plan`]: the frozen install, +//! the same install with the package manager version the deployment image +//! pins when that differs from the manifest's, the type check when the +//! project is typed, the build, the lint, the unit tests and the +//! production-scoped audit. A check the project does not have is named +//! with why (`no tsconfig.json: the project is not typed`). +//! - [`fit`] puts the set into the time one sandbox build has, in priority +//! order, and names what does not fit and why. Nothing is claimed for a +//! check that did not run. +//! - [`script`] is the one sandbox command; [`read`] turns its marked lines +//! into a [`Verified`] record of one head. [`blamed`] compares it with +//! the same set on the base branch, so a failure the base already has is +//! never blamed on the change. +//! +//! Where the commands come from: `pnpm install --frozen-lockfile`, +//! `pnpm audit --prod`, `npm audit --omit=dev` and `uv sync --locked` were +//! read from the tools' own documentation. The other rows are the commands +//! this codebase already runs (`runtime_proof::MANAGERS`, `dep_audit`, +//! `worker::passes::checks::TOOLS`) or each toolchain's standard ones. +//! +//! Everything here is pure; the sandbox run is the worker's +//! (`worker::passes::dep_fix`). + +use serde::{Deserialize, Serialize}; + +use crate::dep_fix::b64; +use crate::e2e::test_package::{ensure_manager, Manager as Js}; + +/// One kind of check of the minimum set. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, +)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// The frozen-lockfile install with the package manager version the + /// manifest declares (or the sandbox's, when it declares none). + #[default] + Install, + /// The same install with the version the deployment image pins. + DeployInstall, + Typecheck, + Build, + Lint, + Tests, + /// The package manager's audit of production dependencies. + Audit, +} + +impl Kind { + pub fn name(self) -> &'static str { + match self { + Kind::Install => "frozen install", + Kind::DeployInstall => "frozen install, deployment version", + Kind::Typecheck => "type check", + Kind::Build => "build", + Kind::Lint => "lint", + Kind::Tests => "unit tests", + Kind::Audit => "production audit", + } + } + + /// What is kept first when the time is short: lower is kept longer. + /// The install carries every other check; the type check is the + /// cheapest way to see a changed signature; the audit costs seconds. + pub fn priority(self) -> u8 { + match self { + Kind::Install => 0, + Kind::Typecheck => 1, + Kind::Audit => 2, + Kind::Build => 3, + Kind::Tests => 4, + Kind::Lint => 5, + Kind::DeployInstall => 6, + } + } + + /// The seconds a check of this kind is given when nothing is known of + /// the project: what it is budgeted, and half of its time limit. + pub fn seconds(self) -> u32 { + match self { + Kind::Install => 150, + Kind::DeployInstall => 120, + Kind::Typecheck => 75, + Kind::Build => 150, + Kind::Lint => 45, + Kind::Tests => 150, + Kind::Audit => 30, + } + } + + /// It needs the install to have passed. + fn needs_install(self) -> bool { + !matches!(self, Kind::Install | Kind::DeployInstall | Kind::Audit) + } + + /// A failure of it can be the change's (lint fails on configuration + /// quirks, and an audit that finds advisories is a result). + pub fn blames(self) -> bool { + !matches!(self, Kind::Lint | Kind::Audit) + } +} + +/// How one check is found in a project. The first way that applies wins. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Found { + pub kind: Kind, + /// Manifest script names; the first one the manifest has is run. + pub scripts: &'static [&'static str], + /// Configuration files whose presence means the project has the check. + pub files: &'static [&'static str], + /// A file and a text in it that mean the same (`pyproject.toml`, + /// `[tool.mypy]`). + pub marks: &'static [(&'static str, &'static str)], + /// The tool's command when a file or a mark found it. + pub cmd: &'static str, + /// The toolchain's own check: it applies to every project. + pub always: bool, +} + +const fn by_script(kind: Kind, scripts: &'static [&'static str]) -> Found { + Found { + kind, + scripts, + files: &[], + marks: &[], + cmd: "", + always: false, + } +} + +const fn by_config( + kind: Kind, + scripts: &'static [&'static str], + files: &'static [&'static str], + marks: &'static [(&'static str, &'static str)], + cmd: &'static str, +) -> Found { + Found { + kind, + scripts, + files, + marks, + cmd, + always: false, + } +} + +const fn own(kind: Kind, cmd: &'static str) -> Found { + Found { + kind, + scripts: &[], + files: &[], + marks: &[], + cmd, + always: true, + } +} + +/// One package manager's minimum set. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Row { + pub manager: &'static str, + pub lockfiles: &'static [&'static str], + /// Installs exactly what the lockfile says and fails when the lockfile + /// and the manifest disagree, with the flag written out. + pub install: &'static str, + /// Makes the manager available first, when it may be missing. + pub ensure: &'static str, + /// The manifest whose scripts name checks. + pub manifest: Option<&'static str>, + /// Runs a manifest script; the script's name follows. + pub run_script: &'static str, + /// Runs a tool of the project; the tool's command follows. + pub run_tool: &'static str, + pub checks: &'static [Found], + /// Runs the install with an exact version of the manager (`{v}` is the + /// version); empty when the sandbox has no way to. + pub at_version: &'static str, + /// Why a kind the row never finds does not apply to its projects. + pub never: &'static [(Kind, &'static str)], +} + +const TS_SCRIPTS: &[&str] = &["typecheck", "type-check", "check-types", "types", "tsc"]; +const ESLINT: &[&str] = &[ + ".eslintrc", + ".eslintrc.js", + ".eslintrc.cjs", + ".eslintrc.json", + ".eslintrc.yml", + ".eslintrc.yaml", + "eslint.config.js", + "eslint.config.mjs", + "eslint.config.cjs", + "eslint.config.ts", +]; +const VITEST: &[&str] = &[ + "vitest.config.ts", + "vitest.config.mts", + "vitest.config.js", + "vitest.config.mjs", +]; +const JEST: &[&str] = &[ + "jest.config.js", + "jest.config.ts", + "jest.config.cjs", + "jest.config.mjs", + "jest.config.json", +]; + +/// The checks of a JavaScript or TypeScript project, whatever its manager. +const JS_CHECKS: &[Found] = &[ + by_config( + Kind::Typecheck, + TS_SCRIPTS, + &["tsconfig.json"], + &[], + "npx --no-install tsc --noEmit", + ), + by_script(Kind::Build, &["build"]), + by_config( + Kind::Lint, + &["lint"], + ESLINT, + &[], + "npx --no-install eslint .", + ), + by_config( + Kind::Lint, + &[], + &["biome.json", "biome.jsonc"], + &[], + "npx --no-install biome ci .", + ), + by_config( + Kind::Tests, + &["test:unit", "test:ci", "test"], + VITEST, + &[], + "npx --no-install vitest run", + ), + by_config(Kind::Tests, &[], JEST, &[], "npx --no-install jest --ci"), +]; + +/// The checks of a Python project, whatever its manager. +const PY_CHECKS: &[Found] = &[ + by_config( + Kind::Typecheck, + &[], + &["mypy.ini", ".mypy.ini"], + &[("pyproject.toml", "[tool.mypy]"), ("setup.cfg", "[mypy]")], + "mypy .", + ), + by_config( + Kind::Typecheck, + &[], + &["pyrightconfig.json"], + &[("pyproject.toml", "[tool.pyright]")], + "pyright", + ), + own(Kind::Build, "python -m compileall -q ."), + by_config( + Kind::Lint, + &[], + &["ruff.toml", ".ruff.toml"], + &[("pyproject.toml", "[tool.ruff")], + "ruff check .", + ), + by_config( + Kind::Lint, + &[], + &[".flake8"], + &[("setup.cfg", "[flake8]"), ("tox.ini", "[flake8]")], + "flake8", + ), + by_config( + Kind::Tests, + &[], + &["pytest.ini", "conftest.py", "tests/conftest.py"], + &[ + ("pyproject.toml", "[tool.pytest"), + ("setup.cfg", "[tool:pytest]"), + ("tox.ini", "[pytest]"), + ], + "pytest -q", + ), +]; + +const NOT_TYPED_PY: &str = "no mypy or pyright configuration: the project is not type-checked"; + +const fn js( + manager: &'static str, + lockfiles: &'static [&'static str], + install: &'static str, + run_script: &'static str, + at_version: &'static str, +) -> Row { + Row { + manager, + lockfiles, + install, + // Made available by `ensure_manager`, per manager, in `discover`. + ensure: "", + manifest: Some("package.json"), + run_script, + run_tool: "", + checks: JS_CHECKS, + at_version, + never: &[], + } +} + +const fn py( + manager: &'static str, + lockfiles: &'static [&'static str], + install: &'static str, + ensure: &'static str, + run_tool: &'static str, +) -> Row { + Row { + manager, + lockfiles, + install, + ensure, + manifest: None, + run_script: "", + run_tool, + checks: PY_CHECKS, + at_version: "", + never: &[(Kind::Typecheck, NOT_TYPED_PY)], + } +} + +/// The minimum set of each package manager CoderHelm writes lockfiles for +/// (`lockfile_sync::lock_manager` names the same ones). +pub const ROWS: &[Row] = &[ + js( + "npm", + &["package-lock.json", "npm-shrinkwrap.json"], + "npm ci --no-audit --no-fund", + "npm run", + "npx -y npm@{v} ci --no-audit --no-fund --ignore-scripts", + ), + js( + "pnpm", + &["pnpm-lock.yaml"], + "pnpm install --frozen-lockfile", + "pnpm run", + "npx -y pnpm@{v} install --frozen-lockfile --ignore-scripts", + ), + js( + "yarn", + &["yarn.lock"], + "yarn install --frozen-lockfile", + "yarn run", + "npx -y yarn@{v} install --frozen-lockfile --ignore-scripts", + ), + js( + "bun", + &["bun.lock", "bun.lockb"], + "bun install --frozen-lockfile", + "bun run", + "", + ), + Row { + manager: "cargo", + lockfiles: &["Cargo.lock"], + install: "cargo fetch --locked", + ensure: "", + manifest: None, + run_script: "", + run_tool: "", + checks: &[ + own(Kind::Typecheck, "cargo check --locked --all-targets"), + own(Kind::Build, "cargo build --locked"), + own( + Kind::Lint, + "cargo clippy --locked --all-targets -- -D warnings", + ), + own(Kind::Tests, "cargo test --locked"), + ], + at_version: "", + never: &[], + }, + py( + "poetry", + &["poetry.lock"], + "poetry install --no-interaction", + "(command -v poetry >/dev/null 2>&1 || pip install -q poetry) && ", + "poetry run ", + ), + py( + "uv", + &["uv.lock"], + "uv sync --locked", + "(command -v uv >/dev/null 2>&1 || pip install -q uv) && ", + "uv run ", + ), + py( + "pipenv", + &["Pipfile.lock"], + "pipenv sync --dev", + "(command -v pipenv >/dev/null 2>&1 || pip install -q pipenv) && ", + "pipenv run ", + ), + Row { + manager: "bundler", + lockfiles: &["Gemfile.lock"], + install: "BUNDLE_FROZEN=true bundle install", + ensure: "", + manifest: None, + run_script: "", + run_tool: "bundle exec ", + checks: &[ + by_config(Kind::Typecheck, &[], &["sorbet/config"], &[], "srb tc"), + by_config(Kind::Lint, &[], &[".rubocop.yml"], &[], "rubocop"), + by_config( + Kind::Tests, + &[], + &[".rspec", "spec/spec_helper.rb"], + &[], + "rspec", + ), + by_config(Kind::Tests, &[], &["test/test_helper.rb"], &[], "rake test"), + ], + at_version: "", + never: &[ + ( + Kind::Typecheck, + "no `sorbet/config`: the project is not typed", + ), + (Kind::Build, "a Ruby project has no build step"), + ], + }, + Row { + manager: "go", + lockfiles: &["go.sum"], + install: "go mod download && go mod verify", + ensure: "", + manifest: None, + run_script: "", + run_tool: "", + checks: &[ + own(Kind::Typecheck, "go vet ./..."), + own(Kind::Build, "go build ./..."), + by_config( + Kind::Lint, + &[], + &[".golangci.yml", ".golangci.yaml", ".golangci.toml"], + &[], + "golangci-lint run", + ), + own(Kind::Tests, "go test ./..."), + ], + at_version: "", + never: &[], + }, +]; + +/// The row of a lockfile's manager. +pub fn row_of(lockfile: &str) -> Option<&'static Row> { + let name = lockfile.rsplit('/').next().unwrap_or(lockfile); + ROWS.iter().find(|r| r.lockfiles.contains(&name)) +} + +fn dir_of(path: &str) -> &str { + path.rsplit_once('/').map(|(d, _)| d).unwrap_or("") +} + +fn under(dir: &str, name: &str) -> String { + if dir.is_empty() { + name.to_string() + } else { + format!("{dir}/{name}") + } +} + +/// A deployment image's file, by name. +fn is_dockerfile(path: &str) -> bool { + let name = path.rsplit('/').next().unwrap_or(path); + name == "Dockerfile" || name.starts_with("Dockerfile.") || name.ends_with(".Dockerfile") +} + +/// Dockerfiles one project's plan reads at most. +const MAX_DOCKERFILES: usize = 4; + +/// The files [`discover`] reads for the project of `lockfile`, of those in +/// `tree`: its manifest, the configuration files a row's marks name, and +/// the Dockerfiles in its folder and at the repository root. +pub fn files_to_read(lockfile: &str, tree: &[String]) -> Vec { + let Some(row) = row_of(lockfile) else { + return vec![]; + }; + let dir = dir_of(lockfile); + let mut want: Vec = vec![]; + if let Some(m) = row.manifest { + want.push(under(dir, m)); + } + for f in row.checks { + for (file, _) in f.marks { + want.push(under(dir, file)); + } + } + let mut docker: Vec<&String> = tree + .iter() + .filter(|p| is_dockerfile(p) && (dir_of(p) == dir || dir_of(p).is_empty())) + .collect(); + // The project's own first, then the root's. + docker.sort_by_key(|p| (dir_of(p) != dir, p.len())); + want.extend(docker.into_iter().take(MAX_DOCKERFILES).cloned()); + want.sort(); + want.dedup(); + want.retain(|p| tree.contains(p)); + want +} + +/// A version number at the start of `s` (`9.1.0`, `1.8`). +fn version_at(s: &str) -> Option { + let v: String = s + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + let v = v.trim_end_matches('.').to_string(); + (v.contains('.') && v.chars().next().is_some_and(|c| c.is_ascii_digit())).then_some(v) +} + +/// The package manager version a manifest declares (`packageManager: +/// "pnpm@9.1.0"`), when it names `manager`. +pub fn declared_version(manifest: &str, manager: &str) -> Option { + let v: serde_json::Value = serde_json::from_str(manifest).ok()?; + let pm = v.get("packageManager")?.as_str()?; + let (name, version) = pm.split_once('@')?; + (name == manager).then(|| version_at(version)).flatten() +} + +/// The version of `manager` a Dockerfile installs: `@` +/// (`npm install -g pnpm@9.1.0`, `corepack prepare pnpm@9.1.0`), +/// `==` (`pip install poetry==1.8.2`), or a +/// `_VERSION` it sets. `None` when it names none. +pub fn image_version(dockerfile: &str, manager: &str) -> Option { + let upper = format!("{}_VERSION", manager.to_ascii_uppercase()); + for line in dockerfile.lines() { + let l = line.trim(); + if l.starts_with('#') { + continue; + } + for sep in ["@", "=="] { + let needle = format!("{manager}{sep}"); + let mut from = 0; + while let Some(i) = l[from..].find(&needle) { + let at = from + i; + let before = l[..at].chars().next_back(); + let word_start = before.is_none_or(|c| !c.is_ascii_alphanumeric() && c != '-'); + if word_start { + if let Some(v) = version_at(&l[at + needle.len()..]) { + return Some(v); + } + } + from = at + needle.len(); + } + } + if let Some(i) = l.find(&upper) { + let rest = l[i + upper.len()..].trim_start_matches(['=', ' ', '"', '\'']); + if let Some(v) = version_at(rest) { + return Some(v); + } + } + } + None +} + +/// One check of a plan. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Check { + pub kind: Kind, + /// The command as people read it. + pub shown: String, + /// The full command, run in the project's folder. + pub cmd: String, + /// Where it was found, in words. + pub found: String, +} + +/// What a project is verified with, found once. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Plan { + pub lockfile: String, + pub manager: String, + /// The project's folder from the repository root. + pub dir: String, + pub checks: Vec, + /// The kinds the project does not have, each with why. + pub not_applicable: Vec<(Kind, String)>, + /// The package manager version the manifest declares; empty for none. + pub declared: String, + /// The version the deployment image pins and the file that pins it; + /// empty for none. + pub image: String, + pub image_file: String, + /// Why nothing can be verified; empty when something can. + pub none: String, +} + +impl Plan { + pub fn is_empty(&self) -> bool { + self.checks.is_empty() + } +} + +/// A folder name a shell command can carry. +fn is_plain_path(p: &str) -> bool { + p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '-' | '.' | '@')) + && !p.contains("..") +} + +fn script_of<'a>(manifest: &'a serde_json::Value, name: &str) -> Option<&'a str> { + let s = manifest.get("scripts")?.get(name)?.as_str()?; + // The placeholder a new package.json comes with tests nothing. + (!s.trim().is_empty() && !s.contains("no test specified")).then_some(s) +} + +/// What the project of `lockfile` is verified with. `tree`: the +/// repository's files; `files`: the ones [`files_to_read`] named, with +/// their text; `audit`: the production-scoped audit of the lockfile's +/// manager (shown, command), when it has one. +pub fn discover( + lockfile: &str, + tree: &[String], + files: &[(String, String)], + audit: Option<(&str, &str)>, +) -> Plan { + let dir = dir_of(lockfile).to_string(); + let mut plan = Plan { + lockfile: lockfile.to_string(), + dir: dir.clone(), + ..Default::default() + }; + let Some(row) = row_of(lockfile) else { + plan.none = format!("`{lockfile}` is not a lockfile CoderHelm installs from"); + return plan; + }; + plan.manager = row.manager.to_string(); + if !is_plain_path(&dir) { + plan.none = format!("the project folder `{dir}` can't be named in a sandbox command"); + return plan; + } + let text = |name: &str| -> Option<&str> { + let path = under(&dir, name); + files + .iter() + .find(|(p, _)| *p == path) + .map(|(_, t)| t.as_str()) + }; + let has_file = |name: &str| tree.contains(&under(&dir, name)); + let manifest_text = row.manifest.and_then(text); + let manifest: Option = + manifest_text.and_then(|t| serde_json::from_str(t).ok()); + // Yarn 2 and later installs with `--immutable`. + let berry = row.manager == "yarn" && has_file(".yarnrc.yml"); + let install = if berry { + "yarn install --immutable" + } else { + row.install + }; + let ensure = match row.manager { + "pnpm" => ensure_manager(Js::Pnpm), + "yarn" => ensure_manager(Js::Yarn), + "bun" => ensure_manager(Js::Bun), + _ => row.ensure, + }; + plan.declared = manifest_text + .and_then(|t| declared_version(t, row.manager)) + .unwrap_or_default(); + plan.checks.push(Check { + kind: Kind::Install, + shown: install.to_string(), + cmd: format!("{ensure}{install}"), + found: if plan.declared.is_empty() { + format!( + "{}'s frozen-lockfile install, with the sandbox's {} (the manifest declares no version)", + row.manager, row.manager + ) + } else { + format!( + "{}'s frozen-lockfile install, with {} {} as `{}` declares", + row.manager, + row.manager, + plan.declared, + under(&dir, row.manifest.unwrap_or("the manifest")) + ) + }, + }); + // The version the deployment image installs, when it pins another. + let pinned = files + .iter() + .filter(|(p, _)| is_dockerfile(p)) + .find_map(|(p, t)| image_version(t, row.manager).map(|v| (p.clone(), v))); + if let Some((file, v)) = pinned { + plan.image = v.clone(); + plan.image_file = file.clone(); + if v == plan.declared { + plan.not_applicable.push(( + Kind::DeployInstall, + format!( + "`{file}` installs {} {v}, the version the manifest declares: one install covers both", + row.manager + ), + )); + } else if row.at_version.is_empty() || berry { + plan.not_applicable.push(( + Kind::DeployInstall, + format!( + "`{file}` installs {} {v}; CoderHelm's sandbox has no way to run that exact version of {}, so the frozen install was not run with it", + row.manager, row.manager + ), + )); + } else { + let cmd = row.at_version.replace("{v}", &v); + plan.checks.push(Check { + kind: Kind::DeployInstall, + shown: cmd.clone(), + cmd, + found: format!("`{file}` installs {} {v}", row.manager), + }); + } + } else { + plan.not_applicable.push(( + Kind::DeployInstall, + "no Dockerfile of the project pins a package manager version".to_string(), + )); + } + for kind in [Kind::Typecheck, Kind::Build, Kind::Lint, Kind::Tests] { + let mut found: Option = None; + for f in row.checks.iter().filter(|f| f.kind == kind) { + let by_file = f.files.iter().find(|n| has_file(n)); + let by_mark = f + .marks + .iter() + .find(|(file, needle)| text(file).is_some_and(|t| t.contains(needle))); + let script = manifest + .as_ref() + .and_then(|m| f.scripts.iter().find(|s| script_of(m, s).is_some())); + // The project has the check when its configuration is there + // (whatever CI or the scripts do with it), or a script runs it. + let applies = f.always || by_file.is_some() || by_mark.is_some() || script.is_some(); + if !applies { + continue; + } + let (shown, source) = match (script, by_file, by_mark) { + (Some(s), _, _) => ( + format!("{} {s}", row.run_script), + format!( + "the `{s}` script of `{}`", + under(&dir, row.manifest.unwrap_or("the manifest")) + ), + ), + (None, Some(file), _) => ( + format!("{}{}", row.run_tool, f.cmd), + format!("`{}` is there and no script runs it", under(&dir, file)), + ), + (None, None, Some((file, needle))) => ( + format!("{}{}", row.run_tool, f.cmd), + format!("`{needle}` in `{}`", under(&dir, file)), + ), + (None, None, None) => ( + format!("{}{}", row.run_tool, f.cmd), + format!("{}'s own {}", row.manager, kind.name()), + ), + }; + found = Some(Check { + kind, + cmd: shown.clone(), + shown, + found: source, + }); + break; + } + match found { + Some(c) => plan.checks.push(c), + None => { + let why = row + .never + .iter() + .find(|(k, _)| *k == kind) + .map(|(_, w)| w.to_string()) + .unwrap_or_else(|| match (kind, row.manifest) { + (Kind::Typecheck, Some(_)) => { + "no `tsconfig.json`: the project is not typed".to_string() + } + (_, Some(m)) => format!( + "`{}` has no script for it and the project has no configuration file of a tool that runs it", + under(&dir, m) + ), + _ => "the project has no configuration file of a tool that runs it" + .to_string(), + }); + plan.not_applicable.push((kind, why)); + } + } + } + match audit { + Some((shown, cmd)) => plan.checks.push(Check { + kind: Kind::Audit, + shown: shown.to_string(), + cmd: cmd.to_string(), + found: format!("{}'s audit of production dependencies", row.manager), + }), + None => plan.not_applicable.push(( + Kind::Audit, + format!( + "CoderHelm has no production-scoped audit for {}; the audit of every dependency runs in the settle stage", + row.manager + ), + )), + } + plan +} + +// ── The time one sandbox build has ────────────────────────────────────── + +/// What a sandbox build spends before the first check: the snapshot of +/// the branch and the image's start. +pub const OVERHEAD_SECS: u32 = 60; + +/// What fits in `secs` of one sandbox build: the checks to run (indices +/// into `plan.checks`, in the plan's order) and the ones left out, each +/// with why. Checks are kept in priority order ([`Kind::priority`]); the +/// install comes first, and without room for it nothing runs. +pub fn fit(plan: &Plan, secs: u32) -> (Vec, Vec<(usize, String)>) { + let room = secs.saturating_sub(OVERHEAD_SECS); + let mut order: Vec = (0..plan.checks.len()).collect(); + order.sort_by_key(|&i| (plan.checks[i].kind.priority(), i)); + let mut used = 0u32; + let mut run: Vec = vec![]; + let mut left: Vec<(usize, String)> = vec![]; + let mut installed = true; + for i in order { + let k = plan.checks[i].kind; + let cost = k.seconds(); + if k.needs_install() && !installed { + left.push(( + i, + "the install it needs did not fit in this sandbox build".to_string(), + )); + continue; + } + if used + cost <= room { + used += cost; + run.push(i); + } else { + if k == Kind::Install { + installed = false; + } + left.push(( + i, + format!( + "the sandbox build had {} seconds left for checks and this one is given {}; the checks before it in priority took {}", + room, cost, used + ), + )); + } + } + run.sort(); + left.sort_by_key(|(i, _)| *i); + (run, left) +} + +// ── The command and its output ────────────────────────────────────────── + +/// What each check's line in the output starts with. +pub const MARK: &str = "CODERHELM_VERIFY"; +/// The line that says which version of the package manager installed. +pub const PM_MARK: &str = "CODERHELM_VERIFY_PM"; +/// The exit code `timeout` gives a command it stopped. +const TIMED_OUT: i32 = 124; + +/// The command that prints a manager's own version. +fn version_cmd(manager: &str) -> Option<&'static str> { + Some(match manager { + "npm" => "npm --version", + "pnpm" => "pnpm --version", + "yarn" => "yarn --version", + "bun" => "bun --version", + "poetry" => "poetry --version", + "uv" => "uv --version", + "pipenv" => "pipenv --version", + "cargo" => "cargo --version", + "bundler" => "bundle --version", + "go" => "go version", + _ => return None, + }) +} + +/// The one sandbox command that runs the checks `run` of `plan`, each on +/// its own with a time limit, so a failing or slow one never hides the +/// next. A failed check's last output is printed, then one +/// `CODERHELM_VERIFY ` line per check, last, where the +/// sandbox's kept output always holds it (`skip` for one whose install +/// failed). `after_audit` is printed by the audit's own reducer +/// (`dep_audit::listing`), given the audit's output file. Always exits 0. +pub fn script(plan: &Plan, run: &[usize], audit_reducer: &str) -> String { + let mut s = String::new(); + let per = 2400 / run.len().max(1); + let install = run + .iter() + .copied() + .find(|&i| plan.checks[i].kind == Kind::Install); + let cd = if plan.dir.is_empty() { + String::new() + } else { + format!("cd '{}' && ", plan.dir) + }; + for &i in run { + let c = &plan.checks[i]; + let limit = c.kind.seconds() * 2; + let body = format!("{cd}{}", c.cmd); + let one = format!( + "echo '{}' | base64 -d > /tmp/coderhelm-verify-{i}.sh; \ + timeout {limit} sh /tmp/coderhelm-verify-{i}.sh > /tmp/coderhelm-verify-{i}.log 2>&1; ch_v{i}=$?", + b64(body.as_bytes()) + ); + match install { + Some(ins) if c.kind.needs_install() => s.push_str(&format!( + "if [ \"$ch_v{ins}\" = 0 ]; then {one}; else ch_v{i}=skip; fi\n" + )), + _ => s.push_str(&format!("{one}\n")), + } + } + for &i in run { + let c = &plan.checks[i]; + if c.kind == Kind::Audit { + continue; + } + s.push_str(&format!( + "if [ \"$ch_v{i}\" != 0 ] && [ \"$ch_v{i}\" != skip ]; then echo \"--- {} failed (exit $ch_v{i}), last output ---\"; tail -c {per} /tmp/coderhelm-verify-{i}.log; echo; fi\n", + c.kind.name() + )); + } + if let Some(i) = run + .iter() + .copied() + .find(|&i| plan.checks[i].kind == Kind::Audit) + { + if !audit_reducer.is_empty() { + s.push_str(&audit_reducer.replace("{out}", &format!("/tmp/coderhelm-verify-{i}.log"))); + s.push('\n'); + } + } + if let Some(v) = version_cmd(&plan.manager) { + s.push_str(&format!( + "echo \"{PM_MARK} $( ({cd}{v}) 2>/dev/null | head -n 1 | tr -cd '0-9A-Za-z. -' | cut -c1-40)\"\n" + )); + } + for &i in run { + s.push_str(&format!("echo \"{MARK} {i} $ch_v{i}\"\n")); + } + s.push_str("true"); + s +} + +/// What one check came to. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case", tag = "is")] +pub enum Status { + Passed, + Failed { + exit: i32, + }, + /// Stopped at its time limit, in seconds. + TimedOut { + after: u32, + }, + /// Not run, with why: never a pass and never a failure. + #[default] + NotRun, +} + +/// One check with its result on one head. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Outcome { + pub kind: Kind, + pub shown: String, + pub found: String, + pub status: Status, + /// Why it did not run; empty when it did. + pub why: String, +} + +impl Outcome { + pub fn ran(&self) -> bool { + !matches!(self.status, Status::NotRun) + } + pub fn passed(&self) -> bool { + matches!(self.status, Status::Passed) + } + /// It ran to its end and failed. A check stopped at its time limit has + /// no result: never a failure to blame on a change. + pub fn failed(&self) -> bool { + matches!(self.status, Status::Failed { .. }) + } +} + +/// The minimum set's results on one commit. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Verified { + /// The commit the checks ran on. + pub sha: String, + pub lockfile: String, + pub manager: String, + /// The package manager version that installed, as it printed it. + pub used: String, + pub declared: String, + pub image: String, + pub image_file: String, + pub outcomes: Vec, + pub not_applicable: Vec<(Kind, String)>, + /// The sandbox gave a result (false: nothing below is a verdict). + pub ran: bool, + /// The end of the output, for a reason. + pub tail: String, +} + +/// The record when the sandbox gave no result: every check not run, with +/// why. +pub fn no_result(plan: &Plan, sha: &str, why: &str) -> Verified { + read(plan, sha, &[], &[], "").with_reason(why) +} + +impl Verified { + /// Every check not run, for this one reason. + pub fn with_reason(mut self, why: &str) -> Self { + for o in &mut self.outcomes { + o.why = why.to_string(); + } + self.tail = why.to_string(); + self + } + + pub fn outcome(&self, kind: Kind) -> Option<&Outcome> { + self.outcomes.iter().find(|o| o.kind == kind) + } + + /// The kinds of the set with no result on this commit, each with why. + pub fn not_run(&self) -> Vec<(Kind, String)> { + self.outcomes + .iter() + .filter(|o| !o.ran()) + .map(|o| (o.kind, o.why.clone())) + .collect() + } +} + +/// A [`script`] run's results. `run`: the checks the script ran; `left`: +/// the ones [`fit`] left out, with why. A check the script ran that has no +/// line (the build was cut short) did not run. +pub fn read( + plan: &Plan, + sha: &str, + run: &[usize], + left: &[(usize, String)], + output: &str, +) -> Verified { + let mut codes: Vec> = vec![None; plan.checks.len()]; + let mut used = String::new(); + for line in output.lines() { + let mut parts = line.split_whitespace(); + match parts.next() { + Some(MARK) => { + if let (Some(i), Some(code)) = ( + parts.next().and_then(|n| n.parse::().ok()), + parts.next(), + ) { + if i < codes.len() { + codes[i] = Some(code.to_string()); + } + } + } + Some(PM_MARK) => used = parts.collect::>().join(" "), + _ => {} + } + } + let any = codes.iter().any(Option::is_some); + let outcomes = plan + .checks + .iter() + .enumerate() + .map(|(i, c)| { + let (status, why) = match (codes[i].as_deref(), run.contains(&i)) { + (Some("skip"), _) => ( + Status::NotRun, + "the frozen install failed, so it could not run".to_string(), + ), + (Some(code), _) => match code.parse::() { + Ok(0) => (Status::Passed, String::new()), + Ok(TIMED_OUT) => ( + Status::TimedOut { + after: c.kind.seconds() * 2, + }, + String::new(), + ), + Ok(exit) => (Status::Failed { exit }, String::new()), + Err(_) => (Status::NotRun, "its result could not be read".to_string()), + }, + (None, true) => ( + Status::NotRun, + "the sandbox build ended before it reported".to_string(), + ), + (None, false) => ( + Status::NotRun, + left.iter() + .find(|(l, _)| *l == i) + .map(|(_, w)| w.clone()) + .unwrap_or_else(|| "it was not started".to_string()), + ), + }; + Outcome { + kind: c.kind, + shown: c.shown.clone(), + found: c.found.clone(), + status, + why, + } + }) + .collect(); + Verified { + sha: sha.to_string(), + lockfile: plan.lockfile.clone(), + manager: plan.manager.clone(), + used, + declared: plan.declared.clone(), + image: plan.image.clone(), + image_file: plan.image_file.clone(), + outcomes, + not_applicable: plan.not_applicable.clone(), + ran: any, + tail: crate::tail_str(output, 2000).to_string(), + } +} + +/// The checks that fail on the head and pass on the base branch, of the +/// kinds a change can be blamed for. Without a base result nothing is +/// blamed: a failure is then shown as not compared. +pub fn blamed<'a>(head: &'a Verified, base: Option<&Verified>) -> Vec<&'a Outcome> { + let Some(base) = base else { + return vec![]; + }; + head.outcomes + .iter() + .filter(|o| o.kind.blames() && o.failed()) + .filter(|o| base.outcome(o.kind).is_some_and(Outcome::passed)) + .collect() +} + +/// Whether the base branch needs a run: the head has a failure a change +/// can be blamed for. +pub fn needs_base(head: &Verified) -> bool { + head.outcomes.iter().any(|o| o.kind.blames() && o.failed()) +} + +fn short(sha: &str) -> &str { + &sha[..sha.len().min(7)] +} + +/// The record as the pull request states it: every check with the command +/// that ran and what it came to on this commit, what the base branch did +/// where the head failed, what the project does not have, and what did not +/// run with why. +pub fn section(head: &Verified, base: Option<&Verified>) -> String { + let mut s = format!( + "**Verified in the sandbox on commit `{}`** (the set a dependency change needs, found in `{}`'s project, whatever CI runs):\n", + short(&head.sha), + head.lockfile + ); + if !head.ran { + s.push_str(&format!( + "- No result: {}. Nothing here claims a check passed.\n", + crate::truncate_str( + head.tail.lines().next().unwrap_or("the sandbox gave none"), + 200 + ) + )); + return s; + } + for o in &head.outcomes { + let verdict = match &o.status { + // An audit that lists advisories is a result, not a failure: + // they are counted with the advisories of this commit. + Status::Passed if o.kind == Kind::Audit => { + "lists no advisory in production dependencies".to_string() + } + Status::Failed { exit } if o.kind == Kind::Audit => format!( + "lists advisories (exit {exit}); they are counted with the advisories of this commit" + ), + Status::Passed => "passes".to_string(), + Status::Failed { exit } => { + let on_base = base.and_then(|b| b.outcome(o.kind)); + match on_base { + Some(b) if b.passed() => { + format!("fails (exit {exit}); it passes on the base branch") + } + Some(b) if b.ran() => format!( + "fails (exit {exit}); it fails on the base branch too, so not caused by this change" + ), + _ => format!("fails (exit {exit}); not compared with the base branch"), + } + } + Status::TimedOut { after } => { + format!("stopped at its time limit of {after} seconds: no result") + } + Status::NotRun => format!("not run: {}", o.why), + }; + let with = match o.kind { + Kind::Install if !head.used.is_empty() => format!(" (ran with {})", head.used), + _ => String::new(), + }; + s.push_str(&format!( + "- {}: `{}`{with}: {verdict}. Found as {}.\n", + o.kind.name(), + o.shown, + o.found + )); + } + for (k, why) in &head.not_applicable { + s.push_str(&format!("- {}: does not apply: {why}.\n", k.name())); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(paths: &[&str]) -> Vec { + paths.iter().map(|p| p.to_string()).collect() + } + + fn files(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + pairs + .iter() + .map(|(p, t)| (p.to_string(), t.to_string())) + .collect() + } + + const PNPM_AUDIT: Option<(&str, &str)> = + Some(("pnpm audit --prod --json", "pnpm audit --prod --json")); + + /// The review's project: typed, with a build and tests, a CI with no + /// type check, and a Dockerfile that installs another pnpm. + fn typed_service() -> Plan { + let t = tree(&[ + "package.json", + "pnpm-lock.yaml", + "tsconfig.json", + "Dockerfile", + "src/main.ts", + ]); + let f = files(&[ + ( + "package.json", + r#"{"packageManager":"pnpm@9.12.3+sha512.abc","scripts":{"build":"nest build","test":"jest","lint":"eslint ."}}"#, + ), + ( + "Dockerfile", + "FROM node:22-slim\nRUN npm install -g pnpm@9.1.0\nCOPY . .\nRUN pnpm install --frozen-lockfile\n", + ), + ]); + discover("pnpm-lock.yaml", &t, &f, PNPM_AUDIT) + } + + fn kinds(p: &Plan) -> Vec { + p.checks.iter().map(|c| c.kind).collect() + } + + #[test] + fn a_typed_project_is_type_checked_though_no_script_or_ci_job_does() { + let p = typed_service(); + assert_eq!( + kinds(&p), + vec![ + Kind::Install, + Kind::DeployInstall, + Kind::Typecheck, + Kind::Build, + Kind::Lint, + Kind::Tests, + Kind::Audit + ] + ); + let tc = &p.checks[2]; + assert_eq!(tc.shown, "npx --no-install tsc --noEmit"); + assert_eq!(tc.found, "`tsconfig.json` is there and no script runs it"); + // The frozen flag is written out, with the manifest's version and + // then with the image's. + assert!(p.checks[0].cmd.ends_with("pnpm install --frozen-lockfile")); + assert!(p.checks[0] + .found + .contains("with pnpm 9.12.3 as `package.json` declares")); + assert_eq!( + p.checks[1].shown, + "npx -y pnpm@9.1.0 install --frozen-lockfile --ignore-scripts" + ); + assert_eq!(p.checks[1].found, "`Dockerfile` installs pnpm 9.1.0"); + assert_eq!(p.checks[3].shown, "pnpm run build"); + assert_eq!(p.checks[5].shown, "pnpm run test"); + assert_eq!(p.checks[6].shown, "pnpm audit --prod --json"); + } + + #[test] + fn a_check_the_project_does_not_have_is_named_with_why() { + let t = tree(&["package.json", "package-lock.json", "index.js"]); + let f = files(&[( + "package.json", + r#"{"scripts":{"test":"echo \"Error: no test specified\" && exit 1"}}"#, + )]); + let p = discover("package-lock.json", &t, &f, None); + assert_eq!(kinds(&p), vec![Kind::Install]); + assert_eq!(p.checks[0].shown, "npm ci --no-audit --no-fund"); + let why = |k: Kind| { + p.not_applicable + .iter() + .find(|(x, _)| *x == k) + .map(|(_, w)| w.as_str()) + .unwrap() + }; + assert_eq!( + why(Kind::Typecheck), + "no `tsconfig.json`: the project is not typed" + ); + assert!(why(Kind::Tests).contains("has no script for it")); + assert!(why(Kind::DeployInstall).contains("no Dockerfile")); + assert!(why(Kind::Audit).contains("no production-scoped audit")); + } + + #[test] + fn the_image_version_is_read_from_every_way_a_dockerfile_pins_it() { + assert_eq!( + image_version("RUN corepack prepare pnpm@9.1.0 --activate", "pnpm"), + Some("9.1.0".into()) + ); + assert_eq!( + image_version("ENV PNPM_VERSION=8.15.4\nRUN curl x", "pnpm"), + Some("8.15.4".into()) + ); + assert_eq!( + image_version("ARG POETRY_VERSION=\"1.8.2\"", "poetry"), + Some("1.8.2".into()) + ); + assert_eq!( + image_version("RUN pip install poetry==1.8.2", "poetry"), + Some("1.8.2".into()) + ); + // Another package's name that ends with the manager's is not it. + assert_eq!(image_version("RUN npm i -g not-pnpm@1.2.3", "pnpm"), None); + assert_eq!(image_version("# pnpm@9.1.0\nRUN true", "pnpm"), None); + assert_eq!( + declared_version(r#"{"packageManager":"yarn@1.22.19"}"#, "yarn"), + Some("1.22.19".into()) + ); + assert_eq!( + declared_version(r#"{"packageManager":"yarn@1.22.19"}"#, "pnpm"), + None + ); + } + + #[test] + fn the_same_image_version_needs_one_install_and_an_unrunnable_one_is_said() { + let t = tree(&["package.json", "pnpm-lock.yaml", "Dockerfile"]); + let same = files(&[ + ("package.json", r#"{"packageManager":"pnpm@9.1.0"}"#), + ("Dockerfile", "RUN npm i -g pnpm@9.1.0"), + ]); + let p = discover("pnpm-lock.yaml", &t, &same, None); + assert!(!kinds(&p).contains(&Kind::DeployInstall)); + assert!(p.not_applicable[0].1.contains("one install covers both")); + // A Python image that pins another Poetry: named, never run as if. + let t = tree(&["pyproject.toml", "poetry.lock", "Dockerfile"]); + let f = files(&[ + ("pyproject.toml", "[tool.mypy]\nstrict = true\n"), + ("Dockerfile", "RUN pip install poetry==1.8.2"), + ]); + let p = discover("poetry.lock", &t, &f, None); + assert!(!kinds(&p).contains(&Kind::DeployInstall)); + let (_, why) = &p.not_applicable[0]; + assert!(why.contains("installs poetry 1.8.2")); + assert!(why.contains("was not run with it")); + } + + #[test] + fn every_ecosystem_finds_its_checks_in_the_project() { + // Python: typed by a table in pyproject.toml, tests by conftest. + let t = tree(&["pyproject.toml", "uv.lock", "conftest.py", "app/main.py"]); + let f = files(&[( + "pyproject.toml", + "[tool.pyright]\ninclude = [\"app\"]\n[tool.ruff.lint]\nselect = [\"E\"]\n", + )]); + let p = discover("uv.lock", &t, &f, None); + let shown: Vec<&str> = p.checks.iter().map(|c| c.shown.as_str()).collect(); + assert_eq!( + shown, + vec![ + "uv sync --locked", + "uv run pyright", + "uv run python -m compileall -q .", + "uv run ruff check .", + "uv run pytest -q" + ] + ); + assert_eq!(p.checks[1].found, "`[tool.pyright]` in `pyproject.toml`"); + // An untyped Python project says so. + let p = discover("uv.lock", &tree(&["pyproject.toml", "uv.lock"]), &[], None); + assert!(p + .not_applicable + .iter() + .any(|(k, w)| *k == Kind::Typecheck && w.contains("not type-checked"))); + // Rust and Go: the toolchain's own, always. + let p = discover( + "Cargo.lock", + &tree(&["Cargo.lock", "Cargo.toml"]), + &[], + None, + ); + let shown: Vec<&str> = p.checks.iter().map(|c| c.shown.as_str()).collect(); + assert_eq!( + shown, + vec![ + "cargo fetch --locked", + "cargo check --locked --all-targets", + "cargo build --locked", + "cargo clippy --locked --all-targets -- -D warnings", + "cargo test --locked" + ] + ); + let p = discover( + "svc/go.sum", + &tree(&["svc/go.sum", "svc/go.mod"]), + &[], + None, + ); + assert_eq!(p.dir, "svc"); + assert_eq!(p.checks[1].shown, "go vet ./..."); + assert!(p.not_applicable.iter().any(|(k, _)| *k == Kind::Lint)); + // Ruby: found by its configuration files. + let p = discover( + "Gemfile.lock", + &tree(&["Gemfile.lock", ".rubocop.yml", ".rspec"]), + &[], + None, + ); + let shown: Vec<&str> = p.checks.iter().map(|c| c.shown.as_str()).collect(); + assert_eq!( + shown, + vec![ + "BUNDLE_FROZEN=true bundle install", + "bundle exec rubocop", + "bundle exec rspec" + ] + ); + // Yarn 2 and later installs immutably. + let p = discover( + "yarn.lock", + &tree(&["yarn.lock", "package.json", ".yarnrc.yml"]), + &files(&[("package.json", "{}")]), + None, + ); + assert_eq!(p.checks[0].shown, "yarn install --immutable"); + // Every manager a lockfile is written for has a row. + for lock in [ + "package-lock.json", + "pnpm-lock.yaml", + "yarn.lock", + "bun.lock", + "Cargo.lock", + "poetry.lock", + "uv.lock", + "Pipfile.lock", + "Gemfile.lock", + "go.sum", + ] { + assert_eq!( + row_of(lock).map(|r| r.manager), + crate::lockfile_sync::lock_manager(lock), + "{lock}" + ); + } + } + + #[test] + fn the_files_read_are_the_manifest_the_marked_files_and_the_dockerfiles() { + let t = tree(&[ + "apps/api/package.json", + "apps/api/pnpm-lock.yaml", + "apps/api/Dockerfile", + "Dockerfile", + "apps/web/Dockerfile", + ]); + assert_eq!( + files_to_read("apps/api/pnpm-lock.yaml", &t), + vec!["Dockerfile", "apps/api/Dockerfile", "apps/api/package.json"] + ); + } + + #[test] + fn what_does_not_fit_is_left_out_in_priority_order_and_named() { + let p = typed_service(); + // A full window: everything. + let (run, left) = fit(&p, 900); + assert_eq!(run, vec![0, 1, 2, 3, 4, 5, 6]); + assert!(left.is_empty()); + // Short: the install, the type check and the audit stay; the + // deployment install is the first to go, then lint, tests, build. + let (run, left) = fit(&p, 60 + 150 + 75 + 30 + 150); + let kept: Vec = run.iter().map(|&i| p.checks[i].kind).collect(); + assert_eq!( + kept, + vec![Kind::Install, Kind::Typecheck, Kind::Build, Kind::Audit] + ); + let gone: Vec = left.iter().map(|(i, _)| p.checks[*i].kind).collect(); + assert_eq!(gone, vec![Kind::DeployInstall, Kind::Lint, Kind::Tests]); + assert!(left[0].1.contains("seconds left for checks")); + // No room for the install: nothing that needs it runs, and each + // says so. The audit needs no install. + let (run, left) = fit(&p, 60 + 40); + assert_eq!( + run.iter().map(|&i| p.checks[i].kind).collect::>(), + vec![Kind::Audit] + ); + assert!(left + .iter() + .any(|(i, w)| p.checks[*i].kind == Kind::Typecheck && w.contains("install it needs"))); + } + + #[test] + fn each_result_is_recorded_against_the_commit_and_nothing_unrun_is_claimed() { + let p = typed_service(); + let (run, left) = fit(&p, 60 + 150 + 75 + 30 + 150); + let cmd = script(&p, &run, ""); + // Each command travels encoded, with its own time limit; the marks + // come last. + assert!(cmd.contains("timeout 300 sh /tmp/coderhelm-verify-0.sh")); + assert!(cmd.contains("if [ \"$ch_v0\" = 0 ]; then")); + assert!(cmd.trim_end().ends_with("true")); + assert!(!cmd.contains("tsc --noEmit")); + let out = "CODERHELM_VERIFY_PM 9.12.3\nCODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 2 2\nCODERHELM_VERIFY 3 124\nCODERHELM_VERIFY 6 1\n"; + let v = read(&p, "abc1234def", &run, &left, out); + assert!(v.ran); + assert_eq!(v.used, "9.12.3"); + assert!(v.outcome(Kind::Install).unwrap().passed()); + assert_eq!( + v.outcome(Kind::Typecheck).unwrap().status, + Status::Failed { exit: 2 } + ); + assert_eq!( + v.outcome(Kind::Build).unwrap().status, + Status::TimedOut { after: 300 } + ); + // What did not fit is not run, with why; never a pass. + let not_run: Vec = v.not_run().into_iter().map(|(k, _)| k).collect(); + assert_eq!(not_run, vec![Kind::DeployInstall, Kind::Lint, Kind::Tests]); + let text = section(&v, None); + assert!(text.contains("on commit `abc1234`")); + assert!(text.contains( + "- type check: `npx --no-install tsc --noEmit`: fails (exit 2); not compared with the base branch." + )); + assert!(text.contains("- unit tests: `pnpm run test`: not run: the sandbox build had")); + assert!(text.contains("stopped at its time limit of 300 seconds: no result")); + assert!(!text.contains("unit tests: `pnpm run test`: passes")); + // A build cut short: what it ran and did not report is not run. + let cut = read(&p, "abc", &run, &left, "CODERHELM_VERIFY 0 0\n"); + assert_eq!( + cut.outcome(Kind::Typecheck).unwrap().why, + "the sandbox build ended before it reported" + ); + // A failed install: the checks that need it say so. + let failed = read(&p, "abc", &run, &left, "CODERHELM_VERIFY 0 1\nCODERHELM_VERIFY 2 skip\nCODERHELM_VERIFY 3 skip\nCODERHELM_VERIFY 6 0\n"); + assert_eq!( + failed.outcome(Kind::Typecheck).unwrap().why, + "the frozen install failed, so it could not run" + ); + // No output at all: no result, and the section claims nothing. + let none = no_result(&p, "abc", "the sandbox build timed out"); + assert!(!none.ran); + assert!(section(&none, None).contains("Nothing here claims a check passed")); + } + + #[test] + fn a_failure_the_base_branch_has_too_is_never_blamed_on_the_change() { + let p = typed_service(); + let all: Vec = (0..p.checks.len()).collect(); + let head = read( + &p, + "head", + &all, + &[], + "CODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 1 0\nCODERHELM_VERIFY 2 2\nCODERHELM_VERIFY 3 0\nCODERHELM_VERIFY 4 1\nCODERHELM_VERIFY 5 1\nCODERHELM_VERIFY 6 1\n", + ); + assert!(needs_base(&head)); + // Without the base nothing is blamed. + assert!(blamed(&head, None).is_empty()); + let base = read( + &p, + "base", + &all, + &[], + "CODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 1 0\nCODERHELM_VERIFY 2 0\nCODERHELM_VERIFY 3 0\nCODERHELM_VERIFY 4 0\nCODERHELM_VERIFY 5 1\nCODERHELM_VERIFY 6 1\n", + ); + // The type check passes on the base and fails with the bumps: + // blamed. The tests fail on both: not. Lint is never blamed, and an + // audit that finds advisories is a result. + let b: Vec = blamed(&head, Some(&base)).iter().map(|o| o.kind).collect(); + assert_eq!(b, vec![Kind::Typecheck]); + let text = section(&head, Some(&base)); + assert!(text.contains("type check: `npx --no-install tsc --noEmit`: fails (exit 2); it passes on the base branch")); + assert!(text.contains("it fails on the base branch too, so not caused by this change")); + let green = read( + &p, + "head", + &all, + &[], + "CODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 2 0\n", + ); + assert!(!needs_base(&green)); + // A check stopped at its time limit has no result: nothing to + // blame, and no base run asked for. + let slow = read( + &p, + "head", + &all, + &[], + "CODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 5 124\n", + ); + assert!(!needs_base(&slow)); + assert!(blamed(&slow, Some(&base)).is_empty()); + } +} diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index 0102ceacf..557a274e6 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -6,7 +6,12 @@ //! Once the batches are settled the repository's real build and its start //! command run in a sandbox build of their own, on the base branch and on //! the branch (`common::runtime_proof`): what the bumps break there takes -//! out the newest commit of bumps, deferred with the cause. +//! out the newest commit of bumps, deferred with the cause. Then the set a +//! dependency change is verified with whatever CI runs +//! (`common::upgrade_quality::verify`: the project's own frozen install, +//! type check, build, lint, tests and production audit) runs on the branch, +//! and on the base branch where the branch fails something. What the run +//! found is recorded for its head commit (`passes::upgrade_quality`). //! //! The run's state is kept on S3 after every probe, so a step that runs out //! of time hands off and the next one resumes where it stopped (and its @@ -17,6 +22,7 @@ use std::time::Instant; use common::dep_fix::{self as df, Action, CodeFixed, DepRun, ProbeResult}; use common::runtime_proof as rp; +use common::upgrade_quality::{family as fam, verify as vq}; use tracing::{info, warn}; use crate::clients::github::{FileOp, GitHubClient}; @@ -99,7 +105,7 @@ pub async fn start( &common::security_fixes::Finding, &common::security_fixes::FindingState, )> = inputs.findings.iter().map(|(f, s)| (f, s)).collect(); - let plan = df::plan_in(&pairs, &inputs.cfg, &locks); + let mut plan = df::plan_in(&pairs, &inputs.cfg, &locks); if !plan .bumps .iter() @@ -116,7 +122,14 @@ pub async fn start( .await .ok()?; let budget = inputs.cfg.fix_run_budget_cents as f64 / 100.0; - let run = DepRun::new(plan, &head, budget); + // A major a parent's release brings in is fixed by raising the parent, + // never by an override; packages released together move together. + let notes = super::security_fixes::dep_notes(state, &msg.team_id, &msg.ticket_id).await; + common::upgrade_quality::safety::route_through_parents(&mut plan, ¬es, &inputs.findings); + let (families, peers) = super::upgrade_quality::families(state, github, msg, &mut plan).await; + let mut run = DepRun::new(plan, &head, budget); + run.families = families; + run.peers = peers; save(state, msg, run_id, &run).await; Some(run) } @@ -271,12 +284,19 @@ struct Probe<'a> { node: Option, deadline: Option, attempt: std::sync::atomic::AtomicUsize, + /// The run's families: every lockfile a probe writes is checked + /// against them. + families: Vec, } /// One probe's result and the manifests and lockfiles it wrote. +#[derive(Default)] struct Probed { result: ProbeResult, files: Vec<(String, String)>, + /// Packages whose parent was raised instead of an override, and that + /// the lockfile the probe wrote still installs below the fixed version. + parent_unmoved: Vec, } impl Probe<'_> { @@ -296,7 +316,7 @@ impl Probe<'_> { tail: format!("the branch could not be snapshotted: {e}"), ..Default::default() }, - files: vec![], + ..Default::default() } } }; @@ -330,7 +350,7 @@ impl Probe<'_> { tail: e.to_string(), ..Default::default() }, - files: vec![], + ..Default::default() } } }; @@ -349,7 +369,7 @@ impl Probe<'_> { tail: common::tail_str(&o.output, 2000).to_string(), ..Default::default() }, - files: vec![], + ..Default::default() }; } self.steps @@ -360,18 +380,126 @@ impl Probe<'_> { } else { vec![] }; + let files: Vec<(String, String)> = o + .changed + .into_iter() + .filter(|(p, _)| df::commit_path(p)) + .collect(); + let mut result = ProbeResult { + ran, + applied, + checks, + tail: common::tail_str(&o.output, 3000).to_string(), + }; + // The lockfile the bumps wrote, against the run's families and the + // parents it raised: a family at two versions fails the set like + // any check. + let (split, parent_unmoved) = if applied { + df::lockfile_violations(&self.families, bumps, &files) + } else { + (vec![], vec![]) + }; + if !split.is_empty() { + result.checks.push((df::FAMILY_CHECK.to_string(), false)); + result.tail = format!("{}\n{}", split.join("; "), result.tail); + } Probed { - result: ProbeResult { - ran, - applied, - checks, - tail: common::tail_str(&o.output, 3000).to_string(), - }, - files: o - .changed - .into_iter() - .filter(|(p, _)| df::commit_path(p)) - .collect(), + result, + files, + parent_unmoved, + } + } +} + +/// The longest one verification build is given, and what a step keeps +/// back from it for the build's start and the step's own end. +const VERIFY_WINDOW: std::time::Duration = std::time::Duration::from_secs(11 * 60); +const VERIFY_MARGIN: std::time::Duration = std::time::Duration::from_secs(90); + +/// The seconds a verification build started now has for its checks. +pub fn verify_window(left: Option) -> u32 { + let w = match left { + Some(l) => l.saturating_sub(VERIFY_MARGIN).min(VERIFY_WINDOW), + None => VERIFY_WINDOW, + }; + w.as_secs() as u32 +} + +/// Whether a verification build should wait for a fresh step: started now +/// it would leave out a check a full window runs, and the run has not +/// already moved to a fresh step for this build. +pub fn verify_waits(plan: &vq::Plan, left: Option, waited: bool) -> bool { + let now = vq::fit(plan, verify_window(left)).0.len(); + let full = vq::fit(plan, verify_window(None)).0.len(); + !waited && now < full +} + +impl Probe<'_> { + /// One build of the verification set on `sha`: the checks that fit the + /// time this step has, each recorded against the commit; the ones that + /// do not fit are recorded as not run, with why. On the branch the + /// audit's listing is read from the same build. + async fn verify( + &self, + sha: &str, + plan: &vq::Plan, + nonce: usize, + ) -> (vq::Verified, Option) { + let (owner, name) = (&self.msg.repo_owner, &self.msg.repo_name); + let left = self + .deadline + .map(|d| d.saturating_duration_since(Instant::now())); + let (run, not) = vq::fit(plan, verify_window(left)); + if run.is_empty() { + return ( + vq::read(plan, sha, &[], ¬, "").with_reason( + "this step had no time left for a sandbox build of the verification set", + ), + None, + ); + } + let source = match self + .sandbox + .ensure_source(self.run_id, sha, || { + self.github.download_tarball(owner, name, sha) + }) + .await + { + Ok(s) => s, + Err(e) => { + return ( + vq::no_result( + plan, + sha, + &format!("the branch could not be snapshotted: {e}"), + ), + None, + ) + } + }; + let reducer = common::dep_audit::listing(&plan.manager, &plan.dir).unwrap_or_default(); + let out = self + .sandbox + .run_codegen( + self.run_id, + 1300 + nonce, + &source, + &vq::script(plan, &run, &reducer), + self.node.as_deref(), + &[], + self.deadline, + ) + .await; + match out { + Ok(o) if o.ran => { + let audited = run.iter().any(|&i| plan.checks[i].kind == vq::Kind::Audit); + ( + vq::read(plan, sha, &run, ¬, &o.output), + audited.then(|| common::dep_audit::listings(&plan.manager, &o.output)), + ) + } + Ok(o) => (vq::no_result(plan, sha, &o.output), None), + Err(e) => (vq::no_result(plan, sha, &e.to_string()), None), } } } @@ -678,6 +806,7 @@ pub async fn drive( node: super::detect_node_version(w.github, owner, name, &msg.base_branch).await, deadline: w.deadline, attempt: std::sync::atomic::AtomicUsize::new(run.probes as usize), + families: run.families.clone(), }; // The team's agent permissions hold the sandbox commands like any other. let gate = crate::agent::policy::gate( @@ -759,10 +888,33 @@ pub async fn drive( .await; let mut results = vec![]; let mut keyed: HashMap, Vec<(String, String)>> = HashMap::new(); + // A parent raised instead of an override that did not move + // its package: the override is written after all, and the + // set is probed again with it. + let mut unmoved: Vec = vec![]; for ((g, ids), o) in groups.iter().zip(probed).zip(outs) { + if !o.parent_unmoved.is_empty() { + unmoved.extend(o.parent_unmoved); + continue; + } keyed.insert(ids, o.files); results.push((*g, o.result)); } + for b in run.plan.bumps.iter_mut() { + if b.via_parent.is_some() && unmoved.contains(&b.package) { + let parent = b.via_parent.take().map(|p| p.package).unwrap_or_default(); + super::add_progress_note( + state, + &msg.team_id, + w.run_id, + &format!( + "Dependency fix: raising `{parent}` did not move `{}` off its vulnerable version, so it is fixed by an override scoped to its version line", + b.package + ), + ) + .await; + } + } run.on_probes(&results); info!( run_id = w.run_id, @@ -848,7 +1000,17 @@ pub async fn drive( run.on_code_fix(bump, r, tokens, usd); } Action::ProofPlan => { - let plan = proof_plan(w, &run).await; + let mut plan = proof_plan(w, &run).await; + // The requests that go through the call sites of the + // applied majors, sent to the base branch's build and to + // the branch's alike. + if plan.start.is_some() { + let planned = + super::upgrade_quality::behaviour_plan(state, w.github, msg, &run).await; + plan.probes = planned.requests; + run.probed = planned.of; + run.not_probed = planned.not_probed; + } // The proof's commands are the repository's own: the team's // agent permissions hold them like any other. let permitted = plan.is_empty() @@ -922,7 +1084,97 @@ pub async fn drive( None => run.on_proof_take_out_failed(), } } + Action::VerifyPlan => { + let plan = super::upgrade_quality::verify_plan(w.github, msg, &run, &tree).await; + // The set's commands are the project's own: the team's + // agent permissions hold them like any other. + let all: Vec = (0..plan.checks.len()).collect(); + let permitted = plan.is_empty() + || matches!( + gate.check_command( + &vq::script(&plan, &all, ""), + "Verify the dependency change with the project's own checks" + ) + .await, + common::agent_policy::Outcome::Run { .. } + ); + run.on_verify_plan(plan); + if !permitted { + run.skip_verify( + "the team's agent permissions do not let the sandbox run the project's install and checks", + ); + } + } + Action::Verify { base } => { + let plan = run.verify.plan.clone().unwrap_or_default(); + let left = w + .deadline + .map(|d| d.saturating_duration_since(Instant::now())); + if verify_waits(&plan, left, run.verify.waited) { + // Its own step, with a full time window. + run.on_verify_wait(); + save(state, msg, w.run_id, &run).await; + return Ok(Driven::Handoff(Box::new(run))); + } + let sha = if base { + match run.base_sha() { + Some(s) => s.to_string(), + None => w + .github + .get_ref(owner, name, &msg.base_branch) + .await + .unwrap_or_default(), + } + } else { + run.head.clone() + }; + let (v, listed) = probe.verify(&sha, &plan, run.verify.runs as usize).await; + let note = verify_note(base, &v); + if !base && v.ran { + run.verify.audit = listed; + } + run.on_verify(base, v); + super::add_progress_note(state, &msg.team_id, w.run_id, ¬e).await; + } + Action::VerifyTakeOut { why } => { + // The state moves only once the branch is written. + let mut next = run.clone(); + let written = match next.take_out_last_commit(&why) { + Some(out) => restore_to(w, &out).await.map(|head| (out, head)), + None => None, + }; + match written { + Some((out, head)) => { + next.on_verify_taken_out(&out, &head); + run = next; + super::add_progress_note( + state, + &msg.team_id, + w.run_id, + &format!( + "Dependency fix: a check of the verification set fails with the newest verified set and passes on the base branch; took out {} bump(s) and kept the {} set(s) before it. {}", + out.lines.len(), + run.commits.len(), + common::truncate_str(&out.lines.join("; "), 600) + ), + ) + .await; + } + None => run.on_verify_take_out_failed(), + } + } Action::Done => { + // What the run found, recorded for the commit it ends on. + if !run.applied.is_empty() && run.facts_sha != run.head { + let at = super::upgrade_quality::At { + state, + gh: w.github, + msg, + branch: w.branch, + }; + let facts = super::upgrade_quality::record(&at, &run).await; + run.facts_sha = facts.sha; + } save(state, msg, w.run_id, &run).await; return Ok(Driven::Done(Box::new(run))); } @@ -931,6 +1183,44 @@ pub async fn drive( } } +/// The run page's line for one build of the verification set. +fn verify_note(base: bool, v: &vq::Verified) -> String { + let on = if base { + "on the base branch" + } else { + "with the bumps" + }; + if !v.ran { + return format!( + "Dependency fix: the verification set {on} gave no result ({})", + common::truncate_str(v.tail.lines().next().unwrap_or(""), 200) + ); + } + let words: Vec = v + .outcomes + .iter() + .map(|o| { + format!( + "{} {}", + o.kind.name(), + match &o.status { + vq::Status::Failed { .. } if o.kind == vq::Kind::Audit => { + "lists advisories".to_string() + } + vq::Status::Passed => "passes".to_string(), + vq::Status::Failed { exit } => format!("fails (exit {exit})"), + vq::Status::TimedOut { .. } => "hit its time limit".to_string(), + vq::Status::NotRun => "did not run".to_string(), + } + ) + }) + .collect(); + format!( + "Dependency fix: verification set {on}: {}", + words.join("; ") + ) +} + /// The run page's line for one runtime proof build. fn proof_note(base: bool, plan: &rp::ProofPlan, r: &rp::ProofResult) -> String { let on = if base { @@ -1307,11 +1597,23 @@ pub async fn settle(state: &WorkerState, msg: &TicketMessage, run: &DepRun) { .map(|(f, _)| f) .filter(|f| f.repo.eq_ignore_ascii_case(&repo)) .collect(); - let report = format!( - "{}\n{}", - run.report_md().trim_end(), - df::remaining_md(&df::remaining(run, &of_repo)) - ); + // One count of what stays open: when the run recorded the advisories + // of this head against the package manager's audit + // (`upgrade_quality::advisories`), that count is the one the pull + // request shows. Without it, CoderHelm's own findings are counted, and + // said to be its own. + let reconciled = super::security_fixes::dep_facts(state, &msg.team_id, &msg.ticket_id) + .await + .is_some_and(|f| f.of_head(&run.head) && f.advisories.is_some()); + let report = if reconciled { + run.report_md().trim_end().to_string() + } else { + format!( + "{}\n{}", + run.report_md().trim_end(), + df::remaining_md(&df::remaining(run, &of_repo)) + ) + }; super::security_fixes::settle_dep_run( state, &msg.team_id, @@ -1378,6 +1680,52 @@ mod tests { assert!(PROOF_WINDOW.as_secs() < super::super::LAMBDA_TIMEOUT_SECS - 150); } + #[test] + fn a_verification_build_runs_what_fits_or_waits_once_for_a_fresh_step() { + let mins = |m: u64| Some(std::time::Duration::from_secs(m * 60)); + let tree: Vec = ["package.json", "pnpm-lock.yaml", "tsconfig.json"] + .iter() + .map(|s| s.to_string()) + .collect(); + let plan = vq::discover( + "pnpm-lock.yaml", + &tree, + &[( + "package.json".to_string(), + r#"{"scripts":{"build":"tsc -p .","test":"vitest run","lint":"eslint ."}}"# + .to_string(), + )], + Some(("pnpm audit --prod --json", "pnpm audit --prod --json")), + ); + // A step never gives a build more than its own window. + assert_eq!(verify_window(None), 11 * 60); + assert_eq!(verify_window(mins(30)), 11 * 60); + assert_eq!(verify_window(mins(5)), 5 * 60 - 90); + // A full window runs the whole set. + assert_eq!( + vq::fit(&plan, verify_window(None)).0.len(), + plan.checks.len() + ); + assert!(!verify_waits(&plan, mins(30), false)); + // Little time left: the build waits for a fresh step, once. + assert!(verify_waits(&plan, mins(5), false)); + assert!(!verify_waits(&plan, mins(5), true)); + // Then it runs what fits, in priority order, and names the rest. + let (run, left) = vq::fit(&plan, verify_window(mins(5))); + let kept: Vec = run.iter().map(|&i| plan.checks[i].kind).collect(); + assert_eq!(kept, vec![vq::Kind::Install]); + assert_eq!(left.len(), plan.checks.len() - 1); + let v = vq::read(&plan, "abc1234", &run, &left, "CODERHELM_VERIFY 0 0\n"); + assert_eq!( + verify_note(false, &v), + "Dependency fix: verification set with the bumps: frozen install passes; type check did not run; build did not run; lint did not run; unit tests did not run; production audit did not run" + ); + // The window fits inside a step. + assert!( + VERIFY_WINDOW.as_secs() + VERIFY_MARGIN.as_secs() < super::super::LAMBDA_TIMEOUT_SECS + ); + } + #[test] fn the_run_page_says_what_a_proof_build_came_to() { let plan = rp::discover( diff --git a/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs b/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs index 9a70c9ca1..9b500b4ae 100644 --- a/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs +++ b/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs @@ -285,6 +285,11 @@ fn drive(run: &mut DepRun, plan: &rp::ProofPlan, breaks: &[&str]) -> u32 { commits += 1; run.on_proof_taken_out(&out, &format!("sha{commits}")); } + // This case replays the runtime proof: nothing to verify with. + Action::VerifyPlan => run.on_verify_plan(Default::default()), + Action::Verify { .. } | Action::VerifyTakeOut { .. } => { + panic!("no verification set in this case") + } Action::Done => return builds, } } diff --git a/services/worker/src/passes/incidents/au_upgrade_decided_and_proven.rs b/services/worker/src/passes/incidents/au_upgrade_decided_and_proven.rs new file mode 100644 index 000000000..3dde8273f --- /dev/null +++ b/services/worker/src/passes/incidents/au_upgrade_decided_and_proven.rs @@ -0,0 +1,924 @@ +//! au. An outside reviewer checked a dependency security pull request of +//! about fifty packages, four of them across a major version. The code was +//! sound. The account of it was not: +//! +//! 1. "three high advisories left" was counted from CoderHelm's own +//! findings; the package manager's production audit of the same head +//! showed one, in a package the pull request does not touch; +//! 2. one package of a framework was raised to 10.4.22 while its siblings +//! from the same source repository stayed at 10.4.15; +//! 3. no type check was recorded, because the repository's CI has none and +//! CoderHelm's checks mirrored CI; the reviewer ran it themselves, and +//! a frozen-lockfile install with the package manager version the +//! deployment image installs; +//! 4. it said "contract unchanged" although a validation library's major +//! changed the 400 error bodies of an endpoint; +//! 5. each override across a major lacked why it is safe: who depends on +//! it, where that code runs, whether it is used, and a probe for the +//! one behind a request (a real upload, with its size-limit error). +//! +//! Guarantee: a dependency update is decided and proven by the pipeline +//! itself. Packages released together are found from the registry and the +//! lockfile and move together, and a lockfile that splits them fails the +//! set. The set a dependency change is verified with is found in the +//! project, whatever CI runs, and each result is recorded against the head. +//! Advisories are counted once, the base branch and the head read the same +//! way and laid beside the package manager's audit, every disagreement +//! with its cause. Each major carries where it runs and how it is fixed. +//! "Unchanged" stands only on a probe: a changed answer is a known +//! behaviour change, and a sentence that claims otherwise is taken out. + +use super::fixture::*; +use crate::passes::{checks, proof, settle}; +use common::dep_audit::{Listed, Listing, Listings}; +use common::dep_fix::{self as df, Action, DepRun}; +use common::dep_head::{self, LockAt}; +use common::runtime_proof as rp; +use common::security_fixes::{self as sec, Advisory, Bump, Finding, FindingState, FixUnit, Scope}; +use common::upgrade_notes::{CallSite, PackageNotes, ParentSupport, WhatToCheck}; +use common::upgrade_quality::{ + advisories as adv, behaviour as bh, family as fam, safety, verify as vq, UpgradeFacts, +}; + +const LOCK: &str = "pnpm-lock.yaml"; +const HEAD: &str = "5e1f00d7a9c4"; + +/// The service's lockfile with each package at the version given. +fn lockfile(versions: &[(&str, &str)]) -> String { + let entry = |n: &str, v: &str| { + if n.starts_with('@') { + format!(" '{n}@{v}': {{}}\n") + } else { + format!(" {n}@{v}: {{}}\n") + } + }; + let list: String = versions.iter().map(|(n, v)| entry(n, v)).collect(); + format!( + "lockfileVersion: '9.0'\nimporters:\n .:\n dependencies:\n shape-check:\n specifier: ^{v}\n version: {v}\npackages:\n{list}snapshots:\n{list}", + v = versions + .iter() + .find(|(n, _)| *n == "shape-check") + .map(|(_, v)| *v) + .unwrap_or("3.2.0"), + ) +} + +/// The base branch: a framework at one version, a validation library and +/// an upload middleware about to cross a major, a development tool, and +/// two packages the change never touches. +const BASE: &[(&str, &str)] = &[ + ("@lattice/common", "10.4.15"), + ("@lattice/core", "10.4.15"), + ("@lattice/platform-http", "10.4.15"), + ("shape-check", "3.2.0"), + ("upload-kit", "1.4.5"), + ("lint-kit", "8.0.0"), + ("xml-read", "1.1.0"), + ("glob-walk", "2.4.0"), +]; + +/// The head the reviewed pull request had: one member of the family raised. +const SPLIT_HEAD: &[(&str, &str)] = &[ + ("@lattice/common", "10.4.22"), + ("@lattice/core", "10.4.15"), + ("@lattice/platform-http", "10.4.15"), + ("shape-check", "4.0.1"), + ("upload-kit", "2.0.2"), + ("lint-kit", "8.0.0"), + ("xml-read", "1.1.0"), + ("glob-walk", "2.4.0"), +]; + +/// The head the pipeline makes: the family moved as one. +const WHOLE_HEAD: &[(&str, &str)] = &[ + ("@lattice/common", "10.4.22"), + ("@lattice/core", "10.4.22"), + ("@lattice/platform-http", "10.4.22"), + ("shape-check", "4.0.1"), + ("upload-kit", "2.0.2"), + ("lint-kit", "8.0.0"), + ("xml-read", "1.1.0"), + ("glob-walk", "2.4.0"), +]; + +fn copies(of: &[(&str, &str)]) -> Vec<(String, String)> { + common::reachability::lock_copies(LOCK, &lockfile(of)).expect("a lockfile CoderHelm reads") +} + +fn bump(package: &str, from: &str, to: &str, id: &str) -> df::PlanBump { + df::PlanBump { + package: package.into(), + from: from.into(), + to: to.into(), + line: sec::version_line(from), + manifest: LOCK.into(), + major: sec::is_major_bump(from, to), + finding_ids: vec![id.into()], + ..Default::default() + } +} + +/// What the registry says of the framework's packages and of one package +/// that only shares their version. +fn registry() -> Vec { + let known = |name: &str, repo: &str| fam::Known { + name: name.into(), + source: Some(repo.into()), + }; + vec![ + known("@lattice/common", "lattice-js/lattice"), + known("@lattice/core", "lattice-js/lattice"), + known("@lattice/platform-http", "lattice-js/lattice"), + ] +} + +/// The family, found the way the run finds it at its start. +fn family() -> fam::Family { + let base = copies(BASE); + let candidates = fam::candidates("@lattice/common", "10.4.15", &base); + assert_eq!(candidates, vec!["@lattice/core", "@lattice/platform-http"]); + let mut f = + fam::detect("@lattice/common", "10.4.15", LOCK, &base, ®istry(), &[]).expect("a family"); + let published = f + .members + .iter() + .map(|m| (m.clone(), vec!["10.4.22".to_string()])) + .collect(); + f.target = fam::target(&f, &["10.4.22".to_string()], &published).unwrap(); + f +} + +/// Point 2. The family is found from the registry and the lockfile; the +/// one bump carries its siblings; and the lockfile the reviewed pull +/// request had fails the set. +#[test] +fn a_family_moves_together_and_a_split_one_fails_the_set() { + let f = family(); + assert_eq!(f.key, "lattice-js/lattice"); + assert_eq!(f.target, "10.4.22"); + let mut plan = df::DepPlan { + bumps: vec![bump("@lattice/common", "10.4.15", "10.4.22", "f-common")], + deferred: vec![], + }; + let mut families = vec![f]; + fam::attach(&mut plan, &mut families); + let told: Vec = df::specs(&[&plan.bumps[0]])[0] + .bumps + .iter() + .map(|b| format!("{}@{}", b.name, b.to)) + .collect(); + assert_eq!( + told, + vec![ + "@lattice/common@10.4.22", + "@lattice/core@10.4.22", + "@lattice/platform-http@10.4.22" + ] + ); + // The reviewed head: found by the probe's own check of the lockfile it + // wrote, and red like any failing check. + let bumps = [&plan.bumps[0]]; + let (split, _) = df::lockfile_violations( + &families, + &bumps, + &[(LOCK.to_string(), lockfile(SPLIT_HEAD))], + ); + assert_eq!(split.len(), 1, "{split:?}"); + assert!(split[0].contains("`@lattice/core` at 10.4.15")); + let (whole, _) = df::lockfile_violations( + &families, + &bumps, + &[(LOCK.to_string(), lockfile(WHOLE_HEAD))], + ); + assert!(whole.is_empty()); + // The run: a probe whose lockfile splits the family never commits. + let mut run = DepRun::new(plan, "base", 3.0); + run.families = families.clone(); + let green = |extra: Option<&str>| df::ProbeResult { + ran: true, + applied: true, + checks: ["install", "tests"] + .iter() + .map(|c| (c.to_string(), true)) + .chain(extra.map(|c| (c.to_string(), false))) + .collect(), + tail: split[0].clone(), + }; + run.on_base(&green(None)); + let Action::Probe(g) = run.next_action() else { + panic!("a probe") + }; + run.on_probes(&[(g[0], green(Some(df::FAMILY_CHECK)))]); + assert!(!matches!(run.next_action(), Action::Commit(_))); + assert!(run.applied.is_empty()); + assert!(run.deferred[0] + .reason + .contains("released together at different versions")); + // The driver makes the check at the probe, and finds families at the + // start of the run. + let drive = include_str!("../dep_fix.rs"); + assert!(fn_src(drive, " async fn run(&self, sha: &str") + .contains("df::lockfile_violations(&self.families, bumps, &files)")); + assert!(fn_src(drive, "pub async fn start(") + .contains("super::upgrade_quality::families(state, github, msg, &mut plan)")); + // The pull request states it. + let text = fam::section(&families, &[], &[]); + assert!( + text.contains("move together from 10.4.15 to 10.4.22"), + "{text}" + ); + assert!( + text.contains("the registry names `lattice-js/lattice` as the source repository of each") + ); +} + +/// The project: typed, with a build and tests, and a deployment image +/// that installs another pnpm than the manifest declares. +fn project() -> (Vec, Vec<(String, String)>) { + let tree = [ + "package.json", + LOCK, + "tsconfig.json", + "Dockerfile", + "src/main.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let files = vec![ + ( + "package.json".to_string(), + r#"{"packageManager":"pnpm@9.12.3","scripts":{"build":"lattice build","test":"vitest run","lint":"eslint ."}}"#.to_string(), + ), + ( + "Dockerfile".to_string(), + "FROM node:22-slim\nRUN npm install -g pnpm@9.1.0\nCOPY . .\nRUN pnpm install --frozen-lockfile && pnpm build\n".to_string(), + ), + ]; + (tree, files) +} + +fn verify_plan() -> vq::Plan { + let (tree, files) = project(); + vq::discover( + LOCK, + &tree, + &files, + Some(("pnpm audit --prod --json", "pnpm audit --prod --json")), + ) +} + +/// Point 3. The repository's CI runs lint and tests and no type check. The +/// set finds the type check in the project, installs with the manifest's +/// pnpm and with the image's, and records every result against the head; +/// an open item "the type check did not run" is closed by the record. +#[test] +fn the_type_check_runs_though_ci_has_none_and_is_recorded_on_the_head() { + // What CI mirrors: nothing that type-checks. + let ci = vec![checks::CiCommand { + id: "C1".into(), + kind: checks::CheckKind::Lint, + tool: "eslint".into(), + cmd: "pnpm exec eslint .".into(), + workflow: "ci.yml".into(), + job: "lint".into(), + dir: None, + sandbox: true, + }]; + assert!(!checks::mirrored_steps(&ci) + .iter() + .any(|s| s.kinds.contains(&checks::CheckKind::Typecheck))); + // What the project needs. + let plan = verify_plan(); + let shown: Vec<&str> = plan.checks.iter().map(|c| c.shown.as_str()).collect(); + assert_eq!( + shown, + vec![ + "pnpm install --frozen-lockfile", + "npx -y pnpm@9.1.0 install --frozen-lockfile --ignore-scripts", + "npx --no-install tsc --noEmit", + "pnpm run build", + "pnpm run lint", + "pnpm run test", + "pnpm audit --prod --json", + ] + ); + // The run reaches the set after its proof, and its result is of the + // commit the branch ends on. + let mut run = DepRun::new( + df::DepPlan { + bumps: vec![bump("shape-check", "3.2.0", "3.2.9", "f-shape")], + deferred: vec![], + }, + "base", + 3.0, + ); + let green = df::ProbeResult { + ran: true, + applied: true, + checks: vec![("install".into(), true), ("tests".into(), true)], + tail: String::new(), + }; + let all: Vec = (0..plan.checks.len()).collect(); + let mut verified = 0; + for _ in 0..50 { + match run.next_action() { + Action::Base => run.on_base(&green), + Action::Probe(g) => run.on_probes(&[(g[0], green.clone())]), + Action::Commit(g) => run.on_commit(g, HEAD), + Action::ProofPlan => run.on_proof_plan(rp::ProofPlan::default()), + Action::VerifyPlan => run.on_verify_plan(plan.clone()), + Action::Verify { base } => { + assert!(!base, "a green head needs no base run"); + verified += 1; + let out: String = all + .iter() + .map(|i| format!("CODERHELM_VERIFY {i} 0\n")) + .collect(); + let sha = run.head.clone(); + run.on_verify(false, vq::read(&plan, &sha, &all, &[], &out)); + } + Action::Done => break, + other => panic!("unexpected {other:?}"), + } + } + assert_eq!(verified, 1); + let v = run.verify.head.clone().expect("a record"); + assert_eq!(v.sha, HEAD); + assert!(v.not_run().is_empty()); + let text = vq::section(&v, None); + assert!( + text.contains("- type check: `npx --no-install tsc --noEmit`: passes."), + "{text}" + ); + assert!(text.contains("`Dockerfile` installs pnpm 9.1.0"), "{text}"); + assert!( + text.contains("with pnpm 9.12.3 as `package.json` declares"), + "{text}" + ); + // The settle stage cites the record: the item never survives, and no + // second build is asked for. + let mut rec = settle::Record { + head: HEAD.into(), + ..Default::default() + }; + rec.adopt_verified(&v, None); + let facts = settle::Facts { + dep_change: true, + planned_by_rules: true, + ..Default::default() + }; + let item = proof::Finding { + point: "unrun_check".into(), + check: "typecheck".into(), + detail: "The type check never ran before the pull request.".into(), + ..Default::default() + }; + let plan_of = settle::plan(std::slice::from_ref(&item), &facts); + assert!(plan_of.checks); + let room = settle::Room { + build: true, + round: true, + sandbox: true, + dep_sets: 1, + }; + rec.audited = true; + assert_eq!(settle::next(&plan_of, &rec, &room), settle::Next::Done); + let settled = settle::apply(vec![item], &facts, &rec); + assert!(settled.open.is_empty(), "{:?}", settled.open); + assert!(settled.closed[0] + .1 + .contains("typecheck: PASS, `npx --no-install tsc --noEmit`")); + // A record of another commit is not taken: the set runs again. + let mut other = settle::Record { + head: "0ddba11".into(), + ..Default::default() + }; + other.adopt_verified(&v, None); + assert!(!other.checked); + assert_eq!(settle::next(&plan_of, &other, &room), settle::Next::Build); + // A change to the dependencies outside a dependency run gets the set's + // checks added to the repository's own. + let steps = settle::with_min_set(checks::mirrored_steps(&ci), std::slice::from_ref(&plan)); + assert!(steps + .iter() + .any(|s| s.kinds == vec![checks::CheckKind::Typecheck] + && s.cmd == "npx --no-install tsc --noEmit")); + // The driver runs the set and the settle stage reads it. + let drive = include_str!("../dep_fix.rs"); + assert!(drive.contains("Action::Verify { base } =>")); + assert!(drive.contains("probe.verify(&sha, &plan, run.verify.runs as usize)")); + let settle_src = include_str!("../settle.rs"); + assert!(fn_src(settle_src, "pub async fn run(").contains("rec.adopt_verified(")); + assert!(fn_src(settle_src, "async fn build(").contains("with_min_set(steps")); +} + +fn finding(id: &str, package: &str, version: &str, patched: &str, scope: Scope) -> Finding { + Finding { + id: format!("f-{package}"), + repo: format!("{OWNER}/{REPO}"), + package: package.into(), + version: version.into(), + fixed_version: (!patched.is_empty()).then(|| patched.to_string()), + manifest: LOCK.into(), + scope, + advisory: Advisory { + primary: id.into(), + ids: vec![id.into()], + source: "dependabot".into(), + ..Default::default() + }, + ..Default::default() + } +} + +/// CoderHelm's findings for the repository after the pull request: three +/// high advisories it still holds as open. +fn left_open() -> Vec<(Finding, FindingState)> { + let high = FindingState { + severity: Some("high".into()), + ..Default::default() + }; + vec![ + // Recorded for a version an override never lets the lockfile have. + ( + finding( + "GHSA-aaaa-aaaa-aaaa", + "glob-walk", + "2.3.1", + "2.3.9", + Scope::Runtime, + ), + high.clone(), + ), + // In a development tool. + ( + finding( + "GHSA-bbbb-bbbb-bbbb", + "lint-kit", + "8.0.0", + "9.0.0", + Scope::Dev, + ), + high.clone(), + ), + // In production, in a package the change does not touch. + ( + finding( + "GHSA-cccc-cccc-cccc", + "xml-read", + "1.1.0", + "", + Scope::Runtime, + ), + high, + ), + ] +} + +fn audit_of_the_head() -> Listings { + let listed = |id: &str, pkg: &str| Listed { + id: id.into(), + severity: "high".into(), + package: pkg.into(), + }; + Listings { + production: Some(Listing { + shown: "pnpm audit --prod --json".into(), + total: 1, + listed: vec![listed("GHSA-CCCC-CCCC-CCCC", "xml-read")], + }), + all: Some(Listing { + shown: "pnpm audit --json".into(), + total: 2, + listed: vec![ + listed("GHSA-CCCC-CCCC-CCCC", "xml-read"), + listed("GHSA-BBBB-BBBB-BBBB", "lint-kit"), + ], + }), + why: String::new(), + } +} + +fn reconciled() -> adv::Reconciled { + let held: Vec = left_open() + .iter() + .map(|(f, st)| adv::Held::of(f, st)) + .collect(); + let overrides = adv::overrides_of(r#"{"pnpm":{"overrides":{"glob-walk@2":"^2.4.0"}}}"#); + adv::reconcile(&adv::Input { + sha: HEAD, + lockfile: LOCK, + held: &held, + base: &copies(BASE), + head: &copies(WHOLE_HEAD), + audit: Some(&audit_of_the_head()), + overrides: &overrides, + ..Default::default() + }) +} + +/// Point 1. The number the pull request gave, and the one count the +/// pipeline now gives for the same head. +#[test] +fn the_advisories_left_are_counted_once_against_the_audit_of_the_head() { + // What was written: three, from CoderHelm's findings alone. + let open = left_open(); + let refs: Vec<&Finding> = open.iter().map(|(f, _)| f).collect(); + let run = DepRun::default(); + let old: usize = df::remaining(&run, &refs) + .iter() + .map(|g| g.advisories) + .sum(); + assert_eq!(old, 3); + // What the head has: two, one of them in production, none in a + // package the change touches; the third was never installed. + let r = reconciled(); + assert_eq!(r.remaining.len(), 2); + assert_eq!(r.remaining_by_scope(), (1, 1, 0)); + assert!(r.remaining.iter().all(|e| !e.touched)); + let causes: Vec = r.differences.iter().map(|d| d.cause).collect(); + assert_eq!( + causes, + vec![adv::Cause::Override, adv::Cause::DevelopmentOnly] + ); + let mut end = Ending::default(); + end.said(r.section()); + assert!(end.says("2 remaining (1 in production, 1 development only), 0 introduced.")); + assert!(end.says("compared with `pnpm audit --prod --json` and `pnpm audit --json`")); + assert!(end.says("in `xml-read` 1.1.0 (production; this change does not touch the package): no patched release exists")); + assert!(end.says("the manifest overrides the package, which the source of the finding does not read. Not counted.")); + end.never_says("3 remaining"); + // The run's report gives one count: the reconciled one when it was + // recorded for this head, CoderHelm's own (said to be its own) only + // without it. + let settle_src = include_str!("../dep_fix.rs"); + let settle_fn = fn_src(settle_src, "pub async fn settle("); + assert!(settle_fn.contains("f.of_head(&run.head) && f.advisories.is_some()")); + assert!(settle_fn.contains("if reconciled {")); +} + +/// The call sites the upgrade notes found for the two production majors. +fn notes() -> Vec { + let note = + |package: &str, from: &str, to: &str, api: &str, file: &str, breaking: &str| PackageNotes { + package: package.into(), + ecosystem: "npm".into(), + from: from.into(), + to: to.into(), + major: true, + versions: vec![to.into()], + breaking: vec![breaking.into()], + apis: vec![api.into()], + call_sites: vec![CallSite { + api: api.into(), + file: file.into(), + line: 12, + text: format!("{api}("), + }], + ..Default::default() + }; + vec![ + note( + "shape-check", + "3.2.0", + "4.0.1", + "safeParse", + "src/orders.controller.ts", + "`safeParse` reports issues in a new format; `message` is replaced by `error`", + ), + PackageNotes { + parents: vec![ParentSupport { + parent: "@lattice/platform-http".into(), + version: "10.4.22".into(), + declares: "^1.4.0".into(), + admits: Some(false), + ..Default::default() + }], + ..note( + "upload-kit", + "1.4.5", + "2.0.2", + "FileInterceptor", + "src/files.controller.ts", + "`FileInterceptor` rejects an oversized file with a new error code", + ) + }, + ] +} + +fn call_site_files() -> Vec<(String, String)> { + vec![ + ( + "src/orders.controller.ts".to_string(), + "@Controller('orders')\nexport class OrdersController {\n @Post()\n create(@Body() body: unknown) { return schema.safeParse(body); }\n}\n".to_string(), + ), + ( + "src/files.controller.ts".to_string(), + "@Controller('files')\nexport class FilesController {\n @Post('upload')\n @UseInterceptors(FileInterceptor('document', { limits: { fileSize: 2 * 1024 * 1024 } }))\n upload() {}\n}\n".to_string(), + ), + ] +} + +/// The answers of the two builds: the validation error's body changed, the +/// uploads answer as before. +fn answers(validation_body: &str, sha: &str) -> Vec> { + let a = |status: u16, sha: &str, excerpt: &str| { + Some(rp::ProbeAnswer { + status, + content_type: "application/json".into(), + sha: sha.into(), + excerpt: excerpt.into(), + stable: true, + }) + }; + vec![ + a(400, sha, validation_body), + a(201, "f11e", "{\"ok\":true}"), + a( + 400, + "bad0", + "{\"message\":\"Unexpected end of JSON input\"}", + ), + a(413, "b166", "{\"message\":\"File too large\"}"), + ] +} + +/// Point 4. The requests go through the call sites; the changed 400 body +/// is a known behaviour change; and the sentence "contract unchanged" +/// does not survive into the description. +#[test] +fn a_changed_error_body_is_found_and_unchanged_is_never_written_without_a_probe() { + let planned = bh::plan(¬es(), &call_site_files()); + let asked: Vec = planned + .requests + .iter() + .map(|q| format!("{} {} ({})", q.method, q.path, q.what)) + .collect(); + assert_eq!( + asked, + vec![ + "POST /orders (an empty JSON object (the validation error))", + "POST /files/upload (a small upload in the field `document`)", + "POST /orders (a malformed JSON body (the parser error))", + "POST /files/upload (an upload over the size limit the file states (2048 KiB))", + ] + ); + // The proof sends them to both builds, and reads the answers back. + let plan = rp::ProofPlan { + install: "pnpm install --frozen-lockfile".into(), + start: Some(rp::ProofCmd { + cmd: "pnpm run start".into(), + ..Default::default() + }), + probes: planned.requests.clone(), + ..Default::default() + }; + let script = rp::script(&plan); + assert!(script.contains("CODERHELM_PROOF_PROBE 4 $ch_t")); + assert!(script.contains("head -c 2162688 /dev/zero >> /tmp/coderhelm-probe-4.in")); + assert!(script.contains("-X POST -H 'Content-Type: multipart/form-data; boundary=coderhelmprobe' --data-binary @/tmp/coderhelm-probe-4.in")); + let read = rp::parse( + "CODERHELM_PROOF_PROBE 1 1 400 application/json aaaa eyJtZXNzYWdlIjpbIm5hbWUiXX0=\nCODERHELM_PROOF_PROBE 1 2 400 application/json aaaa \nCODERHELM_PROOF install=0 start=up port=38411\n", + &plan, + ); + assert_eq!( + read.probes[0].as_ref().unwrap().excerpt, + "{\"message\":[\"name\"]}" + ); + assert!(read.probes[0].as_ref().unwrap().stable); + assert!(read.probes[1].is_none()); + // Base against head. + let base = answers( + "{\"message\":[\"name must be a string\"],\"error\":\"Bad Request\"}", + "aaaa", + ); + let head = answers( + "{\"issues\":[{\"path\":[\"name\"],\"code\":\"invalid_type\"}]}", + "bbbb", + ); + let compared = bh::compare(&planned.requests, &base, &head); + let of = |package: &str| -> Vec { + planned + .of + .iter() + .find(|(p, _)| p == package) + .map(|(_, idx)| idx.iter().map(|i| compared[*i].clone()).collect()) + .unwrap() + }; + let n = notes(); + let shape = bh::Behaviour { + package: "shape-check".into(), + from: "3.2.0".into(), + to: "4.0.1".into(), + breaking_used: bh::used_breaking(&n[0]), + compared: of("shape-check"), + consumers_searched: "2 other repositories of the team, for `/orders`".into(), + ..Default::default() + }; + let upload = bh::Behaviour { + package: "upload-kit".into(), + from: "1.4.5".into(), + to: "2.0.2".into(), + compared: of("upload-kit"), + ..Default::default() + }; + assert_eq!(shape.changes().len(), 1); + assert!(!shape.unchanged_shown()); + // The upload, small and over the limit, answers as before: shown. + assert!(upload.unchanged_shown()); + let facts = UpgradeFacts { + sha: HEAD.into(), + behaviour: vec![shape, upload], + ..Default::default() + }; + assert!(!facts.unchanged_shown()); + // The description: the run's own words claimed it. + let unit = FixUnit { + repo: format!("{OWNER}/{REPO}"), + ecosystem: "npm".into(), + bumps: vec![Bump { + package: "shape-check".into(), + from: "3.2.0".into(), + to: "4.0.1".into(), + major: true, + manifest: LOCK.into(), + }], + ..Default::default() + }; + let fs = [( + finding( + "GHSA-dddd-dddd-dddd", + "shape-check", + "3.2.0", + "4.0.1", + Scope::Runtime, + ), + FindingState::default(), + )]; + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let at_head = dep_head::resolve( + &unit, + HEAD, + &[LockAt { + path: LOCK.into(), + base: Some(copies(BASE)), + head: Some(copies(WHOLE_HEAD)), + why: String::new(), + }], + ); + let check = WhatToCheck { + upgrade_facts: Some(facts), + ..Default::default() + }; + let body = sec::pr_body_at_head( + &unit, + &pairs, + "Raised the validation library. Contract unchanged. The build passes.", + &check, + &sec::BodyLinks::default(), + &at_head, + ); + let mut end = Ending::default(); + end.said(body.clone()); + end.never_says("Contract unchanged"); + assert!(end.says(bh::TAKEN_OUT), "{body}"); + assert!(end.says("Known behaviour change: `POST /orders` (an empty JSON object (the validation error)) answered 400 application/json on the base branch's build and 400 application/json on this head's: body before `{\"message\":[\"name must be a string\"]"), "{body}"); + assert!(end.says("Its notes list a breaking change in an API this repository calls: `safeParse` reports issues in a new format"), "{body}"); + assert!(end.says("Who could care: no other repository names these endpoints (searched 2 other repositories of the team, for `/orders`)."), "{body}"); + assert!( + end.says("Unchanged on these 2 requests; nothing is claimed beyond them."), + "{body}" + ); + assert!( + end.says("Recorded by CoderHelm on commit `5e1f00d`."), + "{body}" + ); + // The proof plan carries the requests, at its place in the run. + let drive = include_str!("../dep_fix.rs"); + assert!(drive.contains("super::upgrade_quality::behaviour_plan(state, w.github, msg, &run)")); + assert!(drive.contains("plan.probes = planned.requests;")); +} + +/// Point 5. Each major carries where it runs, who brings it in, how it is +/// fixed and whether it needs a probe. +#[test] +fn each_major_says_where_it_runs_how_it_is_fixed_and_whether_it_is_probed() { + let n = notes(); + // Behind a request, through a framework package the application + // imports, fixed by an override that leaves the parent's range. + let paths = [safety::PathIn { + root: "@lattice/platform-http".into(), + declared: safety::Declared::Production, + importers: vec!["src/files.controller.ts".into()], + ..Default::default() + }]; + let used = vec!["src/files.controller.ts:12".to_string()]; + let upload = safety::evidence(&safety::MajorIn { + package: "upload-kit", + from: "1.4.5", + to: "2.0.2", + ecosystem: "npm", + why_major: "GHSA-eeee lists no patched release on the 1 line", + paths: &paths, + used_in: &used, + searched: + "`upload-kit` and the APIs its notes name (`FileInterceptor`) in the repository's code", + verdict: sec::Verdict::NotReachable, + parents: &n[1].parents, + selector: "upload-kit@1", + ..Default::default() + }); + // A development tool's dependency. + let dev = [safety::PathIn { + root: "lint-kit".into(), + declared: safety::Declared::Development, + importers: vec![".eslintrc.js".into()], + ..Default::default() + }]; + let tool = safety::evidence(&safety::MajorIn { + package: "glob-walk", + from: "2.4.0", + to: "4.0.4", + paths: &dev, + searched: "`glob-walk` in the repository's code", + verdict: sec::Verdict::NotLoaded, + selector: "glob-walk@2", + ..Default::default() + }); + assert_eq!(upload.class, safety::PathClass::Production); + assert!(matches!(upload.probe, safety::ProbeNeed::Needed { .. })); + assert_eq!(tool.class, safety::PathClass::Development); + assert_eq!(tool.probe, safety::ProbeNeed::NotNeeded); + let facts = UpgradeFacts { + sha: HEAD.into(), + majors: vec![upload, tool], + ..Default::default() + }; + let mut end = Ending::default(); + end.said(facts.section(HEAD)); + assert!(end.says("- `upload-kit` 1.4.5 to 2.0.2 (major): runs in production.")); + assert!(end.says("Path through `@lattice/platform-http` (production): `@lattice/platform-http` is imported by `src/files.controller.ts`.")); + assert!(end.says("Use in this repository: `src/files.controller.ts:12`.")); + assert!(end.says("That is not proof of safety")); + assert!(end.says("Fixed by an override scoped to its version line (`upload-kit@1`)")); + assert!(end.says("Outside a declared range: `@lattice/platform-http` 10.4.22 declares `^1.4.0` for it, and the override installs 2.0.2, outside that range.")); + assert!(end.says("Needs a functional probe: it runs in production and the repository uses it")); + assert!(end.says("- `glob-walk` 2.4.0 to 4.0.4 (major): runs in development only.")); + // A production major with no probe behind it never lets the word + // "unchanged" stand. + assert!(!facts.unchanged_shown()); + // Recorded on another commit: said, never shown as the head's. + assert!(facts.section("0ddba11c0de").contains( + "The head is now `0ddba11`: everything in this section is of the earlier commit" + )); + // The run records the evidence when it ends, and the description + // reads it from the ticket. + let drive = include_str!("../dep_fix.rs"); + assert!(drive.contains("super::upgrade_quality::record(&at, &run).await")); + let sec_src = include_str!("../security_fixes.rs"); + assert!(sec_src.matches("check.upgrade_facts = item").count() >= 2); + let recorder = include_str!("../upgrade_quality.rs"); + let record = fn_src(recorder, "pub async fn record("); + for part in [ + "fam::splits(", + "advisories(at, run,", + "majors(at, run,", + "behaviour(at, run,", + ] { + assert!(record.contains(part), "{part} is gone from the record"); + } +} + +/// All five, in the one description of the reviewed head. +#[test] +fn the_description_carries_all_five_for_the_head_it_is_of() { + let family = family(); + let plan = verify_plan(); + let all: Vec = (0..plan.checks.len()).collect(); + let out: String = all + .iter() + .map(|i| format!("CODERHELM_VERIFY {i} 0\n")) + .collect(); + let facts = UpgradeFacts { + sha: HEAD.into(), + splits: fam::splits(std::slice::from_ref(&family), LOCK, &copies(WHOLE_HEAD)), + families: vec![family], + verified: Some(vq::read(&plan, HEAD, &all, &[], &out)), + advisories: Some(reconciled()), + ..Default::default() + }; + let text = facts.section(HEAD); + for part in [ + "**Advisories on commit `5e1f00d`", + "**Families released together**", + "The head installs every member at one version.", + "**Verified in the sandbox on commit `5e1f00d`**", + "- frozen install, deployment version: `npx -y pnpm@9.1.0 install --frozen-lockfile --ignore-scripts`: passes.", + ] { + assert!(text.contains(part), "{part} is missing from:\n{text}"); + } + // The record round-trips through the ticket. + let json = serde_json::to_string(&facts).unwrap(); + assert_eq!(UpgradeFacts::from_json(&json), Some(facts)); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 7bf2ef65b..781177cec 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -35,6 +35,7 @@ mod aq_comment_during_run; mod ar_description_stamped_to_the_head; mod as_infra_closed_pr_keeps_record; mod at_round_scope; +mod au_upgrade_decided_and_proven; mod aw_quarantine_dead_end; mod b_open_pr_retry; mod ba_verdict_on_old_commit; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 082113884..522d7d6ac 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1353,6 +1353,7 @@ pub mod ticket_history; pub mod tool_proposals; mod triage; pub mod upgrade_notes; +pub mod upgrade_quality; pub mod usage_reconcile; pub mod web_check; pub mod webhooks; diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index 4dfb3fdde..3ab8abb1a 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -4297,6 +4297,9 @@ pub async fn pr_body(state: &WorkerState, msg: &TicketMessage, change: &str) -> .as_ref() .map(|i| s(i, "dep_report")) .unwrap_or_default(); + check.upgrade_facts = item + .as_ref() + .and_then(|i| common::upgrade_quality::UpgradeFacts::from_json(&s(i, "dep_facts"))); let mut links = body_links(state, item.as_ref()); // A bundle too long to describe in full keeps its full detail on its // branch, beside the plan CoderHelm commits there, when the team lets @@ -4634,6 +4637,9 @@ pub(crate) async fn at_head( .as_ref() .map(|i| s(i, "dep_report")) .unwrap_or_default(); + check.upgrade_facts = item + .as_ref() + .and_then(|i| common::upgrade_quality::UpgradeFacts::from_json(&s(i, "dep_facts"))); // The same links as when it opened: the rewritten sections are the // short ones a bundle's description carries. let links = body_links(state, item.as_ref()); @@ -4767,6 +4773,17 @@ pub(crate) async fn dep_inputs( (!findings.is_empty()).then_some(DepInputs { findings, cfg }) } +/// The upgrade evidence a dependency run recorded for its head commit +/// (`passes::upgrade_quality::record`), when it recorded one. +pub(crate) async fn dep_facts( + state: &WorkerState, + team_id: &str, + ticket: &str, +) -> Option { + let item = ticket_item(state, team_id, ticket).await?; + common::upgrade_quality::UpgradeFacts::from_json(&s(&item, "dep_facts")) +} + /// The upgrade notes read for the ticket before its run. pub(crate) async fn dep_notes( state: &WorkerState, diff --git a/services/worker/src/passes/settle.rs b/services/worker/src/passes/settle.rs index 2e138cf21..a8c41868f 100644 --- a/services/worker/src/passes/settle.rs +++ b/services/worker/src/passes/settle.rs @@ -29,6 +29,14 @@ //! and the counts left are quoted on the pull request. //! - A check the coder's step was refused for lack of time is owed: it runs //! here whether or not anything listed it. +//! - A change to the dependencies is verified with the set a senior +//! engineer would run, found in the project and not in its CI +//! (`common::upgrade_quality::verify`): a typed project is type-checked +//! though no workflow does it. A dependency run records that set against +//! its head, and this stage cites the record instead of building again +//! ([`Record::adopt_verified`]); any other change to the dependencies +//! gets the set's checks added to the repository's own ([`with_min_set`]). +//! So "check not run" never stays open for a check of the set: it runs. //! - An item that does not apply to the run is never raised, and items that //! name the same missing fact are one item ([`dedup`]). //! - Open items are derived again whenever the head moves. Each line names @@ -43,6 +51,7 @@ use tracing::{info, warn}; use common::dep_audit; use common::handback::{human_only_in, HumanOnly}; +use common::upgrade_quality::verify as vq; use super::checks::{CheckKind, Step}; use super::proof::{self, Finding, RunEvidence, SandboxRecord}; @@ -355,6 +364,9 @@ pub struct Record { pub reverts: u32, /// Fresh steps taken for a sandbox window. pub steps: u32, + /// The kinds that fail on this head and on the base branch too: not + /// caused by the change, so never fixed or taken out for. + pub base_fails: Vec, } impl Record { @@ -387,9 +399,64 @@ impl Record { [CheckKind::Build, CheckKind::Typecheck, CheckKind::Tests] .into_iter() .filter(|k| self.ran(*k) && !self.passed(*k)) + .filter(|k| !self.base_fails.iter().any(|b| b == k.name())) .collect() } + /// The verification set a dependency run recorded on this head stands + /// as this stage's check run: its results are cited with the commands + /// that ran, and the same build is never run twice. A record of + /// another commit, or one with no result, is not taken. `base`: the + /// set's results on the base branch, when the run needed them. + pub fn adopt_verified(&mut self, v: &vq::Verified, base: Option<&vq::Verified>) { + if self.checked || !v.ran || v.sha != self.head { + return; + } + let kind_of = |k: vq::Kind| match k { + vq::Kind::Typecheck => Some(CheckKind::Typecheck), + vq::Kind::Build => Some(CheckKind::Build), + vq::Kind::Lint => Some(CheckKind::Lint), + vq::Kind::Tests => Some(CheckKind::Tests), + _ => None, + }; + let commit: String = v.sha.chars().take(7).collect(); + // The audit has its own lines here, with its counts. + for o in v.outcomes.iter().filter(|o| o.kind != vq::Kind::Audit) { + let name = kind_of(o.kind).map_or(o.kind.name(), CheckKind::name); + let on_base = base.and_then(|b| b.outcome(o.kind)); + let verdict = match &o.status { + vq::Status::Passed => "PASS".to_string(), + vq::Status::Failed { exit } if on_base.is_some_and(|b| b.ran() && !b.passed()) => { + format!( + "FAIL (exit {exit}) on the base branch too, so not caused by this change" + ) + } + vq::Status::Failed { exit } => format!("FAIL (exit {exit})"), + vq::Status::TimedOut { after } => { + format!("no result (stopped at its time limit of {after} seconds)") + } + vq::Status::NotRun => format!("not run ({})", o.why), + }; + self.checks.push(format!( + "- {name}: {verdict}, `{}` (the dependency run's verification set, on commit `{commit}`)", + common::truncate_str(&o.shown, 300) + )); + let Some(k) = kind_of(o.kind) else { + continue; + }; + if o.ran() && !matches!(o.status, vq::Status::TimedOut { .. }) { + self.ran.push(k.name().to_string()); + if o.passed() { + self.passed.push(k.name().to_string()); + } else if on_base.is_some_and(|b| b.ran() && !b.passed()) { + self.base_fails.push(k.name().to_string()); + } + } + } + self.checked = true; + self.no_result.clear(); + } + /// A check run's steps and exit codes, recorded. pub fn record_checks(&mut self, steps: &[Step], codes: &[Option], output: &str) { let rec = SandboxRecord::from_steps(steps, codes); @@ -459,8 +526,10 @@ pub struct Plan { /// was refused one, the audit when an item names it or the change touches /// the dependencies. pub fn plan(items: &[Finding], facts: &Facts) -> Plan { + // A change to the dependencies is always verified: the set a senior + // engineer would run, whether or not an item asked for it. let mut p = Plan { - checks: facts.checks_owed, + checks: facts.checks_owed || facts.dep_change, audit: facts.dep_change, ..Default::default() }; @@ -606,6 +675,13 @@ fn result_of(actions: &[Action], rec: &Record) -> Result { .unwrap_or_else(|| format!("- {}: PASS", k.name())); proof.push(line.trim_start_matches("- ").to_string()); } + Action::Check(k) if rec.ran(*k) && rec.base_fails.iter().any(|b| b == k.name()) => { + return Err(format!( + "CoderHelm ran {} in its sandbox: it fails on this commit and on the base \ + branch too, so this change did not cause it", + k.name() + )) + } Action::Check(k) if rec.ran(*k) => { return Err(format!( "CoderHelm ran {} in its sandbox and it fails; its fix rounds did not turn it \ @@ -776,6 +852,9 @@ pub fn redrive_due(body: &str, head: &str, redrives: u32, last_head: &str) -> bo // ── Running ───────────────────────────────────────────────────────────── /// How the stage ended in this step. +// One value per step, moved once: the record stays inline so the callers +// that take it apart are unchanged. +#[allow(clippy::large_enum_variant)] pub enum Ran { /// Settled: what goes on the pull request. Settled(Box, Record), @@ -875,6 +954,82 @@ async fn permitted(w: &proof::Work<'_>, steps: Vec) -> Vec { kept } +/// The repository's check steps with the verification set's added: each +/// type check, build, lint and test command `found` names for a kind the +/// steps do not already run. With no step at all, the set's own install +/// comes first. A typed project is then type-checked whatever its CI runs. +pub fn with_min_set(mut steps: Vec, found: &[vq::Plan]) -> Vec { + for plan in found { + let cd = if plan.dir.is_empty() { + String::new() + } else { + format!("cd '{}' && ", plan.dir) + }; + if steps.is_empty() { + if let Some(install) = plan.checks.iter().find(|c| c.kind == vq::Kind::Install) { + steps.push(Step { + kinds: vec![], + cmd: format!("{cd}{}", install.cmd), + scope: None, + }); + } + } + for c in &plan.checks { + let kind = match c.kind { + vq::Kind::Typecheck => CheckKind::Typecheck, + vq::Kind::Build => CheckKind::Build, + vq::Kind::Lint => CheckKind::Lint, + vq::Kind::Tests => CheckKind::Tests, + _ => continue, + }; + if steps.iter().any(|s| s.kinds.contains(&kind)) { + continue; + } + steps.push(Step { + kinds: vec![kind], + cmd: format!("{cd}{}", c.cmd), + scope: Some(format!( + "found in the project of `{}`, not in CI: {}", + plan.lockfile, c.found + )), + }); + } + } + steps +} + +/// Projects whose verification set one settle build adds. +const MAX_MIN_SET_PROJECTS: usize = 2; + +/// The verification set of each project whose lockfile the change touches, +/// found in the project's own files on the branch. +async fn min_set(w: &proof::Work<'_>, audits: &[dep_audit::Audit]) -> Vec { + let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); + let tree: Vec = match w.github.get_tree(owner, name, w.branch).await { + Ok(t) => t + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect(), + Err(_) => return vec![], + }; + let mut out = vec![]; + for a in audits.iter().take(MAX_MIN_SET_PROJECTS) { + let mut files = vec![]; + for path in vq::files_to_read(&a.lockfile, &tree) { + if let Ok(Some(text)) = w + .github + .read_file_if_exists(owner, name, &path, w.branch) + .await + { + files.push((path, text)); + } + } + out.push(vq::discover(&a.lockfile, &tree, &files, None)); + } + out +} + /// Runs what the plan still lacks on `head`, in the sandbox, and records /// it. Every path records something, so the stage never asks for the same /// build twice. @@ -890,7 +1045,11 @@ async fn build( let node = super::detect_node_version(w.github, owner, name, w.branch).await; if plan.checks && !rec.checked && rec.no_result.is_empty() { let sb = sandbox(w).with_egress(egress.clone()); - let steps = permitted(w, super::dep_fix::probe_steps(w.github, w.msg).await).await; + let mut steps = super::dep_fix::probe_steps(w.github, w.msg).await; + if !audits.is_empty() { + steps = with_min_set(steps, &min_set(w, audits).await); + } + let steps = permitted(w, steps).await; if steps.is_empty() { rec.no_result = "the repository has no check command CoderHelm may run in its sandbox".into(); @@ -1027,6 +1186,18 @@ pub async fn run( let save = |rec: &Record| { w.ledger.update(|l| l.settle = rec.clone()); }; + // The verification set a dependency run recorded on this head is this + // stage's check run: cited, never built again. + if !rec.checked && common::security_fixes::is_ticket(&w.msg.ticket_id) { + if let Some(run) = super::dep_fix::load(w.state, w.msg, w.run_id).await { + if let Some(v) = &run.verify.head { + rec.adopt_verified(v, run.verify.base.as_ref()); + if rec.checked { + save(&rec); + } + } + } + } loop { let dep_sets = match common::security_fixes::is_ticket(&w.msg.ticket_id) { true => super::dep_fix::load(w.state, w.msg, w.run_id) @@ -1734,4 +1905,127 @@ mod tests { let out = apply(vec![audit], &chore(), &bad); assert!(out.open[0].needs.contains("gave no report")); } + + fn typed_set() -> vq::Plan { + let tree: Vec = ["package.json", "pnpm-lock.yaml", "tsconfig.json"] + .iter() + .map(|s| s.to_string()) + .collect(); + vq::discover( + "pnpm-lock.yaml", + &tree, + &[( + "package.json".to_string(), + r#"{"scripts":{"build":"tsc -p .","test":"vitest run"}}"#.to_string(), + )], + None, + ) + } + + #[test] + fn a_dependency_change_is_always_checked_and_a_recorded_set_is_cited_not_rebuilt() { + // No item asks: the set runs all the same. + let p = plan(&[], &chore()); + assert!(p.checks && p.audit); + let set = typed_set(); + let all: Vec = (0..set.checks.len()).collect(); + // Install, type check, build pass; the tests fail here and on the + // base branch. + let out = "CODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 1 0\nCODERHELM_VERIFY 2 0\nCODERHELM_VERIFY 3 1\n"; + let head = vq::read(&set, "abc1234def", &all, &[], out); + let base = vq::read(&set, "base", &all, &[], out); + let mut rec = Record { + head: "abc1234def".into(), + audited: true, + ..Default::default() + }; + rec.adopt_verified(&head, Some(&base)); + assert!(rec.checked); + assert_eq!(rec.passed, vec!["typecheck", "build"]); + assert_eq!(rec.base_fails, vec!["tests"]); + // A failure the base branch has too starts no fix round and takes + // out no set. + let room = Room { + build: true, + round: true, + sandbox: true, + dep_sets: 3, + }; + assert_eq!(next(&p, &rec, &room), Next::Done); + let mut unrun = f("unrun_check", "The type check never ran.", ""); + unrun.check = "typecheck".into(); + let mut tests_item = f("unrun_check", "Tests never ran.", ""); + tests_item.check = "tests".into(); + let settled = apply(vec![unrun, tests_item], &chore(), &rec); + assert_eq!(settled.closed.len(), 1); + assert!(settled.closed[0].1.contains( + "typecheck: PASS, `npx --no-install tsc --noEmit` (the dependency run's verification set, on commit `abc1234`)" + )); + // What stays says what ran and what came back. + assert_eq!(settled.open.len(), 1); + assert!(settled.open[0].needs.contains( + "it fails on this commit and on the base branch too, so this change did not cause it" + )); + // The same failure without the base branch failing is the change's. + let green_base = vq::read( + &set, + "base", + &all, + &[], + "CODERHELM_VERIFY 0 0\nCODERHELM_VERIFY 1 0\nCODERHELM_VERIFY 2 0\nCODERHELM_VERIFY 3 0\n", + ); + let mut rec = Record { + head: "abc1234def".into(), + audited: true, + ..Default::default() + }; + rec.adopt_verified(&head, Some(&green_base)); + assert_eq!(next(&p, &rec, &room), Next::TakeOutSet); + // A record with no result, or of another commit, is never taken. + let mut rec = Record { + head: "abc1234def".into(), + ..Default::default() + }; + rec.adopt_verified(&vq::no_result(&set, "abc1234def", "timed out"), None); + assert!(!rec.checked); + } + + #[test] + fn the_sets_checks_join_the_repositorys_own_for_the_kinds_it_lacks() { + let set = typed_set(); + // The repository's steps run its tests; the set adds the type check + // and the build, and leaves the tests to the repository's command. + let own = vec![ + Step { + kinds: vec![], + cmd: "pnpm install --frozen-lockfile".into(), + scope: None, + }, + Step { + kinds: vec![CheckKind::Tests], + cmd: "pnpm test -- --ci".into(), + scope: None, + }, + ]; + let steps = with_min_set(own, std::slice::from_ref(&set)); + let cmds: Vec<&str> = steps.iter().map(|s| s.cmd.as_str()).collect(); + assert_eq!( + cmds, + vec![ + "pnpm install --frozen-lockfile", + "pnpm test -- --ci", + "npx --no-install tsc --noEmit", + "pnpm run build" + ] + ); + assert_eq!( + steps[2].scope.as_deref(), + Some("found in the project of `pnpm-lock.yaml`, not in CI: `tsconfig.json` is there and no script runs it") + ); + // With no step of its own, the set's install comes first. + let steps = with_min_set(vec![], &[set]); + assert!(steps[0].kinds.is_empty()); + assert!(steps[0].cmd.ends_with("pnpm install --frozen-lockfile")); + assert_eq!(steps.len(), 4); + } } diff --git a/services/worker/src/passes/upgrade_notes.rs b/services/worker/src/passes/upgrade_notes.rs index 706c5ca8d..76dc646db 100644 --- a/services/worker/src/passes/upgrade_notes.rs +++ b/services/worker/src/passes/upgrade_notes.rs @@ -27,7 +27,7 @@ const BUDGET: Duration = Duration::from_secs(60); /// One registry read. const READ_TIMEOUT: Duration = Duration::from_secs(10); -async fn registry(state: &WorkerState, url: &str) -> Result { +pub(crate) async fn registry(state: &WorkerState, url: &str) -> Result { let r = state .http .get(url) diff --git a/services/worker/src/passes/upgrade_quality.rs b/services/worker/src/passes/upgrade_quality.rs new file mode 100644 index 000000000..09869db80 --- /dev/null +++ b/services/worker/src/passes/upgrade_quality.rs @@ -0,0 +1,919 @@ +//! The reads `common::upgrade_quality` decides from, and the record it +//! leaves for the pull request. +//! +//! Everything that decides is pure and lives in `common::upgrade_quality`: +//! families, the verification set, the advisory count, why a major is +//! safe, and the behaviour probe. This module reads what those need (the +//! registry's record of a package, the base branch's and the head's +//! lockfiles, the project's own files, the repository's findings and +//! notes), and keeps the result on the security ticket as the run's +//! upgrade evidence, stamped with the head commit it is of. + +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +use common::dep_fix::{self as df, DepRun}; +use common::security_fixes::{self as sec, Finding, FindingState, Scope}; +use common::upgrade_notes as un; +use common::upgrade_quality::{ + advisories as adv, behaviour as bh, family as fam, safety, verify as vq, UpgradeFacts, +}; +use serde_json::Value; +use tracing::{info, warn}; + +use crate::clients::github::GitHubClient; +use crate::models::TicketMessage; +use crate::WorkerState; + +/// Time the family search of one plan may take. +const FAMILY_BUDGET: Duration = Duration::from_secs(45); +/// Bumps of one plan whose families are looked for. +const MAX_FAMILY_BUMPS: usize = 40; +/// Call-site files one behaviour plan reads. +const MAX_CALL_SITE_FILES: usize = 12; +/// Majors one run gathers safety evidence for. +const MAX_MAJORS: usize = 8; +/// Dependency paths read per major. +const MAX_PATHS: usize = 4; + +/// The registry ecosystem a lockfile's packages come from. +pub fn ecosystem_of(lockfile: &str) -> &'static str { + match common::lockfile_sync::lock_manager(lockfile) { + Some("npm" | "pnpm" | "yarn" | "bun") => "npm", + Some("cargo") => "crates.io", + Some("poetry" | "uv" | "pipenv") => "PyPI", + Some("bundler") => "RubyGems", + Some("go") => "Go", + _ => "", + } +} + +/// The registry's record of one version of a package. `Ok(None)`: the +/// registry has no such version. +async fn registry_record( + state: &WorkerState, + ecosystem: &str, + package: &str, + version: &str, +) -> Result, String> { + let Some(url) = un::registry_url(ecosystem, package, version) else { + return Err(format!("CoderHelm reads no registry for {ecosystem}")); + }; + match super::upgrade_notes::registry(state, &url).await { + Ok(v) => Ok(Some(v)), + Err(why) if why.ends_with(" 404") => Ok(None), + Err(why) => Err(why), + } +} + +fn source_key(ecosystem: &str, package: &str, meta: &Value) -> Option { + un::source_repo(ecosystem, package, meta) + .map(|r| format!("{}/{}", r.owner, r.name).to_ascii_lowercase()) +} + +/// The peer ranges a registry record declares (npm's `peerDependencies`; +/// other registries have no such field). +fn peers_of(ecosystem: &str, meta: &Value) -> Vec<(String, String)> { + if ecosystem != "npm" { + return vec![]; + } + meta["peerDependencies"] + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, v)| v.as_str().map(|r| (k.clone(), r.to_string()))) + .collect() +} + +async fn copies_at( + gh: &GitHubClient, + msg: &TicketMessage, + lockfile: &str, + git_ref: &str, +) -> Option> { + let text = gh + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, lockfile, git_ref) + .await + .ok()??; + common::reachability::lock_copies(lockfile, &text) +} + +/// The families of a plan's packages, found from the registry and the base +/// branch's lockfile, and brought into the plan (`family::attach`): each +/// bump of a member then carries the others. Returns the families and the +/// peer ranges the plan's new releases declare. +pub async fn families( + state: &WorkerState, + gh: &GitHubClient, + msg: &TicketMessage, + plan: &mut df::DepPlan, +) -> (Vec, Vec) { + let started = Instant::now(); + let mut base: BTreeMap>> = BTreeMap::new(); + let mut sources: BTreeMap> = BTreeMap::new(); + let mut families: Vec = vec![]; + let mut peers: Vec = vec![]; + for b in plan.bumps.iter().take(MAX_FAMILY_BUMPS) { + if started.elapsed() >= FAMILY_BUDGET { + break; + } + let ecosystem = ecosystem_of(&b.manifest); + if ecosystem.is_empty() { + continue; + } + // Already a member of a family found for an earlier bump. + if families.iter().any(|f| { + f.lockfile == b.manifest + && f.base_version == b.from + && f.members.iter().any(|m| m.eq_ignore_ascii_case(&b.package)) + }) { + continue; + } + if !base.contains_key(&b.manifest) { + let read = copies_at(gh, msg, &b.manifest, &msg.base_branch).await; + base.insert(b.manifest.clone(), read); + } + let Some(Some(copies)) = base.get(&b.manifest) else { + continue; + }; + // The release it moves to: its source repository and its peers. + let to = registry_record(state, ecosystem, &b.package, &b.to) + .await + .ok() + .flatten(); + let peer_ranges = to + .as_ref() + .map(|m| peers_of(ecosystem, m)) + .unwrap_or_default(); + for (on, range) in &peer_ranges { + peers.push(fam::PeerRange { + from: b.package.clone(), + on: on.clone(), + range: range.clone(), + }); + } + let candidates = fam::candidates(&b.package, &b.from, copies); + if candidates.is_empty() && !peer_ranges.iter().any(|(_, r)| fam::pins(r)) { + continue; + } + let mut known = vec![fam::Known { + name: b.package.clone(), + source: to + .as_ref() + .and_then(|m| source_key(ecosystem, &b.package, m)), + }]; + for c in &candidates { + let key = format!("{ecosystem}:{c}"); + if !sources.contains_key(&key) { + let version = copies + .iter() + .find(|(n, _)| n == c) + .map(|(_, v)| v.clone()) + .unwrap_or_default(); + let source = registry_record(state, ecosystem, c, &version) + .await + .ok() + .flatten() + .and_then(|m| source_key(ecosystem, c, &m)); + sources.insert(key.clone(), source); + } + known.push(fam::Known { + name: c.clone(), + source: sources.get(&key).cloned().flatten(), + }); + } + let Some(mut f) = fam::detect( + &b.package, + &b.from, + &b.manifest, + copies, + &known, + &peer_ranges, + ) else { + continue; + }; + if f.members.len() >= 2 { + // Which members publish the version that fixes the advisory. + let wanted = vec![b.to.clone()]; + let mut published: BTreeMap> = BTreeMap::new(); + for m in &f.members { + let has = if m.eq_ignore_ascii_case(&b.package) { + to.as_ref().map(|_| true) + } else { + registry_record(state, ecosystem, m, &b.to) + .await + .ok() + .map(|r| r.is_some()) + }; + if let Some(has) = has { + published.insert(m.clone(), if has { wanted.clone() } else { vec![] }); + } + } + match fam::target(&f, &wanted, &published) { + Ok(v) => f.target = v, + Err(why) => f.held = why, + } + } + families.push(f); + } + fam::attach(plan, &mut families); + info!( + families = families.len(), + moving = families.iter().filter(|f| !f.target.is_empty()).count(), + secs = started.elapsed().as_secs(), + "dep fix: families read" + ); + (families, peers) +} + +/// What the verification set of a run runs: the set of the project most +/// of its applied bumps are in, found in that project's own files. +pub async fn verify_plan( + gh: &GitHubClient, + msg: &TicketMessage, + run: &DepRun, + tree: &[String], +) -> vq::Plan { + let Some(lockfile) = main_lockfile(run) else { + return vq::Plan { + none: "no bump was applied".into(), + ..Default::default() + }; + }; + let mut files = vec![]; + for path in vq::files_to_read(&lockfile, tree) { + if let Ok(Some(text)) = gh + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, &path, &msg.base_branch) + .await + { + files.push((path, text)); + } + } + let manager = common::lockfile_sync::lock_manager(&lockfile).unwrap_or(""); + let audit = common::dep_audit::production(manager); + vq::discover( + &lockfile, + tree, + &files, + audit.as_ref().map(|(shown, cmd)| (*shown, cmd.as_str())), + ) +} + +/// The lockfile most of a run's applied bumps go through. +pub fn main_lockfile(run: &DepRun) -> Option { + let mut by: BTreeMap<&str, usize> = BTreeMap::new(); + for b in run.applied_bumps() { + *by.entry(b.manifest.as_str()).or_default() += 1; + } + by.into_iter() + .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0))) + .map(|(l, _)| l.to_string()) +} + +/// The requests the runtime proof sends for the run's applied majors: the +/// routes declared in the files that call each (`behaviour::plan`). +pub async fn behaviour_plan( + state: &WorkerState, + gh: &GitHubClient, + msg: &TicketMessage, + run: &DepRun, +) -> bh::Planned { + let applied = run.applied_bumps(); + let notes: Vec = + super::security_fixes::dep_notes(state, &msg.team_id, &msg.ticket_id) + .await + .into_iter() + .filter(|n| { + n.major + && applied + .iter() + .any(|b| b.major && b.package.eq_ignore_ascii_case(&n.package)) + }) + .collect(); + let mut paths: Vec = notes + .iter() + .flat_map(|n| n.call_sites.iter().map(|c| c.file.clone())) + .collect(); + paths.sort(); + paths.dedup(); + let mut files = vec![]; + for path in paths.into_iter().take(MAX_CALL_SITE_FILES) { + if let Ok(Some(text)) = gh + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, &path, &msg.base_branch) + .await + { + files.push((path, text)); + } + } + bh::plan(¬es, &files) +} + +/// The team's other repositories, searched through the cross-repository +/// search (`cross_repo::search_others`). +struct OtherRepos<'a> { + gh: &'a GitHubClient, +} + +#[async_trait::async_trait] +impl super::cross_repo::RepoSearch for OtherRepos<'_> { + async fn search(&self, repo: &str, query: &str) -> Result, String> { + let (owner, name) = repo.split_once('/').ok_or("not owner/name")?; + let branch = self + .gh + .get_default_branch(owner, name) + .await + .map_err(|e| e.to_string())?; + self.gh + .search_code(owner, name, &branch, query) + .await + .map(|r| r.into_iter().map(|h| h.path).collect()) + .map_err(|e| e.to_string()) + } +} + +/// The team's other repositories that name an endpoint whose answer +/// changed, and how many were searched, in words. +async fn consumers( + state: &WorkerState, + gh: &GitHubClient, + msg: &TicketMessage, + paths: &[String], +) -> (Vec, String) { + let own = format!("{}/{}", msg.repo_owner, msg.repo_name); + let repos = super::plan::fetch_team_repos(state, &msg.team_id).await; + let others = repos + .iter() + .filter(|r| !r.eq_ignore_ascii_case(&own)) + .take(super::cross_repo::MAX_FALLBACK_REPOS) + .count(); + if others == 0 || paths.is_empty() { + return (vec![], String::new()); + } + let search = OtherRepos { gh }; + let mut found: Vec = vec![]; + for path in paths.iter().take(4) { + if let Some((_, hit)) = super::cross_repo::search_others(&search, &own, &repos, path).await + { + for r in hit { + if !found.contains(&r) { + found.push(r); + } + } + } + } + ( + found, + format!( + "{others} other repositor{} of the team, for {}", + if others == 1 { "y" } else { "ies" }, + paths + .iter() + .take(4) + .map(|p| format!("`{p}`")) + .collect::>() + .join(", ") + ), + ) +} + +/// The manifest scripts whose command runs `package`, by name. +pub fn scripts_running(manifest: &str, package: &str) -> Vec { + let Ok(v) = serde_json::from_str::(manifest) else { + return vec![]; + }; + // A scoped package's command is its last part (`@scope/cli` runs `cli`). + let word = package.rsplit('/').next().unwrap_or(package); + let mut out: Vec = v["scripts"] + .as_object() + .into_iter() + .flatten() + .filter(|(_, cmd)| { + cmd.as_str().is_some_and(|c| { + c.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '-' && ch != '_') + .any(|w| w == word) + }) + }) + .map(|(name, _)| name.clone()) + .collect(); + out.sort(); + out +} + +/// The packages an npm lockfile marks as running a script at install. +pub fn install_script_packages(lockfile: &str, text: &str) -> Vec { + let name = lockfile.rsplit('/').next().unwrap_or(lockfile); + if !matches!(name, "package-lock.json" | "npm-shrinkwrap.json") { + return vec![]; + } + let Ok(v) = serde_json::from_str::(text) else { + return vec![]; + }; + let mut out: Vec = v["packages"] + .as_object() + .into_iter() + .flatten() + .filter(|(_, p)| p["hasInstallScript"].as_bool() == Some(true)) + .filter_map(|(loc, _)| loc.rsplit("node_modules/").next().map(String::from)) + .filter(|n| !n.is_empty()) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// Where the run's work is: what every read here needs. +pub struct At<'a> { + pub state: &'a WorkerState, + pub gh: &'a GitHubClient, + pub msg: &'a TicketMessage, + pub branch: &'a str, +} + +/// The safety evidence of each applied major: its dependency paths with +/// who imports each root, whether the repository uses it, its verdict and +/// how it is fixed. +async fn majors( + at: &At<'_>, + run: &DepRun, + findings: &[(Finding, FindingState)], + notes: &[un::PackageNotes], +) -> Vec { + let (o, n, base) = (&at.msg.repo_owner, &at.msg.repo_name, &at.msg.base_branch); + let mut out = vec![]; + let mut manifests: BTreeMap = BTreeMap::new(); + let mut install: BTreeMap> = BTreeMap::new(); + for b in run + .applied_bumps() + .into_iter() + .filter(|b| b.major) + .take(MAX_MAJORS) + { + let mine: Vec<&(Finding, FindingState)> = findings + .iter() + .filter(|(f, _)| b.finding_ids.contains(&f.id)) + .collect(); + let note = notes + .iter() + .find(|x| x.package.eq_ignore_ascii_case(&b.package)); + let dir = b.manifest.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + let manifest_path = if dir.is_empty() { + "package.json".to_string() + } else { + format!("{dir}/package.json") + }; + if !manifests.contains_key(&manifest_path) { + let text = at + .gh + .read_file_if_exists(o, n, &manifest_path, base) + .await + .ok() + .flatten() + .unwrap_or_default(); + manifests.insert(manifest_path.clone(), text); + } + if !install.contains_key(&b.manifest) { + let text = at + .gh + .read_file_if_exists(o, n, &b.manifest, base) + .await + .ok() + .flatten() + .unwrap_or_default(); + install.insert( + b.manifest.clone(), + install_script_packages(&b.manifest, &text), + ); + } + let manifest = manifests.get(&manifest_path).cloned().unwrap_or_default(); + let scripted = install.get(&b.manifest).cloned().unwrap_or_default(); + // One path per direct dependency that brings it in. + let mut roots: Vec<(String, safety::Declared)> = vec![]; + for (f, _) in &mine { + let root = f.path.first().cloned().unwrap_or_else(|| f.package.clone()); + let declared = match f.scope { + Scope::Runtime => safety::Declared::Production, + Scope::Dev => safety::Declared::Development, + Scope::Unknown => safety::Declared::NotKnown, + }; + if !roots.iter().any(|(r, _)| *r == root) { + roots.push((root, declared)); + } + } + let mut paths = vec![]; + for (root, declared) in roots.into_iter().take(MAX_PATHS) { + let importers = match at.gh.search_code(o, n, base, &root).await { + Ok(hits) => hits + .into_iter() + .map(|h| h.path) + .filter(|p| { + !df::commit_path(p) && !df::is_doc_path(p) && un::is_call_site_file(p) + }) + .take(12) + .collect(), + Err(_) => vec![], + }; + paths.push(safety::PathIn { + scripts: scripts_running(&manifest, &root), + install_script: scripted.contains(&root) || scripted.contains(&b.package), + root, + declared, + importers, + }); + } + let mut used: Vec = note + .map(|x| { + x.call_sites + .iter() + .map(|c| format!("{}:{}", c.file, c.line)) + .collect() + }) + .unwrap_or_default(); + for (f, _) in &mine { + for l in f.evidence.iter().flat_map(|e| e.lines.iter()) { + let at_line = format!("{}:{}", l.file, l.line); + if !used.contains(&at_line) { + used.push(at_line); + } + } + } + used.truncate(12); + let apis = note.map(|x| x.apis.clone()).unwrap_or_default(); + let searched = if apis.is_empty() { + format!("`{}` in the repository's code", b.package) + } else { + format!( + "`{}` and the APIs its notes name ({}) in the repository's code", + b.package, + apis.iter() + .take(4) + .map(|a| format!("`{a}`")) + .collect::>() + .join(", ") + ) + }; + let direct = note.is_some_and(|x| x.direct) + || mine + .iter() + .any(|(f, _)| f.relation == sec::Relation::Direct || f.path.len() == 1); + // Yarn's resolutions have no version line in their key. + let selector = match df::Manager::of_lockfile(&b.manifest) { + Some(df::Manager::Yarn) => b.package.clone(), + _ => format!("{}@{}", b.package, b.line), + }; + let ecosystem = ecosystem_of(&b.manifest); + out.push(safety::evidence(&safety::MajorIn { + package: &b.package, + from: &b.from, + to: &b.to, + ecosystem, + why_major: &b.major_reason, + paths: &paths, + used_in: &used, + searched: &searched, + verdict: sec::worst_verdict(mine.iter().map(|(f, _)| f.verdict)), + direct, + parents: note.map(|x| x.parents.as_slice()).unwrap_or(&[]), + via_parent: b.via_parent.as_ref(), + selector: &selector, + })); + } + out +} + +/// What the runtime proof's requests showed for each applied major. +async fn behaviour(at: &At<'_>, run: &DepRun, notes: &[un::PackageNotes]) -> Vec { + let proof = &run.proof; + let compared: Vec = match (&proof.plan, &proof.base, &proof.head) { + (Some(plan), Some(base), Some(head)) if proof.proved == run.head => { + bh::compare(&plan.probes, &base.probes, &head.probes) + } + _ => vec![], + }; + let why_none = if !proof.skipped.is_empty() { + format!("the runtime proof did not run ({})", proof.skipped) + } else if proof.head.is_some() && proof.proved != run.head { + "the runtime proof is of an earlier commit of this branch".to_string() + } else { + match &proof.plan { + Some(p) if p.start.is_none() => format!( + "the application could not be started to send a request ({})", + p.no_start + ), + _ => "the application was not started in this run".to_string(), + } + }; + let mut out = vec![]; + for b in run.applied_bumps().into_iter().filter(|b| b.major) { + let note = notes + .iter() + .find(|x| x.package.eq_ignore_ascii_case(&b.package)); + let mine: Vec = run + .probed + .iter() + .find(|(p, _)| p.eq_ignore_ascii_case(&b.package)) + .map(|(_, idx)| { + idx.iter() + .filter_map(|i| compared.get(*i).cloned()) + .collect() + }) + .unwrap_or_default(); + let not_probed = if !mine.is_empty() { + String::new() + } else { + run.not_probed + .iter() + .find(|(p, _)| p.eq_ignore_ascii_case(&b.package)) + .map(|(_, why)| why.clone()) + .unwrap_or_else(|| why_none.clone()) + }; + let mut one = bh::Behaviour { + package: b.package.clone(), + from: b.from.clone(), + to: b.to.clone(), + breaking_used: note.map(bh::used_breaking).unwrap_or_default(), + compared: mine, + not_probed, + ..Default::default() + }; + let changed = one.changed_paths(); + if !changed.is_empty() { + let (found, searched) = consumers(at.state, at.gh, at.msg, &changed).await; + one.consumers = found; + one.consumers_searched = searched; + } + out.push(one); + } + out +} + +/// The advisories of the head, counted once: every advisory CoderHelm +/// holds for the lockfile's packages against the base branch's copies and +/// the head's, laid beside the package manager's audit of the head. +async fn advisories( + at: &At<'_>, + run: &DepRun, + lockfile: &str, + of_repo: &[(Finding, FindingState)], + base: &[(String, String)], + head: &[(String, String)], +) -> adv::Reconciled { + let (o, n) = (&at.msg.repo_owner, &at.msg.repo_name); + let lockfiles = vec![lockfile.to_string()]; + let held: Vec = of_repo + .iter() + .filter(|(f, _)| { + f.manifest == lockfile + || df::lockfile_for(&f.manifest, &lockfiles).as_deref() == Some(lockfile) + }) + .filter(|(f, _)| f.status.is_open() || f.status == sec::Status::Withdrawn) + .map(|(f, st)| adv::Held::of(f, st)) + .collect(); + let dir = lockfile.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + let under = |name: &str| { + if dir.is_empty() { + name.to_string() + } else { + format!("{dir}/{name}") + } + }; + let read = |path: String| async move { + at.gh + .read_file_if_exists(o, n, &path, at.branch) + .await + .ok() + .flatten() + .unwrap_or_default() + }; + let manifest = read(under("package.json")).await; + let workspace = read(under("pnpm-workspace.yaml")).await; + let overrides = adv::overrides_of(&manifest); + let ignored = adv::ignored_of(&manifest, &workspace); + let stays: Vec<(String, String)> = run.deferred_ids(); + // The audit's listing is of the commit the set last ran on. + let audited = run + .verify + .head + .as_ref() + .is_some_and(|h| h.sha == run.head && h.ran); + let audit = run.verify.audit.as_ref().filter(|_| audited); + let no_audit = match (&run.verify.plan, audited) { + (_, true) => String::new(), + (Some(p), false) => p + .not_applicable + .iter() + .find(|(k, _)| *k == vq::Kind::Audit) + .map(|(_, why)| why.clone()) + .unwrap_or_else(|| { + if run.verify.skipped.is_empty() { + "the verification set gave no result on this commit".to_string() + } else { + run.verify.skipped.clone() + } + }), + (None, false) => "the verification set did not run".to_string(), + }; + adv::reconcile(&adv::Input { + sha: &run.head, + lockfile, + held: &held, + base, + head, + audit, + no_audit: &no_audit, + ignored: &ignored, + overrides: &overrides, + stays: &stays, + }) +} + +/// The largest record kept on a ticket: well under the store's item size. +const MAX_FACTS_CHARS: usize = 150_000; + +/// Keeps the run's upgrade evidence on the security ticket, where the +/// pull request's description reads it. +async fn save(state: &WorkerState, team_id: &str, ticket: &str, facts: &UpgradeFacts) { + let Ok(json) = serde_json::to_string(facts) else { + return; + }; + if json.len() > MAX_FACTS_CHARS { + warn!( + ticket, + chars = json.len(), + "dep fix: the upgrade evidence is too large to keep" + ); + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&sec::ticket_sk(ticket))) + .update_expression("SET dep_facts = :f") + .condition_expression("attribute_exists(sk)") + .expression_attribute_values(":f", super::attr_s(&json)) + .send() + .await + { + warn!(ticket, error = %e, "dep fix: the upgrade evidence could not be kept"); + } +} + +/// Records the run's upgrade evidence for its head commit: families and +/// their coherence on the head, the verification set's results, the +/// advisory count laid beside the audit, why each major is safe, and what +/// the behaviour probe showed. Nothing here is a claim beyond what ran: +/// what did not run is listed with why. +pub async fn record(at: &At<'_>, run: &DepRun) -> UpgradeFacts { + let mut facts = UpgradeFacts { + sha: run.head.clone(), + families: run.families.clone(), + ..Default::default() + }; + if run.applied.is_empty() { + return facts; + } + let Some(lockfile) = main_lockfile(run) else { + return facts; + }; + let base = copies_at(at.gh, at.msg, &lockfile, &at.msg.base_branch).await; + let head = copies_at(at.gh, at.msg, &lockfile, at.branch).await; + // Every lockfile the run bumped: the families the head installs at + // more than one version, and the peer ranges it leaves unmet. + let mut lockfiles: Vec = run + .applied_bumps() + .iter() + .map(|b| b.manifest.clone()) + .collect(); + lockfiles.sort(); + lockfiles.dedup(); + for l in &lockfiles { + let copies = if *l == lockfile { + head.clone() + } else { + copies_at(at.gh, at.msg, l, at.branch).await + }; + let Some(copies) = copies else { + facts.not_run.push(format!( + "the family check of `{l}`: its lockfile on the head could not be read" + )); + continue; + }; + facts.splits.extend(fam::splits(&run.families, l, &copies)); + let peers: Vec = run + .peers + .iter() + .filter(|p| { + run.applied_bumps() + .iter() + .any(|b| b.manifest == *l && b.package == p.from) + }) + .cloned() + .collect(); + facts + .peers_unmet + .extend(fam::peers_unmet(ecosystem_of(l), &peers, &copies)); + if *l != lockfile { + facts.not_run.push(format!( + "the verification set for the project of `{l}`: it runs for the project most of the bumps are in (`{lockfile}`); this project's bumps were probed with the repository's checks and its lockfile was written by its own package manager" + )); + } + } + // The verification set, of this commit only. + match &run.verify.head { + Some(v) if v.sha == run.head => { + facts.verified = Some(v.clone()); + facts.verified_base = run.verify.base.clone(); + } + _ => facts.not_run.push(format!( + "the verification set (the project's own install, type check, build, lint, tests and production audit): {}", + if run.verify.skipped.is_empty() { + "no result on this commit" + } else { + &run.verify.skipped + } + )), + } + let findings = super::security_fixes::load_findings(at.state, &at.msg.team_id).await; + let repo = format!("{}/{}", at.msg.repo_owner, at.msg.repo_name); + let of_repo: Vec<(Finding, FindingState)> = findings + .into_iter() + .filter(|(f, _)| f.repo.eq_ignore_ascii_case(&repo)) + .collect(); + match (&base, &head) { + (Some(b), Some(h)) => { + facts.advisories = Some(advisories(at, run, &lockfile, &of_repo, b, h).await) + } + _ => facts.not_run.push(format!( + "the advisory count: `{lockfile}` could not be read on the base branch and on the head" + )), + } + let notes = + super::security_fixes::dep_notes(at.state, &at.msg.team_id, &at.msg.ticket_id).await; + facts.majors = majors(at, run, &of_repo, ¬es).await; + facts.behaviour = behaviour(at, run, ¬es).await; + save(at.state, &at.msg.team_id, &at.msg.ticket_id, &facts).await; + info!( + sha = %facts.sha, + families = facts.families.len(), + splits = facts.splits.len(), + majors = facts.majors.len(), + probed = facts.behaviour.iter().filter(|b| !b.compared.is_empty()).count(), + "dep fix: upgrade evidence recorded" + ); + facts +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_lockfile_names_its_registry() { + assert_eq!(ecosystem_of("pnpm-lock.yaml"), "npm"); + assert_eq!(ecosystem_of("apps/api/yarn.lock"), "npm"); + assert_eq!(ecosystem_of("Cargo.lock"), "crates.io"); + assert_eq!(ecosystem_of("svc/uv.lock"), "PyPI"); + assert_eq!(ecosystem_of("Gemfile.lock"), "RubyGems"); + assert_eq!(ecosystem_of("go.sum"), "Go"); + assert_eq!(ecosystem_of("README.md"), ""); + } + + #[test] + fn a_script_that_runs_a_package_and_an_install_script_are_read() { + let manifest = r#"{"scripts":{"build":"bundle-kit --mode production","lint":"lint-kit .","start":"node dist/main.js"}}"#; + assert_eq!(scripts_running(manifest, "bundle-kit"), vec!["build"]); + assert_eq!(scripts_running(manifest, "@tools/lint-kit"), vec!["lint"]); + assert!(scripts_running(manifest, "web-kit").is_empty()); + let lock = r#"{"packages":{"":{},"node_modules/native-kit":{"version":"1.0.0","hasInstallScript":true},"node_modules/a/node_modules/@s/gyp-kit":{"hasInstallScript":true},"node_modules/plain":{"version":"2.0.0"}}}"#; + assert_eq!( + install_script_packages("package-lock.json", lock), + vec!["@s/gyp-kit", "native-kit"] + ); + // Another manager's lockfile does not say: nothing is assumed. + assert!(install_script_packages("pnpm-lock.yaml", lock).is_empty()); + } + + #[test] + fn the_main_lockfile_is_where_most_applied_bumps_are() { + let bump = |m: &str| df::PlanBump { + package: "x".into(), + manifest: m.into(), + ..Default::default() + }; + let mut run = DepRun { + plan: df::DepPlan { + bumps: vec![ + bump("apps/a/pnpm-lock.yaml"), + bump("pnpm-lock.yaml"), + bump("pnpm-lock.yaml"), + ], + deferred: vec![], + }, + ..Default::default() + }; + assert_eq!(main_lockfile(&run), None); + run.applied = vec![0, 1, 2]; + assert_eq!(main_lockfile(&run).as_deref(), Some("pnpm-lock.yaml")); + } +}