diff --git a/docs/incidents.md b/docs/incidents.md index 0a78e99e5..da2e6c6e0 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -71,6 +71,7 @@ pipeline still calls it there. | 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. | | ar. `ar_description_stamped_to_the_head` | A dependency run's pull request was described from a head, and the head then moved on without it. A feedback round changed an override in the manifest and the description was rebuilt on that commit, where the lockfile still resolved the old version ("not moved on the head"); the lockfile was regenerated in the commits after it and the run completed. The description still said not moved, still counted the advisory as not fixed, still listed the package under open findings and "the lockfile is out of sync" under Open items, and CoderHelm's own review of the final head left that as a note. The checks step on an open pull request never rebuilt the computed sections, a regenerated lockfile was pushed with nothing after it, a review wrote its findings into the copy of the description it had read when it started (undoing a rebuild made meanwhile), and nits on CoderHelm's own pull request ended the loop. | The description names the head it was built for, and whenever that is not the pull request's head it is rebuilt: after every message in which CoderHelm moved the branch (seen in the one place every request leaves the GitHub client), in the checks and settle step, before a review of its own pull request, in the pull request watch, and at the end of the run, which never completes while the two differ. A review writes on the description as it is now and only for the head it reviewed. An item that says a lockfile is out of sync is checked on the head, never carried. A finding that the description is behind the code is settled by the rebuild, and every finding on CoderHelm's own pull request that is not pure style is its own to act on. | +| as. `as_infra_closed_pr_keeps_record` | The same gap as `ap` in the other store. An infrastructure finding keeps its own record and nothing released it: after a person closed its fix pull request the record stayed `pr_open`, so the Infrastructure tab kept the closed pull request and never offered "Open fix PR" again; a cancelled or failed fix run left the record `fixing` for good; a reopened pull request was never noticed. | Infrastructure records go through the same reconciliation as dependency findings (one `reconcile` over `common::security_release::Claim`, not a copy): the same reads of GitHub and the run records, events, sweep bounds, person-closed record, holds and Retry. What is this store's own stays: a merge never closes a finding (only a read of the account does), a pull request the replacement guard made a draft is not closed and is left as it is, a finding on its runbook stays there until its code or target changes, a pull request is recorded only after the guard read it, and a fix round that ends without settling its pull request becomes the guard's second step (a draft), never a ready pull request. | | at. `at_round_scope` | A feature run opened its draft pull request and the proof check found three gaps. The fix round went to edit the existing file that builds a page's metadata, which the pull request had not touched yet: two edits were "rejected: outside the ticket's files" and a third failed. The guard held every fix round to the files the pull request already changed and gave way after two refusals of one path, so the round started for work the branch had not done was refused the file that work lives in. A planned task stayed not done, planned-work rounds went on for about an hour on a pull request whose checks passed, and one that hit GitHub's hourly limit was read as "it met an error": its work branch was deleted during the limit, an attempt was spent and the next try started five seconds later. | A round may edit what it was started for (`write_guard`): the pull request's files, the plan's task files (done or not) and listed dependents, and the files its gap, finding or failing check names; a check's output names the files that fail, never the ones it only warns about. Any other existing file is refused every time, however often it is tried, with one message that says how to justify the edit (`outside_plan`, one sentence); a justified edit is made and listed on the pull request under "Changed outside the plan's files". A round that ends with an edit refused and no task finished made no progress whatever it pushed: the next round is told what was refused, and a second one stops and names the file once. GitHub's limit inside a round on the pull request is a wait: the round is parked as it stands (its work branch, its attempt) and goes on after the reset. | | ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | | bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | diff --git a/services/common/src/infra_vuln/records.rs b/services/common/src/infra_vuln/records.rs index 2369f74ab..3610b5fb2 100644 --- a/services/common/src/infra_vuln/records.rs +++ b/services/common/src/infra_vuln/records.rs @@ -5,6 +5,13 @@ //! only a new read of the account closes one, never a merged PR. //! - A merged PR without the new version running stays open and says so. //! - AWS-managed rows are kept as `aws_managed` and never count as open. +//! - A finding is `fixing` only while its run works and `pr_open` only +//! while its pull request is open or merged: a pull request closed +//! unmerged, or a run that ended without one, gives it back +//! ([`crate::security_release::Claim`], the same rules, words and holds +//! as dependency findings). A pull request the replacement guard made a +//! draft is neither: it stays as it is, and its finding stays on its +//! runbook until its code or its target changes. use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; @@ -73,8 +80,17 @@ impl Status { pub struct PrRef { pub number: u64, pub url: String, - /// `open`, `merged` or `closed`. + /// `open`, `draft` (the replacement guard held it), `merged` or + /// `closed`. pub state: String, + /// Closed without merging: when, who (a GitHub login, or the person + /// who closed its run in CoderHelm), and whether that was a person. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub closed_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub closed_by: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub closed_by_person: bool, } /// One stored finding. @@ -107,6 +123,18 @@ pub struct Record { /// starts by itself while the finding still asks for the same. #[serde(default, skip_serializing_if = "String::is_empty")] pub guard_sig: String, + /// Its pull request closed unmerged, or its fix run ended without one: + /// no fix run starts by itself until then. A person asking never + /// waits on it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hold_until: Option, + /// When its run was started for it: a run of the ticket that began + /// after this is the one it waits on. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub claimed_at: Option, + /// What the page says after a person ended its fix run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub release_note: Option, /// A line for the timeline when something changed (not stored). #[serde(skip)] pub event: Option, @@ -136,6 +164,9 @@ impl Record { guard_attempts: 0, drafted: false, guard_sig: String::new(), + hold_until: None, + claimed_at: None, + release_note: None, } } @@ -158,7 +189,11 @@ impl Record { if !self.refused.is_empty() { o.insert("refused".into(), json!(self.refused)); o.insert("drafted".into(), json!(self.drafted)); - if self.drafted { + let closed = self.pr.as_ref().is_some_and(|p| p.state == "closed"); + if closed && !self.drafted { + // The round never finished: its pull request was closed. + o.insert("note".into(), json!(GUARD_CLOSED_NOTE)); + } else if self.drafted { // The guard gave up on the code change: the person // still has a correct way to apply the update. o["fix"]["kind"] = json!(FixKind::Runbook); @@ -171,6 +206,11 @@ impl Record { o.insert("note".into(), json!(GUARD_ROUND_NOTE)); } } + if let (Some(note), Status::Open, true) = + (&self.release_note, self.status, self.refused.is_empty()) + { + o.insert("note".into(), json!(note)); + } if self.status == Status::PrOpen && self.pr.as_ref().is_some_and(|p| p.state == "merged") { @@ -185,6 +225,9 @@ impl Record { pub const GUARD_ROUND_NOTE: &str = "CoderHelm read its own change and it would have replaced or destroyed a resource that holds data. One fix round is correcting the lines below; the change is read again when it ends."; /// What the page says once the guard tripped twice. pub const GUARD_DRAFT_NOTE: &str = "The pull request is kept as a draft with the reason at the top of its description, and is never merged as it is. Nothing was applied."; +/// What the page says when the pull request was closed while the guard's +/// refusal stood. +pub const GUARD_CLOSED_NOTE: &str = "The pull request was closed. CoderHelm had read its own change and it would have replaced or destroyed a resource that holds data, so no new attempt starts by itself until the code that defines the resource or the update's target changes."; /// When CoderHelm tries the code change again. pub const GUARD_STOPPED: &str = "CoderHelm makes no further attempt until the code that defines the resource or the update's target changes."; @@ -256,6 +299,248 @@ impl Record { } } +// ── The claim: fixing and pr_open follow GitHub and the run ───────────── + +use crate::security_release::{self as rel, Change, Claim, OpenPr, PrNow, RunNow, Standing}; + +impl Record { + /// Whether the hold a closed pull request or an ended run left is on: + /// no fix run starts by itself. + pub fn on_hold(&self, now: DateTime) -> bool { + self.hold_until + .as_deref() + .and_then(crate::security_fixes::parse_time) + .is_some_and(|t| t > now) + } + + /// The run claims the finding from `at`: a run of its ticket that + /// began after this is the one it waits on. + pub fn claim(&mut self, ticket: &str, at: DateTime) { + self.status = Status::Fixing; + self.ticket = ticket.to_string(); + self.claimed_at = Some(at.to_rfc3339()); + self.hold_until = None; + self.release_note = None; + } + + fn released(&mut self, hold_days: i64, now: DateTime) { + self.status = Status::Open; + self.ticket.clear(); + self.claimed_at = None; + self.hold_until = Some((now + Duration::days(hold_days)).to_rfc3339()); + self.updated_at = now.to_rfc3339(); + } + + fn pr_is(&self, state: &str) -> bool { + self.pr.as_ref().is_some_and(|p| p.state == state) + } +} + +impl Claim for Record { + fn id(&self) -> &str { + &self.finding.id + } + fn repo(&self) -> &str { + self.finding + .fix + .location + .as_ref() + .map(|l| l.repo.as_str()) + .unwrap_or("") + } + fn pr(&self) -> Option<(u64, &str)> { + self.pr.as_ref().map(|p| (p.number, p.state.as_str())) + } + fn ticket(&self) -> Option<&str> { + (!self.ticket.is_empty()).then_some(self.ticket.as_str()) + } + fn standing(&self) -> Standing { + match self.status { + Status::Open => Standing::Open, + Status::Fixing => Standing::Fixing, + Status::PrOpen => Standing::InPr, + Status::Fixed => Standing::Fixed, + Status::AwsManaged | Status::Dismissed => Standing::Other, + } + } + /// An open pull request and a draft the guard held are read every + /// sweep (either can be closed or merged on GitHub); a closed one while + /// its hold is on (a person may reopen it); a merged one never again. + fn watches_pr(&self, now: DateTime) -> bool { + match self.pr.as_ref().map(|p| p.state.as_str()) { + Some("open" | "draft") => true, + Some("closed") => { + self.status == Status::Open && self.on_hold(now) && self.refused.is_empty() + } + _ => false, + } + } + fn claimed_at(&self) -> Option> { + let parse = crate::security_fixes::parse_time; + self.claimed_at + .as_deref() + .and_then(parse) + .or_else(|| parse(&self.updated_at)) + } + /// The one fix round after a tripped guard works on the open pull + /// request: if that run ends without settling it, the run decides. + fn run_decides_with_pr(&self) -> bool { + self.status == Status::Fixing && self.pr_is("open") + } + /// A pull request is recorded only after the replacement guard read it. + fn opens_through_store(&self) -> bool { + true + } + + /// - Merged: recorded as merged. The finding stays open until a read of + /// the account sees the new version; a merge alone never closes one. + /// - Closed unmerged: the finding is open again with who closed it and + /// when; no fix run starts by itself for + /// [`rel::HOLD_DAYS_CLOSED`] days, and a guard refusal that stood + /// keeps standing. A person asking never waits. + /// - A draft the guard held is not closed: left as it is while GitHub + /// has it open. Closed on GitHub, the record says so and the finding + /// keeps its runbook. + /// - Reopened: the finding is in the pull request again, unless the + /// guard had refused its change or the finding moved on. + fn settle_pr(&mut self, pr_now: &PrNow, now: DateTime) -> Option { + let pr = self.pr.clone()?; + let gone = PrNow::Closed(rel::Closer::default()); + let pr_now = match pr_now { + PrNow::Gone => &gone, + other => other, + }; + match (pr.state.as_str(), pr_now) { + ("open" | "draft", PrNow::Merged) => { + self.pr = Some(PrRef { + state: "merged".into(), + ..pr.clone() + }); + if self.status == Status::Fixing { + self.status = Status::PrOpen; + } + self.updated_at = now.to_rfc3339(); + rel::change( + format!( + "PR #{} merged: the finding closes when CoderHelm reads the account again and sees the new version running", + pr.number + ), + &pr.url, + ) + } + ("open" | "draft", PrNow::Closed(closer)) => { + let (at, by, person) = rel::closed_record(closer, now); + self.pr = Some(PrRef { + state: "closed".into(), + closed_at: Some(at), + closed_by: by, + closed_by_person: person, + ..pr.clone() + }); + let words = rel::closed_words(pr.number, closer); + let then = if pr.state == "draft" { + "; the finding keeps its runbook" + } else if !matches!(self.status, Status::PrOpen | Status::Fixing) { + "" + } else { + self.released(rel::HOLD_DAYS_CLOSED, now); + if self.guard_blocks() { + "; CoderHelm's own check had refused the change, so no new attempt starts by itself until the code or the target changes. Ask for a fix to try again" + } else { + "; automatic fixes wait 7 days. Ask for a fix to open a new pull request now" + } + }; + self.updated_at = now.to_rfc3339(); + rel::change(format!("{words}{then}"), &pr.url) + } + ("closed", PrNow::Open) => { + let moved_on = self.status != Status::Open + || !self.ticket.is_empty() + || !self.refused.is_empty() + || self.drafted; + if moved_on { + return None; + } + self.pr = Some(PrRef { + state: "open".into(), + closed_at: None, + closed_by: None, + closed_by_person: false, + ..pr.clone() + }); + self.status = Status::PrOpen; + self.hold_until = None; + self.release_note = None; + self.updated_at = now.to_rfc3339(); + rel::change( + format!("PR #{} was reopened: the fix is in it again", pr.number), + &pr.url, + ) + } + _ => None, + } + } + + /// - The run is queued or working: left alone. + /// - The run ended with no pull request: the finding is open again, + /// held as a dependency finding is ([`rel::run_end`]). + /// - The fix round after a tripped guard ended and the refused change + /// still stands on its open pull request: the guard's second step. + /// The finding falls back to its runbook, its pull request is + /// recorded as a draft (the caller makes it one on GitHub), and no + /// further attempt starts by itself. + /// - A pull request found on the branch that the record does not have + /// is never recorded here: it goes through the store's opening path, + /// where the guard reads it first. + fn settle_run( + &mut self, + run: &RunNow, + open_pr: Option<&OpenPr>, + now: DateTime, + ) -> Option { + if self.status != Status::Fixing { + return None; + } + let known = self.pr.clone().filter(|p| p.state == "open"); + if open_pr.is_some_and(|o| known.as_ref().is_none_or(|p| p.number != o.number)) { + return None; + } + let end = rel::run_end(run, Claim::claimed_at(self), now)?; + let Some(pr) = known else { + self.released(end.hold_days, now); + self.release_note = end.waiting; + return rel::change(end.text, ""); + }; + if self.refused.is_empty() { + // Nothing was refused: the pull request stands. + self.status = Status::PrOpen; + self.ticket.clear(); + self.claimed_at = None; + self.updated_at = now.to_rfc3339(); + return rel::change(format!("PR #{} is open", pr.number), &pr.url); + } + self.guard_attempts = self.guard_attempts.max(2); + self.drafted = true; + self.status = Status::Open; + self.ticket.clear(); + self.claimed_at = None; + self.pr = Some(PrRef { + state: "draft".into(), + ..pr.clone() + }); + self.updated_at = now.to_rfc3339(); + rel::change( + format!( + "PR #{} is now a draft: the fix round ended without correcting the change, which would still replace or destroy a resource that holds data ({}). The finding shows its runbook. {}", + pr.number, + self.refused.join("; "), + GUARD_STOPPED + ), + &pr.url, + ) + } +} + /// The ticket of the one fix round after a tripped guard: the finding's /// own ticket, then each offending line and what to produce instead. pub fn fix_round_body(r: &Record) -> String { @@ -692,6 +977,7 @@ mod tests { number: 7, url: "u".into(), state: "merged".into(), + ..Default::default() }); let again = reconcile( &stored, @@ -715,6 +1001,261 @@ mod tests { .any(|r| r.finding.id == "a" && r.status == Status::Open)); } + // ── The claim (`security_release::Claim`) ── + + use crate::security_release::{Claim, Closer, OpenPr, PrNow, RunNow, Standing}; + + const WHY: &str = "db/main.tf: `identifier` changes, which replaces the database"; + + /// A finding with a pull request to open, in a run or a pull request. + fn claimed(status: Status, pr_state: Option<&str>) -> Record { + let mut x = f("a", FixKind::Pr); + x.fix.to = "16.6".into(); + x.fix.location = Some(crate::infra_vuln::inventory::Location { + repo: "acme/infra".into(), + file: "db/main.tf".into(), + ..Default::default() + }); + let mut r = Record::new(x, "2026-11-09T12:00:00Z"); + r.status = status; + r.ticket = "SEC-0A1B2C3D4E5F".into(); + r.claimed_at = Some("2026-11-10T11:00:00Z".into()); + r.pr = pr_state.map(|st| PrRef { + number: 7, + url: "https://github.com/acme/infra/pull/7".into(), + state: st.into(), + ..Default::default() + }); + r + } + + fn by(login: &str) -> PrNow { + PrNow::Closed(Closer { + by: login.into(), + person: true, + at: Some("2026-11-10T11:30:00Z".into()), + }) + } + + fn cancelled() -> RunNow { + RunNow::Ended { + status: "cancelled".into(), + by: Some("dev@example.com".into()), + } + } + + #[test] + fn a_pull_request_a_person_closed_gives_the_finding_back_with_who_and_when() { + let mut r = claimed(Status::PrOpen, Some("open")); + let c = r.settle_pr(&by("octo"), now()).unwrap(); + assert_eq!((r.status, r.standing()), (Status::Open, Standing::Open)); + let pr = r.pr.clone().unwrap(); + assert_eq!( + ( + pr.number, + pr.state.as_str(), + pr.closed_by.as_deref(), + pr.closed_by_person + ), + (7, "closed", Some("octo"), true) + ); + assert_eq!(pr.closed_at.as_deref(), Some("2026-11-10T11:30:00Z")); + assert!(r.ticket.is_empty() && r.claimed_at.is_none()); + // No run starts by itself for a week; the page gets the record. + assert!(r.on_hold(now()) && r.on_hold(now() + Duration::days(6))); + assert!(!r.on_hold(now() + Duration::days(8))); + assert!(c.text.contains("PR #7 was closed without merging by octo")); + assert!(c + .text + .contains("Ask for a fix to open a new pull request now")); + let v = r.view(); + assert_eq!(v["status"], "open"); + assert_eq!(v["pr"]["state"], "closed"); + assert_eq!(v["pr"]["closed_by"], "octo"); + assert_eq!(v["pr"]["closed_by_person"], true); + // The same fact again: nothing. + let after = r.clone(); + assert!(r.settle_pr(&by("octo"), now()).is_none()); + assert_eq!(r, after); + // Gone from GitHub releases too; GitHub not answering never does. + let mut gone = claimed(Status::PrOpen, Some("open")); + assert!(gone.settle_pr(&PrNow::Unknown, now()).is_none()); + let c = gone.settle_pr(&PrNow::Gone, now()).unwrap(); + assert_eq!(gone.status, Status::Open); + assert!(c.text.starts_with("PR #7 is no longer on GitHub")); + } + + #[test] + fn a_merge_is_recorded_and_never_closes_the_finding() { + let mut r = claimed(Status::PrOpen, Some("open")); + let c = r.settle_pr(&PrNow::Merged, now()).unwrap(); + // Only a read of the account closes it. + assert_eq!(r.status, Status::PrOpen); + assert_eq!(r.pr.as_ref().unwrap().state, "merged"); + assert!(c.text.contains("reads the account again")); + assert!(r.view()["note"] + .as_str() + .unwrap() + .contains("waiting for the new version")); + assert!(!r.watches_pr(now())); + assert!(r.settle_pr(&PrNow::Merged, now()).is_none()); + assert!(r.settle_pr(&by("octo"), now()).is_none()); + } + + #[test] + fn a_draft_the_guard_held_is_not_closed_and_keeps_its_runbook() { + let mut r = claimed(Status::Open, Some("draft")); + r.ticket.clear(); + r.guard_step(&[WHY.to_string()]); + r.guard_step(&[WHY.to_string()]); + assert!(r.drafted && r.guard_blocks()); + let before = r.clone(); + // GitHub has a draft as open: the record is left exactly as it is. + assert!(r.watches_pr(now())); + assert!(r.settle_pr(&PrNow::Open, now()).is_none()); + assert_eq!(r, before); + // A person closes the draft: recorded, and the finding still falls + // back to its runbook with no attempt by itself. + let c = r.settle_pr(&by("octo"), now()).unwrap(); + assert_eq!(r.pr.as_ref().unwrap().state, "closed"); + assert_eq!(r.status, Status::Open); + assert!(r.drafted && r.guard_blocks() && r.hold_until.is_none()); + assert!( + c.text.ends_with("the finding keeps its runbook"), + "{}", + c.text + ); + assert_eq!(r.view()["fix"]["kind"], "runbook"); + // Reopening it does not put the refused change back as the fix. + assert!(!r.watches_pr(now())); + assert!(r.settle_pr(&PrNow::Open, now()).is_none()); + // Its code or target changed: the refusal no longer stands. + r.finding.fix.to = "16.7".into(); + assert!(!r.guard_blocks()); + } + + #[test] + fn a_reopened_pull_request_takes_the_finding_back_unless_it_moved_on() { + let mut r = claimed(Status::PrOpen, Some("open")); + r.settle_pr(&by("octo"), now()).unwrap(); + assert!(r.watches_pr(now())); + let c = r.settle_pr(&PrNow::Open, now()).unwrap(); + assert_eq!(r.status, Status::PrOpen); + let pr = r.pr.clone().unwrap(); + assert_eq!( + (pr.state.as_str(), pr.closed_by, pr.closed_at), + ("open", None, None) + ); + assert!(r.hold_until.is_none() && c.text.contains("reopened")); + // A new run took the finding in between: it is not pulled back. + let mut r = claimed(Status::PrOpen, Some("open")); + r.settle_pr(&by("octo"), now()).unwrap(); + r.claim("SEC-0A1B2C3D4E5F", now()); + assert!(r.hold_until.is_none(), "a claim ends the hold"); + assert!(r.settle_pr(&PrNow::Open, now()).is_none()); + assert_eq!(r.status, Status::Fixing); + } + + #[test] + fn a_run_that_ended_without_a_pull_request_releases_the_finding() { + let mut r = claimed(Status::Fixing, None); + assert!(r.settle_run(&RunNow::Working, None, now()).is_none()); + assert!(r.settle_run(&RunNow::Unknown, None, now()).is_none()); + // Claimed an hour ago with no run on record: still in the queue. + assert!(r.settle_run(&RunNow::Missing, None, now()).is_none()); + let c = r.settle_run(&cancelled(), None, now()).unwrap(); + assert_eq!(r.status, Status::Open); + assert!(r.ticket.is_empty()); + assert!(r.on_hold(now() + Duration::days(6))); + assert!(c.text.contains("cancelled by dev@example.com")); + assert_eq!( + r.view()["note"], + "The fix run was cancelled by dev@example.com. Ask for a fix to start a new one." + ); + assert!(r.settle_run(&cancelled(), None, now()).is_none()); + // A run that failed: tried again tomorrow. + let mut r = claimed(Status::Fixing, None); + let failed = RunNow::Ended { + status: "failed".into(), + by: None, + }; + r.settle_run(&failed, None, now()).unwrap(); + assert!(r.on_hold(now() + Duration::hours(23))); + assert!(!r.on_hold(now() + Duration::hours(25))); + assert_eq!(r.view().get("note"), None); + } + + #[test] + fn a_pull_request_the_record_never_learned_goes_through_the_guard_not_this_rule() { + let mut r = claimed(Status::Fixing, None); + assert!(r.opens_through_store()); + let found = OpenPr { + number: 9, + url: "https://github.com/acme/infra/pull/9".into(), + }; + let before = r.clone(); + assert!(r.settle_run(&cancelled(), Some(&found), now()).is_none()); + assert_eq!(r, before, "nothing is recorded before the guard reads it"); + } + + #[test] + fn a_fix_round_that_ends_without_settling_is_the_guards_second_step() { + // The guard tripped once: the round works on the open pull request. + let mut r = claimed(Status::Fixing, Some("open")); + assert_eq!(r.guard_step(&[WHY.to_string()]), GuardStep::FixRound); + assert!(r.run_decides_with_pr()); + let same = OpenPr { + number: 7, + url: "https://github.com/acme/infra/pull/7".into(), + }; + assert!(r.settle_run(&RunNow::Working, Some(&same), now()).is_none()); + // The round was cancelled: the refused change still stands. + let c = r.settle_run(&cancelled(), Some(&same), now()).unwrap(); + assert_eq!(r.status, Status::Open); + assert_eq!(r.pr.as_ref().unwrap().state, "draft"); + assert!(r.drafted && r.guard_blocks() && r.ticket.is_empty()); + assert!(c.text.contains("PR #7 is now a draft") && c.text.contains(WHY)); + assert!(c.text.contains(GUARD_STOPPED)); + assert_eq!(r.view()["fix"]["kind"], "runbook"); + assert_eq!(r.view()["note"], GUARD_DRAFT_NOTE); + assert!(r.settle_run(&cancelled(), Some(&same), now()).is_none()); + } + + #[test] + fn a_pull_request_closed_during_the_fix_round_keeps_the_refusal_standing() { + let mut r = claimed(Status::Fixing, Some("open")); + r.guard_step(&[WHY.to_string()]); + let c = r.settle_pr(&by("octo"), now()).unwrap(); + assert_eq!(r.status, Status::Open); + assert!(r.guard_blocks() && !r.drafted); + assert!(c.text.contains("had refused the change"), "{}", c.text); + assert_eq!(r.view()["note"], GUARD_CLOSED_NOTE); + // Not watched for a reopen: the refused change is never the fix. + assert!(!r.watches_pr(now())); + } + + #[test] + fn records_stored_before_these_fields_read_as_before() { + // A record as it was stored before: none of the new fields. + let mut old = claimed(Status::PrOpen, Some("open")); + old.claimed_at = None; + old.event = None; + let stored = serde_json::to_value(&old).unwrap(); + for k in ["hold_until", "claimed_at", "release_note"] { + assert!(stored.get(k).is_none(), "{k}"); + } + for k in ["closed_at", "closed_by", "closed_by_person"] { + assert!(stored["pr"].get(k).is_none(), "{k}"); + } + let back: Record = serde_json::from_value(stored).unwrap(); + assert_eq!(back, old); + // Its claim time falls back to its last write. + assert_eq!( + Claim::claimed_at(&back), + crate::security_fixes::parse_time("2026-11-09T12:00:00Z") + ); + } + #[test] fn aws_managed_rows_never_count_as_open() { let r = reconcile( diff --git a/services/common/src/security_release.rs b/services/common/src/security_release.rs index 223f315aa..5204e671a 100644 --- a/services/common/src/security_release.rs +++ b/services/common/src/security_release.rs @@ -17,6 +17,16 @@ //! 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. +//! +//! Two stores keep such claims: dependency findings (`SECFINDING#`, here) +//! and infrastructure findings (`INFRAFINDING#`, `infra_vuln::records`). +//! Both are a [`Claim`]: the worker's reconciliation, the events and the +//! bounds are written once against it, and the words and holds +//! ([`closed_words`], [`run_end`]) are shared, so the two cannot drift. +//! What differs stays with each store: a merged pull request fixes a +//! dependency finding, while an infrastructure finding is fixed only when +//! AWS is read again; and an infrastructure pull request the replacement +//! guard made a draft is neither open nor closed. use chrono::{DateTime, Duration, Utc}; @@ -93,7 +103,7 @@ pub struct Change { pub link: Option, } -fn change(text: String, link: &str) -> Option { +pub(crate) fn change(text: String, link: &str) -> Option { Some(Change { text, link: (!link.is_empty()).then(|| link.to_string()), @@ -119,6 +129,81 @@ pub fn watches_pr(f: &Finding, st: &FindingState, now: DateTime) -> bool { } } +/// "PR #12 was closed without merging by octo", or "PR #12 is no longer on +/// GitHub" for one that is gone ([`PrNow::Gone`], a closer nobody named). +pub fn closed_words(number: u64, closer: &Closer) -> String { + if !closer.person && closer.by.is_empty() && closer.at.is_none() { + return format!("PR #{number} is no longer on GitHub"); + } + let who = match (closer.person, closer.by.is_empty()) { + (true, false) => format!(" by {}", closer.by), + (false, _) => " by CoderHelm".to_string(), + (true, true) => String::new(), + }; + format!("PR #{number} was closed without merging{who}") +} + +/// The record a closed pull request leaves: when, who, and whether that +/// was a person. The same three fields on both stores' pull requests. +pub fn closed_record(closer: &Closer, now: DateTime) -> (String, Option, bool) { + ( + closer.at.clone().unwrap_or_else(|| now.to_rfc3339()), + (!closer.by.is_empty()).then(|| closer.by.clone()), + closer.person, + ) +} + +/// What a run that is over with no pull request means for the finding it +/// claimed: how long automatic fixes wait, the timeline's line, and what +/// the page says while it waits (when a person ended the run). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunEnd { + pub hold_days: i64, + pub text: String, + pub waiting: Option, +} + +/// Whether a `fixing` claim is released, from what became of its run. +/// `claimed`: when the run was started for it. `None`: the run is queued +/// or working, could not be read, or may still be in the queue. +pub fn run_end(run: &RunNow, claimed: Option>, now: DateTime) -> Option { + let by_itself = || RunEnd { + hold_days: HOLD_DAYS_RUN_ENDED, + text: "The fix run ended without a pull request; it is tried again tomorrow".to_string(), + waiting: None, + }; + match run { + RunNow::Working | RunNow::Unknown => None, + RunNow::Ended { status, by } => { + if !crate::run_status::ended_by_person(status) { + return Some(by_itself()); + } + 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" + }; + Some(RunEnd { + hold_days: HOLD_DAYS_CLOSED, + text: 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" + ), + waiting: Some(format!( + "The fix run was {word}{who}. Ask for a fix to start a new one." + )), + }) + } + RunNow::Missing => claimed + .is_none_or(|t| now - t > Duration::hours(NO_RUN_GRACE_HOURS)) + .then(by_itself), + } +} + /// Brings a finding in line with its pull request. `None` when nothing /// changed (so a second call with the same fact writes nothing). /// @@ -146,7 +231,6 @@ pub fn settle_pr( 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 => { @@ -172,11 +256,12 @@ pub fn settle_pr( if pr.state != "open" { return None; } + let (at, by, person) = closed_record(closer, now); 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, + closed_at: Some(at), + closed_by: by, + closed_by_person: person, ..pr.clone() }); let was_in_it = f.status == Status::PrOpen; @@ -189,11 +274,6 @@ pub fn settle_pr( 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" @@ -201,12 +281,10 @@ pub fn settle_pr( } 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) + change( + format!("{}{then}", closed_words(pr.number, closer)), + &pr.url, + ) } PrNow::Open => { if pr.state != "closed" { @@ -237,6 +315,9 @@ pub fn settle_pr( } } +/// Minutes a run may have begun before its claim was written and still be +/// the claim's run: the two are written on different clocks. +pub const RUN_CLOCK_TOLERANCE_MINS: i64 = 10; /// 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 @@ -318,51 +399,11 @@ pub fn settle_run( 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, - ) - } - }; + let RunEnd { + hold_days: days, + text, + waiting, + } = run_end(run, claimed_at(f, st), now)?; f.status = Status::Open; f.waiting = waiting; st.ticket = None; @@ -373,6 +414,108 @@ pub fn settle_run( change(text, "") } +// ── One reconciliation for both stores ────────────────────────────────── + +/// Where a claim stands, for counting what a reconciliation did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Standing { + Open, + Fixing, + InPr, + Fixed, + Other, +} + +/// The open pull request found on a run's branch. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct OpenPr { + pub number: u64, + pub url: String, +} + +/// A stored finding that a fix run or a pull request can claim. The +/// worker's reconciliation reads GitHub and the run records and applies +/// them through this, whichever store the finding lives in. +pub trait Claim { + fn id(&self) -> &str; + /// `owner/name` of the repository its pull request is in. + fn repo(&self) -> &str; + /// Its pull request as recorded: the number and the state. + fn pr(&self) -> Option<(u64, &str)>; + /// The fix run's ticket, while a run or its pull request has it. + fn ticket(&self) -> Option<&str>; + fn standing(&self) -> Standing; + /// Whether the sweep reads its pull request (see [`watches_pr`]). + fn watches_pr(&self, now: DateTime) -> bool; + /// When its run claimed it. + fn claimed_at(&self) -> Option>; + /// Whether what became of its run matters although its pull request is + /// open (a round still working on that pull request). Otherwise an + /// open pull request is the whole answer and the run is not read. + fn run_decides_with_pr(&self) -> bool { + false + } + /// Whether an open pull request found on its run's branch must go + /// through the store's own opening path (it has checks to make there) + /// instead of being recorded as open here. + fn opens_through_store(&self) -> bool { + false + } + fn settle_pr(&mut self, pr_now: &PrNow, now: DateTime) -> Option; + fn settle_run( + &mut self, + run: &RunNow, + open_pr: Option<&OpenPr>, + now: DateTime, + ) -> Option; +} + +impl Claim for (Finding, FindingState) { + fn id(&self) -> &str { + &self.0.id + } + fn repo(&self) -> &str { + &self.0.repo + } + fn pr(&self) -> Option<(u64, &str)> { + self.0.pr.as_ref().map(|p| (p.number, p.state.as_str())) + } + fn ticket(&self) -> Option<&str> { + self.1.ticket.as_deref() + } + fn standing(&self) -> Standing { + match self.0.status { + Status::Open | Status::NoFix => Standing::Open, + Status::Fixing => Standing::Fixing, + Status::PrOpen => Standing::InPr, + Status::Fixed => Standing::Fixed, + Status::Dismissed | Status::Withdrawn => Standing::Other, + } + } + fn watches_pr(&self, now: DateTime) -> bool { + watches_pr(&self.0, &self.1, now) + } + fn claimed_at(&self) -> Option> { + claimed_at(&self.0, &self.1) + } + fn settle_pr(&mut self, pr_now: &PrNow, now: DateTime) -> Option { + settle_pr(&mut self.0, &mut self.1, pr_now, now) + } + fn settle_run( + &mut self, + run: &RunNow, + open_pr: Option<&OpenPr>, + now: DateTime, + ) -> Option { + let pr = open_pr.map(|p| PrRef { + number: p.number, + url: p.url.clone(), + ..Default::default() + }); + settle_run(&mut self.0, &mut self.1, run, pr.as_ref(), now) + } +} + /// 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. diff --git a/services/gateway/src/routes/infra_security.rs b/services/gateway/src/routes/infra_security.rs index 1751c5be2..75a16aee3 100644 --- a/services/gateway/src/routes/infra_security.rs +++ b/services/gateway/src/routes/infra_security.rs @@ -323,7 +323,10 @@ pub fn findings_view( }) } -async fn load_records(state: &AppState, team_id: &str) -> Result, StatusCode> { +pub(crate) async fn load_records( + state: &AppState, + team_id: &str, +) -> Result, StatusCode> { Ok(rows_in( state, &state.config.settings_table_name, @@ -439,6 +442,39 @@ pub async fn fix( Ok(Json(json!({ "status": "queued", "reason": null }))) } +/// Pure: what a person's Retry of an infrastructure fix run does. When +/// the run's pull request is gone (closed unmerged, or the run ended +/// without one) and the finding still has a pull request to open, the +/// retry is a new request for the finding as it stands now: the event the +/// "Open fix PR" button queues, so the worker checks the record against +/// GitHub, plans from today's finding and opens a new pull request, never +/// the closed one. `None` (the earlier run is taken up as before) while +/// the record has an open pull request, a draft the replacement guard +/// holds, or a run working. +pub fn retry_of( + unit: &common::security_fixes::FixUnit, + found: &[Record], + team_id: &str, + by: &str, +) -> Option { + use common::infra_vuln::matching::FixKind; + let id = unit.finding_ids.first()?; + let r = found.iter().find(|r| &r.finding.id == id)?; + let gone = + r.pr.as_ref() + .is_none_or(|p| p.state == "closed" && !r.drafted); + let can = r.finding.fix.kind == Some(FixKind::Pr) + && r.finding.fix.location.is_some() + && r.status == records::Status::Open; + (gone && can).then(|| SecurityEventMessage { + team_id: team_id.to_string(), + kind: "infrastructure_fix".into(), + repo: id.clone(), + requested_by: by.to_string(), + ..Default::default() + }) +} + /// GET /api/security/infrastructure/resources pub async fn resources( State(state): State>, @@ -469,6 +505,70 @@ mod tests { use super::*; use common::infra_vuln::inventory::Kind; + #[test] + fn retry_after_a_closed_pull_request_asks_for_the_finding_again() { + use common::infra_vuln::inventory::Location; + use common::infra_vuln::matching::{Fix, FixKind, InfraFinding}; + let rec = |status: records::Status, pr_state: Option<&str>| { + let mut r = Record::new( + InfraFinding { + id: "abc".into(), + fix: Fix { + kind: Some(FixKind::Pr), + location: Some(Location { + repo: "acme/infra".into(), + file: "db/main.tf".into(), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }, + "t", + ); + r.status = status; + r.pr = pr_state.map(|st| records::PrRef { + number: 7, + url: "u".into(), + state: st.into(), + ..Default::default() + }); + r + }; + let unit = common::security_fixes::FixUnit { + repo: "acme/infra".into(), + ecosystem: records::UNIT_ECOSYSTEM.into(), + finding_ids: vec!["abc".into()], + ..Default::default() + }; + let ask = |r: Record| retry_of(&unit, &[r], "TEAM#a", "dev@example.com"); + // Closed unmerged and released, or a run that ended with none. + for r in [ + rec(records::Status::Open, Some("closed")), + rec(records::Status::Open, None), + ] { + let m = ask(r).unwrap(); + assert_eq!( + (m.kind.as_str(), m.repo.as_str(), m.requested_by.as_str()), + ("infrastructure_fix", "abc", "dev@example.com") + ); + } + // Still open, merged and waiting for AWS, a run working, a draft + // the guard holds: the earlier run is taken up as before. + assert!(ask(rec(records::Status::PrOpen, Some("open"))).is_none()); + assert!(ask(rec(records::Status::PrOpen, Some("merged"))).is_none()); + assert!(ask(rec(records::Status::Fixing, None)).is_none()); + assert!(ask(rec(records::Status::Open, Some("draft"))).is_none()); + let mut held = rec(records::Status::Open, Some("closed")); + held.drafted = true; + assert!(ask(held).is_none()); + // A runbook has no pull request to ask for. + let mut runbook = rec(records::Status::Open, None); + runbook.finding.fix.kind = Some(FixKind::Runbook); + assert!(ask(runbook).is_none()); + assert!(retry_of(&unit, &[], "TEAM#a", "dev@example.com").is_none()); + } + #[test] fn the_view_lists_resources_and_names_what_an_account_lacks() { let r = Resource { diff --git a/services/gateway/src/routes/security.rs b/services/gateway/src/routes/security.rs index b52aa85e5..dd0be4188 100644 --- a/services/gateway/src/routes/security.rs +++ b/services/gateway/src/routes/security.rs @@ -2038,6 +2038,13 @@ pub(crate) async fn retry_event( .await .ok()??; let unit: sec::FixUnit = serde_json::from_str(&s(&item, "unit")).ok()?; + // An infrastructure fix run: the same decision on its own records. + if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM { + let records = super::infra_security::load_records(state, team_id) + .await + .ok()?; + return super::infra_security::retry_of(&unit, &records, team_id, by); + } let findings = load_findings(state, team_id).await.ok()?; retry_of(&unit, &findings, team_id, ticket, by) } @@ -2050,7 +2057,8 @@ pub fn retry_of( ticket: &str, by: &str, ) -> Option { - // Infrastructure fixes and base images have their own runs. + // Infrastructure fixes decide on their own records + // (`infra_security::retry_of`); base images have their own runs. if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM || unit.ecosystem == common::base_images::ECOSYSTEM { 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 index 4a7df6751..e35eac84f 100644 --- a/services/worker/src/passes/incidents/ap_closed_pr_keeps_findings.rs +++ b/services/worker/src/passes/incidents/ap_closed_pr_keeps_findings.rs @@ -316,7 +316,7 @@ fn every_path_that_ends_a_claim_tells_the_findings() { // 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<'_, '_> {"); + let pr_now = fn_src(rel_src, " pub async fn pr_now("); assert!(pr_now.contains("return PrNow::Unknown")); assert!(pr_now.contains("is_not_found")); } diff --git a/services/worker/src/passes/incidents/as_infra_closed_pr_keeps_record.rs b/services/worker/src/passes/incidents/as_infra_closed_pr_keeps_record.rs new file mode 100644 index 000000000..b660266fa --- /dev/null +++ b/services/worker/src/passes/incidents/as_infra_closed_pr_keeps_record.rs @@ -0,0 +1,280 @@ +//! as. The same gap as `ap`, in the other store. An infrastructure finding +//! keeps its own record, and nothing released it either: a person closed +//! its fix pull request and the record stayed `pr_open`, so the +//! Infrastructure tab kept showing the closed pull request and never +//! offered "Open fix PR" again; a fix run that was cancelled or failed +//! left the record `fixing` for good (this store had no fallback at all); +//! and a reopened pull request was never noticed. Only a read of the AWS +//! account ever changed such a record. +//! +//! Guarantee: an infrastructure record is `fixing` only while its run +//! works and `pr_open` only while its pull request is open or merged. It +//! is the same reconciliation as for dependency findings, not a copy: one +//! `reconcile` over `common::security_release::Claim`, the same reads of +//! GitHub and the run records, the same events from the gateway, the same +//! sweep with its bounds, the same person-closed record and holds, the +//! same Retry. What is this store's own stays: a merged pull request +//! never closes a finding (only a read of the account does); a pull +//! request the replacement guard made a draft is not "closed" and is left +//! as it is; a finding that fell back to its runbook stays there until its +//! code or its target changes; and a pull request is recorded only after +//! the guard read it. + +use chrono::{DateTime, Duration, Utc}; +use common::infra_vuln::inventory::Location; +use common::infra_vuln::matching::{Fix, FixKind, InfraFinding}; +use common::infra_vuln::records::{self, GuardStep, PrRef, Record, Status}; +use common::security_release::{Claim, OpenPr, PrNow, RunNow}; + +use super::fixture::fn_src; +use crate::passes::infra_findings::newly_drafted; +use crate::passes::security_fixes::release::{fake::*, reconcile, Scope}; + +const REPO: &str = "acme/infra"; +const TICKET: &str = "SEC-0A1B2C3D4E5F"; +const PR: u64 = 58; +const REFUSED: &str = + "db/main.tf, line 2: `aws_db_instance.orders` changes `identifier`, which replaces the resource"; + +fn now() -> DateTime { + at("2026-11-13T10:00:00Z") +} + +/// The orders database's engine update, with a pull request to open. +fn finding() -> Record { + Record::new( + InfraFinding { + id: "orders1".into(), + name: "orders".into(), + title: "orders: PostgreSQL 16.4 is behind 16.6".into(), + fix: Fix { + kind: Some(FixKind::Pr), + to: "16.6".into(), + location: Some(Location { + repo: REPO.into(), + file: "db/main.tf".into(), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }, + "2026-11-11T08:00:00Z", + ) +} + +/// As it stood: the run's pull request open, the guard had nothing to say. +fn in_its_pull_request() -> Record { + let mut r = finding(); + r.status = Status::PrOpen; + r.ticket = TICKET.into(); + r.pr = Some(PrRef { + number: PR, + url: format!("https://github.com/{REPO}/pull/{PR}"), + state: "open".into(), + ..Default::default() + }); + r.updated_at = "2026-11-12T09:00:00Z".into(); + r +} + +/// What the page needs to offer the fix again: an open finding with a pull +/// request to make and no pull request standing in the way. +fn offers_the_fix(r: &Record) -> bool { + r.status == Status::Open + && r.view()["fix"]["kind"] == "pr" + && r.pr.as_ref().is_none_or(|p| p.state == "closed") +} + +#[tokio::test] +async fn a_closed_pull_request_gives_the_record_back_with_who_closed_it() { + let mut recs = vec![in_its_pull_request()]; + assert!(!offers_the_fix(&recs[0]), "the button was hidden"); + let github = Fake::default(); + github.pr(REPO, PR, closed_by("octo-admin")); + + // The sweep, with no webhook: one read, the record released. + let r = reconcile(&github, &mut recs, &Scope::All, now()).await; + assert_eq!((r.prs_read, r.released), (1, 1)); + let rec = &recs[0]; + assert!(offers_the_fix(rec)); + let v = rec.view(); + assert_eq!(v["pr"]["state"], "closed"); + assert_eq!(v["pr"]["closed_by"], "octo-admin"); + assert_eq!(v["pr"]["closed_at"], "2026-11-13T09:30:00Z"); + assert!(github.event_texts()[0].contains("PR #58 was closed without merging by octo-admin")); + // No run starts by itself for a week; a person asking never waits + // (`start_fixes` skips the hold only for the finding asked for). + assert!(rec.on_hold(now() + Duration::days(6))); + assert!(!rec.on_hold(now() + Duration::days(8))); + + // Idempotent, and the webhook's event ends in the same place. + let saves = github.saves(); + reconcile(&github, &mut recs, &Scope::All, now()).await; + assert_eq!(github.saves(), saves); + let mut by_event = vec![in_its_pull_request()]; + let scope = Scope::Pr { + repo: REPO.into(), + number: PR, + }; + reconcile(&github, &mut by_event, &scope, now()).await; + assert_eq!(by_event, recs); + + // Reopened by a person: the record is in it again. + github.pr(REPO, PR, PrNow::Open); + let r = reconcile(&github, &mut recs, &Scope::All, now()).await; + assert_eq!(r.attached, 1); + assert_eq!(recs[0].status, Status::PrOpen); + assert!(!recs[0].on_hold(now())); +} + +#[tokio::test] +async fn a_cancelled_or_failed_run_no_longer_keeps_the_record_fixing() { + for (status, by, days) in [ + ("cancelled", Some("admin@example.com"), 7), + ("failed", None, 1), + ] { + let mut r = finding(); + r.claim(TICKET, at("2026-11-13T09:00:00Z")); + let mut recs = vec![r]; + let runs = Fake::default(); + runs.run( + TICKET, + RunNow::Ended { + status: status.into(), + by: by.map(String::from), + }, + ); + let scope = Scope::Ticket(TICKET.into()); + let rep = reconcile(&runs, &mut recs, &scope, now()).await; + assert_eq!(rep.released, 1, "{status}"); + assert!(offers_the_fix(&recs[0]), "{status}"); + assert!(recs[0].on_hold(now() + Duration::days(days) - Duration::hours(1))); + assert!(!recs[0].on_hold(now() + Duration::days(days) + Duration::hours(1))); + } + // GitHub or the run records not answering releases nothing. + let mut r = finding(); + r.claim(TICKET, at("2026-11-13T09:00:00Z")); + let mut recs = vec![r]; + let down = Fake { + branches_down: true, + ..Default::default() + }; + reconcile(&down, &mut recs, &Scope::All, now()).await; + assert_eq!(recs[0].status, Status::Fixing); +} + +#[tokio::test] +async fn the_guards_draft_is_not_closed_and_the_runbook_stays() { + // The guard tripped twice: a draft with a hold, the finding on its + // runbook, exactly as the guard left it. + let mut r = in_its_pull_request(); + assert_eq!(r.guard_step(&[REFUSED.to_string()]), GuardStep::FixRound); + assert_eq!(r.guard_step(&[REFUSED.to_string()]), GuardStep::Draft); + r.status = Status::Open; + r.pr.as_mut().unwrap().state = "draft".into(); + let mut recs = vec![r]; + let before = recs.clone(); + let github = Fake::default(); + // GitHub says a draft is open. + github.pr(REPO, PR, PrNow::Open); + let rep = reconcile(&github, &mut recs, &Scope::All, now()).await; + assert_eq!((rep.prs_read, rep.changed(), github.saves()), (1, 0, 0)); + assert_eq!(recs, before, "a held draft is neither closed nor reopened"); + assert_eq!(recs[0].view()["fix"]["kind"], "runbook"); + assert!(!offers_the_fix(&recs[0])); + + // A person closes the draft: said, and the runbook still stands, with + // no attempt by itself, until the code or the target changes. + github.pr(REPO, PR, closed_by("octo-admin")); + reconcile(&github, &mut recs, &Scope::All, now()).await; + let r = &recs[0]; + assert_eq!(r.pr.as_ref().unwrap().state, "closed"); + assert!(r.drafted && r.guard_blocks()); + assert_eq!(r.view()["fix"]["kind"], "runbook"); + assert!(!offers_the_fix(r)); + let mut changed = r.clone(); + changed.finding.fix.to = "16.7".into(); + assert!(!changed.guard_blocks()); +} + +#[tokio::test] +async fn a_fix_round_that_dies_becomes_the_guards_second_step_never_a_ready_pull_request() { + let mut r = in_its_pull_request(); + assert_eq!(r.guard_step(&[REFUSED.to_string()]), GuardStep::FixRound); + r.status = Status::Fixing; + let mut recs = vec![r]; + let github = Fake::default(); + github.pr(REPO, PR, PrNow::Open); + github.branch_prs.lock().unwrap().insert( + TICKET.into(), + OpenPr { + number: PR, + url: "u".into(), + }, + ); + github.run( + TICKET, + RunNow::Ended { + status: "failed".into(), + by: None, + }, + ); + reconcile(&github, &mut recs, &Scope::All, now()).await; + let r = &recs[0]; + assert_eq!( + (r.status, r.pr.as_ref().unwrap().state.as_str()), + (Status::Open, "draft") + ); + assert!(r.drafted && r.guard_blocks()); + // The pull request is made a draft on GitHub too, never closed. + assert_eq!(newly_drafted(r), Some((REPO.to_string(), PR))); + let line = github.event_texts().pop().unwrap(); + assert!( + line.contains("PR #58 is now a draft") && !line.contains("closed"), + "{line}" + ); +} + +#[test] +fn one_reconciliation_serves_both_stores() { + // Both stores are a `Claim`; nothing of the rules is copied. + fn is_claim() {} + is_claim::(); + is_claim::<( + common::security_fixes::Finding, + common::security_fixes::FindingState, + )>(); + let infra = include_str!("../infra_findings.rs"); + let rel = include_str!("../security_release.rs"); + assert_eq!(rel.matches("async fn reconcile").count(), 1); + assert!(!infra.contains("async fn reconcile")); + assert!(fn_src(infra, "pub(crate) async fn release(").contains("rel::reconcile(")); + // The same reads of GitHub and the run records. + assert!(infra.contains("self.reads.pr_now(") && infra.contains("self.reads.run_now(")); + + // The sweep and the events reach this store through the same calls. + let fixes = include_str!("../security_fixes.rs"); + let tick = fn_src(fixes, "async fn team_tick("); + let at = tick.find("infra_findings::release(").expect("the sweep"); + assert!(at < tick.find("let Some(kev_map) = kev_map else").unwrap()); + let events = fn_src(fixes, "async fn event_for_team("); + assert!(events.contains("infra_findings::release(state, team_id, &cx.gh, &scope)")); + + // A person's request (the button, and Retry) checks the record against + // GitHub first, and only the finding asked for skips the hold. + let on_event = fn_src(infra, "pub async fn on_event("); + assert!( + on_event.find("release(state, team, &gh, &scope)").unwrap() + < on_event.find("start_fixes(").unwrap() + ); + let start = fn_src(infra, "async fn start_fixes("); + assert!(start.contains("if r.on_hold(Utc::now()) && !asked {")); + let gateway = include_str!("../../../../gateway/src/routes/security.rs"); + assert!(fn_src(gateway, "pub(crate) async fn retry_event(") + .contains("super::infra_security::retry_of(")); + + // A pull request is recorded only through the guard. + assert!(fn_src(infra, " async fn opened(").contains("on_pr_opened(")); + let _ = records::GUARD_STOPPED; +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index ea2a4c19f..e24b94e20 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -32,6 +32,7 @@ mod an_six_database_findings; mod ao_stopped_log_finding; mod ap_closed_pr_keeps_findings; mod ar_description_stamped_to_the_head; +mod as_infra_closed_pr_keeps_record; mod at_round_scope; mod b_open_pr_retry; mod ba_verdict_on_old_commit; diff --git a/services/worker/src/passes/infra_findings.rs b/services/worker/src/passes/infra_findings.rs index 73440e1b7..33b0267ae 100644 --- a/services/worker/src/passes/infra_findings.rs +++ b/services/worker/src/passes/infra_findings.rs @@ -10,6 +10,10 @@ //! token limits (`SECRUNS#`), one run per repository at a time, //! the policy's cadence per tier, nothing in a dry run. The run's ticket //! names the file and the Terraform address. +//! - A record is `fixing` only while its run works and `pr_open` only +//! while its pull request is open or merged (`release`): the same +//! reconciliation, events, bounds and holds as dependency findings +//! (`security_fixes::release`), on this store's records. //! - Runbook steps and AWS-managed rows are shown, never run. //! - New P0 and P1 findings post one card each, inside the day's card //! limit shared with dependency findings (`SECCARDS#`). @@ -346,8 +350,7 @@ async fn enqueue( 0, ) .await?; - r.status = Status::Fixing; - r.ticket = unit.ticket.clone(); + r.claim(&unit.ticket, Utc::now()); r.updated_at = Utc::now().to_rfc3339(); save(state, team_id, r).await; super::security_fixes::add_event( @@ -403,6 +406,12 @@ async fn start_fixes( } continue; } + // Its pull request closed unmerged, or its run ended without one: + // no new run by itself while the hold is on. A person's own + // request goes ahead. + if r.on_hold(Utc::now()) && !asked { + continue; + } // The guard refused this finding's change and the finding still // asks for the same: no new run by itself, until its code or its // target changes. A person's own request goes ahead. @@ -613,6 +622,18 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { super::review_reminder::team_installation_id(state, team).await }; if let Some(iid) = iid { + // What the record says is checked against GitHub and its run + // first: a person asking after closing the pull request (or + // pressing Retry on its run) is never told "already open". + if let Ok(gh) = crate::clients::github::GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + iid, + &state.http, + ) { + let scope = Scope::Ids(vec![msg.repo.clone()]); + recs = release(state, team, &gh, &scope).await.0; + } let (n, why) = start_fixes(state, team, iid, &cfg, &mut recs, false, Some(&msg.repo)).await; if n == 0 { @@ -631,6 +652,111 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { } } +// ── Release: fixing and pr_open follow GitHub and the run ─────────────── + +use super::security_fixes::release::{self as rel, ReleaseIo, Scope}; +use common::security_release::{OpenPr, PrNow, RunNow}; + +/// This store's edges for the shared reconciliation +/// (`security_fixes::release::reconcile`): the same reads of GitHub and the +/// run records as dependency findings, and the records' own storage. +struct Release<'a> { + reads: rel::Reads<'a>, + started: std::time::Instant, +} + +#[async_trait::async_trait] +impl ReleaseIo for Release<'_> { + async fn pr_now(&self, repo: &str, number: u64, closer: bool) -> PrNow { + self.reads.pr_now(repo, number, closer).await + } + async fn open_pr(&self, repo: &str, ticket: &str) -> Result, ()> { + self.reads.open_pr(repo, ticket).await + } + async fn run_now(&self, ticket: &str, since: Option>) -> RunNow { + self.reads.run_now(ticket, since).await + } + async fn save(&self, r: &Record) { + save(self.reads.state, self.reads.team_id, r).await; + // The guard's second step, reached because the fix round ended + // without settling the pull request: it becomes a draft on GitHub + // too, with the reason at its top. Never closed, branch kept. + if let Some((repo, number)) = newly_drafted(r) { + draft_with_reason(self.reads.gh, &repo, number, &r.refused).await; + } + } + async fn event(&self, finding_id: &str, text: &str, link: Option<&str>) { + super::security_fixes::add_event( + self.reads.state, + self.reads.team_id, + finding_id, + text, + link, + ) + .await; + } + /// A pull request the run opened that the record never learned: the + /// replacement guard reads it before anything is recorded. + async fn opened(&self, r: &mut Record, pr: &OpenPr) -> bool { + let Some(unit) = unit_for(r) else { + return false; + }; + let (state, team_id) = (self.reads.state, self.reads.team_id); + on_pr_opened(state, team_id, &unit, pr.number, &pr.url).await; + match load_records(state, team_id) + .await + .into_iter() + .find(|x| x.finding.id == r.finding.id) + { + Some(now) => { + *r = now; + true + } + None => false, + } + } + fn out_of_time(&self) -> bool { + self.started.elapsed().as_secs() >= rel::TEAM_BUDGET_SECS + } +} + +/// The pull request to make a draft on GitHub when the record was just +/// settled as the guard's second step (`Claim::settle_run`): a drafted +/// record whose pull request is recorded as a draft. Pure. +pub(crate) fn newly_drafted(r: &Record) -> Option<(String, u64)> { + let pr = r.pr.as_ref().filter(|p| p.state == "draft")?; + let repo = r.finding.fix.location.as_ref()?.repo.clone(); + (r.drafted && !r.refused.is_empty()).then_some((repo, pr.number)) +} + +/// Brings the team's infrastructure records in `scope` in line with GitHub +/// and the run records: the sweep (`Scope::All`), a pull request that +/// closed or reopened, a run a person ended, a person's request. Returns +/// the records as they stand and what was done. +pub(crate) async fn release( + state: &WorkerState, + team_id: &str, + gh: &crate::clients::github::GitHubClient, + scope: &Scope, +) -> (Vec, rel::Report) { + let mut recs = load_records(state, team_id).await; + // Most teams have no infrastructure finding in a run or a pull + // request: nothing to read then. + if !recs + .iter() + .any(|r| r.pr.is_some() || r.status == Status::Fixing) + { + return (recs, rel::Report::default()); + } + let io = Release { + reads: rel::Reads { state, team_id, gh }, + started: std::time::Instant::now(), + }; + let report = rel::reconcile(&io, &mut recs, scope, Utc::now()).await; + rel::said(team_id, "infrastructure", scope, &report); + (recs, report) +} + /// What the replacement guard says of a pull request's files /// (`(path, before, after)`): the reasons to refuse it, empty when none. pub fn guard_refusals(files: &[(String, String, String)]) -> Vec { @@ -715,8 +841,13 @@ pub(crate) fn after_guard( number, url: url.to_string(), state: state.into(), + ..Default::default() }) }; + // A pull request stands (or is held): nothing waits on a hold now. + r.hold_until = None; + r.release_note = None; + r.claimed_at = None; let event = match step { records::GuardStep::Passed => { r.status = Status::PrOpen; @@ -724,9 +855,16 @@ pub(crate) fn after_guard( format!("PR #{number} opened") } records::GuardStep::FixRound => { - // Still CoderHelm's to finish: the fix round is on its way. + // Still CoderHelm's to finish: the fix round is on its way. Its + // run starts after the delay: only a run that began from then + // on is the round (the one that opened the pull request is not). r.status = Status::Fixing; r.pr = pr("open"); + r.claimed_at = sec::parse_time(now).map(|t| { + (t + chrono::Duration::seconds(FIX_ROUND_DELAY_SECS as i64) + + chrono::Duration::minutes(common::security_release::RUN_CLOCK_TOLERANCE_MINS)) + .to_rfc3339() + }); format!( "PR #{number}: the change would replace or destroy a resource that holds data ({}). One fix round corrects it and the change is read again", reasons.join("; ") @@ -748,11 +886,16 @@ pub(crate) fn after_guard( /// The pull request becomes a draft with the reason at the top of its /// description. It is never closed and its branch is never deleted. -async fn draft_with_reason(g: &Guarded, unit: &FixUnit, number: u64, reasons: &[String]) { - let Some((owner, name)) = unit.repo.split_once('/') else { +async fn draft_with_reason( + gh: &crate::clients::github::GitHubClient, + repo: &str, + number: u64, + reasons: &[String], +) { + let Some((owner, name)) = repo.split_once('/') else { return; }; - let pr = match g.gh.get_pull_request(owner, name, number).await { + let pr = match gh.get_pull_request(owner, name, number).await { Ok(pr) => pr, Err(e) => { warn!(number, error = %e, "infra findings: the pull request could not be read to make it a draft"); @@ -761,7 +904,7 @@ async fn draft_with_reason(g: &Guarded, unit: &FixUnit, number: u64, reasons: &[ }; if !pr["draft"].as_bool().unwrap_or(false) { if let Some(node) = pr["node_id"].as_str() { - if let Err(e) = g.gh.convert_pr_to_draft(node).await { + if let Err(e) = gh.convert_pr_to_draft(node).await { warn!(number, error = %e, "infra findings: the pull request could not be made a draft"); } } @@ -769,7 +912,7 @@ async fn draft_with_reason(g: &Guarded, unit: &FixUnit, number: u64, reasons: &[ // The reason is in the description whether or not the conversion // worked: it alone keeps the pull request from being marked ready. let body = common::infra_vuln::guard::put_hold(pr["body"].as_str().unwrap_or(""), reasons); - if let Err(e) = crate::passes::description::save(&g.gh, owner, name, number, &body).await { + if let Err(e) = crate::passes::description::save(gh, owner, name, number, &body).await { warn!(number, error = %e, "infra findings: the reason could not be written on the pull request"); } } @@ -820,7 +963,7 @@ pub async fn on_pr_opened( } } (records::GuardStep::Draft, Some(g)) if !drafted => { - draft_with_reason(g, unit, number, &reasons).await; + draft_with_reason(&g.gh, &unit.repo, number, &reasons).await; drafted = true; } _ => {} @@ -1007,6 +1150,189 @@ mod tests { assert!(!code.contains(&[".update_pr", "_body("].concat())); } + // ── Release: the shared reconciliation on this store's records ── + + use crate::passes::security_fixes::release::{fake::*, reconcile}; + use common::security_release::{Claim, RunNow}; + + const TICKET: &str = "SEC-0A1B2C3D4E5F"; + + fn day() -> chrono::DateTime { + at("2026-11-13T10:00:00Z") + } + + /// A record whose fix run opened pull request 7 and the guard passed it. + fn in_pr_record(id: &str, number: u64) -> Record { + let mut r = pr_record(); + r.finding.id = id.into(); + r.ticket = TICKET.into(); + after_guard( + &mut r, + &[], + number, + "https://github.com/acme/infra/pull/7", + "2026-11-12T09:00:00Z", + ); + r.updated_at = "2026-11-12T09:00:00Z".into(); + r + } + + #[tokio::test] + async fn the_sweep_releases_a_record_whose_pull_request_a_person_closed() { + let mut recs = vec![in_pr_record("a", 7), in_pr_record("b", 8)]; + let github = Fake::default(); + github.pr("acme/infra", 7, closed_by("octo")); + github.pr("acme/infra", 8, common::security_release::PrNow::Open); + let r = reconcile(&github, &mut recs, &Scope::All, day()).await; + assert_eq!((r.prs_read, r.released), (2, 1)); + assert_eq!(recs[0].status, Status::Open); + assert_eq!( + recs[0].pr.as_ref().unwrap().closed_by.as_deref(), + Some("octo") + ); + assert_eq!(recs[1].status, Status::PrOpen); + assert!(recs[0].on_hold(day())); + assert!(github.event_texts()[0].contains("closed without merging by octo")); + // Again: read once more while the hold is on, nothing written. + let saves = github.saves(); + let again = reconcile(&github, &mut recs, &Scope::All, day()).await; + assert_eq!((again.changed(), github.saves()), (0, saves)); + // The webhook's event ends in the same place as the sweep. + let mut by_event = vec![in_pr_record("a", 7), in_pr_record("b", 8)]; + let scope = Scope::Pr { + repo: "acme/infra".into(), + number: 7, + }; + let r = reconcile(&github, &mut by_event, &scope, day()).await; + assert_eq!((r.prs_read, r.released), (1, 1)); + assert_eq!(by_event, recs); + } + + #[tokio::test] + async fn github_down_releases_nothing_and_a_merge_never_closes_the_finding() { + let mut recs = vec![in_pr_record("a", 7)]; + let before = recs.clone(); + let github = Fake::default(); + let r = reconcile(&github, &mut recs, &Scope::All, day()).await; + assert_eq!((r.changed(), github.saves()), (0, 0)); + assert_eq!(recs, before); + github.pr("acme/infra", 7, common::security_release::PrNow::Merged); + let r = reconcile(&github, &mut recs, &Scope::All, day()).await; + // Recorded, not "fixed": only a read of the account closes it, and + // no merged card is this store's to post. + assert_eq!((r.fixed, r.released, github.saves()), (0, 0, 1)); + assert_eq!(recs[0].status, Status::PrOpen); + assert_eq!(recs[0].pr.as_ref().unwrap().state, "merged"); + assert!(github.merged_cards.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_cancelled_run_releases_its_record_and_a_working_one_is_left() { + let mut a = pr_record(); + a.claim(TICKET, at("2026-11-13T09:00:00Z")); + let mut b = pr_record(); + b.finding.id = "other".into(); + b.claim("SEC-BBBBBBBBBBBB", at("2026-11-13T09:00:00Z")); + let mut recs = vec![a, b]; + let runs = Fake::default(); + runs.run( + TICKET, + RunNow::Ended { + status: "cancelled".into(), + by: Some("dev@example.com".into()), + }, + ); + runs.run("SEC-BBBBBBBBBBBB", RunNow::Working); + let r = reconcile(&runs, &mut recs, &Scope::Ticket(TICKET.into()), day()).await; + assert_eq!((r.runs_read, r.released), (1, 1)); + assert_eq!(recs[0].status, Status::Open); + assert!(recs[0].on_hold(day()) && recs[0].ticket.is_empty()); + let r = reconcile(&runs, &mut recs, &Scope::All, day()).await; + assert_eq!((r.runs_read, r.changed()), (1, 0)); + assert_eq!(recs[1].status, Status::Fixing); + } + + #[tokio::test] + async fn a_pull_request_the_record_never_learned_is_read_by_the_guard_first() { + let mut a = pr_record(); + a.claim(TICKET, at("2026-11-13T09:00:00Z")); + let mut recs = vec![a]; + let github = Fake::default(); + github.branch_prs.lock().unwrap().insert( + TICKET.into(), + OpenPr { + number: 9, + url: "https://github.com/acme/infra/pull/9".into(), + }, + ); + let before = recs.clone(); + reconcile(&github, &mut recs, &Scope::All, day()).await; + // Handed to the store's opening path (the guard); nothing recorded + // by the shared rule, and the run was not even asked. + assert_eq!( + *github.opened_through_store.lock().unwrap(), + vec![("abc".to_string(), 9)] + ); + assert_eq!(recs, before); + assert_eq!(github.saves(), 0); + assert!(github.run_reads.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_fix_round_that_ended_makes_the_pull_request_a_draft_and_a_draft_is_never_closed() { + // The guard tripped once: the round is to start in five minutes, + // and only a run that begins from then on is the round. + let mut r = pr_record(); + r.ticket = TICKET.into(); + let (step, _) = after_guard(&mut r, &[WHY.to_string()], 7, "u", "2026-11-13T09:00:00Z"); + assert_eq!(step, records::GuardStep::FixRound); + assert_eq!(Claim::claimed_at(&r), Some(at("2026-11-13T09:15:00Z"))); + assert_eq!(newly_drafted(&r), None); + let mut recs = vec![r]; + let github = Fake::default(); + github.branch_prs.lock().unwrap().insert( + TICKET.into(), + OpenPr { + number: 7, + url: "u".into(), + }, + ); + github.pr("acme/infra", 7, common::security_release::PrNow::Open); + // The round works: nothing changes. + github.run(TICKET, RunNow::Working); + let rep = reconcile(&github, &mut recs, &Scope::All, day()).await; + assert_eq!((rep.changed(), github.saves()), (0, 0)); + assert_eq!(github.run_reads.lock().unwrap().len(), 1, "the run decides"); + // The round was cancelled: the refused change still stands, so the + // pull request is to be made a draft and the finding falls back. + github.run( + TICKET, + RunNow::Ended { + status: "cancelled".into(), + by: None, + }, + ); + reconcile(&github, &mut recs, &Scope::Ticket(TICKET.into()), day()).await; + let r = &recs[0]; + assert_eq!( + (r.status, r.pr.as_ref().unwrap().state.as_str()), + (Status::Open, "draft") + ); + assert!(r.drafted && r.guard_blocks()); + assert_eq!(newly_drafted(r), Some(("acme/infra".to_string(), 7))); + assert!(github + .event_texts() + .last() + .unwrap() + .contains("PR #7 is now a draft")); + // From then on the draft is read every sweep and left as it is: + // open on GitHub is not closed, and never "reopened" either. + let saves = github.saves(); + let rep = reconcile(&github, &mut recs, &Scope::All, day()).await; + assert_eq!((rep.prs_read, rep.changed(), github.saves()), (1, 0, saves)); + assert_eq!(recs[0].pr.as_ref().unwrap().state, "draft"); + } + #[test] fn the_guard_reads_a_pull_requests_files_before_and_after() { let before = "resource \"aws_db_instance\" \"orders\" {\n identifier = \"orders-prod\"\n engine_version = \"16.4\"\n}\n"; diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index 2bfe56c7a..4dfb3fdde 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -2326,11 +2326,10 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) { p.ci = ci.clone().or(p.ci); match state_now.as_str() { "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; + let v = io.reads().pr_now(&f.repo, pr.number, true).await; facts.insert(key.clone(), v.clone()); v } @@ -3610,6 +3609,11 @@ async fn team_tick( ) .await .changed(); + // ...and so are its infrastructure records, by the same reconciliation. + report.released += super::infra_findings::release(state, team_id, &cx.gh, &release::Scope::All) + .await + .1 + .changed(); let Some(kev_map) = kev_map else { return Ok(report); }; @@ -4177,7 +4181,11 @@ async fn event_for_team( 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"); + // The same event for the team's infrastructure records. + let infra = super::infra_findings::release(state, team_id, &cx.gh, &scope) + .await + .1; + info!(team_id, kind = %msg.kind, repo = %msg.repo, pr = msg.pr_number, ticket = %msg.ticket, changed = r.changed(), infrastructure = infra.changed(), "security: release event handled"); return Ok(()); } // A person pressed Retry on a fix run whose pull request is gone: diff --git a/services/worker/src/passes/security_release.rs b/services/worker/src/passes/security_release.rs index e0169d397..5f8ef9736 100644 --- a/services/worker/src/passes/security_release.rs +++ b/services/worker/src/passes/security_release.rs @@ -12,6 +12,13 @@ //! went stale before these paths existed) is put right within one sweep, //! whatever the rest of the sweep has to do. //! +//! Dependency findings and infrastructure findings are both a +//! `common::security_release::Claim`, so there is one `reconcile` for the +//! two stores: the same reads of GitHub and the run records (`Reads`), the +//! same bounds, the same events. Each store brings only its own storage +//! (`ReleaseIo::save`) and what is its own on the way (`ReleaseIo::merged`, +//! `ReleaseIo::opened`). +//! //! 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 @@ -21,11 +28,13 @@ 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 common::security_fixes::{Finding, FindingState, Stage}; +use common::security_release::{self as rel, Claim, Closer, OpenPr, PrNow, RunNow, Standing}; use tracing::{info, warn}; use super::{add_event, attr_s, post_card, s, save_finding, team_channels, ticket_branch, Ctx}; +use crate::clients::github::GitHubClient; +use crate::WorkerState; /// Seconds one team's reconciliation may take in a sweep. pub(crate) const TEAM_BUDGET_SECS: u64 = 45; @@ -44,15 +53,14 @@ pub(crate) enum Scope { } impl Scope { - fn has(&self, f: &Finding, st: &FindingState) -> bool { + fn has(&self, c: &C) -> 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) + c.repo().eq_ignore_ascii_case(repo) && c.pr().is_some_and(|p| p.0 == *number) } - Scope::Ticket(t) => st.ticket.as_deref() == Some(t.as_str()), - Scope::Ids(ids) => ids.contains(&f.id), + Scope::Ticket(t) => c.ticket() == Some(t.as_str()), + Scope::Ids(ids) => ids.iter().any(|id| id == c.id()), } } } @@ -82,51 +90,69 @@ impl Report { } } -/// The edges: GitHub, the run records, the findings' storage. A trait so -/// the reconciliation runs in tests on a fake GitHub and fake runs. +/// The edges: GitHub, the run records, a store's findings. A trait so the +/// reconciliation runs in tests on a fake GitHub and fake runs, and so both +/// stores (`C`: a dependency finding, or an infrastructure record) go +/// through the same `reconcile`. #[async_trait::async_trait] -pub(crate) trait ReleaseIo: Send + Sync { +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, ()>; + 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 save(&self, c: &C); 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); + /// A pull request merged and fixed its finding: its card, once. + async fn merged(&self, _c: &C) {} + /// A pull request the run opened and the store never recorded, for a + /// store that records one only through its own opening path + /// (`Claim::opens_through_store`): take it through that path and leave + /// `c` as it now stands. True when it was taken. + async fn opened(&self, _c: &mut C, _pr: &OpenPr) -> bool { + false + } 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)], +pub(crate) async fn reconcile( + io: &dyn ReleaseIo, + findings: &mut [C], scope: &Scope, now: DateTime, ) -> Report { let mut report = Report::default(); let sweep = *scope == Scope::All; + let count = |report: &mut Report, was: Standing, is: Standing| match (was, is) { + (w, Standing::Fixed) if w != Standing::Fixed => report.fixed += 1, + (Standing::InPr | Standing::Fixing, Standing::Open) => report.released += 1, + (Standing::Open | Standing::Fixing, Standing::InPr) => report.attached += 1, + _ => {} + }; // 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 }; + for c in findings.iter() { + let Some((number, state)) = c.pr() else { + continue; + }; let watched = if sweep { - rel::watches_pr(f, st, now) + c.watches_pr(now) } else { - scope.has(f, st) && p.state != "merged" + scope.has(c) && 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"; + .entry((c.repo().to_ascii_lowercase(), number)) + .or_insert_with(|| (c.repo().to_string(), false)); + // Not yet recorded as closed by some finding: a close needs + // its closer. + e.1 |= state != "closed"; } } let all: Vec<((String, u64), (String, bool))> = prs.into_iter().collect(); @@ -144,38 +170,34 @@ pub(crate) async fn reconcile( 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) { + for c in findings.iter_mut() { + let same = + c.repo().to_ascii_lowercase() == key.0 && c.pr().is_some_and(|p| p.0 == key.1); + if !same || !scope.has(c) { continue; } - let was = f.status; - let Some(change) = rel::settle_pr(f, st, &fact, now) else { + let was = c.standing(); + let Some(change) = c.settle_pr(&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, - _ => {} + io.save(c).await; + io.event(c.id(), &change.text, change.link.as_deref()).await; + count(&mut report, was, c.standing()); + if was != Standing::Fixed && c.standing() == Standing::Fixed && !carded { + io.merged(c).await; + carded = true; } } } // 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())); + for c in findings.iter() { + if c.standing() == Standing::Fixing && scope.has(c) { + tickets.insert(( + c.ticket().unwrap_or_default().to_string(), + c.repo().to_string(), + )); } } let all: Vec<(String, String)> = tickets.into_iter().collect(); @@ -190,10 +212,10 @@ pub(crate) async fn reconcile( 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 + let of_ticket = |c: &C| { + c.standing() == Standing::Fixing + && c.ticket().unwrap_or_default() == ticket.as_str() + && c.repo() == repo.as_str() }; // A finding claimed with no ticket has no run to wait on. let (open, run) = if ticket.is_empty() { @@ -203,34 +225,44 @@ pub(crate) async fn reconcile( 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 - } + // An open pull request is the whole answer, unless a round is + // still working on it and its end decides. + let decides = findings + .iter() + .any(|c| of_ticket(c) && c.run_decides_with_pr()); + let run = if open.is_some() && !decides { + RunNow::Working + } else { + let since = findings + .iter() + .filter(|c| of_ticket(c)) + .filter_map(|c| c.claimed_at()) + .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) { + for c in findings.iter_mut() { + if !of_ticket(c) || !scope.has(c) { continue; } - let Some(change) = rel::settle_run(f, st, &run, open.as_ref(), now) else { + let was = c.standing(); + if let Some(pr) = &open { + let recorded = c.pr().is_some_and(|p| p.0 == pr.number && p.1 == "open"); + if c.opens_through_store() && !recorded { + if io.opened(c, pr).await { + count(&mut report, was, c.standing()); + } + continue; + } + } + let Some(change) = c.settle_run(&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; - } + io.save(c).await; + io.event(c.id(), &change.text, change.link.as_deref()).await; + count(&mut report, was, c.standing()); } } report @@ -238,36 +270,27 @@ pub(crate) async fn reconcile( // ── 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, +/// What both stores read to know the truth: GitHub's pull requests and +/// the run records, for one team. +pub(crate) struct Reads<'a> { + pub state: &'a WorkerState, + pub team_id: &'a str, + pub gh: &'a GitHubClient, } -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(), - } - } - +impl Reads<'_> { /// 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 state = self.state; let run_id = - crate::passes::review_pr::lookup_run_by_pr(state, self.cx.team_id, owner, name, number) + crate::passes::review_pr::lookup_run_by_pr(state, self.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("team_id", attr_s(self.team_id)) .key("run_id", attr_s(&run_id)) .projection_expression("#s, closed_by_name, closed_by") .expression_attribute_names("#s", "status") @@ -285,20 +308,17 @@ impl<'a, 'c> Live<'a, 'c> { .unwrap_or_default(), ) } -} -#[async_trait::async_trait] -impl ReleaseIo for Live<'_, '_> { - async fn pr_now(&self, repo: &str, number: u64, closer: bool) -> PrNow { + pub 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 gh = self.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"); + warn!(team_id = self.team_id, repo, number, error = %e, "security: a pull request's state couldn't be read; left as it is"); return PrNow::Unknown; } }; @@ -319,28 +339,27 @@ impl ReleaseIo for Live<'_, '_> { .await } - async fn open_pr(&self, repo: &str, ticket: &str) -> Result, ()> { + pub 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 { + let Some(branch) = ticket_branch(self.state, self.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 { + match self.gh.find_open_pr_for_branch(o, n, &branch).await { + Ok(pr) => Ok(pr.map(|pr| OpenPr { 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"); + warn!(team_id = self.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; + pub async fn run_now(&self, ticket: &str, since: Option>) -> RunNow { + let state = self.state; let mut latest: Option<(String, super::Item)> = None; let mut start = None; loop { @@ -350,7 +369,7 @@ impl ReleaseIo for Live<'_, '_> { .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(":tid", attr_s(self.team_id)) .expression_attribute_values(":ticket", attr_s(ticket)) .projection_expression( "created_at, updated_at, #s, closed_by_name, cancelled_by, closed_by", @@ -361,7 +380,7 @@ impl ReleaseIo for Live<'_, '_> { .await; let Ok(out) = out else { warn!( - team_id = self.cx.team_id, + team_id = self.team_id, ticket, "security: the ticket's runs couldn't be read; left as it is" ); return RunNow::Unknown; @@ -395,16 +414,60 @@ impl ReleaseIo for Live<'_, '_> { Utc::now(), ) } +} + +/// Dependency findings' edges: the shared reads, their storage and the +/// team's channels. +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(), + } + } - async fn save(&self, f: &Finding, st: &FindingState) { - save_finding(self.cx.state, self.cx.team_id, f, st).await; + pub fn reads(&self) -> Reads<'_> { + Reads { + state: self.cx.state, + team_id: self.cx.team_id, + gh: &self.cx.gh, + } + } +} + +#[async_trait::async_trait] +impl ReleaseIo<(Finding, FindingState)> for Live<'_, '_> { + async fn pr_now(&self, repo: &str, number: u64, closer: bool) -> PrNow { + self.reads().pr_now(repo, number, closer).await + } + + async fn open_pr(&self, repo: &str, ticket: &str) -> Result, ()> { + self.reads().open_pr(repo, ticket).await + } + + async fn run_now(&self, ticket: &str, since: Option>) -> RunNow { + self.reads().run_now(ticket, since).await + } + + async fn save(&self, c: &(Finding, FindingState)) { + save_finding(self.cx.state, self.cx.team_id, &c.0, &c.1).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) { + async fn merged(&self, c: &(Finding, FindingState)) { + let (f, st) = c; if !self.cx.cfg.acts() || !st.cards.iter().any(|c| c == "new") { return; } @@ -488,7 +551,7 @@ pub(super) fn run_fact( // 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), + (Some(b), Some(s)) => b < s - chrono::Duration::minutes(rel::RUN_CLOCK_TOLERANCE_MINS), _ => false, }; if earlier { @@ -506,9 +569,17 @@ pub(super) async fn run( ) -> Report { let io = Live::new(cx, budget_secs); let report = reconcile(&io, findings, scope, Utc::now()).await; + said(cx.team_id, "dependency", scope, &report); + report +} + +/// The line a reconciliation leaves in the log when it did something or +/// left something for later. +pub(crate) fn said(team_id: &str, store: &str, scope: &Scope, report: &Report) { if report.changed() > 0 || report.left > 0 { info!( - team_id = cx.team_id, + team_id, + store, scope = ?scope, prs_read = report.prs_read, runs_read = report.runs_read, @@ -519,7 +590,6 @@ pub(super) async fn run( "security: findings brought in line with their pull requests and runs" ); } - report } #[cfg(test)] @@ -527,6 +597,7 @@ 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 common::security_fixes::{PrRef, Status}; use std::sync::Mutex; #[derive(Default)] @@ -534,12 +605,14 @@ pub(crate) mod 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>, + 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>, + /// Pull requests handed to a store's own opening path: (id, number). + pub opened_through_store: Mutex>, /// Every pull request read, in order, and those whose closer was /// asked for. pub pr_reads: Mutex>, @@ -578,7 +651,7 @@ pub(crate) mod fake { } #[async_trait::async_trait] - impl ReleaseIo for Fake { + 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()); @@ -594,7 +667,7 @@ pub(crate) mod fake { .cloned() .unwrap_or(PrNow::Unknown) } - async fn open_pr(&self, _repo: &str, ticket: &str) -> Result, ()> { + async fn open_pr(&self, _repo: &str, ticket: &str) -> Result, ()> { if self.branches_down { return Err(()); } @@ -609,8 +682,8 @@ pub(crate) mod fake { .cloned() .unwrap_or(RunNow::Missing) } - async fn save(&self, f: &Finding, _st: &FindingState) { - self.saved.lock().unwrap().push(f.id.clone()); + async fn save(&self, c: &C) { + self.saved.lock().unwrap().push(c.id().to_string()); } async fn event(&self, finding_id: &str, text: &str, _link: Option<&str>) { self.events @@ -618,8 +691,15 @@ pub(crate) mod fake { .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()); + async fn merged(&self, c: &C) { + self.merged_cards.lock().unwrap().push(c.id().to_string()); + } + async fn opened(&self, c: &mut C, pr: &OpenPr) -> bool { + self.opened_through_store + .lock() + .unwrap() + .push((c.id().to_string(), pr.number)); + true } fn out_of_time(&self) -> bool { self.time_for.is_some_and(|n| self.reads() >= n) @@ -687,6 +767,7 @@ pub(crate) mod fake { mod tests { use super::fake::*; use super::*; + use common::security_fixes::Status; const REPO: &str = "acme/web"; const TICKET: &str = "SEC-AAAAAAAAAAAA"; @@ -850,10 +931,9 @@ mod tests { let io = Fake::default(); io.branch_prs.lock().unwrap().insert( TICKET.into(), - PrRef { + OpenPr { number: 31, url: "https://github.com/acme/web/pull/31".into(), - ..Default::default() }, ); io.run(