Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/incidents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
208 changes: 208 additions & 0 deletions services/common/src/dep_audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,181 @@ pub fn read(audits: &[Audit], output: &str) -> Vec<Audited> {
.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<Listed>,
}

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<Listing>,
pub all: Option<Listing>,
/// 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<String> {
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<String> = vec![];
for (scope, shown) in [("production", shown_prod), ("all", shown_all)] {
let mut listed: Vec<Listed> = 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::*;
Expand Down Expand Up @@ -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"
);
}
}
Loading
Loading