diff --git a/docs/incidents.md b/docs/incidents.md index 22df5085b..6e4a8c33e 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -69,6 +69,7 @@ pipeline still calls it there. | am. `am_description_from_the_head` | A dependency security run's pull request had the right code after a review round and the wrong description. Its table still showed the plan (five packages as major version jumps the final manifest no longer makes, a headline counting twenty major versions), its count of fixed advisories had never been compared with the final lockfile, the round that fixed the code wrote that it could not edit the description and left the corrections to a person, and the repository's second app (a CMS studio no CI job builds) took a package an override moved to a new major and was never built. | The description is a function of the head. A dependency pull request's table and headline are what the lockfile on the head resolves compared with the base branch; an advisory counts as fixed only at or past its patched version; what can't be read is said as not known and the plan is marked as a plan. Every write of a description goes through `description::save`, every path that moves the head rebuilds it through `description::head_moved`, and a round's sentence that hands the description to a person is taken out and becomes the rebuild. A sentence a run writes into a file that says a check passes needs that check's recorded passing result, or it is taken out. Every workspace project that takes a changed package line is built when its manifest declares a build, CI job or not; a project that can't be proven in the sandbox is named with why, and a build only the bumps break feeds the take-out. | | an. `an_six_database_findings` | Security, Infrastructure showed six database findings, every one a one-command runbook with no pull request although the databases were in the team's code. The same CVE stood on an operating system update, an Aurora PostgreSQL patch and a MySQL upgrade. A database with a Terraform-generated identifier and an Aurora cluster defined through a module were "not found in code". A patch and an upgrade pending on one cluster were unrelated rows, an update on a second instance was dropped, and the account was read one page deep. | An advisory is attached only where it applies (service, engine, version range, kind of action, date); an action AWS publishes with no CVE list gets none. An action is named for what it means on its ARN. One database's pending actions are one ordered set of rows. The defining code is found from stack records, resource type and attributes, module calls and variable files, graded, and a guess never becomes a pull request. An update with a code equivalent is a pull request on the line that sets the value; one that cannot be expressed in code stays a complete runbook and says why. A change that would replace a database is refused. | | ao. `ao_stopped_log_finding` | Two log findings of one production service stayed on the Logs page as Critical and New, each with "Create fix PR" and "Not started automatically: not sure the repo is ...; check it and start the fix", a day and a half after their error had stopped: 735 matching lines in one six-hour window, then none while the service wrote its usual volume. The team had fixed the cause the day before. Only time closed a finding (three days without a line), so a problem that was over read as a live emergency that needed a person. | Every analysis counts each open finding's own lines on its own log group and keeps the count with the lines the group wrote. Two analyses in a row with no matching line at the service's usual volume make the finding stopped: shown and counted as stopped, never New or a live critical, with no automatic fix and no stale "choose a repo" reason. When the service itself went quiet nobody can tell, and it stays as it was. A burst that stopped after a change in its repo resolves after one day instead of three, with that evidence in the reason; an error that keeps coming back keeps its longer period. Seen again, it is live again and its fix may start. Evidence for the repo that couldn't be weighed is weighed again next sweep and never put to a person. | +| ap. `ap_closed_pr_keeps_findings` | An admin closed CoderHelm's dependency fix pull request for a repository to start again and cancelled its fix run. On the Security page every checkbox for that repository was off, the header's too, with nothing to say why: 274 findings still read "in a pull request" a day later. The pull request webhook recorded the close on the run and never told the findings, cancelling a run wrote only the run, and the one comparison with GitHub was the last step of the scheduled sweep, behind the time every team's sources and triage left, reading a failed request as "still open". | A finding is `pr_open` only while its pull request is open and `fixing` only while its run works (`common::security_release`). A pull request closed unmerged gives its findings back with who closed it and when, a cancelled or closed run releases what it claimed, a reopened pull request takes its findings back, and a merge fixes them: on the webhook or the person's action, and again on every sweep, first for each team and on a clock of its own, bounded and in turn, so a missed webhook and records stale from before heal within a sweep. A person asking for a fix always gets one; automatic fixes wait a week after a person said no. Retry on the run is a new request from the findings as they are now and opens a new pull request. GitHub not answering is never read as open, closed or merged. | | 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. | | bc. `bc_stays_through_merge_and_deploy` | Pull requests were left as they were after their runs finished: one conflicted after its base moved, one went red a day later on a commit status no event carries, and one merged by a person had its production deploy fail with nothing watching. | A finished run's pull request is looked at on completion and by the sweep: a conflict starts the conflict round once per base commit, red checks not red on the base go to the fix loop once per head, and a merge by anyone gets its merge commit's deploy watched once. A deploy of CoderHelm's own change that fails on checks passing before the merge gets a revert pull request with the failing jobs as evidence, ready for the team's approval and never merged by CoderHelm; files changed again since are never overwritten. | diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 0ff95c341..812c4f266 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -104,6 +104,7 @@ pub mod reachability; pub mod review_config; /// Security fixes: advisories, triage, fix runs and cards (gateway and worker). pub mod security_fixes; +pub mod security_release; pub mod settings_index; /// Setup: the settings registry, the repo analysis, runs, apply and undo. pub mod setup; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index ad8dd9ce2..4d494d418 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -600,7 +600,11 @@ pub struct SecurityEventMessage { pub team_id: String, #[serde(default)] pub installation_id: u64, - /// `dependabot_alert`, `security_advisory`, `push`, `scan` or `fix`. + /// `dependabot_alert`, `security_advisory`, `push`, `scan`, `fix`, or + /// one of the release kinds (`common::security_release`): `pr` (a + /// pull request closed or reopened), `run` (a fix run a person + /// cancelled or closed) and `retry` (a person's Retry of a fix run + /// whose pull request is gone). pub kind: String, /// `owner/name`; empty for a scan of every repository. #[serde(default)] @@ -622,6 +626,12 @@ pub struct SecurityEventMessage { /// `fix`: how the picked findings combine into pull requests. #[serde(default)] pub combine: crate::security_fixes::Combine, + /// `pr`: the pull request's number (in `repo`). + #[serde(default, skip_serializing_if = "is_zero_u64")] + pub pr_number: u64, + /// `run` and `retry`: the fix run's ticket (`SEC-...`). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub ticket: String, } /// One repository's stale pull request preview (`common::stale_prs`). diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index cb60237be..2b750032b 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -286,6 +286,16 @@ pub struct PrRef { /// `open`, `merged` or `closed`. pub state: String, pub adopted: bool, + /// Closed without merging: when (`security_release::settle_pr`). + #[serde(skip_serializing_if = "Option::is_none")] + pub closed_at: Option, + /// ...and who closed it: a GitHub login, or the name of the person who + /// closed its run in CoderHelm. None when GitHub does not say. + #[serde(skip_serializing_if = "Option::is_none")] + pub closed_by: Option, + /// A person closed it (false: CoderHelm did, for a reason of its own). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub closed_by_person: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -355,6 +365,9 @@ pub struct FindingState { pub withdrawn: Vec, /// The fix run working on it. pub ticket: Option, + /// When that run was started for it: a run of the ticket that began + /// after this is the one it waits on (`security_release::settle_run`). + pub claimed_at: Option, /// What the last triage read (so it isn't read twice). pub triaged: Option, /// When the last triage ran: verdicts are read again weekly (the code @@ -362,7 +375,9 @@ pub struct FindingState { pub triaged_at: Option, /// The tier its first card posted at: a later rise to P0 posts again. pub carded_tier: Option, - /// A person closed its pull request unmerged: not opened again until. + /// Its pull request closed unmerged, or its fix run ended without one: + /// automatic fixes don't start again until then. A person asking for a + /// fix never waits on it. pub hold_until: Option, pub merged_at: Option, /// Stages whose card posted (`new`, `half`, `deadline`, ...). @@ -2163,7 +2178,9 @@ pub fn requested_units( st.requested_by.is_some() && st.requested_as == combine && f.status == Status::Open - && f.pr.is_none() + // A pull request that closed unmerged is history, not a + // claim: the person asked for a new one. + && f.pr.as_ref().is_none_or(|p| p.state != "open") }) .map(|(f, _)| f.id.clone()) .collect(); @@ -5041,7 +5058,12 @@ pub struct Group { pub malware: bool, pub epss: Option, pub manifests: Vec, + /// The open pull request a member is in; otherwise the last one (merged, + /// or closed unmerged with who closed it and when). pub pr: Option, + /// The fix run working on a member (`fixing`) or behind its open pull + /// request, so the dashboard can link to it. + pub ticket: Option, pub finding_ids: Vec, pub advisories: Vec, } @@ -5099,12 +5121,18 @@ fn verdict_rank(v: Verdict) -> u8 { /// package). Open members decide an open group's tier and due date. pub fn groups(findings: &[(Finding, FindingState)]) -> Vec { let mut by: BTreeMap> = BTreeMap::new(); - for (f, _) in findings { - by.entry(group_key(f)).or_default().push(f); + let mut tickets: BTreeMap = BTreeMap::new(); + for (f, st) in findings { + let key = group_key(f); + if let (Status::Fixing | Status::PrOpen, Some(t)) = (f.status, &st.ticket) { + tickets.entry(key.clone()).or_insert_with(|| t.clone()); + } + by.entry(key).or_default().push(f); } let mut out: Vec = by .into_iter() .map(|(key, members)| { + let ticket = tickets.get(&key).cloned(); let status = members .iter() .map(|f| f.status) @@ -5174,7 +5202,13 @@ pub fn groups(findings: &[(Finding, FindingState)]) -> Vec { .filter_map(|f| f.advisory.epss) .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)), manifests, - pr: members.iter().find_map(|f| f.pr.clone()), + pr: members + .iter() + .filter_map(|f| f.pr.as_ref()) + .find(|p| p.state == "open") + .or_else(|| members.iter().find_map(|f| f.pr.as_ref())) + .cloned(), + ticket, finding_ids: members.iter().map(|f| f.id.clone()).collect(), advisories, } @@ -7860,6 +7894,7 @@ mod tests { ci: None, state: "merged".into(), adopted: false, + ..Default::default() }); a.1.pr_opened_at = Some("2026-11-10T12:00:00Z".into()); a.1.merged_at = Some("2026-11-11T10:00:00Z".into()); @@ -7994,6 +8029,7 @@ mod tests { ci: Some("passing".into()), state: "open".into(), adopted: false, + ..Default::default() }); v[5].0.status = Status::PrOpen; v[6].0.status = Status::Dismissed; @@ -8538,6 +8574,7 @@ mod tests { ci: Some("pending".into()), state: "open".into(), adopted: false, + ..Default::default() }); st.bundled = true; st.ticket = Some("SEC-OPEN".into()); diff --git a/services/common/src/security_release.rs b/services/common/src/security_release.rs new file mode 100644 index 000000000..223f315aa --- /dev/null +++ b/services/common/src/security_release.rs @@ -0,0 +1,763 @@ +//! Security fixes: a finding's `fixing` and `pr_open` always say what is +//! true on GitHub and in the run's record. +//! +//! A finding is claimed twice on its way to fixed: by a fix run (`fixing`, +//! with the run's ticket) and by the pull request the run opens (`pr_open`, +//! with the pull request). Either claim can end without the fix: a person +//! closes the pull request, the run is cancelled, fails or is closed, the +//! branch is deleted (GitHub closes its pull request). A claim nothing +//! releases is a finding nobody can ask a fix for: the dashboard's checkbox +//! is off for a finding in a pull request or a run. +//! +//! The rules here are pure: what GitHub says about a pull request +//! ([`PrNow`]) or what became of a run ([`RunNow`]) goes in, and the +//! finding comes out as it should stand, with the line for its timeline. +//! Three callers read the facts and apply the rules (the worker's +//! `passes::security_release`): a pull request webhook, a run a person +//! cancelled or closed, and the scheduled sweep, which finds what the first +//! two missed and what was stale before they existed. Applying a fact twice +//! changes nothing the second time. + +use chrono::{DateTime, Duration, Utc}; + +use crate::security_fixes::{parse_time, Finding, FindingState, PrRef, Status}; + +/// Days automatic fixes wait after a pull request closed unmerged or a +/// person ended the fix run: the team said no for now. A person asking for +/// a fix never waits on it. +pub const HOLD_DAYS_CLOSED: i64 = 7; +/// Days automatic fixes wait after a fix run ended by itself with no pull +/// request (it failed): tried again tomorrow. +pub const HOLD_DAYS_RUN_ENDED: i64 = 1; +/// Hours a `fixing` finding with no run on record waits before it is +/// released: the run's message may still be queued. +pub const NO_RUN_GRACE_HOURS: i64 = 12; +/// Pull requests one sweep reads per team at most; the rest are read on +/// the following sweeps, in turn. +pub const MAX_PRS_PER_SWEEP: usize = 100; +/// Fix runs one sweep reads per team at most. +pub const MAX_TICKETS_PER_SWEEP: usize = 50; +/// Seconds between two sweeps: what the turn-taking counts in. +pub const SWEEP_SECS: i64 = 1_200; + +/// Who closed a pull request without merging it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Closer { + /// Their GitHub login, or their name when they closed it from + /// CoderHelm; empty when GitHub does not say. + pub by: String, + /// A person closed it (on GitHub, or by closing the run in CoderHelm). + /// False when CoderHelm closed it for a reason of its own. + pub person: bool, + /// When, as GitHub wrote it. + pub at: Option, +} + +/// What GitHub says about a pull request now. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PrNow { + Open, + Merged, + Closed(Closer), + /// GitHub answers that there is no such pull request (its repository + /// was deleted or moved, or the app no longer has it): released like a + /// closed one, since no fix is coming from it. + Gone, + /// GitHub could not be read: the finding is left as it is and read + /// again next time. Never taken for open, closed or merged. + Unknown, +} + +/// What became of the fix run a `fixing` finding waits on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunNow { + /// Queued or working. + Working, + /// Over with no pull request to show for it. + Ended { + /// The run record's status (`cancelled`, `failed`, ...). + status: String, + /// The person who ended it, when one did. + by: Option, + }, + /// No run of the ticket since the finding was claimed. + Missing, + /// The run records could not be read: nothing changes. + Unknown, +} + +/// What a rule did to a finding: the line for its timeline, with a link. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Change { + pub text: String, + pub link: Option, +} + +fn change(text: String, link: &str) -> Option { + Some(Change { + text, + link: (!link.is_empty()).then(|| link.to_string()), + }) +} + +/// Whether the hold a closed pull request or an ended run left is still on. +pub fn held(st: &FindingState, now: DateTime) -> bool { + st.hold_until + .as_deref() + .and_then(parse_time) + .is_some_and(|t| t > now) +} + +/// Whether a finding's pull request is one the sweep reads: recorded as +/// open, or closed unmerged with its hold still on (a person may reopen +/// it, and the finding then belongs to it again). +pub fn watches_pr(f: &Finding, st: &FindingState, now: DateTime) -> bool { + match &f.pr { + Some(p) if p.state == "open" => true, + Some(p) => p.state == "closed" && f.status == Status::Open && held(st, now), + None => false, + } +} + +/// Brings a finding in line with its pull request. `None` when nothing +/// changed (so a second call with the same fact writes nothing). +/// +/// - Merged: the finding is fixed. +/// - Closed unmerged: it is open again, its claim released, with who closed +/// the pull request and when kept on the pull request's record. Automatic +/// fixes wait [`HOLD_DAYS_CLOSED`] days; a person asking never waits. +/// - Open again after it was closed (a person reopened it): the finding is +/// in the pull request again and the hold is lifted. +/// - Unknown: left alone. +/// +/// Only a finding that is `pr_open` changes status; one a person dismissed, +/// or one fixed another way, keeps its status and only its pull request's +/// recorded state follows GitHub. +pub fn settle_pr( + f: &mut Finding, + st: &mut FindingState, + pr_now: &PrNow, + now: DateTime, +) -> Option { + let pr = f.pr.clone()?; + let now_s = now.to_rfc3339(); + let gone = PrNow::Closed(Closer::default()); + let pr_now = match pr_now { + PrNow::Gone => &gone, + other => other, + }; + let is_gone = |c: &Closer| !c.person && c.by.is_empty() && c.at.is_none(); + match pr_now { + PrNow::Unknown | PrNow::Gone => None, + PrNow::Merged => { + if pr.state == "merged" { + return None; + } + f.pr = Some(PrRef { + state: "merged".into(), + closed_at: None, + closed_by: None, + ..pr.clone() + }); + if matches!(f.status, Status::PrOpen | Status::Open | Status::Fixing) { + f.status = Status::Fixed; + f.waiting = None; + st.merged_at = Some(now_s.clone()); + st.hold_until = None; + } + f.updated_at = now_s; + change(format!("PR #{} merged", pr.number), &pr.url) + } + PrNow::Closed(closer) => { + if pr.state != "open" { + return None; + } + f.pr = Some(PrRef { + state: "closed".into(), + closed_at: Some(closer.at.clone().unwrap_or_else(|| now_s.clone())), + closed_by: (!closer.by.is_empty()).then(|| closer.by.clone()), + closed_by_person: closer.person, + ..pr.clone() + }); + let was_in_it = f.status == Status::PrOpen; + if was_in_it { + f.status = Status::Open; + f.waiting = None; + st.ticket = None; + st.bundled = false; + st.claimed_at = None; + st.hold_until = Some((now + Duration::days(HOLD_DAYS_CLOSED)).to_rfc3339()); + } + f.updated_at = now_s; + let who = match (closer.person, closer.by.is_empty()) { + (true, false) => format!(" by {}", closer.by), + (false, _) => " by CoderHelm".to_string(), + (true, true) => String::new(), + }; + let then = if was_in_it { + format!( + "; automatic fixes wait {HOLD_DAYS_CLOSED} days. Ask for a fix to open a new pull request now" + ) + } else { + String::new() + }; + let what = if is_gone(closer) { + format!("PR #{} is no longer on GitHub", pr.number) + } else { + format!("PR #{} was closed without merging{who}", pr.number) + }; + change(format!("{what}{then}"), &pr.url) + } + PrNow::Open => { + if pr.state != "closed" { + return None; + } + // Reopened. A finding that moved on since (a new run, another + // pull request, fixed, dismissed) is not pulled back. + if f.status != Status::Open || st.ticket.is_some() || st.requested_by.is_some() { + return None; + } + f.pr = Some(PrRef { + state: "open".into(), + ci: Some("pending".into()), + closed_at: None, + closed_by: None, + closed_by_person: false, + ..pr.clone() + }); + f.status = Status::PrOpen; + f.waiting = None; + st.hold_until = None; + f.updated_at = now_s; + change( + format!("PR #{} was reopened: the fix is in it again", pr.number), + &pr.url, + ) + } + } +} + +/// Days a run waiting on a person's answer keeps its findings. +pub const WAITING_RUN_DAYS: i64 = 7; +/// Hours a run recorded as queued or working keeps its findings after its +/// record last moved: a run whose worker died never ends on its own record. +pub const SILENT_RUN_HOURS: i64 = 26; + +/// What a run record says became of the run: working while it is in flight +/// (or waits on a person's answer) and its record still moves; ended +/// otherwise. `by`: who cancelled or closed it. +pub fn run_now_of( + status: &str, + updated_at: &str, + by: Option, + now: DateTime, +) -> RunNow { + use crate::run_status as rs; + let age = parse_time(updated_at).map(|t| now - t); + let within = |d: Duration| age.is_none_or(|a| a < d); + let working = if rs::IN_FLIGHT.contains(&status) { + within(Duration::hours(SILENT_RUN_HOURS)) + } else if matches!(status, rs::NEEDS_INPUT | rs::NEEDS_OUTSIDE_CHANGE) { + within(Duration::days(WAITING_RUN_DAYS)) + } else { + false + }; + if working { + RunNow::Working + } else { + RunNow::Ended { + status: status.to_string(), + by: by.filter(|b| !b.is_empty()), + } + } +} + +/// When a `fixing` finding was claimed by its run: recorded at the claim, +/// or (a finding claimed before that was kept) its last write. +pub fn claimed_at(f: &Finding, st: &FindingState) -> Option> { + st.claimed_at + .as_deref() + .and_then(parse_time) + .or_else(|| parse_time(&f.updated_at)) +} + +/// Brings a `fixing` finding in line with its run. `open_pr`: the open pull +/// request on the run's branch, when there is one (the finding was never +/// told). `None` when nothing changed. +/// +/// - A pull request is open on the branch: the finding is in it. +/// - The run is queued or working: left alone. +/// - The run ended with no pull request: the finding is open again. A run a +/// person cancelled or closed holds automatic fixes [`HOLD_DAYS_CLOSED`] +/// days; one that ended by itself, [`HOLD_DAYS_RUN_ENDED`] day. +/// - No run on record: released once [`NO_RUN_GRACE_HOURS`] have passed. +pub fn settle_run( + f: &mut Finding, + st: &mut FindingState, + run: &RunNow, + open_pr: Option<&PrRef>, + now: DateTime, +) -> Option { + if f.status != Status::Fixing { + return None; + } + let now_s = now.to_rfc3339(); + if let Some(pr) = open_pr { + f.status = Status::PrOpen; + f.pr = Some(PrRef { + ci: Some("pending".into()), + state: "open".into(), + adopted: false, + closed_at: None, + closed_by: None, + closed_by_person: false, + ..pr.clone() + }); + f.waiting = None; + st.pr_opened_at.get_or_insert_with(|| now_s.clone()); + f.updated_at = now_s; + return change(format!("PR #{} opened", pr.number), &pr.url); + } + let (days, text, waiting) = match run { + RunNow::Working | RunNow::Unknown => return None, + RunNow::Ended { status, by } => { + if crate::run_status::ended_by_person(status) { + let who = by + .as_deref() + .filter(|b| !b.is_empty()) + .map(|b| format!(" by {b}")) + .unwrap_or_default(); + let word = if status == crate::run_status::CLOSED { + "closed" + } else { + "cancelled" + }; + ( + HOLD_DAYS_CLOSED, + format!( + "The fix run was {word}{who} before it opened a pull request; automatic fixes wait {HOLD_DAYS_CLOSED} days. Ask for a fix to start one now" + ), + Some(format!( + "The fix run was {word}{who}. Ask for a fix to start a new one." + )), + ) + } else { + ( + HOLD_DAYS_RUN_ENDED, + "The fix run ended without a pull request; it is tried again tomorrow" + .to_string(), + None, + ) + } + } + RunNow::Missing => { + let waited = + claimed_at(f, st).is_none_or(|t| now - t > Duration::hours(NO_RUN_GRACE_HOURS)); + if !waited { + return None; + } + ( + HOLD_DAYS_RUN_ENDED, + "The fix run ended without a pull request; it is tried again tomorrow".to_string(), + None, + ) + } + }; + f.status = Status::Open; + f.waiting = waiting; + st.ticket = None; + st.bundled = false; + st.claimed_at = None; + st.hold_until = Some((now + Duration::days(days)).to_rfc3339()); + f.updated_at = now_s; + change(text, "") +} + +/// The `limit` items of `all` this sweep reads, in turn: every sweep starts +/// where the last one stopped, so a team with more than fit in one sweep +/// has each read within `ceil(n / limit)` sweeps and none is starved. +pub fn turn(all: &[T], limit: usize, now: DateTime) -> Vec { + if all.len() <= limit || limit == 0 { + return all.to_vec(); + } + let sweep = (now.timestamp() / SWEEP_SECS).max(0) as usize; + let start = (sweep % all.len().div_ceil(limit)) * limit; + all.iter() + .cycle() + .skip(start) + .take(limit) + .cloned() + .collect() +} + +/// What a person's Retry of a security fix run does, from the unit's +/// findings as they stand: `Some(ids)` when the run's pull request is gone +/// (closed unmerged, or never opened and the run is over), with the +/// findings a new pull request can still fix, so the retry is a new run on +/// the plan as it is now; `None` when the unit still has an open pull +/// request or a run working (the earlier run is taken up as before). +pub fn retry_ids(members: &[(Finding, FindingState)]) -> Option> { + let busy = members.iter().any(|(f, _)| { + f.status == Status::Fixing || f.pr.as_ref().is_some_and(|p| p.state == "open") + }); + if busy { + return None; + } + let ids: Vec = members + .iter() + .filter(|(f, _)| matches!(f.status, Status::Open | Status::NoFix)) + .filter(|(f, _)| f.fixed_version.is_some()) + .map(|(f, _)| f.id.clone()) + .collect(); + (!ids.is_empty()).then_some(ids) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(t: &str) -> DateTime { + DateTime::parse_from_rfc3339(t).unwrap().with_timezone(&Utc) + } + + fn now() -> DateTime { + at("2026-11-13T10:00:00Z") + } + + fn in_pr(id: &str, number: u64) -> (Finding, FindingState) { + ( + Finding { + id: id.into(), + repo: "acme/web".into(), + package: "left-pad".into(), + version: "1.0.0".into(), + fixed_version: Some("1.0.1".into()), + status: Status::PrOpen, + pr: Some(PrRef { + number, + url: format!("https://github.com/acme/web/pull/{number}"), + ci: Some("passing".into()), + state: "open".into(), + ..Default::default() + }), + updated_at: "2026-11-12T09:00:00Z".into(), + ..Default::default() + }, + FindingState { + ticket: Some("SEC-AAAAAAAAAAAA".into()), + bundled: true, + ..Default::default() + }, + ) + } + + fn fixing(id: &str) -> (Finding, FindingState) { + let (mut f, mut st) = in_pr(id, 1); + f.status = Status::Fixing; + f.pr = None; + st.claimed_at = Some("2026-11-13T09:00:00Z".into()); + (f, st) + } + + fn person(by: &str) -> PrNow { + PrNow::Closed(Closer { + by: by.into(), + person: true, + at: Some("2026-11-13T09:30:00Z".into()), + }) + } + + #[test] + fn a_pull_request_a_person_closed_gives_its_finding_back_with_who_and_when() { + let (mut f, mut st) = in_pr("a", 12); + let c = settle_pr(&mut f, &mut st, &person("octo"), now()).unwrap(); + assert_eq!(f.status, Status::Open); + let pr = f.pr.clone().unwrap(); + assert_eq!( + ( + pr.number, + pr.state.as_str(), + pr.closed_by.as_deref(), + pr.closed_by_person + ), + (12, "closed", Some("octo"), true) + ); + assert_eq!(pr.closed_at.as_deref(), Some("2026-11-13T09:30:00Z")); + // The claim is gone, and automatic fixes wait a week. + assert_eq!((st.ticket.clone(), st.bundled), (None, false)); + assert_eq!( + st.hold_until.as_deref().and_then(parse_time), + Some(now() + Duration::days(7)) + ); + assert!(held(&st, now())); + assert!(c.text.contains("PR #12 was closed without merging by octo")); + assert!(c.text.contains("Ask for a fix")); + assert_eq!( + c.link.as_deref(), + Some("https://github.com/acme/web/pull/12") + ); + assert_eq!(f.updated_at, now().to_rfc3339()); + } + + #[test] + fn the_same_fact_twice_changes_nothing_the_second_time() { + for fact in [person("octo"), PrNow::Merged] { + let (mut f, mut st) = in_pr("a", 12); + assert!(settle_pr(&mut f, &mut st, &fact, now()).is_some()); + let after = (f.clone(), st.clone()); + assert!(settle_pr(&mut f, &mut st, &fact, now() + Duration::minutes(20)).is_none()); + assert_eq!((f, st), after); + } + // An open pull request recorded as open: nothing to do. + let (mut f, mut st) = in_pr("a", 12); + let before = (f.clone(), st.clone()); + assert!(settle_pr(&mut f, &mut st, &PrNow::Open, now()).is_none()); + assert_eq!((f, st), before); + } + + #[test] + fn a_merge_fixes_the_finding() { + let (mut f, mut st) = in_pr("a", 12); + let c = settle_pr(&mut f, &mut st, &PrNow::Merged, now()).unwrap(); + assert_eq!(f.status, Status::Fixed); + assert_eq!(f.pr.unwrap().state, "merged"); + assert!(st.merged_at.is_some()); + assert_eq!(c.text, "PR #12 merged"); + } + + #[test] + fn github_unreadable_is_never_taken_for_open_closed_or_merged() { + let (mut f, mut st) = in_pr("a", 12); + let before = (f.clone(), st.clone()); + assert!(settle_pr(&mut f, &mut st, &PrNow::Unknown, now()).is_none()); + assert_eq!((f, st), before); + } + + #[test] + fn a_pull_request_coderhelm_closed_says_so_and_still_releases() { + let (mut f, mut st) = in_pr("a", 12); + let by_us = PrNow::Closed(Closer { + by: "coderhelm[bot]".into(), + person: false, + at: None, + }); + let c = settle_pr(&mut f, &mut st, &by_us, now()).unwrap(); + assert_eq!(f.status, Status::Open); + assert!(c.text.contains("by CoderHelm"), "{}", c.text); + assert!(!f.pr.unwrap().closed_by_person); + assert!(held(&st, now())); + } + + #[test] + fn a_dismissed_finding_keeps_its_status_when_its_pull_request_closes() { + let (mut f, mut st) = in_pr("a", 12); + f.status = Status::Dismissed; + let c = settle_pr(&mut f, &mut st, &person("octo"), now()).unwrap(); + assert_eq!(f.status, Status::Dismissed); + assert_eq!(f.pr.unwrap().state, "closed"); + assert_eq!(st.hold_until, None); + assert!(!c.text.contains("Ask for a fix")); + } + + #[test] + fn a_reopened_pull_request_takes_its_finding_back_unless_it_moved_on() { + let (mut f, mut st) = in_pr("a", 12); + settle_pr(&mut f, &mut st, &person("octo"), now()).unwrap(); + assert!(watches_pr(&f, &st, now())); + let later = now() + Duration::hours(1); + let c = settle_pr(&mut f, &mut st, &PrNow::Open, later).unwrap(); + assert_eq!(f.status, Status::PrOpen); + let pr = f.pr.clone().unwrap(); + assert_eq!( + (pr.state.as_str(), pr.closed_by, pr.closed_at), + ("open", None, None) + ); + assert_eq!(st.hold_until, None); + assert!(c.text.contains("reopened")); + + // A person asked for a new fix in between: the old pull request + // coming back does not take the finding from the new run. + let (mut f, mut st) = in_pr("b", 12); + settle_pr(&mut f, &mut st, &person("octo"), now()).unwrap(); + st.requested_by = Some("dev@example.com".into()); + assert!(settle_pr(&mut f, &mut st, &PrNow::Open, later).is_none()); + let (mut f, mut st) = in_pr("c", 12); + settle_pr(&mut f, &mut st, &person("octo"), now()).unwrap(); + f.status = Status::Fixing; + st.ticket = Some("SEC-BBBBBBBBBBBB".into()); + assert!(settle_pr(&mut f, &mut st, &PrNow::Open, later).is_none()); + assert_eq!(f.status, Status::Fixing); + } + + #[test] + fn a_closed_pull_request_is_watched_only_while_its_hold_is_on() { + let (mut f, mut st) = in_pr("a", 12); + settle_pr(&mut f, &mut st, &person("octo"), now()).unwrap(); + assert!(watches_pr(&f, &st, now() + Duration::days(6))); + assert!(!watches_pr(&f, &st, now() + Duration::days(8))); + let (mut f, mut st) = in_pr("m", 12); + settle_pr(&mut f, &mut st, &PrNow::Merged, now()).unwrap(); + assert!(!watches_pr(&f, &st, now())); + } + + #[test] + fn a_run_a_person_cancelled_releases_what_it_claimed_and_says_who() { + let (mut f, mut st) = fixing("a"); + let run = RunNow::Ended { + status: "cancelled".into(), + by: Some("dev@example.com".into()), + }; + let c = settle_run(&mut f, &mut st, &run, None, now()).unwrap(); + assert_eq!(f.status, Status::Open); + assert_eq!( + (st.ticket.clone(), st.bundled, st.claimed_at.clone()), + (None, false, None) + ); + assert_eq!( + st.hold_until.as_deref().and_then(parse_time), + Some(now() + Duration::days(7)) + ); + assert!(c.text.contains("cancelled by dev@example.com")); + assert_eq!( + f.waiting.as_deref(), + Some("The fix run was cancelled by dev@example.com. Ask for a fix to start a new one.") + ); + // Again: nothing. + assert!(settle_run(&mut f, &mut st, &run, None, now()).is_none()); + } + + #[test] + fn a_run_that_failed_is_tried_again_tomorrow_and_a_working_one_is_left_alone() { + let (mut f, mut st) = fixing("a"); + for run in [RunNow::Working, RunNow::Unknown] { + assert!(settle_run(&mut f, &mut st, &run, None, now()).is_none()); + assert_eq!(f.status, Status::Fixing); + } + let failed = RunNow::Ended { + status: "failed".into(), + by: None, + }; + let c = settle_run(&mut f, &mut st, &failed, None, now()).unwrap(); + assert_eq!(f.status, Status::Open); + assert_eq!( + st.hold_until.as_deref().and_then(parse_time), + Some(now() + Duration::days(1)) + ); + assert_eq!(f.waiting, None); + assert!(c.text.contains("tried again tomorrow")); + } + + #[test] + fn a_finding_with_no_run_on_record_waits_out_the_queue_first() { + let (mut f, mut st) = fixing("a"); + // Claimed an hour ago: the run's message may still be queued. + assert!(settle_run(&mut f, &mut st, &RunNow::Missing, None, now()).is_none()); + let later = now() + Duration::hours(12); + assert!(settle_run(&mut f, &mut st, &RunNow::Missing, None, later).is_some()); + assert_eq!(f.status, Status::Open); + // A finding claimed before the claim time was kept: its last write. + let (mut f, mut st) = fixing("b"); + st.claimed_at = None; + f.updated_at = "2026-11-12T09:00:00Z".into(); + assert!(settle_run(&mut f, &mut st, &RunNow::Missing, None, now()).is_some()); + } + + #[test] + fn a_pull_request_open_on_the_runs_branch_takes_the_finding_whatever_the_run_says() { + let (mut f, mut st) = fixing("a"); + let pr = PrRef { + number: 31, + url: "https://github.com/acme/web/pull/31".into(), + ..Default::default() + }; + let ended = RunNow::Ended { + status: "failed".into(), + by: None, + }; + let c = settle_run(&mut f, &mut st, &ended, Some(&pr), now()).unwrap(); + assert_eq!(f.status, Status::PrOpen); + assert_eq!( + f.pr.as_ref().map(|p| (p.number, p.state.as_str())), + Some((31, "open")) + ); + assert_eq!(st.ticket.as_deref(), Some("SEC-AAAAAAAAAAAA")); + assert_eq!(c.text, "PR #31 opened"); + } + + #[test] + fn a_run_record_reads_as_working_only_while_it_is_in_flight_and_moving() { + let n = now(); + let recent = "2026-11-13T09:50:00Z"; + for s in ["pending", "queued", "running", "awaiting_ci", "needs_input"] { + assert_eq!(run_now_of(s, recent, None, n), RunNow::Working, "{s}"); + } + for s in ["cancelled", "closed", "failed", "completed", "retried"] { + assert!( + matches!(run_now_of(s, recent, None, n), RunNow::Ended { .. }), + "{s}" + ); + } + assert_eq!( + run_now_of("cancelled", recent, Some("dev@example.com".into()), n), + RunNow::Ended { + status: "cancelled".into(), + by: Some("dev@example.com".into()) + } + ); + // A run whose worker died two days ago never holds its findings. + assert!(matches!( + run_now_of("running", "2026-11-11T09:00:00Z", None, n), + RunNow::Ended { .. } + )); + } + + #[test] + fn a_pull_request_that_is_gone_releases_its_finding_too() { + let (mut f, mut st) = in_pr("a", 12); + let c = settle_pr(&mut f, &mut st, &PrNow::Gone, now()).unwrap(); + assert_eq!(f.status, Status::Open); + assert_eq!(f.pr.as_ref().unwrap().state, "closed"); + assert!( + c.text.starts_with("PR #12 is no longer on GitHub"), + "{}", + c.text + ); + assert!(settle_pr(&mut f, &mut st, &PrNow::Gone, now()).is_none()); + } + + #[test] + fn every_pull_request_gets_its_turn_when_more_wait_than_one_sweep_reads() { + let all: Vec = (0..250).collect(); + assert_eq!(turn(&all[..80], 100, now()), all[..80].to_vec()); + let mut seen = std::collections::BTreeSet::new(); + for sweep in 0..3 { + let t = turn(&all, 100, now() + Duration::seconds(sweep * SWEEP_SECS)); + assert_eq!(t.len(), 100); + seen.extend(t); + } + assert_eq!(seen.len(), 250, "three sweeps read all 250"); + } + + #[test] + fn a_retry_after_the_pull_request_closed_is_a_new_run_on_what_is_still_open() { + let (mut a, mut sa) = in_pr("a", 12); + let (mut b, mut sb) = in_pr("b", 12); + // Still in the open pull request: the earlier run is taken up. + assert_eq!( + retry_ids(&[(a.clone(), sa.clone()), (b.clone(), sb.clone())]), + None + ); + settle_pr(&mut a, &mut sa, &person("octo"), now()).unwrap(); + settle_pr(&mut b, &mut sb, &person("octo"), now()).unwrap(); + // One was fixed another way since: only the other is asked for. + b.status = Status::Fixed; + assert_eq!( + retry_ids(&[(a.clone(), sa.clone()), (b, sb)]), + Some(vec!["a".to_string()]) + ); + // A run already working on it: nothing new starts. + let (c, sc) = fixing("c"); + assert_eq!(retry_ids(&[(a, sa), (c, sc)]), None); + assert_eq!(retry_ids(&[]), None); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 88fcf0543..e6c8e95a1 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -2313,6 +2313,43 @@ pub async fn retry_run( return Err(StatusCode::BAD_REQUEST); } + // A security fix run whose pull request is gone (a person closed it, + // or the run ended without one): the retry is a new request for the + // unit's findings as they stand now, so the new run plans from today's + // findings and opens a new pull request. It never reopens the closed + // one, and never runs the old plan. + let ticket_id = item + .get("ticket_id") + .and_then(|v| v.as_s().ok()) + .map(|s| s.as_str()) + .unwrap_or(""); + if let Some(event) = + super::security::retry_event(&state, &claims.team_id, ticket_id, &claims.email).await + { + super::security::queue_retry(&state, event) + .await + .map_err(|_| { + error!(run_id, "Failed to enqueue the security retry"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + mark_retried(&state, &claims.team_id, &run_id).await; + info!( + run_id, + ticket_id, "Security fix run retried as a new request for its findings" + ); + common::decision_log::on_run_acted( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + &run_id, + common::decision_log::Outcome::Retried, + ) + .await; + return Ok(Json(RunActionResult { + status: "retrying".into(), + })); + } + let mut ticket = retry_message(&state, &claims, item).await?; // The new run takes up this run's plan and the commits on its branch, // unless the plan was what failed (Start over always starts over). @@ -2347,21 +2384,7 @@ pub async fn retry_run( StatusCode::INTERNAL_SERVER_ERROR })?; - // Mark the old run as retried so it can't be retried again - let now = chrono::Utc::now().to_rfc3339(); - let _ = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(&claims.team_id)) - .key("run_id", attr_s(&run_id)) - .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") - .expression_attribute_names("#status", "status") - .expression_attribute_values(":s", attr_s("retried")) - .expression_attribute_values(":sri", attr_s(&format!("retried#{run_id}"))) - .expression_attribute_values(":t", attr_s(&now)) - .send() - .await; + mark_retried(&state, &claims.team_id, &run_id).await; info!(run_id, "Run retried — dispatched to SQS"); // A retry as it was says the stop wasn't needed (the outcome log). @@ -2379,6 +2402,24 @@ pub async fn retry_run( })) } +/// Marks a run as retried, so it can't be retried again. +async fn mark_retried(state: &AppState, team_id: &str, run_id: &str) { + let now = chrono::Utc::now().to_rfc3339(); + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") + .expression_attribute_names("#status", "status") + .expression_attribute_values(":s", attr_s("retried")) + .expression_attribute_values(":sri", attr_s(&format!("retried#{run_id}"))) + .expression_attribute_values(":t", attr_s(&now)) + .send() + .await; +} + /// The message that starts a run's ticket again, from the run's record: /// the ticket, its repository (cleared for Jira, so the worker picks it /// fresh), its body for Jira and alerts (GitHub re-reads the issue) and the @@ -3061,6 +3102,23 @@ pub async fn cancel_run( })?; info!(run_id, "Run cancelled by user"); + // A security fix run: the findings it claimed are released now (the + // run opened no pull request, or the pull request's own state decides). + let ticket = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&claims.team_id)) + .key("run_id", attr_s(&run_id)) + .projection_expression("ticket_id") + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get("ticket_id").and_then(|v| v.as_s().ok()).cloned()); + if let Some(ticket) = ticket { + super::security::on_run_ended(&state, &claims.team_id, &ticket).await; + } common::decision_log::on_run_acted( &state.dynamo, &state.config.settings_table_name, diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 92a04cac5..d67c7a846 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1801,6 +1801,13 @@ async fn handle_pull_request( ) -> Result { let action = payload["action"].as_str().unwrap_or(""); + // A security fix's pull request closed or reopened (CoderHelm's, or a + // bot's it adopted): its findings follow at once, before any return + // below. The worker's sweep catches a delivery that never arrives. + if action == "closed" || action == "reopened" { + super::security::on_pull_request(state, payload, installation_id, team_id).await; + } + // Reviewer agent triggers (opt-in, off by default per repo): // - human PRs: the review label added, or a new commit on a labeled PR. // - CoderHelm's own PRs: auto-reviewed on open/reopen/push with no label diff --git a/services/gateway/src/routes/run_close.rs b/services/gateway/src/routes/run_close.rs index edc3d3a1b..c4c5f31ae 100644 --- a/services/gateway/src/routes/run_close.rs +++ b/services/gateway/src/routes/run_close.rs @@ -568,6 +568,10 @@ impl Ctx<'_> { if let Some(ticket) = &steps.ticket_lock { super::api::delete_ticket_lock(self.state, self.team_id, ticket).await; } + // A security fix run: the findings it claimed are released now. + if let Some(ticket) = &steps.ticket_lock { + super::security::on_run_ended(self.state, self.team_id, ticket).await; + } let actor = Actor { by: self .closer diff --git a/services/gateway/src/routes/security.rs b/services/gateway/src/routes/security.rs index 8c034cbee..b52aa85e5 100644 --- a/services/gateway/src/routes/security.rs +++ b/services/gateway/src/routes/security.rs @@ -18,6 +18,11 @@ //! - The `dependabot_alert` and `security_advisory` webhooks, and a push to //! a default branch that touches a dependency file, queue a //! `security_event` for the worker when the team turned this on. +//! - A security pull request closing or reopening, a person cancelling or +//! closing a fix run, and a person's Retry of a fix run whose pull +//! request is gone queue the release kinds (`common::security_release`): +//! the findings follow what happened at once, and the worker's sweep +//! catches what a webhook missed. use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; @@ -1932,6 +1937,150 @@ pub fn advisory_event( }) } +/// Pure: the event a `pull_request` webhook queues, if any: a pull request +/// that closed (merged or not) or was reopened and that security fixes may +/// have a finding in. Those are CoderHelm's own security pull requests (by +/// branch or by the marker in the description) and the Dependabot and +/// Renovate ones it adopts. The worker reads the pull request itself and +/// finds none when no finding names it. +pub fn pr_event( + payload: &Value, + installation_id: u64, + team_id: &str, +) -> Option { + let action = payload["action"].as_str().unwrap_or(""); + if !matches!(action, "closed" | "reopened") { + return None; + } + let pr = &payload["pull_request"]; + let number = pr["number"].as_u64().filter(|n| *n > 0)?; + let repo = payload["repository"]["full_name"] + .as_str() + .filter(|r| sec::valid_repo(r))?; + let head = pr["head"]["ref"].as_str().unwrap_or(""); + let ours = head.starts_with("coderhelm/security-") + || head.starts_with("dependabot/") + || head.starts_with("renovate/") + || pr["body"].as_str().is_some_and(|b| b.contains(sec::MARKER)); + ours.then(|| SecurityEventMessage { + team_id: team_id.to_string(), + installation_id, + kind: "pr".into(), + repo: repo.to_string(), + action: action.to_string(), + pr_number: number, + ..Default::default() + }) +} + +/// The `pull_request` webhook, closed or reopened: the findings in that +/// pull request follow it now. For every team with security findings, +/// turned on or not (a release is the truth about a finding, not an +/// action). Best effort: the worker's sweep finds what is missed here. +pub(crate) async fn on_pull_request( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, +) { + let Some(msg) = pr_event(payload, installation_id, team_id) else { + return; + }; + if !matches!(load_config(state, team_id).await, Ok(Some(_))) { + return; + } + info!(team_id, repo = %msg.repo, pr = msg.pr_number, action = %msg.action, "Security pull request change queued for its findings"); + if queue(state, msg).await.is_err() { + warn!( + team_id, + "Could not queue a security pull request's change; the sweep picks it up" + ); + } +} + +/// A person cancelled or closed a run: when it is a security fix run, the +/// findings it claimed are released now. Best effort, as above. +pub(crate) async fn on_run_ended(state: &AppState, team_id: &str, ticket: &str) { + if !sec::is_ticket(ticket) { + return; + } + let msg = SecurityEventMessage { + team_id: team_id.to_string(), + kind: "run".into(), + ticket: ticket.to_string(), + ..Default::default() + }; + if queue(state, msg).await.is_err() { + warn!( + team_id, + ticket, "Could not queue a fix run's end; the sweep picks it up" + ); + } +} + +/// A person's Retry of a security fix run. When the run's pull request is +/// gone (closed unmerged, or the run ended without one) and its findings +/// still need the fix, the retry is a new request for those findings as +/// they stand now, so the new run plans from today's findings and opens a +/// new pull request; the event to queue is returned. `None`: not a +/// dependency fix run, or the unit still has an open pull request or a +/// run, and the retry takes up the earlier run as any other does. +pub(crate) async fn retry_event( + state: &AppState, + team_id: &str, + ticket: &str, + by: &str, +) -> Option { + if !sec::is_ticket(ticket) { + return None; + } + let item = get_item(state, team_id, &sec::ticket_sk(ticket)) + .await + .ok()??; + let unit: sec::FixUnit = serde_json::from_str(&s(&item, "unit")).ok()?; + let findings = load_findings(state, team_id).await.ok()?; + retry_of(&unit, &findings, team_id, ticket, by) +} + +/// Pure: [`retry_event`]'s decision. +pub fn retry_of( + unit: &sec::FixUnit, + findings: &[(Finding, FindingState)], + team_id: &str, + ticket: &str, + by: &str, +) -> Option { + // Infrastructure fixes and base images have their own runs. + if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM + || unit.ecosystem == common::base_images::ECOSYSTEM + { + return None; + } + let members: Vec<(Finding, FindingState)> = findings + .iter() + .filter(|(f, _)| unit.finding_ids.contains(&f.id)) + .cloned() + .collect(); + let ids = common::security_release::retry_ids(&members)?; + Some(SecurityEventMessage { + team_id: team_id.to_string(), + kind: "retry".into(), + repo: unit.repo.clone(), + ticket: ticket.to_string(), + requested_by: by.to_string(), + finding_ids: ids, + ..Default::default() + }) +} + +/// Queues a release event built by [`retry_event`]. +pub(crate) async fn queue_retry( + state: &AppState, + msg: SecurityEventMessage, +) -> Result { + queue(state, msg).await +} + /// Pure: whether a push changed a dependency file. pub fn push_touches_dependencies(payload: &Value) -> bool { payload["commits"] @@ -2133,6 +2282,173 @@ mod tests { assert_eq!(dismissed_reason(&fi), "not_used"); } + #[test] + fn a_security_pull_request_closing_or_reopening_tells_its_findings() { + let p = |action: &str, head: &str, body: &str| { + json!({ + "action": action, + "repository": {"full_name": "acme/web"}, + "pull_request": {"number": 412, "merged": false, "head": {"ref": head}, "body": body}, + }) + }; + let ours = "coderhelm/security-updates-2026-11-12-0a1b2c"; + let m = pr_event(&p("closed", ours, ""), 7, "TEAM#a").unwrap(); + assert_eq!( + ( + m.kind.as_str(), + m.repo.as_str(), + m.pr_number, + m.action.as_str(), + m.installation_id + ), + ("pr", "acme/web", 412, "closed", 7) + ); + assert!(pr_event(&p("reopened", ours, ""), 7, "TEAM#a").is_some()); + // A bot's pull request CoderHelm may have adopted, and one named by + // its description whatever its branch. + assert!(pr_event( + &p("closed", "dependabot/npm_and_yarn/ws-8.17.1", ""), + 7, + "T" + ) + .is_some()); + assert!(pr_event(&p("closed", "renovate/ws-8.x", ""), 7, "T").is_some()); + let marked = format!("Fixes two advisories.\n\n{}", sec::MARKER); + assert!(pr_event(&p("closed", "feature/x", &marked), 7, "T").is_some()); + // Anyone else's pull request, and anything but a close or a reopen. + assert!(pr_event(&p("closed", "feature/x", "A feature"), 7, "T").is_none()); + for action in ["opened", "synchronize", "edited", "labeled"] { + assert!(pr_event(&p(action, ours, ""), 7, "T").is_none(), "{action}"); + } + // The message the worker reads keeps the pull request and the kind. + let wire = serde_json::to_value(&m).unwrap(); + assert_eq!( + (wire["kind"].as_str(), wire["pr_number"].as_u64()), + (Some("pr"), Some(412)) + ); + let back: SecurityEventMessage = serde_json::from_value(wire).unwrap(); + assert_eq!(back.pr_number, 412); + } + + #[test] + fn retry_after_a_closed_pull_request_asks_for_the_findings_as_they_are_now() { + let mk = |id: &str, status: Status, pr_state: Option<&str>| { + let mut x = f(id, Tier::P1, status, "2026-11-20", "acme/web"); + x.fixed_version = Some("2.0.0".into()); + x.pr = pr_state.map(|st| sec::PrRef { + number: 412, + url: "https://github.com/acme/web/pull/412".into(), + state: st.into(), + ..Default::default() + }); + (x, FindingState::default()) + }; + let unit = sec::FixUnit { + repo: "acme/web".into(), + ecosystem: "npm".into(), + bundle: true, + finding_ids: vec!["a".into(), "b".into(), "c".into()], + ..Default::default() + }; + // Closed unmerged and released: a new request, for what still + // needs the fix (one was fixed since). + let released = vec![ + mk("a", Status::Open, Some("closed")), + mk("b", Status::Open, Some("closed")), + mk("c", Status::Fixed, Some("closed")), + mk("other", Status::Open, None), + ]; + let m = retry_of( + &unit, + &released, + "TEAM#a", + "SEC-0A1B2C3D4E5F", + "dev@example.com", + ) + .unwrap(); + assert_eq!( + (m.kind.as_str(), m.ticket.as_str(), m.requested_by.as_str()), + ("retry", "SEC-0A1B2C3D4E5F", "dev@example.com") + ); + assert_eq!(m.finding_ids, vec!["a".to_string(), "b".to_string()]); + // Its pull request still open, or a run working: the earlier run + // is taken up as before. + let open = vec![ + mk("a", Status::PrOpen, Some("open")), + mk("b", Status::PrOpen, Some("open")), + ]; + assert!(retry_of(&unit, &open, "T", "SEC-0A1B2C3D4E5F", "d").is_none()); + let working = vec![mk("a", Status::Fixing, None)]; + assert!(retry_of(&unit, &working, "T", "SEC-0A1B2C3D4E5F", "d").is_none()); + // Nothing left to fix, and an infrastructure fix: not this path. + let done = vec![mk("a", Status::Fixed, Some("merged"))]; + assert!(retry_of(&unit, &done, "T", "SEC-0A1B2C3D4E5F", "d").is_none()); + let infra = sec::FixUnit { + ecosystem: common::infra_vuln::records::UNIT_ECOSYSTEM.into(), + ..unit.clone() + }; + assert!(retry_of(&infra, &released, "T", "SEC-0A1B2C3D4E5F", "d").is_none()); + } + + #[test] + fn a_group_says_who_closed_its_pull_request_and_which_run_works_on_it() { + let mk = |id: &str, status: Status| { + let mut x = f(id, Tier::P1, status, "2026-11-20", "acme/web"); + x.package = "ws".into(); + x.version = "8.0.0".into(); + x.fixed_version = Some("8.17.1".into()); + x + }; + // Closed by a person: selectable again, with the record on the row. + let mut closed = mk("a", Status::Open); + closed.pr = Some(sec::PrRef { + number: 412, + url: "https://github.com/acme/web/pull/412".into(), + state: "closed".into(), + closed_at: Some("2026-11-13T09:30:00Z".into()), + closed_by: Some("octo".into()), + closed_by_person: true, + ..Default::default() + }); + let groups = sec::groups(&[(closed, FindingState::default())]); + assert!(group_fixable(&groups[0])); + let row = serde_json::to_value(&groups[0]).unwrap(); + assert_eq!(row["pr"]["state"], "closed"); + assert_eq!(row["pr"]["closed_by"], "octo"); + assert_eq!(row["pr"]["closed_at"], "2026-11-13T09:30:00Z"); + assert_eq!(row["pr"]["closed_by_person"], true); + assert_eq!(row["ticket"], Value::Null); + // A run working on it: not selectable, and the row names the run. + let st = FindingState { + ticket: Some("SEC-0A1B2C3D4E5F".into()), + ..Default::default() + }; + let groups = sec::groups(&[(mk("a", Status::Fixing), st.clone())]); + assert!(!group_fixable(&groups[0])); + assert_eq!( + serde_json::to_value(&groups[0]).unwrap()["ticket"], + "SEC-0A1B2C3D4E5F" + ); + // An open pull request wins over an older closed one in the group. + let mut old = mk("old", Status::Open); + old.pr = Some(sec::PrRef { + number: 300, + state: "closed".into(), + ..Default::default() + }); + let mut now_open = mk("new", Status::PrOpen); + now_open.pr = Some(sec::PrRef { + number: 412, + state: "open".into(), + ..Default::default() + }); + let groups = sec::groups(&[(old, FindingState::default()), (now_open, st)]); + assert_eq!(groups[0].pr.as_ref().map(|p| p.number), Some(412)); + // An open pull request's record carries no closed fields. + let row = serde_json::to_value(&groups[0]).unwrap(); + assert!(row["pr"].get("closed_by").is_none() && row["pr"].get("closed_at").is_none()); + } + #[test] fn webhooks_queue_only_what_matters() { let p = json!({"action": "created", "repository": {"full_name": "acme/web"}, "alert": {"number": 88, "security_advisory": {"ghsa_id": "GHSA-q9fx-2w5c-8m4r"}}}); diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 77a3ba9fb..9abf9bacb 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -592,6 +592,7 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) let sec = passes::security_fixes::sweep(&state).await; info!( teams = sec.teams, + released = sec.released, repos = sec.repos_synced, new_findings = sec.new_findings, triaged = sec.triaged, diff --git a/services/worker/src/passes/incidents/ap_closed_pr_keeps_findings.rs b/services/worker/src/passes/incidents/ap_closed_pr_keeps_findings.rs new file mode 100644 index 000000000..4a7df6751 --- /dev/null +++ b/services/worker/src/passes/incidents/ap_closed_pr_keeps_findings.rs @@ -0,0 +1,322 @@ +//! ap. An admin closed CoderHelm's dependency fix pull request for one +//! repository on GitHub to start again, and cancelled its fix run. On the +//! Security page, filtered to that repository, every checkbox was off, +//! the header's too, with nothing to say why: 274 of the repository's +//! findings still read "in a pull request" a day after it was closed (3 +//! were open, with no fix yet), and a finding in a pull request cannot be +//! picked. Nothing told the findings: the pull request webhook recorded +//! the close on the run and stopped there, cancelling a run wrote only the +//! run, and the one place that compared a finding with GitHub was the last +//! step of the scheduled sweep, behind the time every team's sources and +//! triage had left, reading any failed request as "still open". +//! +//! Guarantee: a finding is `pr_open` only while its pull request is open +//! and `fixing` only while its run works. A pull request closed unmerged +//! gives its findings back with who closed it and when; a cancelled run +//! releases what it claimed. Both happen on the event, and the sweep makes +//! the same comparison first, on a clock of its own, for every team, so a +//! missed webhook and the records that were stale before are put right +//! within a sweep with no step by a person. A person who asks for a fix +//! always gets one; automatic fixes wait a week after a person said no. A +//! Retry on the run opens a new pull request from the findings as they are +//! now, never the closed one again. GitHub not answering is never read as +//! open, closed or merged. + +use chrono::{DateTime, Duration, Utc}; +use common::security_fixes::{ + self as sec, Finding, FindingState, FixUnit, SecurityConfig, Status, Tier, Verdict, +}; +use common::security_release::{self as rel, RunNow}; + +use super::fixture::fn_src; +use crate::passes::security_fixes::release::{fake::*, reconcile, Scope}; +use crate::passes::security_fixes::{mark_retry, release}; + +const REPO: &str = "acme/site"; +const TICKET: &str = "SEC-0A1B2C3D4E5F"; +const PR: u64 = 412; + +fn day_after() -> DateTime { + at("2026-11-13T10:00:00Z") +} + +fn cfg() -> SecurityConfig { + SecurityConfig { + enabled: true, + ..Default::default() + } +} + +/// The repository as it stood: 274 findings in the bundle pull request, +/// last written when it opened the day before, and 3 open with no fix yet. +fn the_repository() -> Vec<(Finding, FindingState)> { + let mut all: Vec<(Finding, FindingState)> = (0..274) + .map(|i| { + let (mut f, st) = in_pr(&format!("f{i:03}"), REPO, PR, TICKET); + f.tier = Some(if i < 4 { Tier::P1 } else { Tier::P2 }); + f.verdict = Verdict::NotReachable; + (f, st) + }) + .collect(); + for i in 0..3 { + let (mut f, mut st) = in_pr(&format!("n{i}"), REPO, PR, TICKET); + f.status = Status::Open; + f.pr = None; + f.fixed_version = None; + f.tier = Some(Tier::P2); + f.verdict = Verdict::NotReachable; + st.ticket = None; + st.bundled = false; + all.push((f, st)); + } + all +} + +fn ids(all: &[(Finding, FindingState)]) -> Vec { + all.iter().map(|(f, _)| f.id.clone()).collect() +} + +/// What a person's request for every finding of the repository gets. +fn asked(all: &[(Finding, FindingState)], now: DateTime) -> (usize, Vec) { + let (units, skipped) = sec::manual_units(all, &ids(all), &cfg(), now); + ( + units.iter().map(|u| u.finding_ids.len()).sum(), + skipped.into_iter().map(|s| s.reason).collect(), + ) +} + +#[tokio::test] +async fn before_the_sweep_nothing_could_be_asked_for() { + let all = the_repository(); + let (fixes, reasons) = asked(&all, day_after()); + assert_eq!(fixes, 0, "the page had no row to pick"); + assert_eq!( + reasons + .iter() + .filter(|r| *r == "already has an open PR") + .count(), + 274 + ); +} + +#[tokio::test] +async fn the_sweep_puts_yesterdays_stale_records_right_with_no_step_by_a_person() { + let mut all = the_repository(); + let github = Fake::default(); + // The pull request as GitHub has it: closed by a person, not merged. + github.pr(REPO, PR, closed_by("octo-admin")); + let now = day_after(); + + let r = reconcile(&github, &mut all, &Scope::All, now).await; + assert_eq!((r.prs_read, r.released), (1, 274), "one read of GitHub"); + assert!(all.iter().all(|(f, _)| f.status != Status::PrOpen)); + + // Each finding keeps who closed its pull request, when, and which. + let (f, st) = &all[0]; + let pr = f.pr.as_ref().unwrap(); + assert_eq!( + ( + pr.number, + pr.state.as_str(), + pr.closed_by.as_deref(), + pr.closed_by_person + ), + (PR, "closed", Some("octo-admin"), true) + ); + assert_eq!(pr.closed_at.as_deref(), Some("2026-11-13T09:30:00Z")); + assert_eq!(st.ticket, None); + let line = &github.event_texts()[0]; + assert!( + line.contains("PR #412 was closed without merging by octo-admin"), + "{line}" + ); + + // A person asks: every finding with a fix gets one. The 3 with no + // fixed version are skipped for that reason, never for the pull request. + let (fixes, reasons) = asked(&all, now); + assert_eq!(fixes, 274); + assert_eq!(reasons, vec!["no fixed version"; 3]); + + // Automatic fixes do not open the same bundle again against the + // person's wishes: nothing is planned for a week, then it is. + assert!(sec::plan_units(&all, &cfg(), now).is_empty()); + assert!(sec::plan_units(&all, &cfg(), now + Duration::days(6)).is_empty()); + let later = sec::plan_units(&all, &cfg(), now + Duration::days(8)); + assert_eq!( + later.iter().map(|u| u.finding_ids.len()).sum::(), + 274 + ); + + // The same sweep again: one read, nothing written. + let saves = github.saves(); + let again = reconcile(&github, &mut all, &Scope::All, now + Duration::minutes(20)).await; + assert_eq!((again.changed(), github.saves()), (0, saves)); +} + +#[tokio::test] +async fn the_webhook_and_the_cancel_release_at_once_and_agree_with_the_sweep() { + // The close's webhook: the findings follow it now. + let mut by_webhook = the_repository(); + let github = Fake::default(); + github.pr(REPO, PR, closed_by("octo-admin")); + let scope = Scope::Pr { + repo: REPO.into(), + number: PR, + }; + let r = reconcile(&github, &mut by_webhook, &scope, day_after()).await; + assert_eq!(r.released, 274); + // The sweep, had the webhook never arrived, ends in the same place. + let mut by_sweep = the_repository(); + reconcile(&github, &mut by_sweep, &Scope::All, day_after()).await; + assert_eq!(by_webhook, by_sweep); + + // A run cancelled before it opened a pull request releases its claim. + let mut claimed: Vec<_> = (0..5) + .map(|i| fixing(&format!("c{i}"), REPO, TICKET)) + .collect(); + let runs = Fake::default(); + runs.run( + TICKET, + RunNow::Ended { + status: "cancelled".into(), + by: Some("admin@example.com".into()), + }, + ); + let r = reconcile( + &runs, + &mut claimed, + &Scope::Ticket(TICKET.into()), + day_after(), + ) + .await; + assert_eq!(r.released, 5); + assert!(claimed + .iter() + .all(|(f, st)| f.status == Status::Open && st.ticket.is_none())); + assert!(runs.event_texts()[0].contains("cancelled by admin@example.com")); + assert_eq!( + claimed[0].0.waiting.as_deref(), + Some("The fix run was cancelled by admin@example.com. Ask for a fix to start a new one.") + ); +} + +#[tokio::test] +async fn github_not_answering_releases_nothing_and_the_next_sweep_heals() { + let mut all = the_repository(); + let before = all.clone(); + let down = Fake::default(); + let r = reconcile(&down, &mut all, &Scope::All, day_after()).await; + assert_eq!((r.changed(), down.saves()), (0, 0)); + assert_eq!( + all, before, + "an unread pull request is never taken for closed" + ); + down.pr(REPO, PR, closed_by("octo-admin")); + let r = reconcile( + &down, + &mut all, + &Scope::All, + day_after() + Duration::minutes(20), + ) + .await; + assert_eq!(r.released, 274); +} + +#[tokio::test] +async fn retry_on_the_run_is_a_new_request_from_the_findings_as_they_are_now() { + let mut all = the_repository(); + let unit = FixUnit { + repo: REPO.into(), + bundle: true, + ticket: TICKET.into(), + finding_ids: ids(&all)[..274].to_vec(), + ..Default::default() + }; + let now = day_after(); + // While the pull request reads as open, Retry asks for nothing new. + assert!(mark_retry(&mut all, &unit, "admin@example.com", now).is_empty()); + + let github = Fake::default(); + github.pr(REPO, PR, closed_by("octo-admin")); + reconcile( + &github, + &mut all, + &Scope::Ids(unit.finding_ids.clone()), + now, + ) + .await; + // One was fixed another way since the plan was made. + all[7].0.status = Status::Fixed; + let asked = mark_retry(&mut all, &unit, "admin@example.com", now); + assert_eq!(asked.len(), 273); + assert!(!asked.contains(&all[7].0.id)); + + // The request starts as any a person made: one pull request for the + // bundle, on a plan made now, whatever the hold says. + let units = sec::requested_units(&all, &cfg(), now); + assert_eq!(units.len(), 1); + let new = &units[0]; + assert_eq!(new.finding_ids.len(), 273); + assert!(new.bundle); + assert_ne!(new.ticket, TICKET, "a new run, not the old plan"); + assert_ne!(new.branch, "", "on a branch of its own"); + // And the closed pull request is never the one it joins. + assert_eq!(sec::open_bundle_pr(&all, new, true), None); +} + +#[test] +fn a_reopened_pull_request_and_a_merge_are_followed_too() { + let (mut f, mut st) = in_pr("a", REPO, PR, TICKET); + rel::settle_pr(&mut f, &mut st, &closed_by("octo-admin"), day_after()).unwrap(); + rel::settle_pr(&mut f, &mut st, &rel::PrNow::Open, day_after()).unwrap(); + assert_eq!(f.status, Status::PrOpen); + rel::settle_pr(&mut f, &mut st, &rel::PrNow::Merged, day_after()).unwrap(); + assert_eq!(f.status, Status::Fixed); +} + +/// The places the pipeline calls the release: each was missing. +#[test] +fn every_path_that_ends_a_claim_tells_the_findings() { + let fixes = include_str!("../security_fixes.rs"); + // The sweep: first for the team, before its sources, and for a team the + // sweep's budget never reached. + let tick = fn_src(fixes, "async fn team_tick("); + let release_at = tick.find("release::run(").expect("the tick releases"); + let sync_at = tick.find("sync_repo(").expect("the tick syncs"); + assert!(release_at < sync_at, "the release comes before the sources"); + assert!(tick[release_at..sync_at].contains("let Some(kev_map) = kev_map else")); + let sweep = fn_src(fixes, "async fn sweep_inner("); + assert!(sweep.contains("TICK_BUDGET_SECS + RELEASE_BUDGET_SECS")); + // Its own clock, not the sweep's. + assert!(tick.contains("release::TEAM_BUDGET_SECS")); + assert_eq!(release::TEAM_BUDGET_SECS, 45); + // The events. + let events = fn_src(fixes, "async fn event_for_team("); + assert!(events.contains("\"pr\" | \"run\" =>")); + assert!(events.contains("\"retry\" =>")); + assert!(events.contains("retry_asked(")); + + // The gateway: the pull request webhook, the cancel, the close, Retry. + let webhook = include_str!("../../../../gateway/src/routes/github_webhook.rs"); + let handler = fn_src(webhook, "async fn handle_pull_request("); + let told = handler + .find("super::security::on_pull_request(") + .expect("the webhook tells the findings"); + // Before any early return of the handler (a reopen returns early). + assert!(told < handler.find("return ").unwrap()); + let api = include_str!("../../../../gateway/src/routes/api.rs"); + assert!(fn_src(api, "pub async fn cancel_run(").contains("super::security::on_run_ended(")); + let retry = fn_src(api, "pub async fn retry_run("); + let event_at = retry + .find("super::security::retry_event(") + .expect("Retry asks security"); + assert!(event_at < retry.find("retry_message(").unwrap()); + let close = include_str!("../../../../gateway/src/routes/run_close.rs"); + assert!(close.contains("super::security::on_run_ended(")); + + // GitHub failing is never "open": the release reads it as unknown. + let rel_src = include_str!("../security_release.rs"); + let pr_now = fn_src(rel_src, "impl ReleaseIo for Live<'_, '_> {"); + assert!(pr_now.contains("return PrNow::Unknown")); + assert!(pr_now.contains("is_not_found")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 09e07c6be..ce9e89168 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -30,6 +30,7 @@ mod al_learning_loop; mod am_description_from_the_head; mod an_six_database_findings; mod ao_stopped_log_finding; +mod ap_closed_pr_keeps_findings; mod b_open_pr_retry; mod ba_verdict_on_old_commit; mod bb_flaky_not_broken; diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index cbbbd0830..6e1e82772 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -24,6 +24,11 @@ //! repository and ecosystem, through the normal run pipeline (`SEC-` //! tickets). An open Dependabot or Renovate pull request for the package is //! adopted instead. Nothing opens or posts in a dry run. +//! - **Release**: a finding's `fixing` and `pr_open` follow GitHub and the +//! run's record (`release`): a pull request closed unmerged or a run that +//! ended without one gives its findings back, on the webhook, on the +//! person's cancel, and on every sweep before anything else, on a clock +//! of its own. //! - **Cards**: P0 and P1 post to the team's alert channel once, then on the //! pull request opening, CI passing and the merge, and at half the //! deadline and the deadline. Every card is claimed once. @@ -47,11 +52,18 @@ use crate::models::{SecurityEventMessage, TicketMessage, TicketSource, TokenUsag use crate::passes::{attr_n, attr_s}; use crate::WorkerState; +/// Releasing a finding from a pull request or a run that is over. +#[path = "security_release.rs"] +pub(crate) mod release; + type Error = Box; type Item = HashMap; /// Time one tick may spend on security work. const TICK_BUDGET_SECS: u64 = 300; +/// Time past that budget the sweep may still spend releasing findings for +/// the teams the budget never reached (`release`). +const RELEASE_BUDGET_SECS: u64 = 240; /// Model calls triage makes per team per tick at most (one call reads one /// package at one version, with every advisory it has); fewer when the /// day's token cap is near (`reachability::model_calls_allowed`). With a @@ -1923,6 +1935,8 @@ async fn post_card( /// What one team's tick did. #[derive(Debug, Default)] pub struct TeamReport { + /// Findings brought in line with their pull request or run (`release`). + pub released: usize, pub repos_synced: usize, pub new_findings: usize, pub triaged: usize, @@ -2273,7 +2287,10 @@ fn verdict_word(v: Verdict) -> &'static str { } } -/// Pull requests: merged, closed, CI; runs that ended without one. +/// Open pull requests: their CI, its cards and its lines in the +/// description. A pull request that merged or closed, and a run that ended +/// without one, are `release`'s (it runs first, on its own clock); one that +/// merges or closes between the two is settled here by the same rules. async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) { let now = Utc::now(); let mut seen: HashMap<(String, u64), (String, Option)> = HashMap::new(); @@ -2283,52 +2300,12 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) { } else { None }; + let io = release::Live::new(cx, release::TEAM_BUDGET_SECS); + let mut facts: HashMap<(String, u64), common::security_release::PrNow> = HashMap::new(); for (f, st) in findings.iter_mut() { if cx.out_of_time() { return; } - if f.status == Status::Fixing { - // A run that ended without a pull request lets the finding open again. - let stale = - sec::parse_time(&f.updated_at).is_some_and(|t| now - t > Duration::hours(12)); - if let (true, Some(ticket)) = (stale, st.ticket.clone()) { - let branch = ticket_branch(cx.state, cx.team_id, &ticket).await; - let open = match (branch, f.repo.split_once('/')) { - (Some(b), Some((o, n))) => { - cx.gh.find_open_pr_for_branch(o, n, &b).await.ok().flatten() - } - _ => None, - }; - match open { - Some(pr) => { - f.status = Status::PrOpen; - f.pr = Some(sec::PrRef { - number: pr["number"].as_u64().unwrap_or(0), - url: pr["html_url"].as_str().unwrap_or("").to_string(), - ci: Some("pending".into()), - state: "open".into(), - adopted: false, - }); - } - None => { - f.status = Status::Open; - st.ticket = None; - st.hold_until = Some((now + Duration::days(1)).to_rfc3339()); - add_event( - cx.state, - cx.team_id, - &f.id, - "The fix run ended without a pull request; it is tried again tomorrow", - None, - ) - .await; - } - } - f.updated_at = now.to_rfc3339(); - save_finding(cx.state, cx.team_id, f, st).await; - } - continue; - } let Some(pr) = f.pr.clone() .filter(|p| p.state == "open" && f.status == Status::PrOpen) @@ -2348,34 +2325,28 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) { let mut p = pr.clone(); p.ci = ci.clone().or(p.ci); match state_now.as_str() { - "merged" => { - p.state = "merged".into(); - f.status = Status::Fixed; - st.merged_at = Some(now.to_rfc3339()); - add_event( - cx.state, - cx.team_id, - &f.id, - &format!("PR #{} merged", p.number), - Some(&p.url), - ) - .await; - } - "closed" => { - p.state = "closed".into(); - f.status = Status::Open; - st.hold_until = Some((now + Duration::days(7)).to_rfc3339()); - add_event( - cx.state, - cx.team_id, - &f.id, - &format!( - "PR #{} was closed without merging; not opened again for 7 days", - p.number - ), - Some(&p.url), - ) - .await; + "merged" | "closed" => { + use release::ReleaseIo; + let fact = match facts.get(&key) { + Some(v) => v.clone(), + None => { + let v = io.pr_now(&f.repo, pr.number, true).await; + facts.insert(key.clone(), v.clone()); + v + } + }; + if let Some(change) = common::security_release::settle_pr(f, st, &fact, now) { + save_finding(cx.state, cx.team_id, f, st).await; + add_event( + cx.state, + cx.team_id, + &f.id, + &change.text, + change.link.as_deref(), + ) + .await; + } + p = f.pr.clone().unwrap_or(p); } _ => { if p.ci != pr.ci && p.ci.as_deref() == Some("passing") { @@ -2411,10 +2382,12 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) { } } } - f.pr = Some(p.clone()); - if *f != before { - f.updated_at = now.to_rfc3339(); - save_finding(cx.state, cx.team_id, f, st).await; + if p.state == "open" { + f.pr = Some(p.clone()); + if *f != before { + f.updated_at = now.to_rfc3339(); + save_finding(cx.state, cx.team_id, f, st).await; + } } // One card per pull request and stage, when its findings post. if let Some(ch) = &channels { @@ -2697,6 +2670,84 @@ async fn start_requested(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) started } +/// The `retry` event: the fix unit behind `ticket` is asked for again by +/// `by`, from its findings as they are now. First they are brought in line +/// with GitHub (the closed pull request releases them), then the ones a new +/// pull request can still fix carry the person's request, combined as the +/// unit was: `start_requested` starts it with room under the day's limits, +/// dry run or not, and the hold a closed pull request left does not apply +/// to a person's request. Returns how many findings were asked for. +async fn retry_asked( + cx: &Ctx<'_>, + findings: &mut [(Finding, FindingState)], + ticket: &str, + by: &str, +) -> usize { + let Some(unit) = load_unit(cx.state, cx.team_id, ticket).await else { + warn!( + team_id = cx.team_id, + ticket, "security: retry of a fix run whose plan is gone" + ); + return 0; + }; + let scope = release::Scope::Ids(unit.finding_ids.clone()); + release::run(cx, findings, &scope, release::TEAM_BUDGET_SECS).await; + let asked = mark_retry(findings, &unit, by, Utc::now()); + for id in &asked { + if let Some((f, st)) = findings.iter().find(|(f, _)| &f.id == id) { + save_finding(cx.state, cx.team_id, f, st).await; + add_event( + cx.state, + cx.team_id, + &f.id, + &format!("A new fix pull request was asked for by {by} (Retry on the fix run)"), + None, + ) + .await; + } + } + info!( + team_id = cx.team_id, + ticket, + by, + findings = asked.len(), + "security: fix run retried as a new request" + ); + asked.len() +} + +/// Pure: marks the unit's findings a retry asks for again (see +/// `security_release::retry_ids`) with who asked and how they combine, one +/// pull request for a bundle and one per package otherwise. Returns their +/// ids; empty when the unit still has an open pull request or a run. +pub(crate) fn mark_retry( + findings: &mut [(Finding, FindingState)], + unit: &FixUnit, + by: &str, + now: chrono::DateTime, +) -> Vec { + let members: Vec<(Finding, FindingState)> = findings + .iter() + .filter(|(f, _)| unit.finding_ids.contains(&f.id)) + .cloned() + .collect(); + let Some(ids) = common::security_release::retry_ids(&members) else { + return vec![]; + }; + let combine = if unit.bundle { + sec::Combine::OnePr + } else { + sec::Combine::PerPackage + }; + for (f, st) in findings.iter_mut().filter(|(f, _)| ids.contains(&f.id)) { + st.requested_by = Some(by.to_string()); + st.requested_as = combine; + f.waiting = None; + f.updated_at = now.to_rfc3339(); + } + ids +} + /// The `fix` event: the gateway took the run slots for these findings when a /// person asked; start their runs now. async fn start_asked( @@ -3281,6 +3332,7 @@ async fn adopt( ci: Some("pending".into()), state: "open".into(), adopted: true, + ..Default::default() }); f.waiting = None; st.pr_opened_at @@ -3411,6 +3463,7 @@ async fn enqueue( st.requested_by = None; st.bundled = unit.bundle; st.ticket = Some(unit.ticket.clone()); + st.claimed_at = Some(Utc::now().to_rfc3339()); f.updated_at = Utc::now().to_rfc3339(); save_finding(cx.state, cx.team_id, f, st).await; add_event( @@ -3524,12 +3577,16 @@ async fn dependabot_sync( .created } +/// One team's tick. `kev_map`: the CISA list when the sweep still has time +/// for the team's sources, triage and fix runs; `None` when its time is +/// spent on the teams before, and only the release runs (it has a clock of +/// its own, so no team's stale findings wait on another team's work). async fn team_tick( state: &WorkerState, team_id: &str, installation_id: u64, cfg: &SecurityConfig, - kev_map: &BTreeMap, + kev_map: Option<&BTreeMap>, started: Instant, ) -> Result { let cx = Ctx { @@ -3542,6 +3599,19 @@ async fn team_tick( }; let mut report = TeamReport::default(); let mut findings = load_findings(state, team_id).await; + // First, and whatever else the tick has time for: every finding in a + // pull request or a run is checked against GitHub and the run's record. + report.released = release::run( + &cx, + &mut findings, + &release::Scope::All, + release::TEAM_BUDGET_SECS, + ) + .await + .changed(); + let Some(kev_map) = kev_map else { + return Ok(report); + }; let day = Utc::now().format("%Y%m%d").to_string(); // Dependabot access is read again every sweep until it works, so a // permission accepted on GitHub shows within one sweep. @@ -3586,6 +3656,8 @@ async fn team_tick( #[derive(Debug, Default)] pub struct SweepReport { pub teams: usize, + /// Findings brought in line with their pull request or run. + pub released: usize, pub repos_synced: usize, pub new_findings: usize, pub triaged: usize, @@ -3900,25 +3972,39 @@ async fn sweep_inner(state: &WorkerState) -> SweepReport { let started = Instant::now(); let mut kev_map: Option> = None; for team in teams { - if started.elapsed().as_secs() >= TICK_BUDGET_SECS { + // The sources, triage and fix runs share the sweep's budget. The + // release does not: a team reached after the budget is spent still + // has its findings checked against GitHub, until the sweep's hard + // stop. + let spent = started.elapsed().as_secs(); + if spent >= TICK_BUDGET_SECS + RELEASE_BUDGET_SECS { break; } + let heavy = spent < TICK_BUDGET_SECS; let Some(cfg) = load_config(state, &team).await else { continue; }; + // A team that turned security fixes off still sees its findings: + // they are released once a day, and nothing else runs. if !cfg.enabled { - continue; + let day = Utc::now().format("%Y%m%d").to_string(); + if !claim(state, &team, &format!("SECRELEASE#{day}"), 2 * 86_400).await { + continue; + } } let Some(iid) = super::review_reminder::team_installation_id(state, &team).await else { continue; }; - if kev_map.is_none() { + if heavy && cfg.enabled && kev_map.is_none() { kev_map = Some(kev(state).await); } - let kev_ref = kev_map.as_ref().expect("set above"); - report.teams += 1; + let kev_ref = kev_map.as_ref().filter(|_| heavy && cfg.enabled); + if cfg.enabled { + report.teams += 1; + } match team_tick(state, &team, iid, &cfg, kev_ref, started).await { Ok(r) => { + report.released += r.released; report.repos_synced += r.repos_synced; report.new_findings += r.new_findings; report.triaged += r.triaged; @@ -3939,6 +4025,7 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { } async fn on_event_inner(state: &WorkerState, msg: &SecurityEventMessage) { + let release = matches!(msg.kind.as_str(), "pr" | "run" | "retry"); let teams: Vec = if msg.team_id.is_empty() { common::settings_index::members( &state.dynamo, @@ -3950,9 +4037,20 @@ async fn on_event_inner(state: &WorkerState, msg: &SecurityEventMessage) { } else { vec![msg.team_id.clone()] }; - let kev_map = kev(state).await; + // A release reads GitHub and the run records only; the rest tends the + // findings afterwards and needs the CISA list. + let kev_map = if matches!(msg.kind.as_str(), "pr" | "run") { + BTreeMap::new() + } else { + kev(state).await + }; for team in teams { - let Some(cfg) = load_config(state, &team).await.filter(|c| c.enabled) else { + // A release is the truth about a finding, not an action: it runs + // for a team that turned security fixes off too. + let Some(cfg) = load_config(state, &team) + .await + .filter(|c| c.enabled || release) + else { continue; }; let iid = if msg.installation_id > 0 && !msg.team_id.is_empty() { @@ -4065,6 +4163,28 @@ async fn event_for_team( .await; } } + // A security pull request closed or reopened (the gateway's + // webhook), or a person cancelled or closed a fix run: the findings + // follow, now. + "pr" | "run" => { + let scope = if msg.kind == "pr" { + release::Scope::Pr { + repo: msg.repo.clone(), + number: msg.pr_number, + } + } else { + release::Scope::Ticket(msg.ticket.clone()) + }; + let r = release::run(&cx, &mut findings, &scope, release::TEAM_BUDGET_SECS).await; + info!(team_id, kind = %msg.kind, repo = %msg.repo, pr = msg.pr_number, ticket = %msg.ticket, changed = r.changed(), "security: release event handled"); + return Ok(()); + } + // A person pressed Retry on a fix run whose pull request is gone: + // its findings, as they stand now, are asked for again, and the + // request starts below like any other a person made. + "retry" => { + retry_asked(&cx, &mut findings, &msg.ticket, &msg.requested_by).await; + } "fix" => { report.runs += start_asked( &cx, @@ -4580,16 +4700,26 @@ pub async fn on_pr_opened( let mut carded = false; for (f, st) in members.iter_mut() { // Told already (the pull request was there before this run). - if f.pr.as_ref().is_some_and(|p| p.number == number) { + if f.pr + .as_ref() + .is_some_and(|p| p.number == number && p.state == "open") + { + continue; + } + // Fixed, dismissed or withdrawn while the run worked: it stays so. + if f.status.is_handled() { continue; } f.status = Status::PrOpen; + f.waiting = None; + st.hold_until = None; f.pr = Some(sec::PrRef { number, url: url.to_string(), ci: Some("pending".into()), state: "open".into(), adopted: false, + ..Default::default() }); st.pr_opened_at .get_or_insert_with(|| Utc::now().to_rfc3339()); diff --git a/services/worker/src/passes/security_release.rs b/services/worker/src/passes/security_release.rs new file mode 100644 index 000000000..e0169d397 --- /dev/null +++ b/services/worker/src/passes/security_release.rs @@ -0,0 +1,1017 @@ +//! Security fixes: releasing a finding from a pull request or a fix run +//! that is over (`common::security_release` has the rules). +//! +//! `reconcile` reads what is true (GitHub's state of each pull request a +//! finding is in, the run record behind each `fixing` finding) and applies +//! the rules. It is called three ways, all through the same code: +//! +//! - a `pr` event: the gateway saw a security pull request close or reopen; +//! - a `run` event: a person cancelled or closed a fix run; +//! - the scheduled sweep, before anything else it does for the team and on +//! a clock of its own, so a webhook that never arrived (or a record that +//! went stale before these paths existed) is put right within one sweep, +//! whatever the rest of the sweep has to do. +//! +//! It is bounded: at most `MAX_PRS_PER_SWEEP` pull requests and +//! `MAX_TICKETS_PER_SWEEP` runs per team per sweep, the rest in turn on the +//! following sweeps. It is idempotent: a fact applied twice writes nothing +//! the second time. + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Instant; + +use chrono::{DateTime, Utc}; +use common::security_fixes::{Finding, FindingState, PrRef, Stage, Status}; +use common::security_release::{self as rel, Closer, PrNow, RunNow}; +use tracing::{info, warn}; + +use super::{add_event, attr_s, post_card, s, save_finding, team_channels, ticket_branch, Ctx}; + +/// Seconds one team's reconciliation may take in a sweep. +pub(crate) const TEAM_BUDGET_SECS: u64 = 45; + +/// Which findings a call looks at. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Scope { + /// The sweep: every pull request and run a finding waits on, in turn. + All, + /// A pull request closed or reopened. + Pr { repo: String, number: u64 }, + /// A fix run ended. + Ticket(String), + /// These findings (a fix unit's). + Ids(Vec), +} + +impl Scope { + fn has(&self, f: &Finding, st: &FindingState) -> bool { + match self { + Scope::All => true, + Scope::Pr { repo, number } => { + f.repo.eq_ignore_ascii_case(repo) + && f.pr.as_ref().is_some_and(|p| p.number == *number) + } + Scope::Ticket(t) => st.ticket.as_deref() == Some(t.as_str()), + Scope::Ids(ids) => ids.contains(&f.id), + } + } +} + +/// What one reconciliation did. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub(crate) struct Report { + /// Pull requests and runs read. + pub prs_read: usize, + pub runs_read: usize, + /// Findings given back to open (their pull request closed unmerged, or + /// their run ended without one). + pub released: usize, + /// Findings whose pull request merged. + pub fixed: usize, + /// Findings put back in a pull request (reopened, or opened by a run + /// that never told them). + pub attached: usize, + /// Pull requests and runs left for the next sweep (its turn or its + /// time ran out). + pub left: usize, +} + +impl Report { + pub fn changed(&self) -> usize { + self.released + self.fixed + self.attached + } +} + +/// The edges: GitHub, the run records, the findings' storage. A trait so +/// the reconciliation runs in tests on a fake GitHub and fake runs. +#[async_trait::async_trait] +pub(crate) trait ReleaseIo: Send + Sync { + /// What GitHub says about the pull request. `closer`: whether who + /// closed it is needed (it is not for one already recorded as closed, + /// read only to see whether a person reopened it). + async fn pr_now(&self, repo: &str, number: u64, closer: bool) -> PrNow; + /// The open pull request on the ticket's branch; `Err` when GitHub + /// could not be read. + async fn open_pr(&self, repo: &str, ticket: &str) -> Result, ()>; + /// What became of the ticket's run started at or after `since`. + async fn run_now(&self, ticket: &str, since: Option>) -> RunNow; + async fn save(&self, f: &Finding, st: &FindingState); + async fn event(&self, finding_id: &str, text: &str, link: Option<&str>); + /// A pull request merged: its card, once. + async fn merged(&self, f: &Finding, st: &FindingState); + fn out_of_time(&self) -> bool; +} + +/// Brings the findings in `scope` in line with GitHub and the run records. +pub(crate) async fn reconcile( + io: &dyn ReleaseIo, + findings: &mut [(Finding, FindingState)], + scope: &Scope, + now: DateTime, +) -> Report { + let mut report = Report::default(); + let sweep = *scope == Scope::All; + + // Pull requests: one read each, whatever the number of findings in it. + let mut prs: BTreeMap<(String, u64), (String, bool)> = BTreeMap::new(); + for (f, st) in findings.iter() { + let Some(p) = &f.pr else { continue }; + let watched = if sweep { + rel::watches_pr(f, st, now) + } else { + scope.has(f, st) && p.state != "merged" + }; + if watched { + let e = prs + .entry((f.repo.to_ascii_lowercase(), p.number)) + .or_insert_with(|| (f.repo.clone(), false)); + // Recorded as open by any finding: a close needs its closer. + e.1 |= p.state == "open"; + } + } + let all: Vec<((String, u64), (String, bool))> = prs.into_iter().collect(); + let mine = if sweep { + rel::turn(&all, rel::MAX_PRS_PER_SWEEP, now) + } else { + all.clone() + }; + report.left += all.len() - mine.len(); + for (i, (key, (repo, open))) in mine.iter().enumerate() { + if io.out_of_time() { + report.left += mine.len() - i; + break; + } + let fact = io.pr_now(repo, key.1, *open).await; + report.prs_read += 1; + let mut carded = false; + for (f, st) in findings.iter_mut() { + let same = f.repo.to_ascii_lowercase() == key.0 + && f.pr.as_ref().is_some_and(|p| p.number == key.1); + if !same || !scope.has(f, st) { + continue; + } + let was = f.status; + let Some(change) = rel::settle_pr(f, st, &fact, now) else { + continue; + }; + io.save(f, st).await; + io.event(&f.id, &change.text, change.link.as_deref()).await; + match (was, f.status) { + (_, Status::Fixed) if was != Status::Fixed => { + report.fixed += 1; + if !carded { + io.merged(f, st).await; + carded = true; + } + } + (Status::PrOpen, Status::Open) => report.released += 1, + (Status::Open, Status::PrOpen) => report.attached += 1, + _ => {} + } + } + } + + // Fix runs: one read per ticket. + let mut tickets: BTreeSet<(String, String)> = BTreeSet::new(); + for (f, st) in findings.iter() { + if f.status == Status::Fixing && scope.has(f, st) { + tickets.insert((st.ticket.clone().unwrap_or_default(), f.repo.clone())); + } + } + let all: Vec<(String, String)> = tickets.into_iter().collect(); + let mine = if sweep { + rel::turn(&all, rel::MAX_TICKETS_PER_SWEEP, now) + } else { + all.clone() + }; + report.left += all.len() - mine.len(); + for (i, (ticket, repo)) in mine.iter().enumerate() { + if io.out_of_time() { + report.left += mine.len() - i; + break; + } + let of_ticket = |f: &Finding, st: &FindingState| { + f.status == Status::Fixing + && st.ticket.clone().unwrap_or_default() == *ticket + && f.repo == *repo + }; + // A finding claimed with no ticket has no run to wait on. + let (open, run) = if ticket.is_empty() { + (None, RunNow::Missing) + } else { + let Ok(open) = io.open_pr(repo, ticket).await else { + report.left += 1; + continue; + }; + let run = match &open { + Some(_) => RunNow::Working, + None => { + let since = findings + .iter() + .filter(|(f, st)| of_ticket(f, st)) + .filter_map(|(f, st)| rel::claimed_at(f, st)) + .min(); + io.run_now(ticket, since).await + } + }; + (open, run) + }; + report.runs_read += 1; + for (f, st) in findings.iter_mut() { + if !of_ticket(f, st) || !scope.has(f, st) { + continue; + } + let Some(change) = rel::settle_run(f, st, &run, open.as_ref(), now) else { + continue; + }; + io.save(f, st).await; + io.event(&f.id, &change.text, change.link.as_deref()).await; + if f.status == Status::PrOpen { + report.attached += 1; + } else { + report.released += 1; + } + } + } + report +} + +// ── The real edges ────────────────────────────────────────────────────── + +/// GitHub, DynamoDB and the team's channels, for one team. +pub(super) struct Live<'a, 'c> { + pub cx: &'a Ctx<'c>, + pub started: Instant, + pub budget_secs: u64, + channels: tokio::sync::OnceCell, +} + +impl<'a, 'c> Live<'a, 'c> { + pub fn new(cx: &'a Ctx<'c>, budget_secs: u64) -> Self { + Self { + cx, + started: Instant::now(), + budget_secs, + channels: tokio::sync::OnceCell::new(), + } + } + + /// The run that opened a pull request, when CoderHelm's own account + /// closed it: a person who closed the run in CoderHelm is the closer. + async fn closed_through_run(&self, owner: &str, name: &str, number: u64) -> Option { + let state = self.cx.state; + let run_id = + crate::passes::review_pr::lookup_run_by_pr(state, self.cx.team_id, owner, name, number) + .await?; + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(self.cx.team_id)) + .key("run_id", attr_s(&run_id)) + .projection_expression("#s, closed_by_name, closed_by") + .expression_attribute_names("#s", "status") + .send() + .await + .ok()? + .item?; + if s(&item, "status") != common::run_status::CLOSED { + return None; + } + Some( + [s(&item, "closed_by_name"), s(&item, "closed_by")] + .into_iter() + .find(|v| !v.is_empty()) + .unwrap_or_default(), + ) + } +} + +#[async_trait::async_trait] +impl ReleaseIo for Live<'_, '_> { + async fn pr_now(&self, repo: &str, number: u64, closer: bool) -> PrNow { + let Some((o, n)) = repo.split_once('/') else { + return PrNow::Unknown; + }; + let gh = &self.cx.gh; + let pr = match gh.get_pull_request(o, n, number).await { + Ok(pr) => pr, + Err(e) if crate::clients::github::is_not_found(e.as_ref()) => return PrNow::Gone, + Err(e) => { + warn!(team_id = self.cx.team_id, repo, number, error = %e, "security: a pull request's state couldn't be read; left as it is"); + return PrNow::Unknown; + } + }; + closed_fact(&pr, || async { + if !closer { + return (String::new(), true); + } + // The pull request doesn't carry who closed it; its issue does. + let login = gh.get_pr_closed_by(o, n, number).await; + let through_run = match &login { + Some(l) if crate::passes::is_own_login(l) => { + self.closed_through_run(o, n, number).await + } + _ => None, + }; + closer_of(login, through_run) + }) + .await + } + + async fn open_pr(&self, repo: &str, ticket: &str) -> Result, ()> { + let Some((o, n)) = repo.split_once('/') else { + return Ok(None); + }; + let Some(branch) = ticket_branch(self.cx.state, self.cx.team_id, ticket).await else { + return Ok(None); + }; + match self.cx.gh.find_open_pr_for_branch(o, n, &branch).await { + Ok(pr) => Ok(pr.map(|pr| PrRef { + number: pr["number"].as_u64().unwrap_or(0), + url: pr["html_url"].as_str().unwrap_or("").to_string(), + ..Default::default() + })), + Err(e) => { + warn!(team_id = self.cx.team_id, repo, ticket, error = %e, "security: the run's branch couldn't be read; left as it is"); + Err(()) + } + } + } + + async fn run_now(&self, ticket: &str, since: Option>) -> RunNow { + let state = self.cx.state; + let mut latest: Option<(String, super::Item)> = None; + let mut start = None; + loop { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", attr_s(self.cx.team_id)) + .expression_attribute_values(":ticket", attr_s(ticket)) + .projection_expression( + "created_at, updated_at, #s, closed_by_name, cancelled_by, closed_by", + ) + .expression_attribute_names("#s", "status") + .set_exclusive_start_key(start.take()) + .send() + .await; + let Ok(out) = out else { + warn!( + team_id = self.cx.team_id, + ticket, "security: the ticket's runs couldn't be read; left as it is" + ); + return RunNow::Unknown; + }; + for item in out.items() { + let created = s(item, "created_at"); + if latest.as_ref().is_none_or(|(c, _)| created > *c) { + latest = Some((created, item.clone())); + } + } + match out.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + let Some((created, item)) = latest else { + return RunNow::Missing; + }; + run_fact( + &created, + &s(&item, "status"), + &s(&item, "updated_at"), + [ + s(&item, "closed_by_name"), + s(&item, "cancelled_by"), + s(&item, "closed_by"), + ] + .into_iter() + .find(|v| !v.is_empty()), + since, + Utc::now(), + ) + } + + async fn save(&self, f: &Finding, st: &FindingState) { + save_finding(self.cx.state, self.cx.team_id, f, st).await; + } + + async fn event(&self, finding_id: &str, text: &str, link: Option<&str>) { + add_event(self.cx.state, self.cx.team_id, finding_id, text, link).await; + } + + async fn merged(&self, f: &Finding, st: &FindingState) { + if !self.cx.cfg.acts() || !st.cards.iter().any(|c| c == "new") { + return; + } + let Some(p) = &f.pr else { return }; + let channels = self + .channels + .get_or_init(|| team_channels(self.cx.state, self.cx.team_id)) + .await; + let thing = format!("PR#{}#{}", f.repo.to_ascii_lowercase(), p.number); + post_card( + self.cx.state, + self.cx.team_id, + channels, + &thing, + Stage::Merged, + f, + ) + .await; + } + + fn out_of_time(&self) -> bool { + self.started.elapsed().as_secs() >= self.budget_secs + } +} + +/// Who closed a pull request, and whether that was a person: `login` is +/// GitHub's closer; `through_run` the person who closed the pull request's +/// run in CoderHelm, when CoderHelm's own account did the closing for +/// them. A person on GitHub (which is also who deletes a branch and so +/// closes its pull request) and a person through CoderHelm are both a +/// person; CoderHelm's account with no such run closed it for a reason of +/// its own. An unknown closer is taken for a person, so that no automatic +/// fix opens against what may have been a person's decision. +pub(super) fn closer_of(login: Option, through_run: Option) -> (String, bool) { + match (login, through_run) { + (Some(l), Some(name)) if crate::passes::is_own_login(&l) => { + (if name.is_empty() { l } else { name }, true) + } + (Some(l), _) if crate::passes::is_own_login(&l) => (l, false), + (Some(l), _) => (l, true), + (None, _) => (String::new(), true), + } +} + +/// GitHub's pull request as a fact. `closer` is asked only for one closed +/// unmerged: (who, whether a person). +pub(super) async fn closed_fact(pr: &serde_json::Value, closer: F) -> PrNow +where + F: FnOnce() -> Fut, + Fut: std::future::Future, +{ + if pr["merged"].as_bool() == Some(true) || pr["merged_at"].is_string() { + return PrNow::Merged; + } + match pr["state"].as_str() { + Some("closed") => { + let (by, person) = closer().await; + PrNow::Closed(Closer { + by, + person, + at: pr["closed_at"].as_str().map(str::to_string), + }) + } + Some("open") => PrNow::Open, + // An answer with no state is not an answer. + _ => PrNow::Unknown, + } +} + +/// The ticket's latest run as a fact for a finding claimed at `since`: a +/// run that began before the claim is an earlier attempt, not this one. +pub(super) fn run_fact( + created_at: &str, + status: &str, + updated_at: &str, + by: Option, + since: Option>, + now: DateTime, +) -> RunNow { + let began = common::security_fixes::parse_time(created_at); + // The claim is written just before the run's message is sent; a clock a + // few minutes apart must not hide the run. + let earlier = match (began, since) { + (Some(b), Some(s)) => b < s - chrono::Duration::minutes(10), + _ => false, + }; + if earlier { + return RunNow::Missing; + } + rel::run_now_of(status, updated_at, by, now) +} + +/// The sweep's and the events' entry: reconcile and say what was done. +pub(super) async fn run( + cx: &Ctx<'_>, + findings: &mut [(Finding, FindingState)], + scope: &Scope, + budget_secs: u64, +) -> Report { + let io = Live::new(cx, budget_secs); + let report = reconcile(&io, findings, scope, Utc::now()).await; + if report.changed() > 0 || report.left > 0 { + info!( + team_id = cx.team_id, + scope = ?scope, + prs_read = report.prs_read, + runs_read = report.runs_read, + released = report.released, + fixed = report.fixed, + attached = report.attached, + left = report.left, + "security: findings brought in line with their pull requests and runs" + ); + } + report +} + +#[cfg(test)] +pub(crate) mod fake { + //! A fake GitHub and fake run records for the reconciliation's tests + //! (here and in the incident suite). + use super::*; + use std::sync::Mutex; + + #[derive(Default)] + pub(crate) struct Fake { + /// What GitHub says, by (repo lowercase, number). + pub prs: Mutex>, + /// The open pull request on a ticket's branch, by ticket. + pub branch_prs: Mutex>, + /// What became of a ticket's run, by ticket. + pub runs: Mutex>, + pub saved: Mutex>, + pub events: Mutex>, + pub merged_cards: Mutex>, + /// Every pull request read, in order, and those whose closer was + /// asked for. + pub pr_reads: Mutex>, + pub closer_asked: Mutex>, + pub run_reads: Mutex>, + /// Reads after which the time is up. + pub time_for: Option, + /// GitHub is down for branch lookups. + pub branches_down: bool, + } + + impl Fake { + pub fn pr(&self, repo: &str, number: u64, now: PrNow) { + self.prs + .lock() + .unwrap() + .insert((repo.to_ascii_lowercase(), number), now); + } + pub fn run(&self, ticket: &str, now: RunNow) { + self.runs.lock().unwrap().insert(ticket.to_string(), now); + } + pub fn saves(&self) -> usize { + self.saved.lock().unwrap().len() + } + pub fn reads(&self) -> usize { + self.pr_reads.lock().unwrap().len() + self.run_reads.lock().unwrap().len() + } + pub fn event_texts(&self) -> Vec { + self.events + .lock() + .unwrap() + .iter() + .map(|(_, t)| t.clone()) + .collect() + } + } + + #[async_trait::async_trait] + impl ReleaseIo for Fake { + async fn pr_now(&self, repo: &str, number: u64, closer: bool) -> PrNow { + let key = (repo.to_ascii_lowercase(), number); + self.pr_reads.lock().unwrap().push(key.clone()); + if closer { + self.closer_asked.lock().unwrap().push(number); + } + // A pull request the fake was never told about is one GitHub + // could not be asked about. + self.prs + .lock() + .unwrap() + .get(&key) + .cloned() + .unwrap_or(PrNow::Unknown) + } + async fn open_pr(&self, _repo: &str, ticket: &str) -> Result, ()> { + if self.branches_down { + return Err(()); + } + Ok(self.branch_prs.lock().unwrap().get(ticket).cloned()) + } + async fn run_now(&self, ticket: &str, _since: Option>) -> RunNow { + self.run_reads.lock().unwrap().push(ticket.to_string()); + self.runs + .lock() + .unwrap() + .get(ticket) + .cloned() + .unwrap_or(RunNow::Missing) + } + async fn save(&self, f: &Finding, _st: &FindingState) { + self.saved.lock().unwrap().push(f.id.clone()); + } + async fn event(&self, finding_id: &str, text: &str, _link: Option<&str>) { + self.events + .lock() + .unwrap() + .push((finding_id.to_string(), text.to_string())); + } + async fn merged(&self, f: &Finding, _st: &FindingState) { + self.merged_cards.lock().unwrap().push(f.id.clone()); + } + fn out_of_time(&self) -> bool { + self.time_for.is_some_and(|n| self.reads() >= n) + } + } + + pub(crate) fn at(t: &str) -> DateTime { + DateTime::parse_from_rfc3339(t).unwrap().with_timezone(&Utc) + } + + /// A finding in pull request `number` of `repo`, claimed by `ticket`. + pub(crate) fn in_pr( + id: &str, + repo: &str, + number: u64, + ticket: &str, + ) -> (Finding, FindingState) { + ( + Finding { + id: id.into(), + repo: repo.into(), + ecosystem: "npm".into(), + package: format!("pkg-{id}"), + version: "1.0.0".into(), + fixed_version: Some("1.0.1".into()), + status: Status::PrOpen, + pr: Some(PrRef { + number, + url: format!("https://github.com/{repo}/pull/{number}"), + ci: Some("passing".into()), + state: "open".into(), + ..Default::default() + }), + updated_at: "2026-11-12T09:00:00Z".into(), + ..Default::default() + }, + FindingState { + ticket: Some(ticket.into()), + bundled: true, + cards: vec!["new".into()], + ..Default::default() + }, + ) + } + + /// A finding a run of `ticket` is working on. + pub(crate) fn fixing(id: &str, repo: &str, ticket: &str) -> (Finding, FindingState) { + let (mut f, mut st) = in_pr(id, repo, 1, ticket); + f.status = Status::Fixing; + f.pr = None; + st.claimed_at = Some("2026-11-13T09:00:00Z".into()); + (f, st) + } + + pub(crate) fn closed_by(login: &str) -> PrNow { + PrNow::Closed(Closer { + by: login.into(), + person: true, + at: Some("2026-11-13T09:30:00Z".into()), + }) + } +} + +#[cfg(test)] +mod tests { + use super::fake::*; + use super::*; + + const REPO: &str = "acme/web"; + const TICKET: &str = "SEC-AAAAAAAAAAAA"; + + fn now() -> DateTime { + at("2026-11-13T10:00:00Z") + } + + fn statuses(findings: &[(Finding, FindingState)]) -> Vec { + findings.iter().map(|(f, _)| f.status).collect() + } + + #[tokio::test] + async fn the_sweep_releases_a_closed_pull_requests_findings_with_one_read() { + // 274 findings in one bundle pull request a person closed; the + // webhook never arrived. + let mut findings: Vec<_> = (0..274) + .map(|i| in_pr(&format!("f{i}"), REPO, 12, TICKET)) + .collect(); + let io = Fake::default(); + io.pr(REPO, 12, closed_by("octo")); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!( + r, + Report { + prs_read: 1, + released: 274, + ..Default::default() + } + ); + assert!(findings.iter().all(|(f, st)| f.status == Status::Open + && st.ticket.is_none() + && f.pr.as_ref().is_some_and(|p| p.state == "closed" + && p.closed_by.as_deref() == Some("octo") + && p.closed_by_person))); + assert_eq!(io.saves(), 274); + assert!(io.event_texts()[0].contains("closed without merging by octo")); + + // The next sweep reads it once more (a person may reopen it while + // the hold is on) and writes nothing. + let later = now() + chrono::Duration::minutes(20); + let r = reconcile(&io, &mut findings, &Scope::All, later).await; + assert_eq!(r.changed(), 0); + // ...without asking GitHub again who closed it. + assert_eq!(io.pr_reads.lock().unwrap().len(), 2); + assert_eq!(*io.closer_asked.lock().unwrap(), vec![12]); + assert_eq!(io.saves(), 274); + assert_eq!(io.events.lock().unwrap().len(), 274); + } + + #[tokio::test] + async fn a_pull_request_event_releases_only_that_pull_requests_findings() { + let mut findings = vec![ + in_pr("a", REPO, 12, TICKET), + in_pr("b", REPO, 13, "SEC-BBBBBBBBBBBB"), + in_pr("c", "acme/api", 12, "SEC-CCCCCCCCCCCC"), + ]; + let io = Fake::default(); + io.pr(REPO, 12, closed_by("octo")); + io.pr(REPO, 13, closed_by("octo")); + io.pr("acme/api", 12, closed_by("octo")); + let scope = Scope::Pr { + repo: "Acme/Web".into(), + number: 12, + }; + let r = reconcile(&io, &mut findings, &scope, now()).await; + assert_eq!((r.prs_read, r.released), (1, 1)); + assert_eq!( + statuses(&findings), + vec![Status::Open, Status::PrOpen, Status::PrOpen] + ); + } + + #[tokio::test] + async fn a_merge_fixes_the_findings_and_posts_its_card_once() { + let mut findings = vec![in_pr("a", REPO, 12, TICKET), in_pr("b", REPO, 12, TICKET)]; + let io = Fake::default(); + io.pr(REPO, 12, PrNow::Merged); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!((r.fixed, r.released), (2, 0)); + assert_eq!(statuses(&findings), vec![Status::Fixed, Status::Fixed]); + assert_eq!(io.merged_cards.lock().unwrap().len(), 1); + // Merged pull requests are not read again. + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!(r, Report::default()); + } + + #[tokio::test] + async fn github_down_changes_nothing_and_the_next_sweep_heals() { + let mut findings = vec![in_pr("a", REPO, 12, TICKET)]; + let io = Fake::default(); + // The fake was told nothing: the read fails. + let before = findings.clone(); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!((r.prs_read, r.changed()), (1, 0)); + assert_eq!(findings, before); + assert_eq!(io.saves(), 0); + io.pr(REPO, 12, closed_by("octo")); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!(r.released, 1); + } + + #[tokio::test] + async fn a_reopened_pull_request_takes_its_findings_back() { + let mut findings = vec![in_pr("a", REPO, 12, TICKET)]; + let io = Fake::default(); + io.pr(REPO, 12, closed_by("octo")); + reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!(findings[0].0.status, Status::Open); + io.pr(REPO, 12, PrNow::Open); + let scope = Scope::Pr { + repo: REPO.into(), + number: 12, + }; + let r = reconcile(&io, &mut findings, &scope, now()).await; + assert_eq!(r.attached, 1); + assert_eq!(findings[0].0.status, Status::PrOpen); + assert!(io.event_texts().last().unwrap().contains("reopened")); + // And the sweep alone finds a reopen whose webhook was missed. + io.pr(REPO, 12, closed_by("octo")); + reconcile(&io, &mut findings, &Scope::All, now()).await; + io.pr(REPO, 12, PrNow::Open); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!(r.attached, 1); + } + + #[tokio::test] + async fn a_cancelled_run_releases_what_it_claimed() { + let mut findings = vec![ + fixing("a", REPO, TICKET), + fixing("b", REPO, TICKET), + fixing("c", REPO, "SEC-BBBBBBBBBBBB"), + ]; + let io = Fake::default(); + io.run( + TICKET, + RunNow::Ended { + status: "cancelled".into(), + by: Some("dev@example.com".into()), + }, + ); + io.run("SEC-BBBBBBBBBBBB", RunNow::Working); + let r = reconcile(&io, &mut findings, &Scope::Ticket(TICKET.into()), now()).await; + assert_eq!((r.runs_read, r.released), (1, 2)); + assert_eq!( + statuses(&findings), + vec![Status::Open, Status::Open, Status::Fixing] + ); + assert!(io.event_texts()[0].contains("cancelled by dev@example.com")); + // The sweep leaves the working run's finding alone, and a second + // pass over the released ones writes nothing. + let saves = io.saves(); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!((r.runs_read, r.changed()), (1, 0)); + assert_eq!(io.saves(), saves); + } + + #[tokio::test] + async fn a_run_that_opened_a_pull_request_nobody_recorded_puts_its_findings_in_it() { + let mut findings = vec![fixing("a", REPO, TICKET)]; + let io = Fake::default(); + io.branch_prs.lock().unwrap().insert( + TICKET.into(), + PrRef { + number: 31, + url: "https://github.com/acme/web/pull/31".into(), + ..Default::default() + }, + ); + io.run( + TICKET, + RunNow::Ended { + status: "failed".into(), + by: None, + }, + ); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!(r.attached, 1); + assert_eq!(findings[0].0.status, Status::PrOpen); + // The run was not even asked: the pull request is the fact. + assert!(io.run_reads.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_branch_that_cannot_be_read_never_releases_a_finding() { + let mut findings = vec![fixing("a", REPO, TICKET)]; + let io = Fake { + branches_down: true, + ..Default::default() + }; + io.run( + TICKET, + RunNow::Ended { + status: "failed".into(), + by: None, + }, + ); + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!((r.changed(), r.left), (0, 1)); + assert_eq!(findings[0].0.status, Status::Fixing); + } + + #[tokio::test] + async fn the_sweep_is_bounded_and_every_pull_request_gets_its_turn() { + // 250 pull requests, each closed, each with one finding. + let mut findings: Vec<_> = (0..250u64) + .map(|i| in_pr(&format!("f{i}"), REPO, 1000 + i, TICKET)) + .collect(); + let io = Fake::default(); + for i in 0..250u64 { + io.pr(REPO, 1000 + i, closed_by("octo")); + } + let mut t = now(); + let r = reconcile(&io, &mut findings, &Scope::All, t).await; + assert_eq!( + (r.prs_read, r.released, r.left), + (rel::MAX_PRS_PER_SWEEP, rel::MAX_PRS_PER_SWEEP, 150) + ); + // Every pull request is released within a few sweeps, none starved. + for _ in 0..6 { + t += chrono::Duration::seconds(rel::SWEEP_SECS); + reconcile(&io, &mut findings, &Scope::All, t).await; + } + assert!(findings.iter().all(|(f, _)| f.status == Status::Open)); + } + + #[tokio::test] + async fn out_of_time_stops_reading_and_says_what_is_left() { + let mut findings: Vec<_> = (0..10u64) + .map(|i| in_pr(&format!("f{i}"), REPO, 100 + i, TICKET)) + .collect(); + let io = Fake { + time_for: Some(3), + ..Default::default() + }; + for i in 0..10u64 { + io.pr(REPO, 100 + i, closed_by("octo")); + } + let r = reconcile(&io, &mut findings, &Scope::All, now()).await; + assert_eq!((r.prs_read, r.released, r.left), (3, 3, 7)); + } + + #[tokio::test] + async fn github_facts_are_read_as_what_they_say() { + let nobody = || async { (String::new(), true) }; + let merged = serde_json::json!({"state": "closed", "merged": true}); + assert_eq!(closed_fact(&merged, nobody).await, PrNow::Merged); + let open = serde_json::json!({"state": "open", "merged": false}); + assert_eq!(closed_fact(&open, nobody).await, PrNow::Open); + let closed = serde_json::json!({"state": "closed", "merged": false, "merged_at": null, "closed_at": "2026-11-13T09:30:00Z"}); + assert_eq!( + closed_fact(&closed, || async { ("octo".to_string(), true) }).await, + closed_by("octo") + ); + // An answer with no state (an error body) is never open or closed. + assert_eq!( + closed_fact(&serde_json::json!({"message": "Server Error"}), nobody).await, + PrNow::Unknown + ); + } + + #[test] + fn the_closer_is_a_person_unless_coderhelm_closed_it_for_its_own_reason() { + // A person on GitHub; deleting the branch closes it in their name too. + assert_eq!(closer_of(Some("octo".into()), None), ("octo".into(), true)); + // CoderHelm's account, because a person closed the run in CoderHelm. + assert_eq!( + closer_of(Some("coderhelm[bot]".into()), Some("Dana Admin".into())), + ("Dana Admin".into(), true) + ); + // CoderHelm's account for a reason of its own (a withdrawn advisory, + // a stale pull request). + assert_eq!( + closer_of(Some("coderhelm[bot]".into()), None), + ("coderhelm[bot]".into(), false) + ); + // GitHub did not say: a person, so nothing reopens it by itself. + assert_eq!(closer_of(None, None), (String::new(), true)); + // A person's login is never replaced by a run's closer. + assert_eq!( + closer_of(Some("octo".into()), Some("Dana Admin".into())), + ("octo".into(), true) + ); + } + + #[test] + fn a_run_that_began_before_the_claim_is_not_the_claims_run() { + let n = now(); + let since = Some(at("2026-11-13T09:00:00Z")); + // The retried run of yesterday: this claim's run has not started yet. + assert_eq!( + run_fact( + "2026-11-12T08:00:00Z", + "retried", + "2026-11-12T09:00:00Z", + None, + since, + n + ), + RunNow::Missing + ); + assert_eq!( + run_fact( + "2026-11-13T09:00:05Z", + "running", + "2026-11-13T09:55:00Z", + None, + since, + n + ), + RunNow::Working + ); + assert_eq!( + run_fact( + "2026-11-13T09:00:05Z", + "cancelled", + "2026-11-13T09:20:00Z", + Some("dev@example.com".into()), + since, + n + ), + RunNow::Ended { + status: "cancelled".into(), + by: Some("dev@example.com".into()) + } + ); + } +}