diff --git a/docs/incidents.md b/docs/incidents.md index f57786b7d..65ef2f192 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -66,6 +66,8 @@ pipeline still calls it there. | ai. `ai_open_items_settled` | A dependency update finished completed with five Open items on its pull request for a person: the package manager's audit never ran so the advisory counts were unknown (listed twice, in different words), nothing showed that the packages an override moved still built and passed their tests, a README line claimed checks no run had made (and was still listed after a later round rewrote it), and the plan had no end-to-end checklist for a change with nothing to deploy. The coder's full checks had been refused twice for lack of time after two lockfile regenerations in one step, and nothing carried them anywhere. | A run settles its own open items before it finishes (`settle`). Each item is classified: CoderHelm runs it in its sandbox, the repository's CI settles it, it does not apply to the run, or only a person has what it needs (a reason on the human-only list). What CoderHelm can run it runs in a step with a full sandbox window, a fresh step when this one has too little time, and a check the coder was refused for lack of time is owed whether or not an item names it. A change to the dependencies is always audited by its package manager after the bumps (`common::dep_audit`, one row per manager) and the counts left are quoted. A passing result closes the item and is quoted under "Checked by CoderHelm"; a failing one takes out a dependency fix's newest verified set of bumps, or gives any other run a fix round with the real output. An end-to-end checklist is not raised for upkeep, the same missing fact is one item, every item names the head it was written on, and a run about to finish with items of an earlier head derives them again first. What stays says why. Lockfiles are regenerated once per state of the branch. | | aj. `aj_coder_habits` | A bug fix was right on its face and wrong four ways. Its plan named two files and nothing about them. The fix was written first and its test after, and the test passed with or without the fix. It rounded per line, an approach one pull request had shipped and another had reverted two months earlier, with the reason one commit list away. It changed a response field another of the team's repositories read and never named that repository. Its one real doubt (half up or half even) was listed at the bottom of the finished pull request, and a helper file no task named was reformatted along the way. | Before code, a bug's plan names the test that fails on the code as it is (or why none can and the next best proof), and that test is the first task. The worker itself reads the commits of the files the plan modifies and what depends on them (the code graph, a search of the team's other repositories for each changed name); a revert must be answered by name, and every dependent is updated by a task or called safe with the reason. A doubt that changes what is built is asked at planning time with the default the run builds. After the build each new or changed test runs with and without the change: one that passes either way, a bug's test that can't build on the base, a changed file outside the plan with no reason and a planned dependent left untouched all go back to the coder. The pull request carries the failing and the passing result, the history, and who the change affects. | | al. `al_learning_loop` | A person pushed the same fix on top of two of CoderHelm's pull requests two weeks apart, and the same reviewer asked for the same test both times. All that was kept from the first was "PR #101 was rewritten by people before merging", and nobody could say how often its pull requests were edited, closed or reverted without reading the runs. | What becomes of every pull request CoderHelm opens is counted from the webhooks, each pull request once however often an event is delivered: merged, closed, reverted, review rounds, a person's commit on top, open items. A person's edit, a close with a comment and a revert with a reason each become a lesson that names the code and says how to check a change against it, with the evidence attached. The same lesson from another pull request is counted on the kept one, and a lesson people go against loses weight until it is no longer given. What a reviewer asked for on several pull requests is given to the next build when that reviewer is likely to review it, and nothing personal is kept. A lesson seen on enough pull requests is proposed for the repository's guide file as one pull request at a time, never as a push to the default branch. | +| am. `am_description_from_the_head` | A dependency security run's pull request had the right code after a review round and the wrong description. Its table still showed the plan (five packages as major version jumps the final manifest no longer makes, a headline counting twenty major versions), its count of fixed advisories had never been compared with the final lockfile, the round that fixed the code wrote that it could not edit the description and left the corrections to a person, and the repository's second app (a CMS studio no CI job builds) took a package an override moved to a new major and was never built. | The description is a function of the head. A dependency pull request's table and headline are what the lockfile on the head resolves compared with the base branch; an advisory counts as fixed only at or past its patched version; what can't be read is said as not known and the plan is marked as a plan. Every write of a description goes through `description::save`, every path that moves the head rebuilds it through `description::head_moved`, and a round's sentence that hands the description to a person is taken out and becomes the rebuild. A sentence a run writes into a file that says a check passes needs that check's recorded passing result, or it is taken out. Every workspace project that takes a changed package line is built when its manifest declares a build, CI job or not; a project that can't be proven in the sandbox is named with why, and a build only the bumps break feeds the take-out. | +| an. `an_six_database_findings` | Security, Infrastructure showed six database findings, every one a one-command runbook with no pull request although the databases were in the team's code. The same CVE stood on an operating system update, an Aurora PostgreSQL patch and a MySQL upgrade. A database with a Terraform-generated identifier and an Aurora cluster defined through a module were "not found in code". A patch and an upgrade pending on one cluster were unrelated rows, an update on a second instance was dropped, and the account was read one page deep. | An advisory is attached only where it applies (service, engine, version range, kind of action, date); an action AWS publishes with no CVE list gets none. An action is named for what it means on its ARN. One database's pending actions are one ordered set of rows. The defining code is found from stack records, resource type and attributes, module calls and variable files, graded, and a guess never becomes a pull request. An update with a code equivalent is a pull request on the line that sets the value; one that cannot be expressed in code stays a complete runbook and says why. A change that would replace a database is refused. | | ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | | bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | | bc. `bc_stays_through_merge_and_deploy` | Pull requests were left as they were after their runs finished: one conflicted after its base moved, one went red a day later on a commit status no event carries, and one merged by a person had its production deploy fail with nothing watching. | A finished run's pull request is looked at on completion and by the sweep: a conflict starts the conflict round once per base commit, red checks not red on the base go to the fix loop once per head, and a merge by anyone gets its merge commit's deploy watched once. A deploy of CoderHelm's own change that fails on checks passing before the merge gets a revert pull request with the failing jobs as evidence, ready for the team's approval and never merged by CoderHelm; files changed again since are never overwritten. | diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index 586094918..c62e56075 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -303,6 +303,10 @@ Resources: - "es:ListDomainNames" - "es:DescribeDomains" - "ecr:DescribeImageScanFindings" + # Which stack made a resource (its name and the resource's + # logical id), where CloudFormation does not tag the resource: + # never a template, parameters or outputs. + - "cloudformation:DescribeStackResources" - "ssm:ListInventoryEntries" Resource: "*" - !Ref AWS::NoValue diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 7c6c623ce..925224189 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -376,6 +376,10 @@ Resources: - "es:ListDomainNames" - "es:DescribeDomains" - "ecr:DescribeImageScanFindings" + # Which stack made a resource (its name and the resource's + # logical id), where CloudFormation does not tag the resource: + # never a template, parameters or outputs. + - "cloudformation:DescribeStackResources" - "ssm:ListInventoryEntries" Resource: "*" # AWS's public "latest AMI" parameters only. diff --git a/services/common/src/dep_head.rs b/services/common/src/dep_head.rs new file mode 100644 index 000000000..1eca2fffb --- /dev/null +++ b/services/common/src/dep_head.rs @@ -0,0 +1,629 @@ +//! What a dependency pull request's head resolves, read from its lockfiles. +//! +//! A dependency run planned five packages as major version jumps. A review +//! round then kept each of them inside its current major with a scoped +//! override, and the code was right. The description still showed the plan: +//! its table listed the five as "(major)", its headline counted twenty major +//! versions, and its count of fixed advisories had never been compared with +//! what the final lockfile installs. +//! +//! The description of a dependency pull request is written from the head, +//! never from the plan: +//! +//! - [`resolve`] compares each lockfile on the base branch with the same +//! lockfile on the head, one answer per package and version line of the +//! plan: where the line's copies are now, whether that crosses a major +//! version, whether the line is gone, or that it did not move. +//! - [`HeadFacts::fixed`] counts an advisory as fixed only when every copy +//! left on its line is at or past the advisory's patched version (or the +//! line is no longer installed). +//! - What can't be read is said as not known ([`Resolved::Unknown`], with +//! why). The plan's numbers are then shown as a plan, never as a result. +//! +//! Everything here is pure; the worker reads the lockfiles +//! (`worker::passes::security_fixes::head_facts`). + +use std::cmp::Ordering; + +use crate::security_fixes::{ + compare_versions, in_bump, is_major_bump, version_line, Finding, FindingState, FixUnit, +}; + +/// One lockfile as the base branch and the head have it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct LockAt { + pub path: String, + /// Every copy it installs on the base branch (name, version); `None` + /// when it could not be read there. + pub base: Option>, + /// The same on the head. + pub head: Option>, + /// Why a side could not be read; empty when both were. + pub why: String, +} + +/// Where one package and version line of the plan stands on the head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Resolved { + /// The line's lowest copy moved from `from` to `to`. + Moved { + from: String, + to: String, + major: bool, + }, + /// The head installs the same version as the base branch. + NotMoved { at: String }, + /// The head no longer installs the package at all. + Removed { from: String }, + /// The lockfile could not be read on one side. + Unknown { why: String }, +} + +/// One line of the plan with what the head resolves for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeadLine { + pub package: String, + pub planned_from: String, + pub planned_to: String, + pub resolved: Resolved, +} + +/// Whether the head fixes one advisory. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fixed { + Yes, + No, + Unknown, +} + +/// What the head of a dependency pull request resolves: one [`HeadLine`] +/// per bump of the unit, in the unit's order. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct HeadFacts { + /// The head commit the lockfiles were read on. + pub sha: String, + pub lines: Vec, +} + +fn lowest<'a>(versions: impl Iterator) -> Option<&'a str> { + versions.min_by(|a, b| compare_versions(a, b)) +} + +fn versions_of<'a>(copies: &'a [(String, String)], package: &str) -> Vec<&'a str> { + copies + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(package)) + .map(|(_, v)| v.as_str()) + .collect() +} + +fn resolve_line(package: &str, planned_from: &str, lock: &LockAt) -> Resolved { + let (Some(base), Some(head)) = (&lock.base, &lock.head) else { + return Resolved::Unknown { + why: if lock.why.is_empty() { + format!("`{}` could not be read", lock.path) + } else { + lock.why.clone() + }, + }; + }; + let line = version_line(planned_from); + let on_line = |v: &&str| version_line(v) == line; + let base_all = versions_of(base, package); + let head_all = versions_of(head, package); + // The line's weakest copy on the base branch is where it starts. + let from = lowest(base_all.iter().copied().filter(on_line)) + .unwrap_or(planned_from) + .to_string(); + if head_all.is_empty() { + return Resolved::Removed { from }; + } + // Still on its line: the weakest copy left decides what is fixed. + if let Some(to) = lowest(head_all.iter().copied().filter(on_line)) { + return if compare_versions(to, &from) == Ordering::Equal { + Resolved::NotMoved { at: from } + } else { + Resolved::Moved { + major: false, + to: to.to_string(), + from, + } + }; + } + // The line is gone and the package is still installed: its copies moved + // to another line. The version the head has and the base did not is + // where they went; with none new, they joined a line already installed. + let new = lowest( + head_all + .iter() + .copied() + .filter(|v| !base_all.iter().any(|b| b == v)), + ); + let above = lowest( + head_all + .iter() + .copied() + .filter(|v| compare_versions(v, &from) == Ordering::Greater), + ); + let to = new + .or(above) + .or_else(|| lowest(head_all.iter().copied())) + .unwrap_or_default() + .to_string(); + Resolved::Moved { + major: is_major_bump(&from, &to), + from, + to, + } +} + +/// What the head resolves for each bump of `unit`. `locks`: the +/// repository's lockfiles as read on the base branch and on `sha`. +pub fn resolve(unit: &FixUnit, sha: &str, locks: &[LockAt]) -> HeadFacts { + let paths: Vec = locks.iter().map(|l| l.path.clone()).collect(); + let lines = unit + .bumps + .iter() + .map(|b| { + let lock = match crate::dep_fix::lockfile_for(&b.manifest, &paths) { + Some(p) => locks.iter().find(|l| l.path == p), + None if locks.len() == 1 => locks.first(), + None => None, + }; + let resolved = match lock { + Some(l) => resolve_line(&b.package, &b.from, l), + None => Resolved::Unknown { + why: if b.manifest.is_empty() { + "the lockfile that installs it is not known".to_string() + } else { + format!( + "the lockfile that installs it could not be told from `{}`", + b.manifest + ) + }, + }, + }; + HeadLine { + package: b.package.clone(), + planned_from: b.from.clone(), + planned_to: b.to.clone(), + resolved, + } + }) + .collect(); + HeadFacts { + sha: sha.to_string(), + lines, + } +} + +/// The facts when nothing could be read: every line unknown, with why. +pub fn unknown(unit: &FixUnit, why: &str) -> HeadFacts { + HeadFacts { + sha: String::new(), + lines: unit + .bumps + .iter() + .map(|b| HeadLine { + package: b.package.clone(), + planned_from: b.from.clone(), + planned_to: b.to.clone(), + resolved: Resolved::Unknown { + why: why.to_string(), + }, + }) + .collect(), + } +} + +fn plural(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +impl HeadFacts { + /// The table's Version cell for the unit's bump `i`. + pub fn version_cell(&self, i: usize) -> String { + match self.lines.get(i).map(|l| (&l.resolved, l)) { + Some((Resolved::Moved { from, to, major }, _)) => { + format!("{from} to {to}{}", if *major { " (major)" } else { "" }) + } + Some((Resolved::NotMoved { at }, _)) => format!("{at}, not moved on the head"), + Some((Resolved::Removed { from }, _)) => format!("{from}, no longer installed"), + Some((Resolved::Unknown { .. }, l)) => format!( + "{} to {} planned; not read from the head", + l.planned_from, l.planned_to + ), + None => "not known".to_string(), + } + } + + /// `unit` with each bump as the head resolves it: the real versions and + /// whether it crosses a major. A line that could not be read keeps the + /// plan's (the table marks it as a plan). + pub fn unit_at_head(&self, unit: &FixUnit) -> FixUnit { + let mut out = unit.clone(); + for (b, l) in out.bumps.iter_mut().zip(&self.lines) { + match &l.resolved { + Resolved::Moved { from, to, major } => { + b.from = from.clone(); + b.to = to.clone(); + b.major = *major; + } + Resolved::NotMoved { at } => { + b.from = at.clone(); + b.to = at.clone(); + b.major = false; + } + Resolved::Removed { from } => { + b.from = from.clone(); + b.major = false; + } + Resolved::Unknown { .. } => {} + } + } + out + } + + /// Lines the head moves across a major version. + pub fn majors(&self) -> usize { + self.lines + .iter() + .filter(|l| matches!(l.resolved, Resolved::Moved { major: true, .. })) + .count() + } + + /// Lines the head could not be read for, with the first reason. + pub fn unknown_lines(&self) -> (usize, &str) { + let mut why = ""; + let mut n = 0; + for l in &self.lines { + if let Resolved::Unknown { why: w } = &l.resolved { + n += 1; + if why.is_empty() { + why = w; + } + } + } + (n, why) + } + + /// Whether the head fixes `f`: every copy left on its line is at or + /// past the advisory's patched version, or the line is gone. + pub fn fixed(&self, unit: &FixUnit, f: &Finding) -> Fixed { + let Some(line) = unit + .bumps + .iter() + .position(|b| in_bump(b, f)) + .and_then(|i| self.lines.get(i)) + else { + return Fixed::Unknown; + }; + let at = match &line.resolved { + Resolved::Removed { .. } => return Fixed::Yes, + Resolved::Unknown { .. } => return Fixed::Unknown, + Resolved::NotMoved { at } => at, + Resolved::Moved { to, .. } => to, + }; + match f.fixed_version.as_deref().filter(|v| !v.is_empty()) { + // No patched version is recorded for it: a move alone proves + // nothing. + None => Fixed::Unknown, + Some(patched) if compare_versions(at, patched) != Ordering::Less => Fixed::Yes, + Some(_) => Fixed::No, + } + } + + /// Each advisory of `members` once, with whether the head fixes it: an + /// advisory in several places is fixed only when every place is. + pub fn advisories( + &self, + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + ) -> Vec<(String, Fixed)> { + let mut out: Vec<(String, Fixed)> = vec![]; + for (f, _) in members { + let id = f.advisory.primary.clone(); + let now = self.fixed(unit, f); + match out.iter_mut().find(|(i, _)| *i == id) { + Some((_, was)) => { + *was = match (*was, now) { + (Fixed::No, _) | (_, Fixed::No) => Fixed::No, + (Fixed::Unknown, _) | (_, Fixed::Unknown) => Fixed::Unknown, + _ => Fixed::Yes, + } + } + None => out.push((id, now)), + } + } + out + } + + /// The description's first sentences: how many advisories the head + /// fixes, in how many package version lines, how many of those cross a + /// major version, and what is not fixed or not known. + pub fn headline(&self, unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> String { + let advisories = self.advisories(unit, members); + let count = |want: Fixed| advisories.iter().filter(|(_, f)| *f == want).count(); + let (fixed, open, unknown) = (count(Fixed::Yes), count(Fixed::No), count(Fixed::Unknown)); + let (unread, why) = self.unknown_lines(); + let at = if self.sha.is_empty() { + "the head".to_string() + } else { + format!("the head `{}`", &self.sha[..self.sha.len().min(7)]) + }; + if unread == self.lines.len() && !self.lines.is_empty() { + return format!( + "What {at} installs is not known: {why}. No count of fixed advisories is claimed \ + here, and the versions in the table are the run's plan, marked as such." + ); + } + let moved = self + .lines + .iter() + .filter(|l| { + matches!( + l.resolved, + Resolved::Moved { .. } | Resolved::Removed { .. } + ) + }) + .count(); + let majors = self.majors(); + let mut s = format!( + "Fixes {} of {} in {} ({} a major version), read from the lockfile on {at}.", + fixed, + plural(advisories.len(), "advisory", "advisories"), + plural(moved, "package version line", "package version lines"), + if majors == 1 { + "1 crosses".to_string() + } else { + format!("{majors} cross") + }, + ); + if open > 0 { + let ids: Vec<&str> = advisories + .iter() + .filter(|(_, f)| *f == Fixed::No) + .map(|(i, _)| i.as_str()) + .take(5) + .collect(); + s.push_str(&format!( + " Not fixed on the head: {}{} (the version installed is below the patched one).", + ids.join(", "), + if open > ids.len() { + format!(" and {} more", open - ids.len()) + } else { + String::new() + } + )); + } + if unknown > 0 { + s.push_str(&format!( + " Not known for {}: {}.", + plural(unknown, "advisory", "advisories"), + if unread > 0 { + why + } else { + "no patched version is recorded for it" + } + )); + } + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::security_fixes::{Advisory, Bump}; + + fn copies(v: &[(&str, &str)]) -> Option> { + Some( + v.iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(), + ) + } + + fn bump(package: &str, from: &str, to: &str) -> Bump { + Bump { + package: package.into(), + from: from.into(), + to: to.into(), + major: is_major_bump(from, to), + manifest: "pnpm-lock.yaml".into(), + } + } + + fn finding(id: &str, package: &str, version: &str, patched: Option<&str>) -> Finding { + Finding { + id: format!("f-{id}"), + package: package.into(), + version: version.into(), + fixed_version: patched.map(String::from), + manifest: "pnpm-lock.yaml".into(), + advisory: Advisory { + primary: id.into(), + ids: vec![id.into()], + ..Default::default() + }, + ..Default::default() + } + } + + /// The plan said a major version for each; the head keeps each on its + /// line through a scoped override. + fn planned_major_stays_on_its_line() -> (FixUnit, HeadFacts, Vec) { + let unit = FixUnit { + bundle: true, + bumps: vec![ + bump("glob-walk", "2.3.1", "4.0.4"), + bump("path-match", "3.1.2", "11.0.1"), + bump("left-trim", "1.0.2", "1.0.5"), + ], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[ + ("glob-walk", "2.3.1"), + ("glob-walk", "4.0.1"), + ("path-match", "3.1.2"), + ("left-trim", "1.0.2"), + ]), + head: copies(&[ + ("glob-walk", "2.3.2"), + ("glob-walk", "4.0.1"), + ("path-match", "3.1.5"), + ("left-trim", "1.0.5"), + ]), + why: String::new(), + }; + let facts = resolve(&unit, "abc1234def", &[lock]); + let findings = vec![ + finding("GHSA-aaaa", "glob-walk", "2.3.1", Some("2.3.2")), + finding("GHSA-bbbb", "path-match", "3.1.2", Some("3.1.5")), + finding("GHSA-cccc", "left-trim", "1.0.2", Some("1.0.5")), + ]; + (unit, facts, findings) + } + + #[test] + fn a_line_the_plan_called_major_is_shown_as_the_head_resolves_it() { + let (unit, facts, findings) = planned_major_stays_on_its_line(); + assert_eq!(facts.version_cell(0), "2.3.1 to 2.3.2"); + assert_eq!(facts.version_cell(1), "3.1.2 to 3.1.5"); + assert_eq!(facts.majors(), 0); + let at_head = facts.unit_at_head(&unit); + assert!(at_head.bumps.iter().all(|b| !b.major), "{at_head:?}"); + assert_eq!(at_head.bumps[0].to, "2.3.2"); + let st = FindingState::default(); + let members: Vec<(&Finding, &FindingState)> = findings.iter().map(|f| (f, &st)).collect(); + let h = facts.headline(&unit, &members); + assert_eq!( + h, + "Fixes 3 of 3 advisories in 3 package version lines (0 cross a major version), read \ + from the lockfile on the head `abc1234`." + ); + assert!(!h.contains("4.0.4") && !h.contains("11.0.1")); + } + + #[test] + fn a_line_that_really_crosses_a_major_is_counted_as_one() { + let unit = FixUnit { + bumps: vec![bump("glob-walk", "2.3.1", "2.3.2")], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("glob-walk", "2.3.1")]), + head: copies(&[("glob-walk", "4.0.4")]), + why: String::new(), + }; + let facts = resolve(&unit, "", &[lock]); + assert_eq!(facts.version_cell(0), "2.3.1 to 4.0.4 (major)"); + assert_eq!(facts.majors(), 1); + assert!(facts.unit_at_head(&unit).bumps[0].major); + } + + #[test] + fn an_advisory_is_fixed_only_at_or_past_its_patched_version() { + let unit = FixUnit { + bumps: vec![ + bump("glob-walk", "2.3.1", "2.3.4"), + bump("path-match", "3.1.2", "3.1.5"), + bump("old-dep", "0.4.0", "0.4.2"), + bump("no-patch", "1.0.0", "1.0.1"), + ], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[ + ("glob-walk", "2.3.1"), + ("path-match", "3.1.2"), + ("old-dep", "0.4.0"), + ("no-patch", "1.0.0"), + ]), + // glob-walk moved, but short of the patch; path-match did not + // move; old-dep is gone; no-patch moved with no patched version + // on record. + head: copies(&[ + ("glob-walk", "2.3.2"), + ("path-match", "3.1.2"), + ("no-patch", "1.0.1"), + ]), + why: String::new(), + }; + let facts = resolve(&unit, "f00", &[lock]); + let fs = [ + finding("GHSA-1", "glob-walk", "2.3.1", Some("2.3.4")), + finding("GHSA-2", "path-match", "3.1.2", Some("3.1.5")), + finding("GHSA-3", "old-dep", "0.4.0", Some("0.4.2")), + finding("GHSA-4", "no-patch", "1.0.0", None), + ]; + assert_eq!(facts.fixed(&unit, &fs[0]), Fixed::No); + assert_eq!(facts.fixed(&unit, &fs[1]), Fixed::No); + assert_eq!(facts.fixed(&unit, &fs[2]), Fixed::Yes); + assert_eq!(facts.fixed(&unit, &fs[3]), Fixed::Unknown); + assert_eq!(facts.version_cell(1), "3.1.2, not moved on the head"); + assert_eq!(facts.version_cell(2), "0.4.0, no longer installed"); + let st = FindingState::default(); + let members: Vec<(&Finding, &FindingState)> = fs.iter().map(|f| (f, &st)).collect(); + let h = facts.headline(&unit, &members); + assert!( + h.starts_with("Fixes 1 of 4 advisories in 3 package version lines"), + "{h}" + ); + assert!(h.contains("Not fixed on the head: GHSA-1, GHSA-2"), "{h}"); + assert!(h.contains("Not known for 1 advisory"), "{h}"); + } + + #[test] + fn what_cannot_be_read_is_said_as_not_known_never_as_the_plan() { + let unit = FixUnit { + bumps: vec![bump("glob-walk", "2.3.1", "4.0.4")], + ..Default::default() + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("glob-walk", "2.3.1")]), + head: None, + why: "`pnpm-lock.yaml` could not be read on the head (too large)".into(), + }; + let facts = resolve(&unit, "abc", &[lock]); + assert_eq!( + facts.version_cell(0), + "2.3.1 to 4.0.4 planned; not read from the head" + ); + let f = finding("GHSA-1", "glob-walk", "2.3.1", Some("2.3.2")); + let st = FindingState::default(); + let h = facts.headline(&unit, &[(&f, &st)]); + assert!( + h.starts_with("What the head `abc` installs is not known"), + "{h}" + ); + assert!(!h.contains("Fixes"), "{h}"); + assert_eq!( + facts.majors(), + 0, + "an unread line is never counted as a major" + ); + // A bump whose lockfile can't be told is unknown too. + let mut other = unit.clone(); + other.bumps[0].manifest = "sbom".into(); + let two = [ + LockAt { + path: "a/yarn.lock".into(), + ..Default::default() + }, + LockAt { + path: "b/yarn.lock".into(), + ..Default::default() + }, + ]; + assert!(matches!( + resolve(&other, "abc", &two).lines[0].resolved, + Resolved::Unknown { .. } + )); + } +} diff --git a/services/common/src/description_handoff.rs b/services/common/src/description_handoff.rs new file mode 100644 index 000000000..7cdc5b044 --- /dev/null +++ b/services/common/src/description_handoff.rs @@ -0,0 +1,203 @@ +//! A round never hands the pull request's description to a person. +//! +//! A fix round corrected the code a review asked about, then ended its +//! account with "I can't edit the PR description from here" and listed the +//! corrections for a person to make. The description stayed wrong. +//! +//! The description is CoderHelm's: after every push it is rebuilt from the +//! branch (`worker::passes::description`). A round has no tool that writes +//! it and needs none, so the round is told that ([`ROUND_NOTE`]) and its +//! account is checked ([`handoffs`]): a sentence that says the description +//! can't be edited, or leaves an edit of it to a person, is taken out +//! ([`scrub`]) and the rebuild runs, whether or not the round pushed code. +//! +//! The check is narrow on purpose. It reads one sentence at a time and needs +//! both the description as the thing edited and either an inability or a +//! person asked to do it; a sentence that only mentions the description +//! passes. + +use std::sync::OnceLock; + +use regex::Regex; + +/// What every fix round is told about the description. +pub const ROUND_NOTE: &str = "The pull request's description is kept by CoderHelm: right after \ + this round it is rebuilt from the branch as it stands (the versions the lockfile resolves, \ + the counts, the changes, the verification and the open items). You have no tool that writes \ + it and need none. When a finding says the description is wrong, fix what is wrong in the \ + code if anything is, and say in your account which statement was wrong; never write that \ + you cannot edit the description, and never leave an edit of it to a person."; + +/// What replaces a handed-off edit in a round's account. +pub const REBUILT: &str = + "CoderHelm rebuilds the pull request's description from the branch after this round."; + +/// The description, as the object of an edit: `the PR description`, `the +/// table in the description`. +const OBJECT: &str = r"(?:(?:the|this|that|its|their|my|our|pr|pr's|prs|pull|request|request's|current|existing)\s+){0,5}(?:description|pr body|pull request body)\b"; +const IN_OBJECT: &str = r"[^.;!?]{0,60}?\b(?:in|of|from) (?:(?:the|this|that|its|pr|pr's|pull|request|request's)\s+){0,4}(?:description|pr body|pull request body)\b"; +const EDIT: &str = r"(?:edit|update|change|modify|rewrite|fix|correct|amend|touch|adjust|revise)"; +const EDITED: &str = + r"(?:edited|updated|changed|modified|rewritten|fixed|corrected|amended|adjusted|revised)"; +const CANNOT: &str = r"(?:can't|cannot|can not|couldn't|could not|won't be able to|am unable to|was unable to|unable to|am not able to|not able to|have no way to|no way to|don't have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|do not have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|have no (?:tool|tools|access|permission|ability) to|lack (?:a |the )?(?:tool|tools|access|permission|ability) to)"; +const PERSON: &str = r"(?:you|someone|somebody|a person|a human|a maintainer|the maintainer|the author|a reviewer|the reviewer|the team|a teammate)"; + +fn patterns() -> &'static [Regex] { + static P: OnceLock> = OnceLock::new(); + P.get_or_init(|| { + [ + // "I can't edit the PR description from here." + format!(r"(?i)\b{CANNOT}\s+(?:\w+\s+){{0,2}}?{EDIT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "The description can't be changed from this round." + format!(r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{{0,40}}?\b(?:can't|cannot|can not|could not|couldn't) be {EDITED}"), + // "You will need to update the description." + format!(r"(?i)\b{PERSON}(?:'ll| will| would| should| must| may| can)?(?: need to| needs to| have to| has to| want to)?\s+(?:please\s+)?(?:manually\s+)?{EDIT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "Please fix the count in the description." + format!(r"(?i)\bplease\s+(?:manually\s+)?{EDIT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "The description needs a manual update." + r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{0,60}?\b(?:needs?|requires?|will need|still needs?) (?:a |to be )?(?:manual|manually|hand|human)".to_string(), + // "The description must be updated by hand." + format!(r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{{0,60}}?\b{EDITED} (?:by hand|manually|by a person|by someone|by a maintainer|by the author)"), + // "I left the description corrections for you." + format!(r"(?i)\b(?:left|leave|leaving)\b[^.;!?]{{0,50}}?\b(?:description|pr body|pull request body)\b[^.;!?]{{0,50}}?\b(?:for|to) {PERSON}"), + ] + .iter() + .map(|p| Regex::new(p).expect("a fixed pattern")) + .collect() + }) +} + +fn hands_off(sentence: &str) -> bool { + let s = sentence.replace('\u{2019}', "'"); + // An instruction not to ("never write that you cannot edit the + // description") is the rule itself, not a handoff. + let lower = s.to_ascii_lowercase(); + if lower.contains("never ") { + return false; + } + patterns().iter().any(|p| p.is_match(&s)) +} + +/// Each line's sentences, as (line index, byte range in the line). +fn spans(text: &str) -> Vec<(usize, usize, usize)> { + let mut out = vec![]; + for (i, line) in text.lines().enumerate() { + for (a, b) in crate::prose::sentence_spans(line) { + out.push((i, a, b)); + } + } + out +} + +/// The sentences of a round's account that say the description can't be +/// edited or leave an edit of it to a person. +pub fn handoffs(text: &str) -> Vec { + let lines: Vec<&str> = text.lines().collect(); + spans(text) + .into_iter() + .map(|(i, a, b)| lines[i][a..b].trim()) + .filter(|s| hands_off(s)) + .map(String::from) + .collect() +} + +/// `text` without its [`handoffs`], [`REBUILT`] in place of the first. +/// `None` when it has none, so a caller rebuilds only when there is cause. +pub fn scrub(text: &str) -> Option { + let mut found = false; + let mut out: Vec = vec![]; + for line in text.lines() { + let mut kept = String::new(); + let mut cut = false; + for (a, b) in crate::prose::sentence_spans(line) { + let piece = &line[a..b]; + if !hands_off(piece.trim()) { + kept.push_str(piece); + continue; + } + cut = true; + if !found { + // Keep the sentence's lead (indent, bullet) with the text + // that replaces it. + let lead: String = piece + .chars() + .take_while(|c| c.is_whitespace() || matches!(c, '-' | '*' | '>')) + .collect(); + kept.push_str(&lead); + kept.push_str(REBUILT); + found = true; + } + } + if !cut { + out.push(line.to_string()); + } else if !kept.trim().trim_matches(['-', '*', '>']).trim().is_empty() { + out.push(kept); + } + } + found.then(|| out.join("\n")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_round_that_hands_the_description_to_a_person_is_caught() { + for s in [ + "I can't edit the PR description from here.", + "I cannot update the pull request description in this round, so it still lists the old versions.", + "I don't have a tool to change the description.", + "I was unable to fix the table in the PR description.", + "The description can't be changed from this round.", + "You will need to update the PR description: the table still says 4.0.4.", + "Please correct the count in the description.", + "The PR description needs a manual update.", + "The description should be corrected by hand.", + "I left the description corrections for the author.", + "Someone should fix the headline in the PR body.", + "I can\u{2019}t edit the PR description from here.", + ] { + assert_eq!(handoffs(s), vec![s.to_string()], "{s}"); + } + } + + #[test] + fn a_sentence_that_only_mentions_the_description_passes() { + for s in [ + "Updated the description as asked.", + "The description said five packages cross a major version; the manifest keeps each on its line.", + "I can't reproduce the failure the description mentions.", + "You should update the tests the ticket's description lists.", + "The table in the description was wrong about glob-walk.", + "Please review the override for path-match.", + "I could not run the build in the sandbox.", + "The description of the `retry` option in the README is unchanged.", + "CoderHelm rebuilds the pull request's description from the branch after this round.", + "No change to the meta description tag was needed.", + ] { + assert!(handoffs(s).is_empty(), "{s}: {:?}", handoffs(s)); + } + } + + #[test] + fn the_handoff_is_replaced_by_the_rebuild_once() { + let account = "Kept glob-walk on the 2 line with a scoped override.\n\ + - I can't edit the PR description from here. Please update the table in the description.\n\ + - The lockfile was written by the sandbox."; + let out = scrub(account).unwrap(); + assert_eq!( + out, + format!( + "Kept glob-walk on the 2 line with a scoped override.\n- {REBUILT}\n- The lockfile was written by the sandbox." + ) + ); + assert!(handoffs(&out).is_empty()); + assert_eq!(scrub("Kept glob-walk on the 2 line."), None); + // The round's note itself is never read as a handoff. + assert!( + handoffs(ROUND_NOTE).is_empty(), + "{:?}", + handoffs(ROUND_NOTE) + ); + } +} diff --git a/services/common/src/file_claims.rs b/services/common/src/file_claims.rs new file mode 100644 index 000000000..677e377bc --- /dev/null +++ b/services/common/src/file_claims.rs @@ -0,0 +1,461 @@ +//! A sentence a run writes into the repository is held to the same proof as +//! one it writes on the pull request. +//! +//! A run that edits a README, a changelog or a docs page can write "the +//! build passes with these versions" there, and the file is then merged with +//! a claim nothing checked. The pull request's own sections say only what a +//! check recorded; a file the run writes must too. +//! +//! - [`claims_in_patch`] reads the lines a change adds to a prose file and +//! returns each sentence that states, as a fact, that the build, the +//! tests, the linter or the type check passes. +//! - [`unproven`] keeps the ones no recorded passing result covers on this +//! head. The run then runs the check, or takes the sentence out +//! ([`without`]) before it finishes. +//! +//! The reading is narrow on purpose, since most prose that names a build or +//! a test is not a claim: an instruction ("make sure the tests pass"), a +//! condition ("once CI is green"), a plan ("the build should pass"), a +//! question, a heading, a command, a negative ("the tests fail on Node 18") +//! and a sentence where the word is something else ("the build passes +//! options to the bundler") are all left alone. Only a plain statement with +//! the check as its subject and a passing result as what is said of it +//! counts. + +use std::sync::OnceLock; + +use regex::Regex; +use serde::{Deserialize, Serialize}; + +/// The kinds of check a sentence can claim. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ClaimKind { + Build, + Tests, + Lint, + Typecheck, +} + +impl ClaimKind { + /// The name the run's check records use (`checks::CheckKind::name`). + pub fn name(self) -> &'static str { + match self { + ClaimKind::Build => "build", + ClaimKind::Tests => "tests", + ClaimKind::Lint => "lint", + ClaimKind::Typecheck => "typecheck", + } + } + + fn words(self) -> &'static str { + match self { + ClaimKind::Build => "the build", + ClaimKind::Tests => "the tests", + ClaimKind::Lint => "the linter", + ClaimKind::Typecheck => "the type check", + } + } +} + +/// One sentence a change adds to a file that claims a check passes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Claim { + pub path: String, + /// The line in the new file. + pub line: u64, + pub sentence: String, + pub kinds: Vec, +} + +impl Claim { + /// What the claim says passes, in words (`the build and the tests`). + pub fn what(&self) -> String { + let w: Vec<&str> = self.kinds.iter().map(|k| k.words()).collect(); + match w.as_slice() { + [] => String::new(), + [one] => one.to_string(), + [init @ .., last] => format!("{} and {last}", init.join(", ")), + } + } +} + +/// A file whose added sentences are read: prose a person reads as fact. +pub fn is_prose_path(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + let name = lower.rsplit('/').next().unwrap_or(&lower); + [".md", ".mdx", ".rst", ".adoc", ".txt"] + .iter() + .any(|e| name.ends_with(e)) + || matches!( + name, + "readme" | "changelog" | "changes" | "history" | "news" + ) +} + +struct Patterns { + subjects: Vec<(ClaimKind, Regex)>, + /// A word that makes the sentence something other than a statement of + /// fact about now: an instruction, a plan, a requirement. + not_a_fact: Regex, + /// A word that, before the check's name, makes what follows a + /// condition ("once the build is green") and not a statement. + condition: Regex, + negative: Regex, + /// "0 failed", "no failures": a pass said through its failures. + zero_failures: Regex, +} + +/// What may follow the check's name before the passing word: a few plain +/// words ("now", "and lint", "of the web app"), never a clause. +const GAP: &str = r"(?:,?[ \t]+(?:and|&|or|plus)?[ \t]*[\w`'./@:-]+){0,4}?,?[ \t]+"; +/// The passing word, and what may follow `pass`: a sentence end or a word +/// that continues the result ("on Node 22", "with these versions"). `pass` +/// with an object ("passes options to") is another verb. +const PASSES: &str = r"(?:(?:(?:all|both|now|still|again|also)[ \t]+)*(?:pass(?:es|ed)?|succeeds?|succeeded)(?:[ \t]+(?:on|with|in|for|again|now|locally|cleanly|successfully|after|against|at|under|and|too|here|there|everywhere)\b|[ \t]*(?:$|[.,;:!)]))|(?:is|are|was|were|stays?|remains?|came back|comes back|runs?|ran)[ \t]+(?:(?:all|now|still|again)[ \t]+)*(?:green|clean|passing|successful)\b|(?:builds?|compiles?|built|compiled)[ \t]+(?:successfully|cleanly|without (?:errors?|warnings?)|with no errors?)\b)"; + +fn patterns() -> &'static Patterns { + static P: OnceLock = OnceLock::new(); + P.get_or_init(|| { + let re = |p: &str| Regex::new(p).expect("a fixed pattern"); + let subject = |names: &str| re(&format!(r"(?i)\b(?:{names})\b{GAP}{PASSES}")); + Patterns { + subjects: vec![ + ( + ClaimKind::Build, + subject(r"build|production build|app build|compilation|compile"), + ), + ( + ClaimKind::Tests, + subject(r"tests|test suite|unit tests|integration tests|end-to-end tests|e2e tests|specs|suite"), + ), + ( + ClaimKind::Lint, + subject(r"lint|linter|linting|eslint|clippy|lint check"), + ), + ( + ClaimKind::Typecheck, + subject(r"type[- ]?check|type[- ]?checks|type[- ]?checking|typecheck|tsc"), + ), + ], + not_a_fact: re( + r"(?i)\b(?:should|must|shall|will|would|could|might|may|can|need|needs|needed|want|wants|expect|expects|expected|require|requires|required|ensure|verify|check that|confirm|make sure|whether|so that|in order|to make|to get|to keep|todo|tbd|try|please|let's|how to|example|e\.g)\b", + ), + condition: re(r"(?i)\b(?:if|when|whenever|once|until|unless|before|after|while|as soon as)\b"), + negative: re(r"(?i)(?:\b(?:not|never|no longer|fail|fails|failed|failing|broken|breaks|flaky|red)\b|n't\b)"), + zero_failures: re(r"(?i)\b(?:0|zero|no)[ \t]+(?:failed|failures?|errors?)\b|\bwithout (?:failures?|errors?|warnings?)\b|\bwith no errors?\b"), + } + }) +} + +/// The builds a sentence names with the `builds successfully` form, where +/// the check's name and the passing word are one word. +fn build_verb() -> &'static Regex { + static R: OnceLock = OnceLock::new(); + R.get_or_init(|| { + Regex::new( + r"(?i)\b(?:builds?|compiles?|built|compiled)[ \t]+(?:successfully|cleanly|without (?:errors?|warnings?)|with no errors?)\b", + ) + .expect("a fixed pattern") + }) +} + +/// The kinds of check `sentence` states as passing; empty when it is not +/// such a statement. +pub fn claimed(sentence: &str) -> Vec { + let p = patterns(); + let s = sentence.trim(); + if s.is_empty() || s.ends_with('?') || p.not_a_fact.is_match(s) { + return vec![]; + } + // A pass said through its failures ("0 failed") is not a negative. + let plain = p.zero_failures.replace_all(s, " "); + if p.negative.is_match(&plain) { + return vec![]; + } + let stated = |re: &Regex| { + re.find(s) + .is_some_and(|m| !p.condition.is_match(&s[..m.start()])) + }; + let mut kinds: Vec = p + .subjects + .iter() + .filter(|(_, re)| stated(re)) + .map(|(k, _)| *k) + .collect(); + if !kinds.contains(&ClaimKind::Build) && stated(build_verb()) { + kinds.insert(0, ClaimKind::Build); + } + kinds +} + +/// A line that is not prose: a heading, a command, a table rule, an image +/// or badge, a quoted line of someone else's text. +fn skipped_line(line: &str) -> bool { + let t = line.trim_start(); + t.starts_with('#') + || t.starts_with('$') + || t.starts_with("![") + || t.starts_with("[![") + || t.starts_with('>') + || t.starts_with("|-") + || t.starts_with("- [ ]") + || t.starts_with("* [ ]") + || line.starts_with(" ") + || line.starts_with('\t') +} + +/// The text of a line with its inline code taken out: a command in +/// backticks is not a sentence's words. +fn without_inline_code(line: &str) -> String { + let mut out = String::new(); + let mut code = false; + for c in line.chars() { + if c == '`' { + code = !code; + out.push('`'); + } else if !code { + out.push(c); + } + } + out +} + +/// The claims a change adds to `path`, read from its patch (a unified diff +/// as GitHub's compare gives it). Nothing for a file that is not prose. +pub fn claims_in_patch(path: &str, patch: &str) -> Vec { + if !is_prose_path(path) { + return vec![]; + } + let mut out = vec![]; + let mut line_no: u64 = 0; + let mut fenced = false; + for raw in patch.lines() { + if let Some(rest) = raw.strip_prefix("@@") { + // `@@ -a,b +c,d @@`: the new file's line the hunk starts at. A + // hunk never starts inside a fence this reader has seen open. + line_no = rest + .split('+') + .nth(1) + .and_then(|s| s.split([',', ' ']).next()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(1); + fenced = false; + continue; + } + let (added, text) = match raw.chars().next() { + Some('+') => (true, &raw[1..]), + Some('-') | Some('\\') => continue, + Some(' ') => (false, &raw[1..]), + _ => (false, raw), + }; + let here = line_no; + line_no += 1; + let t = text.trim_start(); + if t.starts_with("```") || t.starts_with("~~~") { + fenced = !fenced; + continue; + } + if !added || fenced || skipped_line(text) { + continue; + } + for (a, b) in crate::prose::sentence_spans(text) { + // The sentence as the file has it, without its bullet. + let sentence = text[a..b] + .trim() + .trim_start_matches(['-', '*', '+']) + .trim_start(); + let kinds = claimed(&without_inline_code(sentence)); + if kinds.is_empty() { + continue; + } + out.push(Claim { + path: path.to_string(), + line: here, + sentence: sentence.to_string(), + kinds, + }); + } + } + out +} + +/// The claims no recorded passing result covers: `proven` holds the kinds +/// of check with a passing result recorded on this head. +pub fn unproven(claims: &[Claim], proven: &[ClaimKind]) -> Vec { + claims + .iter() + .filter(|c| c.kinds.iter().any(|k| !proven.contains(k))) + .cloned() + .collect() +} + +/// `text` (the file at `path`) without the sentences of `claims` that are +/// in it. A line left with nothing but its bullet goes too. Returns `None` +/// when no sentence was found, so nothing is written for nothing. +pub fn without(path: &str, text: &str, claims: &[Claim]) -> Option { + let mine: Vec<&Claim> = claims.iter().filter(|c| c.path == path).collect(); + let mut changed = false; + let mut out: Vec = vec![]; + for line in text.lines() { + if !mine.iter().any(|c| line.contains(c.sentence.as_str())) { + out.push(line.to_string()); + continue; + } + let mut kept = line.to_string(); + for c in &mine { + if let Some(at) = kept.find(c.sentence.as_str()) { + let end = at + c.sentence.len(); + // The space that joined it to the next sentence goes with it. + let end = if kept[end..].starts_with(' ') { + end + 1 + } else { + end + }; + kept.replace_range(at..end, ""); + changed = true; + } + } + let bare = kept + .trim() + .trim_start_matches(['-', '*', '+']) + .trim_start_matches(|c: char| c.is_ascii_digit() || c == '.') + .trim(); + if !bare.is_empty() { + out.push(kept.trim_end().to_string()); + } + } + if !changed { + return None; + } + let mut joined = out.join("\n"); + if text.ends_with('\n') { + joined.push('\n'); + } + Some(joined) +} + +#[cfg(test)] +mod tests { + use super::*; + use ClaimKind::*; + + #[test] + fn a_plain_statement_that_a_check_passes_is_a_claim() { + for (s, want) in [ + ("All tests pass.", vec![Tests]), + ("The build passes with these versions.", vec![Build]), + ("Lint and type check are clean.", vec![Lint, Typecheck]), + ("The test suite is green on Node 22.", vec![Tests]), + ("Verified: the production build succeeds.", vec![Build]), + ( + "The app builds successfully after the upgrade.", + vec![Build], + ), + ("Build, lint and tests all pass.", vec![Build, Tests, Lint]), + ( + "The unit tests ran clean (212 passed, 0 failed).", + vec![Tests], + ), + ("tsc passes.", vec![Typecheck]), + ("The e2e tests passed against staging.", vec![Tests]), + ("The build passes after the upgrade.", vec![Build]), + ] { + assert_eq!(claimed(s), want, "{s}"); + } + } + + #[test] + fn ordinary_prose_about_builds_and_tests_is_not_a_claim() { + for s in [ + // Instructions, conditions, plans, requirements. + "Make sure the tests pass before you open a pull request.", + "Run `pnpm build` and check that the build passes.", + "Once the build is green, deploy from the release branch.", + "After the tests pass, the release job tags the commit.", + "The build should pass on Node 20 and later.", + "A pull request needs the tests passing to merge.", + "If the linter is clean, the hook lets the commit through.", + "Tests must pass on every supported version.", + "Does the build pass on Windows?", + // Negatives. + "The tests fail on Node 18.", + "The build does not pass without the env file.", + "Type checking isn't clean yet for the legacy folder.", + // The word means something else. + "The build passes options to the bundler through `--config`.", + "Each test passes a fixture to the handler.", + "The suite passes the locale to every spec.", + "The linter is configured in `eslint.config.js`.", + "Tests live in `packages/*/test`.", + "Bumped the build tooling to version 5.", + "Fixed the failing tests for the date parser.", + "The build step runs after lint in CI.", + "Added a test for the retry option.", + "The types are generated from the schema.", + "This release changes how the build output is cached.", + "", + ] { + assert!(claimed(s).is_empty(), "{s}: {:?}", claimed(s)); + } + } + + const PATCH: &str = "@@ -10,6 +10,12 @@ ## Upgrading\n context line\n+## Verified: the build passes\n+The build passes with these versions. Path matching is unchanged.\n+- All tests pass.\n+\n+```sh\n+pnpm build # the build passes\n+```\n+Make sure the tests pass before releasing.\n-An old line where the tests pass.\n unchanged: the tests pass.\n"; + + #[test] + fn only_added_prose_lines_of_prose_files_are_read() { + let found = claims_in_patch("docs/upgrading.md", PATCH); + let got: Vec<(u64, &str, &[ClaimKind])> = found + .iter() + .map(|c| (c.line, c.sentence.as_str(), c.kinds.as_slice())) + .collect(); + assert_eq!( + got, + vec![ + (12, "The build passes with these versions.", &[Build][..]), + (13, "All tests pass.", &[Tests][..]), + ], + "the heading, the fenced command, the instruction, the removed line and the \ + unchanged line are not claims this change adds" + ); + assert!(claims_in_patch("src/build.ts", PATCH).is_empty()); + assert!(is_prose_path("CHANGELOG") && is_prose_path("apps/web/README.md")); + assert!(!is_prose_path("package.json")); + } + + #[test] + fn a_claim_stands_only_with_a_recorded_passing_result() { + let found = claims_in_patch("README.md", PATCH); + assert_eq!(unproven(&found, &[Build, Tests]), vec![]); + let open = unproven(&found, &[Tests]); + assert_eq!(open.len(), 1); + assert_eq!(open[0].what(), "the build"); + assert_eq!(unproven(&found, &[]).len(), 2); + } + + #[test] + fn an_unproven_claim_is_taken_out_and_the_rest_of_the_file_stays() { + let file = "## Upgrading\n\nThe build passes with these versions. Path matching is unchanged.\n- All tests pass.\n- Node 20 or later.\n"; + let found = vec![ + Claim { + path: "README.md".into(), + line: 3, + sentence: "The build passes with these versions.".into(), + kinds: vec![Build], + }, + Claim { + path: "README.md".into(), + line: 4, + sentence: "All tests pass.".into(), + kinds: vec![Tests], + }, + ]; + assert_eq!( + without("README.md", file, &found).unwrap(), + "## Upgrading\n\nPath matching is unchanged.\n- Node 20 or later.\n" + ); + assert_eq!(without("docs/other.md", file, &found), None); + assert_eq!(without("README.md", "Nothing here.\n", &found), None); + } +} diff --git a/services/common/src/infra_vuln/actions.rs b/services/common/src/infra_vuln/actions.rs new file mode 100644 index 000000000..18b50c2bd --- /dev/null +++ b/services/common/src/infra_vuln/actions.rs @@ -0,0 +1,1061 @@ +//! What a pending action means, which advisories apply to it, and how +//! several pending actions on one resource become one coherent, ordered +//! set of rows. +//! +//! - **Meaning by ARN type.** AWS reuses action names: `system-update` on +//! an Aurora cluster ARN patches the DB engine (Aurora PostgreSQL), and +//! on an instance ARN updates the operating system ([`meaning_of`]). +//! - **In code or not.** An engine version change has a code equivalent; +//! an operating system update, an Aurora PostgreSQL patch and a +//! service-managed patch do not ([`Meaning::in_code`]). +//! - **Advisories.** A bulletin is attached only when it ties to this +//! service, this kind of action, this engine and version (or this named +//! update) and its date ([`tie`]). An action AWS publishes without a CVE +//! list never gets one. +//! - **One row per meaning.** The same update listed on a cluster and on +//! each of its instances is one row naming every ARN; two upgrade +//! actions with different targets are one row for the higher target; +//! the rows of one resource are numbered in the order to do them +//! ([`reconcile`]). + +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use super::feeds::{Bulletin, ServiceStatus, Who}; +use super::inventory::Pending; +use super::matching::version_lt; + +/// What a pending action does. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum Meaning { + /// The operating system under a database. + OsUpdate, + /// An Aurora PostgreSQL engine patch (the third digit). + EnginePatch, + /// A new engine version (`db-upgrade`). + EngineUpgrade, + HardwareMaintenance, + CertificateRotation, + /// The platform version of serverless instances. + ServerlessPlatform, + /// An ElastiCache service update. + ServiceUpdate, + /// OpenSearch service software. + ServiceSoftware, + /// An AWS Health event. + Health, + #[default] + Unknown, +} + +impl Meaning { + /// The guidance store's name for it. + pub fn guidance_action(self) -> &'static str { + match self { + Meaning::OsUpdate => "os_update", + Meaning::EnginePatch => "engine_patch", + Meaning::EngineUpgrade => "engine_upgrade", + Meaning::ServiceUpdate => "service_update", + Meaning::ServiceSoftware => "service_software", + _ => "any", + } + } + + /// Whether changing the code that defines the resource does the same + /// thing. Only an engine version change does. + pub fn in_code(self) -> bool { + self == Meaning::EngineUpgrade + } + + /// AWS publishes this action with no CVE list of its own, and nothing + /// names the fixed version: no CVE may be attached to it. + pub fn never_has_cves(self) -> bool { + matches!( + self, + Meaning::OsUpdate + | Meaning::HardwareMaintenance + | Meaning::CertificateRotation + | Meaning::ServerlessPlatform + ) + } + + /// A plain name for a title. + pub fn label(self) -> &'static str { + match self { + Meaning::OsUpdate => "operating system update", + Meaning::EnginePatch => "engine patch", + Meaning::EngineUpgrade => "engine version upgrade", + Meaning::HardwareMaintenance => "hardware maintenance", + Meaning::CertificateRotation => "certificate rotation", + Meaning::ServerlessPlatform => "serverless platform update", + Meaning::ServiceUpdate => "service update", + Meaning::ServiceSoftware => "service software update", + Meaning::Health => "AWS Health event", + Meaning::Unknown => "pending maintenance", + } + } +} + +/// `cluster` or `instance`, from an RDS ARN (`...:cluster:name`, `...:db:name`). +pub fn scope_of(arn: &str) -> &'static str { + if arn.contains(":cluster:") { + "cluster" + } else if arn.contains(":db:") { + "instance" + } else { + "" + } +} + +/// What an RDS or Aurora pending maintenance action means on this ARN. +/// `engine` is the resource's (`aurora-postgresql`, `mysql`). +pub fn meaning_of(action: &str, scope: &str, engine: &str) -> Meaning { + match (action, scope) { + ("db-upgrade", _) => Meaning::EngineUpgrade, + ("os-upgrade", _) => Meaning::OsUpdate, + ("system-update", "instance") => Meaning::OsUpdate, + // AWS documents the cluster-level action as "patch the DB engine + // for Aurora PostgreSQL". For any other engine it is not + // documented, so it is not given a meaning here. + ("system-update", "cluster") if engine.contains("postgres") => Meaning::EnginePatch, + ("hardware-maintenance", _) => Meaning::HardwareMaintenance, + ("ca-certificate-rotation" | "server-certificate-rotation", _) => { + Meaning::CertificateRotation + } + ("serverless-platform-version-update", _) => Meaning::ServerlessPlatform, + _ => Meaning::Unknown, + } +} + +fn re(p: &str) -> Regex { + Regex::new(p).expect("a valid pattern") +} + +/// The version a description names (`Upgrade to Aurora PostgreSQL 3.3.2`, +/// `... to 8.0.mysql_aurora.3.08.2`): the last version in it, empty when +/// it names none. +pub fn target_in(description: &str) -> String { + if let Some(m) = re(r"\d+\.\d+\.mysql_aurora\.\d+(?:\.\d+){1,2}") + .find_iter(description) + .last() + { + return m.as_str().to_string(); + } + re(r"\b\d+\.\d+(?:\.\d+){0,2}\b") + .find_iter(description) + .last() + .map(|m| m.as_str().to_string()) + .unwrap_or_default() +} + +/// The part of an engine version that names its major version. +fn major_of(engine: &str, version: &str) -> String { + if let Some(a) = version.split("mysql_aurora.").nth(1) { + return a.split('.').next().unwrap_or("").to_string(); + } + let parts: Vec<&str> = version.split('.').collect(); + let two = engine.contains("mysql") || engine.contains("mariadb"); + if two && parts.len() >= 2 { + format!("{}.{}", parts[0], parts[1]) + } else { + parts.first().copied().unwrap_or("").to_string() + } +} + +/// Whether moving `from` to `to` crosses a major version. `None` when +/// either is not known. +pub fn is_major(engine: &str, from: &str, to: &str) -> Option { + if from.is_empty() || to.is_empty() { + return None; + } + Some(major_of(engine, from) != major_of(engine, to)) +} + +/// The engine family a bulletin's words or an API engine name speak of. +pub fn engine_family(s: &str) -> &'static str { + let l = s.to_ascii_lowercase(); + let aurora = l.contains("aurora"); + if l.contains("postgres") { + if aurora { + "aurora-postgresql" + } else { + "postgres" + } + } else if l.contains("mysql") { + if aurora { + "aurora-mysql" + } else { + "mysql" + } + } else if l.contains("mariadb") { + "mariadb" + } else if l.contains("valkey") { + "valkey" + } else if l.contains("redis") { + "redis" + } else if l.contains("opensearch") { + "opensearch" + } else { + "" + } +} + +/// The `(engine family, version)` pairs a bulletin row names as fixed +/// (`Aurora PostgreSQL 16.4.3`, `RDS for MySQL version 8.0.40`). +pub fn engines_fixed(text: &str) -> Vec<(String, String)> { + let r = re( + r"(?i)\b(aurora postgresql|aurora mysql|rds for postgresql|rds for mysql|rds for mariadb|postgresql|mysql|mariadb|valkey|redis oss)(?:[- ]compatible(?: edition)?)?\s+(?:versions?\s+)?(\d+(?:\.\d+){1,3})", + ); + let mut out: Vec<(String, String)> = Vec::new(); + for c in r.captures_iter(text) { + let pair = (engine_family(&c[1]).to_string(), c[2].to_string()); + if !pair.0.is_empty() && !out.contains(&pair) { + out.push(pair); + } + } + out +} + +fn names_os_patch(text: &str) -> bool { + let l = text.to_ascii_lowercase(); + [ + "database os", + "operating system", + "os patch", + "os update", + "patch your database os", + ] + .iter() + .any(|w| l.contains(w)) +} + +/// A bulletin older than this is not taken to speak of an operating +/// system update pending today (AWS schedules required patching "once +/// every few months"). +pub const OS_TIE_DAYS: i64 = 120; + +/// What a bulletin is being matched to. +#[derive(Debug, Clone, Default)] +pub struct Target<'a> { + pub meaning: Meaning, + /// The resource's engine (`aurora-postgresql`). + pub engine: &'a str, + /// The version it runs, and the version the action moves it to. + pub running: &'a str, + pub target: &'a str, + /// The update's own name (an ElastiCache service update, an + /// OpenSearch service software release). + pub name: &'a str, + /// YYYY-MM-DD. + pub today: &'a str, +} + +/// How a bulletin ties to an action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Tie { + /// The bulletin names this update, or this engine with a fixed version + /// the action reaches: its CVEs are this action's. + Exact { cves: Vec, why: String }, + /// The bulletin tells customers of this service to make this kind of + /// update, recently, but AWS does not say this pending action is that + /// update: shown as related, with no CVE. + Related { why: String }, +} + +/// Why a bulletin does not apply. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NoTie { + /// The bulletin's row is not something the customer applies in AWS. + NotACustomerAction, + /// Published after today. + NotYetPublished, + /// The row speaks of another kind of update. + DifferentAction, + /// Too old to speak of an update pending today. + TooOld, + /// It names no fixed version for this engine. + NoVersionForEngine, + /// The resource already runs the fixed version or a later one. + AlreadyFixed, + /// The action's target is not known, or is below the fixed version. + TargetDoesNotReachFix, + /// It does not name this update. + DifferentUpdate, + /// AWS publishes this action with no CVE list and no bulletin can + /// stand in for one. + NoAdvisoriesForThisAction, +} + +fn days_between(from: &str, to: &str) -> Option { + let d = |s: &str| chrono::NaiveDate::parse_from_str(s.get(..10)?, "%Y-%m-%d").ok(); + Some((d(to)? - d(from)?).num_days()) +} + +fn row_cves(b: &Bulletin, row: &ServiceStatus) -> Vec { + let mut named: Vec = Vec::new(); + for m in re(r"CVE-\d{4}-\d{4,7}").find_iter(&row.reason) { + let c = m.as_str().to_string(); + if !named.contains(&c) { + named.push(c); + } + } + if named.is_empty() { + b.cves.clone() + } else { + named + } +} + +/// Whether a bulletin's row for the resource's service applies to this +/// action: service (the caller picked the row), who acts, the kind of +/// action, the engine and version range or the update's name, and the +/// date. +pub fn tie(b: &Bulletin, row: &ServiceStatus, t: &Target) -> Result { + if !matches!(row.who, Who::CustomerInAws | Who::Customer) { + return Err(NoTie::NotACustomerAction); + } + if !b.published.is_empty() && !t.today.is_empty() && b.published.as_str() > t.today { + return Err(NoTie::NotYetPublished); + } + match t.meaning { + Meaning::OsUpdate => { + if !names_os_patch(&row.reason) { + return Err(NoTie::DifferentAction); + } + let last = if b.updated.is_empty() { + &b.published + } else { + &b.updated + }; + if days_between(last, t.today).is_none_or(|d| d > OS_TIE_DAYS) { + return Err(NoTie::TooOld); + } + Ok(Tie::Related { + why: format!( + "AWS publishes no CVE list for this action. Bulletin {} ({}) tells customers of this service to patch the database operating system; AWS does not say this pending update is that patch.", + b.id, b.published + ), + }) + } + Meaning::EnginePatch | Meaning::EngineUpgrade => { + let family = engine_family(t.engine); + let fixed: Vec = engines_fixed(&row.reason) + .into_iter() + .filter(|(f, _)| f == family) + .map(|(_, v)| v) + .collect(); + if family.is_empty() || fixed.is_empty() { + return Err(NoTie::NoVersionForEngine); + } + // The fixed version in the running version's line: the same + // major, and for a patch the same major.minor. + let line = |v: &str| -> String { + if t.meaning == Meaning::EnginePatch { + v.split('.').take(2).collect::>().join(".") + } else { + major_of(t.engine, v) + } + }; + let Some(fix) = fixed.iter().find(|v| line(v) == line(t.running)) else { + return Err(NoTie::NoVersionForEngine); + }; + let patch = t.meaning == Meaning::EnginePatch; + if !patch && !version_lt(t.running, fix) { + return Err(NoTie::AlreadyFixed); + } + // A patch's target is the Aurora version; the fixed version + // a bulletin names is one too, in the same numbering. + if t.target.is_empty() || version_lt(t.target, fix) { + return Err(NoTie::TargetDoesNotReachFix); + } + Ok(Tie::Exact { + cves: row_cves(b, row), + why: format!( + "Bulletin {} names {} {fix} as fixed; this action moves {} to {}.", + b.id, family, t.running, t.target + ), + }) + } + Meaning::ServiceUpdate | Meaning::ServiceSoftware => { + let named = !t.name.is_empty() + && (row.fixed.service_updates.iter().any(|u| u == t.name) + || row.reason.contains(t.name)); + if !named { + return Err(NoTie::DifferentUpdate); + } + Ok(Tie::Exact { + cves: row_cves(b, row), + why: format!("Bulletin {} names the update {}.", b.id, t.name), + }) + } + _ => Err(NoTie::NoAdvisoriesForThisAction), + } +} + +/// One pending maintenance action as AWS lists it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Line { + pub arn: String, + pub action: String, + pub description: String, + /// YYYY-MM-DD, empty when AWS gives none. + pub apply_by: String, + pub auto_applied_after: String, + /// The instance is its cluster's writer (it goes last). + pub writer: bool, +} + +fn earliest(a: &str, b: &str) -> String { + match (a.is_empty(), b.is_empty()) { + (true, _) => b.to_string(), + (_, true) => a.to_string(), + _ => a.min(b).to_string(), + } +} + +/// The pending actions of one database (a cluster with its instances, or +/// one instance) as rows: one per meaning, each naming every ARN it is +/// applied to, numbered in the order to do them. +/// +/// - The cluster-level `os-upgrade` stands for the same operating system +/// update listed on each instance (AWS recommends it); with only +/// instance-level actions the row lists the instances, readers first. +/// - Two upgrade actions with different targets are one row for the +/// higher target, and the row says what it stands for. +/// - Order: operating system updates before a MySQL major upgrade (AWS +/// says so); otherwise the earlier AWS date first; with nothing to tell +/// them apart, the engine upgrade, then the patch, then the operating +/// system, and the row says that this order is CoderHelm's. +pub fn reconcile(engine: &str, running: &str, lines: &[Line]) -> Vec { + let mut rows: Vec = Vec::new(); + for l in lines { + let scope = scope_of(&l.arn); + let meaning = meaning_of(&l.action, scope, engine); + let target = if matches!(meaning, Meaning::EngineUpgrade | Meaning::EnginePatch) { + target_in(&l.description) + } else { + String::new() + }; + match rows.iter_mut().find(|r| r.meaning == meaning) { + None => rows.push(Pending { + kind: l.action.clone(), + name: if meaning == Meaning::EnginePatch { + "engine-patch".into() + } else { + l.action.clone() + }, + description: l.description.clone(), + apply_by: l.apply_by.clone(), + auto_applied_after: l.auto_applied_after.clone(), + status: "pending".into(), + meaning, + scope: scope.into(), + arns: vec![l.arn.clone()], + target, + ..Default::default() + }), + Some(r) => { + r.apply_by = earliest(&r.apply_by, &l.apply_by); + r.auto_applied_after = earliest(&r.auto_applied_after, &l.auto_applied_after); + let cluster_wide = meaning == Meaning::OsUpdate && l.action == "os-upgrade"; + if cluster_wide && r.kind != "os-upgrade" { + // The cluster-level action replaces the per-instance ones. + r.merged.push(format!( + "also listed as `{}` on {} instance{}; the cluster-level `os-upgrade` covers every instance", + r.kind, + r.arns.len(), + if r.arns.len() == 1 { "" } else { "s" } + )); + r.kind = l.action.clone(); + r.name = l.action.clone(); + r.scope = scope.into(); + r.description = l.description.clone(); + r.arns = vec![l.arn.clone()]; + } else if meaning == Meaning::OsUpdate && r.kind == "os-upgrade" { + if !r.merged.iter().any(|m| m.starts_with("also listed")) { + r.merged.push(format!( + "also listed as `{}` on its instances; the cluster-level `os-upgrade` covers every instance", + l.action + )); + } + } else if !target.is_empty() && target != r.target { + let (keep, drop) = if r.target.is_empty() || version_lt(&r.target, &target) { + (target.clone(), r.target.clone()) + } else { + (r.target.clone(), target.clone()) + }; + if !drop.is_empty() { + r.merged.push(format!( + "AWS lists two {}s, to {drop} and to {keep}; this row is the one to {keep}, which passes {drop}", + meaning.label() + )); + } + if keep == target { + r.description = l.description.clone(); + } + r.target = keep; + if !r.arns.contains(&l.arn) { + r.arns.push(l.arn.clone()); + } + } else if !r.arns.contains(&l.arn) { + // The same action on another instance: readers first. + if l.writer { + r.arns.push(l.arn.clone()); + } else { + let at = r + .arns + .iter() + .position(|a| lines.iter().any(|x| &x.arn == a && x.writer)) + .unwrap_or(r.arns.len()); + r.arns.insert(at, l.arn.clone()); + } + } + } + } + } + // An upgrade row on a cluster's instances is the cluster's. + order(engine, running, &mut rows); + rows +} + +fn order(engine: &str, running: &str, rows: &mut [Pending]) { + let acted: Vec = rows + .iter() + .enumerate() + .filter(|(_, r)| { + matches!( + r.meaning, + Meaning::OsUpdate | Meaning::EnginePatch | Meaning::EngineUpgrade + ) + }) + .map(|(i, _)| i) + .collect(); + if acted.len() < 2 { + return; + } + let mysql_major = engine_family(engine) == "mysql" + && rows.iter().any(|r| { + r.meaning == Meaning::EngineUpgrade + && is_major(engine, running, &r.target) == Some(true) + }); + let rank = |m: Meaning| match m { + Meaning::EngineUpgrade => 0, + Meaning::EnginePatch => 1, + _ => 2, + }; + let mut sorted = acted.clone(); + let mut by_date = false; + sorted.sort_by(|&a, &b| { + let (ra, rb) = (&rows[a], &rows[b]); + if mysql_major { + let os = |r: &Pending| r.meaning != Meaning::OsUpdate; + if os(ra) != os(rb) { + return os(ra).cmp(&os(rb)); + } + } + let key = |r: &Pending| (r.apply_by.is_empty(), r.apply_by.clone()); + key(ra) + .cmp(&key(rb)) + .then(rank(ra.meaning).cmp(&rank(rb.meaning))) + }); + let dates: Vec<&str> = acted.iter().map(|&i| rows[i].apply_by.as_str()).collect(); + if dates.iter().any(|d| !d.is_empty()) && dates.windows(2).any(|w| w[0] != w[1]) { + by_date = true; + } + let of = sorted.len() as u8; + let has_upgrade = rows.iter().any(|r| r.meaning == Meaning::EngineUpgrade); + for (n, &i) in sorted.iter().enumerate() { + let others: Vec = sorted + .iter() + .filter(|&&j| j != i) + .map(|&j| rows[j].meaning.label().to_string()) + .collect(); + let mut why = format!( + "{} of {of} pending on this database (with the {}).", + n + 1, + others.join(" and the ") + ); + if mysql_major && rows[i].meaning == Meaning::OsUpdate { + why.push_str(" AWS says to apply available operating system updates before a MySQL major version upgrade."); + } else if by_date { + why.push_str(" Ordered by the date AWS applies each one, earliest first."); + } else { + why.push_str(" AWS gives no order for these; this order is CoderHelm's."); + } + if rows[i].meaning == Meaning::EnginePatch && has_upgrade { + why.push_str(" AWS does not say whether this patch is still offered after the engine version upgrade: read pending maintenance again once the upgrade has run, and apply the patch only if it is still listed."); + } + if rows[i].meaning == Meaning::EngineUpgrade && rows.len() > 1 && n > 0 { + why.push_str( + " Each of these restarts the database: plan them as separate interruptions.", + ); + } + rows[i].step = (n + 1) as u8; + rows[i].steps = of; + rows[i].order_why = why; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const CLUSTER: &str = "arn:aws:rds:us-east-1:111122223333:cluster:orders"; + const WRITER: &str = "arn:aws:rds:us-east-1:111122223333:db:orders-1"; + const READER: &str = "arn:aws:rds:us-east-1:111122223333:db:orders-2"; + + fn line(arn: &str, action: &str, description: &str, by: &str) -> Line { + Line { + arn: arn.into(), + action: action.into(), + description: description.into(), + apply_by: by.into(), + writer: arn == WRITER, + ..Default::default() + } + } + + #[test] + fn the_same_action_name_means_different_things_on_a_cluster_and_an_instance() { + let pg = "aurora-postgresql"; + assert_eq!(scope_of(CLUSTER), "cluster"); + assert_eq!(scope_of(WRITER), "instance"); + assert_eq!( + meaning_of("system-update", "cluster", pg), + Meaning::EnginePatch + ); + assert_eq!( + meaning_of("system-update", "instance", pg), + Meaning::OsUpdate + ); + assert_eq!(meaning_of("os-upgrade", "cluster", pg), Meaning::OsUpdate); + assert_eq!( + meaning_of("db-upgrade", "cluster", pg), + Meaning::EngineUpgrade + ); + assert_eq!( + meaning_of("system-update", "instance", "mysql"), + Meaning::OsUpdate + ); + // Not documented for a cluster of another engine: no meaning is made up. + assert_eq!( + meaning_of("system-update", "cluster", "aurora-mysql"), + Meaning::Unknown + ); + assert_eq!( + meaning_of("hardware-maintenance", "instance", pg), + Meaning::HardwareMaintenance + ); + // Only an engine version change has a code equivalent. + assert!(Meaning::EngineUpgrade.in_code()); + for m in [ + Meaning::OsUpdate, + Meaning::EnginePatch, + Meaning::ServiceUpdate, + Meaning::ServiceSoftware, + Meaning::HardwareMaintenance, + ] { + assert!(!m.in_code(), "{m:?}"); + } + assert!(Meaning::OsUpdate.never_has_cves()); + assert!(!Meaning::EnginePatch.never_has_cves()); + } + + #[test] + fn a_description_names_its_target_version() { + assert_eq!(target_in("Upgrade to Aurora PostgreSQL 3.3.2"), "3.3.2"); + assert_eq!( + target_in("Automatic minor version upgrade to postgres 16.6"), + "16.6" + ); + assert_eq!( + target_in("Upgrade to 8.0.mysql_aurora.3.08.2"), + "8.0.mysql_aurora.3.08.2" + ); + assert_eq!(target_in("New Operating System update is available"), ""); + assert_eq!(is_major("postgres", "16.4", "16.6"), Some(false)); + assert_eq!(is_major("postgres", "15.8", "16.6"), Some(true)); + assert_eq!(is_major("mysql", "8.0.36", "8.0.40"), Some(false)); + assert_eq!(is_major("mysql", "8.0.36", "8.4.7"), Some(true)); + assert_eq!( + is_major( + "aurora-mysql", + "8.0.mysql_aurora.3.04.0", + "8.0.mysql_aurora.3.08.2" + ), + Some(false) + ); + assert_eq!(is_major("postgres", "16.4", ""), None); + } + + #[test] + fn one_os_update_listed_on_the_cluster_and_each_instance_is_one_row() { + let rows = reconcile( + "aurora-postgresql", + "16.4", + &[ + line( + WRITER, + "system-update", + "New Operating System patch is available", + "2026-12-01", + ), + line( + READER, + "system-update", + "New Operating System patch is available", + "2026-11-28", + ), + line( + CLUSTER, + "os-upgrade", + "New Operating System patch is available", + "", + ), + ], + ); + assert_eq!(rows.len(), 1, "{rows:#?}"); + let r = &rows[0]; + assert_eq!(r.meaning, Meaning::OsUpdate); + assert_eq!( + (r.kind.as_str(), r.scope.as_str()), + ("os-upgrade", "cluster") + ); + assert_eq!(r.arns, vec![CLUSTER.to_string()]); + assert_eq!( + r.apply_by, "2026-11-28", + "the earliest date of what it stands for" + ); + assert!( + r.merged[0].contains("covers every instance"), + "{:?}", + r.merged + ); + assert_eq!(r.step, 0, "one row needs no order"); + } + + #[test] + fn instance_level_updates_list_every_instance_readers_first() { + let rows = reconcile( + "aurora-postgresql", + "16.4", + &[ + line( + WRITER, + "system-update", + "New Operating System patch is available", + "", + ), + line( + READER, + "system-update", + "New Operating System patch is available", + "", + ), + ], + ); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].arns, vec![READER.to_string(), WRITER.to_string()]); + assert_eq!(rows[0].kind, "system-update"); + } + + #[test] + fn a_patch_and_an_upgrade_on_one_cluster_are_two_ordered_rows() { + let rows = reconcile( + "aurora-postgresql", + "16.4", + &[ + line( + CLUSTER, + "system-update", + "Upgrade to Aurora PostgreSQL 16.4.3", + "", + ), + line( + CLUSTER, + "db-upgrade", + "Upgrade to Aurora PostgreSQL 16.6", + "", + ), + line( + WRITER, + "system-update", + "New Operating System patch is available", + "", + ), + ], + ); + assert_eq!(rows.len(), 3, "{rows:#?}"); + let by = |m: Meaning| rows.iter().find(|r| r.meaning == m).unwrap(); + let (up, patch, os) = ( + by(Meaning::EngineUpgrade), + by(Meaning::EnginePatch), + by(Meaning::OsUpdate), + ); + assert_eq!((up.step, up.steps), (1, 3)); + assert_eq!(patch.step, 2); + assert_eq!(os.step, 3); + assert_eq!(up.target, "16.6"); + assert_eq!(patch.target, "16.4.3"); + // The engine patch and the OS update share an action name: their + // keys differ. + assert_ne!( + (patch.kind.as_str(), patch.name.as_str()), + (os.kind.as_str(), os.name.as_str()) + ); + assert!( + up.order_why.contains("this order is CoderHelm's"), + "{}", + up.order_why + ); + assert!( + patch + .order_why + .contains("AWS does not say whether this patch is still offered"), + "{}", + patch.order_why + ); + } + + #[test] + fn aws_dates_decide_the_order_and_mysql_majors_wait_for_the_os() { + let rows = reconcile( + "aurora-postgresql", + "16.4", + &[ + line(CLUSTER, "db-upgrade", "Upgrade to 16.6", "2027-01-15"), + line( + CLUSTER, + "system-update", + "Upgrade to Aurora PostgreSQL 16.4.3", + "2026-12-01", + ), + ], + ); + let patch = rows + .iter() + .find(|r| r.meaning == Meaning::EnginePatch) + .unwrap(); + assert_eq!(patch.step, 1, "the earlier AWS date goes first"); + assert!(patch.order_why.contains("earliest first")); + let db = "arn:aws:rds:us-east-1:111122223333:db:billing"; + let rows = reconcile( + "mysql", + "8.0.36", + &[ + line(db, "db-upgrade", "Upgrade to 8.4.7", "2026-12-01"), + line( + db, + "system-update", + "New Operating System update is available", + "", + ), + ], + ); + let os = rows + .iter() + .find(|r| r.meaning == Meaning::OsUpdate) + .unwrap(); + assert_eq!(os.step, 1); + assert!(os + .order_why + .contains("before a MySQL major version upgrade")); + } + + #[test] + fn two_upgrades_with_different_targets_are_one_row_for_the_higher() { + let rows = reconcile( + "postgres", + "16.4", + &[ + line(WRITER, "db-upgrade", "Upgrade to 16.6", "2026-12-10"), + line(WRITER, "db-upgrade", "Upgrade to 16.8", "2026-12-20"), + ], + ); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].target, "16.8"); + assert_eq!(rows[0].apply_by, "2026-12-10"); + assert!( + rows[0].merged[0].contains("to 16.6 and to 16.8"), + "{:?}", + rows[0].merged + ); + } + + fn bulletin(reason: &str, who: Who, published: &str) -> (Bulletin, ServiceStatus) { + let row = ServiceStatus { + service: "rds".into(), + who, + reason: reason.into(), + ..Default::default() + }; + ( + Bulletin { + id: "2026-160-AWS".into(), + published: published.into(), + cves: vec!["CVE-2026-98432".into()], + services: vec![row.clone()], + ..Default::default() + }, + row, + ) + } + + const OS_ROW: &str = "Long term remediation will be for you to patch your database OS. This patch is now available for you to apply."; + + #[test] + fn an_os_update_never_gets_a_cve_and_only_a_recent_bulletin_about_the_os_is_related() { + let (b, row) = bulletin(OS_ROW, Who::CustomerInAws, "2026-10-30"); + let os = Target { + meaning: Meaning::OsUpdate, + engine: "aurora-postgresql", + running: "16.4", + today: "2026-11-10", + ..Default::default() + }; + match tie(&b, &row, &os).unwrap() { + Tie::Related { why } => assert!(why.contains("no CVE list"), "{why}"), + t => panic!("an OS update got {t:?}"), + } + // Too old to be about an update pending today. + let late = Target { + today: "2027-06-01", + ..os.clone() + }; + assert_eq!(tie(&b, &row, &late), Err(NoTie::TooOld)); + // Not yet published. + let early = Target { + today: "2026-10-01", + ..os.clone() + }; + assert_eq!(tie(&b, &row, &early), Err(NoTie::NotYetPublished)); + // AWS patched it itself: nothing for the customer. + let (b2, row2) = bulletin(OS_ROW, Who::Aws, "2026-10-30"); + assert_eq!(tie(&b2, &row2, &os), Err(NoTie::NotACustomerAction)); + // A bulletin about an engine version says nothing of an OS update. + let (b3, row3) = bulletin( + "Upgrade to Aurora PostgreSQL 16.4.3 or later.", + Who::CustomerInAws, + "2026-10-30", + ); + assert_eq!(tie(&b3, &row3, &os), Err(NoTie::DifferentAction)); + // Hardware maintenance: no advisory at all. + let hw = Target { + meaning: Meaning::HardwareMaintenance, + ..os + }; + assert_eq!(tie(&b, &row, &hw), Err(NoTie::NoAdvisoriesForThisAction)); + } + + #[test] + fn an_engine_action_gets_a_bulletin_only_for_its_engine_and_version_range() { + let text = "Customers should upgrade to Aurora PostgreSQL 16.4.3 or 15.8.5, or RDS for MySQL version 8.0.40."; + let (b, row) = bulletin(text, Who::CustomerInAws, "2026-10-30"); + assert_eq!( + engines_fixed(text), + vec![ + ("aurora-postgresql".to_string(), "16.4.3".to_string()), + ("mysql".to_string(), "8.0.40".to_string()) + ] + ); + let patch = Target { + meaning: Meaning::EnginePatch, + engine: "aurora-postgresql", + running: "16.4", + target: "16.4.3", + today: "2026-11-10", + ..Default::default() + }; + match tie(&b, &row, &patch).unwrap() { + Tie::Exact { cves, .. } => assert_eq!(cves, vec!["CVE-2026-98432"]), + t => panic!("{t:?}"), + } + // The same bulletin on a MySQL upgrade that reaches the fix. + let mysql = Target { + meaning: Meaning::EngineUpgrade, + engine: "mysql", + running: "8.0.36", + target: "8.0.40", + today: "2026-11-10", + ..Default::default() + }; + assert!(matches!(tie(&b, &row, &mysql), Ok(Tie::Exact { .. }))); + // Already past the fix, a target short of it, a target not known, + // another engine, another minor line: none get the CVE. + for (t, why) in [ + ( + Target { + running: "8.0.41", + target: "8.0.43", + ..mysql.clone() + }, + NoTie::AlreadyFixed, + ), + ( + Target { + target: "8.0.39", + ..mysql.clone() + }, + NoTie::TargetDoesNotReachFix, + ), + ( + Target { + target: "", + ..mysql.clone() + }, + NoTie::TargetDoesNotReachFix, + ), + ( + Target { + engine: "mariadb", + ..mysql.clone() + }, + NoTie::NoVersionForEngine, + ), + ( + Target { + running: "8.4.3", + target: "8.4.7", + ..mysql.clone() + }, + NoTie::NoVersionForEngine, + ), + ( + Target { + running: "14.9", + target: "14.9.2", + ..patch.clone() + }, + NoTie::NoVersionForEngine, + ), + ] { + assert_eq!(tie(&b, &row, &t), Err(why), "{t:?}"); + } + // A bulletin that only speaks of the OS says nothing of an engine patch. + let (b2, row2) = bulletin(OS_ROW, Who::CustomerInAws, "2026-10-30"); + assert_eq!(tie(&b2, &row2, &patch), Err(NoTie::NoVersionForEngine)); + } + + #[test] + fn a_service_update_gets_a_bulletin_only_by_its_own_name() { + let (b, mut row) = bulletin( + "Apply the self-service update named elasticache-20261106-intel.", + Who::CustomerInAws, + "2026-10-30", + ); + row.fixed.service_updates = vec!["elasticache-20261106-intel".into()]; + let t = Target { + meaning: Meaning::ServiceUpdate, + name: "elasticache-20261106-intel", + today: "2026-11-10", + ..Default::default() + }; + assert!(matches!(tie(&b, &row, &t), Ok(Tie::Exact { .. }))); + let other = Target { + name: "elasticache-20260901-intel", + ..t + }; + assert_eq!(tie(&b, &row, &other), Err(NoTie::DifferentUpdate)); + } +} diff --git a/services/common/src/infra_vuln/feeds.rs b/services/common/src/infra_vuln/feeds.rs index 68ef167da..fb771933f 100644 --- a/services/common/src/infra_vuln/feeds.rs +++ b/services/common/src/infra_vuln/feeds.rs @@ -1056,7 +1056,19 @@ pub fn parse_bulletin(page: &str, url: &str) -> Result { }); } } - let cves = cves_in(&text_of(&body)); + // The CVEs the bulletin is about: those its title and summary name, + // above the per-service status. A CVE named only inside one service's + // words belongs to that service's row (`actions::tie` reads it there) + // and is not put on every finding the bulletin touches. A page with + // no CVE above the status falls back to every CVE on it. + let head = ["Mitigation Status", "Affected"] + .iter() + .find_map(|m| body.split_once(m).map(|(h, _)| h)) + .unwrap_or(&body); + let mut cves = cves_in(&format!("{title} {}", text_of(head))); + if cves.is_empty() { + cves = cves_in(&text_of(&body)); + } Ok(Bulletin { id, title, @@ -1443,6 +1455,29 @@ mod tests { .any(|s| s.heading.to_ascii_lowercase().contains("workaround"))); } + #[test] + fn a_cve_named_only_in_one_services_words_is_not_the_bulletins() { + let b = parse_bulletin(BULLETIN, "u").unwrap(); + assert_eq!(b.cves, vec!["CVE-2026-98432"]); + // The same page with another CVE named only under ElastiCache. + let page = BULLETIN.replacen( + "ElastiCache clusters named either", + "ElastiCache clusters (it also addresses CVE-2026-11112) named either", + 1, + ); + assert_ne!( + page, BULLETIN, + "the fixture still has the ElastiCache sentence" + ); + let b = parse_bulletin(&page, "u").unwrap(); + assert_eq!(b.cves, vec!["CVE-2026-98432"], "not put on every service"); + assert!(b + .status("elasticache") + .unwrap() + .reason + .contains("CVE-2026-11112")); + } + #[test] fn a_bulletin_without_a_service_table_has_no_rows() { let body = r#"

Bulletin ID: 2026-175-AWS
Scope: AWS
Content Type: Informational
Publication Date: 11/09/2026 10:00 AM PST

Summary

An SDK issue (CVE-2026-115419).

"#; diff --git a/services/common/src/infra_vuln/guard.rs b/services/common/src/infra_vuln/guard.rs new file mode 100644 index 000000000..e674b1ebe --- /dev/null +++ b/services/common/src/infra_vuln/guard.rs @@ -0,0 +1,811 @@ +//! The replacement guard: a change to infrastructure code that would +//! replace or destroy a resource that holds data is refused, with the +//! reason, unless the guidance says the change is in place. +//! +//! CoderHelm runs no plan and no change set (it holds no cloud +//! credentials), so the guard reads the change itself: each changed file +//! before and after. +//! +//! - A data resource's block, logical id or construct that is gone or +//! renamed: the tool would destroy it or replace it. +//! - A change to an attribute the guidance store lists as replacing +//! ([`super::guidance`], section `replacement`). +//! - A version that goes down: no service here downgrades in place, and +//! Terraform re-creates an ElastiCache group for it. +//! - A version raised on a cluster member and not on its cluster. +//! - An OpenSearch version change through CloudFormation or CDK without +//! the version upgrade policy, which replaces the domain. +//! - A safeguard taken away in the same change (deletion protection, +//! `prevent_destroy`, a retaining deletion policy). +//! +//! When the guard trips, the pull request is never closed and its branch +//! is never deleted: one fix round is told each offending line +//! ([`fix_round`]); if the change still trips, the pull request becomes a +//! draft with the reason at the top of its description ([`put_hold`]) and +//! the finding falls back to its runbook (`records::guard_step`). +//! +//! What the guidance documents as in place (an engine version raised, a +//! node group release, a runtime) passes. The guard is a floor, not a +//! plan: the pull request still says what the plan must show. + +use regex::Regex; + +use super::guidance; +use super::hcl::{self, Block, Value}; +use super::locate; +use super::matching::version_lt; + +/// One changed file, before and after (empty when it did not exist). +#[derive(Debug, Clone, Default)] +pub struct Change<'a> { + pub path: &'a str, + pub before: &'a str, + pub after: &'a str, +} + +/// Terraform types that hold data, and the guidance service that lists +/// what replaces them (empty when none does). +const TF_DATA: &[(&str, &str)] = &[ + ("aws_db_instance", "rds"), + ("aws_rds_cluster", "aurora"), + ("aws_rds_cluster_instance", "aurora"), + ("aws_rds_global_cluster", ""), + ("aws_elasticache_replication_group", "elasticache"), + ("aws_elasticache_cluster", "elasticache"), + ("aws_opensearch_domain", "opensearch"), + ("aws_elasticsearch_domain", "opensearch"), + ("aws_docdb_cluster", ""), + ("aws_neptune_cluster", ""), + ("aws_redshift_cluster", ""), + ("aws_msk_cluster", ""), + ("aws_dynamodb_table", ""), + ("aws_efs_file_system", ""), + ("aws_ebs_volume", ""), + ("aws_s3_bucket", ""), +]; + +/// CloudFormation types that hold data. +const CFN_DATA: &[(&str, &str)] = &[ + ("AWS::RDS::DBInstance", "rds"), + ("AWS::RDS::DBCluster", "aurora"), + ("AWS::RDS::GlobalCluster", ""), + ("AWS::ElastiCache::ReplicationGroup", "elasticache"), + ("AWS::ElastiCache::CacheCluster", "elasticache"), + ("AWS::OpenSearchService::Domain", "opensearch"), + ("AWS::Elasticsearch::Domain", "opensearch"), + ("AWS::DocDB::DBCluster", ""), + ("AWS::Neptune::DBCluster", ""), + ("AWS::Redshift::Cluster", ""), + ("AWS::MSK::Cluster", ""), + ("AWS::DynamoDB::Table", ""), + ("AWS::EFS::FileSystem", ""), + ("AWS::S3::Bucket", ""), +]; + +/// Words in a CDK construct's class that say it holds data. +const CDK_DATA: &[&str] = &[ + "databasecluster", + "databaseinstance", + "serverlesscluster", + "cfndbcluster", + "cfndbinstance", + "cfnreplicationgroup", + "cfncachecluster", + "domain", + "table", + "bucket", + "filesystem", +]; + +const VERSION_ATTRS: &[&str] = &[ + "engine_version", + "elasticsearch_version", + "kafka_version", + "cluster_version", + "EngineVersion", + "ElasticsearchVersion", + "KafkaVersion", +]; + +fn re(p: &str) -> Regex { + Regex::new(p).expect("a valid pattern") +} + +/// The attributes the guidance lists as replacing, for a service and tool. +pub fn replacing(service: &str, tool: &str) -> Vec<&'static str> { + guidance::store() + .iter() + .filter(|e| e.section == "replacement" && e.service == service && e.tool == tool) + .flat_map(|e| e.attributes.iter().map(String::as_str)) + .collect() +} + +fn lit(expr: &str) -> Option { + match hcl::value(expr) { + Value::Lit(s) => Some(s), + _ => None, + } +} + +fn resources(blocks: &[Block]) -> Vec<&Block> { + blocks + .iter() + .filter(|b| b.kind == "resource" && b.labels.len() == 2) + .collect() +} + +fn terraform(c: &Change, out: &mut Vec) { + if c.path.ends_with(".tfvars") { + let (b, a) = (hcl::assignments(c.before), hcl::assignments(c.after)); + for x in b.iter().filter(|x| x.name.contains("version")) { + let Some(y) = a.iter().find(|y| y.name == x.name) else { + continue; + }; + if let (Some(old), Some(new)) = (lit(&x.expr), lit(&y.expr)) { + if version_lt(&new, &old) { + out.push(format!( + "{}: `{}` goes down, from {old} to {new}. A lower version is a downgrade: the service refuses it or the tool re-creates the resource.", + c.path, x.name + )); + } + } + } + return; + } + let before = hcl::parse(c.before); + let after = hcl::parse(c.after); + let moved: Vec = after + .iter() + .filter(|b| b.kind == "moved") + .filter_map(|b| b.attr("from").map(|a| a.expr.trim().to_string())) + .collect(); + let cluster_raised = resources(&before).iter().any(|b| { + b.label(0) == "aws_rds_cluster" + && resources(&after) + .iter() + .find(|a| a.labels == b.labels) + .is_some_and(|a| { + a.attr("engine_version").map(|x| &x.expr) + != b.attr("engine_version").map(|x| &x.expr) + }) + }); + for b in resources(&before) { + let Some((_, service)) = TF_DATA.iter().find(|(t, _)| *t == b.label(0)) else { + continue; + }; + let address = format!("{}.{}", b.label(0), b.label(1)); + let Some(a) = resources(&after).into_iter().find(|a| a.labels == b.labels) else { + if !moved.contains(&address) { + out.push(format!( + "{}: `{address}` (line {} before the change) is removed or renamed with no `moved` block. Terraform would destroy the resource it manages.", + c.path, b.line + )); + } + continue; + }; + // The file and the line of the changed attribute as it now stands + // (the block's line when the attribute is gone). + let at = |n: &str| { + format!( + "{}, line {}", + c.path, + a.attr(n).map(|x| x.line).unwrap_or(a.line) + ) + }; + let changed = + |n: &str| b.attr(n).map(|x| x.expr.trim()) != a.attr(n).map(|x| x.expr.trim()); + for n in replacing(service, "terraform") { + if changed(n) { + out.push(format!( + "{}: `{address}` changes `{n}`, which replaces the resource (a new one is created and this one is destroyed).", + at(n) + )); + } + } + for n in ["for_each", "count"] { + if changed(n) { + out.push(format!( + "{}: `{address}` changes `{n}`: the addresses of the resources it creates change, and Terraform destroys the ones that no longer have one.", + at(n) + )); + } + } + for n in VERSION_ATTRS { + if let (Some(old), Some(new)) = ( + b.attr(n).and_then(|x| lit(&x.expr)), + a.attr(n).and_then(|x| lit(&x.expr)), + ) { + if version_lt(&new, &old) { + out.push(format!( + "{}: `{address}` lowers `{n}` from {old} to {new}. No downgrade is done in place: the service refuses it, and for an ElastiCache replication group the provider destroys and re-creates the group.", + at(n) + )); + } + } + } + if b.label(0) == "aws_rds_cluster_instance" && changed("engine_version") && !cluster_raised + { + out.push(format!( + "{}: `{address}` changes `engine_version` on a cluster instance. An Aurora upgrade is made on the `aws_rds_cluster`; on the instance it does not upgrade anything.", + at("engine_version") + )); + } + let truthy = |x: Option<&hcl::Attr>| x.is_some_and(|x| x.expr.trim() == "true"); + if truthy(b.attr("deletion_protection")) && !truthy(a.attr("deletion_protection")) { + out.push(format!( + "{}: `{address}` turns `deletion_protection` off.", + at("deletion_protection") + )); + } + if !truthy(b.attr("skip_final_snapshot")) && truthy(a.attr("skip_final_snapshot")) { + out.push(format!( + "{}: `{address}` turns `skip_final_snapshot` on.", + at("skip_final_snapshot") + )); + } + let guarded = |x: &Block| { + x.child("lifecycle") + .is_some_and(|l| truthy(l.attr("prevent_destroy"))) + }; + if guarded(b) && !guarded(a) { + out.push(format!( + "{}: `{address}` removes `prevent_destroy`.", + at("lifecycle") + )); + } + } +} + +/// The data resources of a template: `(logical id, type, body lines)`. +fn template_data<'a>(lines: &[&'a str]) -> Vec<(String, &'static str, &'static str, Vec<&'a str>)> { + let key = re(r#"^\s*["']?([A-Za-z0-9]+)["']?\s*:\s*\{?\s*$"#); + let mut out = Vec::new(); + for l in lines { + let Some(c) = key.captures(l) else { + continue; + }; + for (t, service) in CFN_DATA { + if let Some((_, body)) = locate::template_resource(lines, &c[1], &[t]) { + // The resource's own `Type`: a direct child of its key, + // not the type of something nested further down. + let depth = |x: &str| x.len() - x.trim_start().len(); + let child = body + .iter() + .filter(|(_, x)| !x.trim().is_empty()) + .map(|(_, x)| depth(x)) + .min(); + let first_type = body + .iter() + .find(|(_, x)| { + Some(depth(x)) == child + && x.trim_start() + .trim_start_matches(['"', '\'']) + .starts_with("Type") + }) + .is_some_and(|(_, x)| x.contains(t)); + if first_type + && !out + .iter() + .any(|(id, _, _, _): &(String, _, _, _)| id == &c[1]) + { + out.push(( + c[1].to_string(), + *t, + *service, + body.iter().map(|(_, x)| *x).collect(), + )); + } + } + } + } + out +} + +fn property(body: &[&str], name: &str) -> Option { + let p = re(&format!( + r#"^\s*["']?{}["']?\s*:\s*(.*)$"#, + regex::escape(name) + )); + body.iter().find_map(|l| { + p.captures(l).map(|c| { + c[1].trim() + .trim_end_matches(',') + .trim_matches(|x| x == '"' || x == '\'') + .to_string() + }) + }) +} + +fn template(c: &Change, out: &mut Vec) { + let (bl, al): (Vec<&str>, Vec<&str>) = (c.before.lines().collect(), c.after.lines().collect()); + let after = template_data(&al); + for (id, typ, service, body) in template_data(&bl) { + let Some((_, _, _, new)) = after.iter().find(|(a, t, _, _)| a == &id && *t == typ) else { + out.push(format!( + "{}: the {typ} `{id}` is removed, renamed or changes type. CloudFormation would delete it, or replace it with a new empty one.", + c.path + )); + continue; + }; + for n in replacing(service, "cloudformation") { + if property(&body, n) != property(new, n) { + out.push(format!( + "{}: `{id}` changes `{n}`, a replacement property: CloudFormation creates a new resource and deletes this one.", + c.path + )); + } + } + for n in VERSION_ATTRS { + if let (Some(old), Some(now)) = (property(&body, n), property(new, n)) { + let numeric = |s: &str| { + s.trim_start_matches(|x: char| !x.is_ascii_digit()) + .to_string() + }; + if old != now + && !numeric(&old).is_empty() + && !numeric(&now).is_empty() + && version_lt(&numeric(&now), &numeric(&old)) + { + out.push(format!( + "{}: `{id}` lowers `{n}` from {old} to {now}. No downgrade is done in place.", + c.path + )); + } + let policy = property(new, "EnableVersionUpgrade").is_some_and(|v| v == "true"); + if service == "opensearch" && old != now && !policy { + out.push(format!( + "{}: `{id}` changes `{n}` without `UpdatePolicy: EnableVersionUpgrade: true`. Without the policy CloudFormation replaces the whole domain with a new empty one.", + c.path + )); + } + } + } + for n in ["DeletionPolicy", "UpdateReplacePolicy"] { + let keeps = |v: &Option| { + v.as_deref() + .is_some_and(|v| v == "Retain" || v == "Snapshot") + }; + if keeps(&property(&body, n)) && !keeps(&property(new, n)) { + out.push(format!( + "{}: `{id}` no longer keeps its data on `{n}`.", + c.path + )); + } + } + if property(&body, "DeletionProtection").as_deref() == Some("true") + && property(new, "DeletionProtection").as_deref() != Some("true") + { + out.push(format!( + "{}: `{id}` turns `DeletionProtection` off.", + c.path + )); + } + } +} + +fn cdk(c: &Change, out: &mut Vec) { + let data = |content: &str| -> Vec<(String, String)> { + locate::constructs(content) + .into_iter() + .filter(|k| { + let class = k + .class + .rsplit('.') + .next() + .unwrap_or("") + .to_ascii_lowercase(); + CDK_DATA.iter().any(|w| class.contains(w)) + }) + .map(|k| (k.class, k.id)) + .collect() + }; + let after = data(c.after); + for (class, id) in data(c.before) { + if !after.iter().any(|(_, a)| a == &id) { + out.push(format!( + "{}: the construct `{id}` ({class}) is removed or its id changes. A changed construct id changes the logical id, and CloudFormation replaces the resource.", + c.path + )); + } + } + let os_version = re(r"EngineVersion\.[A-Z_0-9]+(?:\([^)]*\))?"); + let versions = |s: &str| -> Vec { + os_version + .find_iter(s) + .map(|m| m.as_str().to_string()) + .collect() + }; + let domain = c.after.contains("opensearchservice") || c.after.contains("opensearch.Domain"); + if domain + && versions(c.before) + .iter() + .filter(|v| { + v.contains("OPENSEARCH") || v.contains("ELASTICSEARCH") || v.contains("openSearch") + }) + .collect::>() + != versions(c.after) + .iter() + .filter(|v| { + v.contains("OPENSEARCH") + || v.contains("ELASTICSEARCH") + || v.contains("openSearch") + }) + .collect::>() + && !re(r"enableVersionUpgrade\s*[:=]\s*(?:true|True)").is_match(c.after) + { + out.push(format!( + "{}: the OpenSearch domain's version changes without `enableVersionUpgrade: true`. It defaults to false, and without it the deploy replaces the whole domain with a new empty one.", + c.path + )); + } + let destroys = |s: &str| s.matches("RemovalPolicy.DESTROY").count(); + if destroys(c.after) > destroys(c.before) && !after.is_empty() { + out.push(format!( + "{}: a `RemovalPolicy.DESTROY` is added in a file that defines a data resource.", + c.path + )); + } +} + +/// Why a change must not be opened as a pull request: one line per +/// reason, empty when the guard has no objection. +pub fn refusals(changes: &[Change]) -> Vec { + let mut out = Vec::new(); + for c in changes { + // A file that is new cannot replace anything. + if c.before.is_empty() { + continue; + } + let tool = locate::tool_of(c.path, c.before).or_else(|| locate::tool_of(c.path, c.after)); + match tool { + Some("terraform" | "opentofu") => terraform(c, &mut out), + Some("cloudformation" | "sam" | "serverless") => template(c, &mut out), + Some("cdk") => cdk(c, &mut out), + _ => {} + } + } + out.dedup(); + out +} + +/// What the one fix round after a tripped guard is told: each line that +/// would replace, remove or downgrade the resource, and what to produce +/// instead. Goes under the ticket's own text. +pub fn fix_round(reasons: &[String]) -> String { + let mut out = String::from( + "\n\nThe change on this branch was read before anything else happened to it, and it would replace or destroy a resource that holds data, or take away what protects it:\n\n", + ); + for r in reasons { + out.push_str(&format!("- {r}\n")); + } + out.push_str("\nUndo exactly those lines on this branch, so each attribute, block, logical id and construct id named above is as it is on the base branch, and make the in-place change this ticket asks for: only the one value it names, raised and never lowered. Change nothing else. The change is read again when this round ends.\n"); + out +} + +/// Around the section at the top of a description that says why the pull +/// request is a draft. While the section is there the pull request is +/// never marked ready (`worker::passes::ready`), so it is never merged. +pub const HOLD_START: &str = ""; +pub const HOLD_END: &str = ""; + +/// The section: the reason and the offending lines. +pub fn hold_section(reasons: &[String]) -> String { + let mut out = format!( + "{HOLD_START}\n## This pull request is a draft: do not merge it as it is\n\nCoderHelm read its own change twice and both times it would replace or destroy a resource that holds data, or take away what protects it:\n\n" + ); + for r in reasons { + out.push_str(&format!("- {r}\n")); + } + out.push_str("\nNothing was merged or applied, and CoderHelm makes no further attempt until the code that defines the resource or the update's target changes. The finding in CoderHelm carries the runbook to apply the update in AWS. The branch is kept: a person can correct the lines above on it, then remove this section and mark the pull request ready.\n"); + out.push_str(HOLD_END); + out.push('\n'); + out +} + +/// A description with the section at its top (after a first-line marker +/// comment, which stays first), replacing an earlier one. +pub fn put_hold(body: &str, reasons: &[String]) -> String { + let without = match (body.find(HOLD_START), body.find(HOLD_END)) { + (Some(a), Some(b)) if b > a => format!( + "{}{}", + &body[..a], + body[b + HOLD_END.len()..].trim_start_matches('\n') + ), + _ => body.to_string(), + }; + let section = hold_section(reasons); + match without.split_once('\n') { + Some((first, rest)) if first.trim_start().starts_with("\n\n## Summary\n\nRaised the version.\n"; + assert_eq!(hold(body), None); + let held = put_hold(body, &reasons); + assert!( + held.starts_with("\n\n"), + "{held}" + ); + assert!(held.contains("## This pull request is a draft")); + assert!(held.contains("db/main.tf, line 3")); + assert!(held.contains("The branch is kept")); + assert!( + held.ends_with("## Summary\n\nRaised the version.\n"), + "{held}" + ); + assert!(hold(&held).is_some()); + // Put again with new reasons: one section, the new lines. + let again = put_hold(&held, &["x.tf, line 9: other".to_string()]); + assert_eq!(again.matches(HOLD_START).count(), 1); + assert!(again.contains("x.tf, line 9") && !again.contains("db/main.tf, line 3")); + // A description with no marker line: the section is first. + assert!(put_hold("## Summary\n", &reasons).starts_with(HOLD_START)); + } + + #[test] + fn the_replacing_attributes_come_from_the_guidance_store() { + assert!(replacing("rds", "terraform").contains(&"identifier")); + assert!(replacing("aurora", "cloudformation").contains(&"DBClusterIdentifier")); + assert!(replacing("opensearch", "cloudformation").contains(&"DomainName")); + assert!(!replacing("rds", "terraform").contains(&"engine_version")); + } +} diff --git a/services/common/src/infra_vuln/guidance.rs b/services/common/src/infra_vuln/guidance.rs new file mode 100644 index 000000000..a201fe738 --- /dev/null +++ b/services/common/src/infra_vuln/guidance.rs @@ -0,0 +1,459 @@ +//! What AWS and each infrastructure tool say about applying an update, +//! kept as data: one entry per fact, per service, per kind of update and +//! per tool, each with the page it came from and the day it was last read +//! (`guidance/*.json`). +//! +//! Both the pull request ticket ([`super::records`]) and the runbook +//! ([`super::runbook`]) are written from these entries; neither holds +//! service facts of its own. The replacement guard ([`super::guard`]) +//! reads its lists of replacing attributes from here too. +//! +//! - An entry with no source or no review date fails the tests. +//! - An entry not re-read for [`MAX_AGE_DAYS`] is stale: it is still +//! shown, flagged with its date, so a reader knows to check the page. +//! - Version numbers, dates and thresholds that move are not kept here: +//! they come from the account's own reads and the daily feeds. + +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use chrono::NaiveDate; +use serde::{Deserialize, Serialize}; + +/// An entry not re-read for this long is flagged. +pub const MAX_AGE_DAYS: i64 = 180; + +/// The services with entries. +pub const SERVICES: &[&str] = &[ + "rds", + "aurora", + "elasticache", + "opensearch", + "eks_nodegroup", + "ami", + "lambda_runtime", + "any", +]; + +/// The kinds of update an entry speaks of. +pub const ACTIONS: &[&str] = &[ + "os_update", + "engine_patch", + "engine_upgrade", + "service_update", + "service_software", + "nodegroup_release", + "ami_replace", + "runtime_change", + "any", +]; + +/// The tools an entry speaks of (`any`: true whatever defines the resource). +pub const TOOLS: &[&str] = &["terraform", "cloudformation", "cdk", "any"]; + +/// What an entry says. +pub const SECTIONS: &[&str] = &[ + "what", + "in_code", + "cve", + "attribute", + "takes_effect", + "interruption", + "replacement", + "option", + "trap", + "permissions", + "precheck", + "backup", + "console", + "apply", + "validation", + "rollback", + "if_nothing", + "order", + "plan", + "pipeline", +]; + +/// One fact. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Entry { + pub id: String, + pub service: String, + pub action: String, + pub tool: String, + pub section: String, + /// The fact, with `{placeholders}` for the resource's own identifiers. + pub text: String, + /// A command that goes with it, with the same placeholders. + #[serde(default)] + pub cli: String, + /// Facts about the resource that must not contradict (`major`: `true`). + #[serde(default)] + pub when: BTreeMap, + /// `attribute`: the attribute the change edits. `replacement`: the + /// attributes whose change replaces the resource. + #[serde(default)] + pub attributes: Vec, + /// `replacement`: what must be present for the change to be in place. + #[serde(default)] + pub requires: String, + /// The page the fact was read from. + pub source: String, + /// The day it was last read (YYYY-MM-DD). + pub reviewed_on: String, +} + +const FILES: &[&str] = &[ + include_str!("guidance/rds.json"), + include_str!("guidance/aurora.json"), + include_str!("guidance/elasticache.json"), + include_str!("guidance/opensearch.json"), + include_str!("guidance/compute.json"), +]; + +/// Reads one guidance file. A file that does not parse is an error, never +/// an empty store. +pub fn parse(json: &str) -> Result, String> { + serde_json::from_str(json).map_err(|e| e.to_string()) +} + +/// Every entry. +pub fn store() -> &'static [Entry] { + static STORE: OnceLock> = OnceLock::new(); + STORE.get_or_init(|| { + FILES + .iter() + .flat_map(|f| parse(f).expect("the guidance files parse (a test keeps them so)")) + .collect() + }) +} + +/// What is wrong with an entry, empty when nothing is. +pub fn problems(e: &Entry) -> Vec { + let mut out = Vec::new(); + if e.id.trim().is_empty() { + out.push("no id".to_string()); + } + if !SERVICES.contains(&e.service.as_str()) { + out.push(format!("unknown service `{}`", e.service)); + } + if !ACTIONS.contains(&e.action.as_str()) { + out.push(format!("unknown action `{}`", e.action)); + } + if !TOOLS.contains(&e.tool.as_str()) { + out.push(format!("unknown tool `{}`", e.tool)); + } + if !SECTIONS.contains(&e.section.as_str()) { + out.push(format!("unknown section `{}`", e.section)); + } + if e.text.trim().len() < 20 { + out.push("no text".to_string()); + } + if !e.source.starts_with("https://") || e.source.len() < 20 { + out.push("no source link".to_string()); + } + if NaiveDate::parse_from_str(&e.reviewed_on, "%Y-%m-%d").is_err() { + out.push("no review date (YYYY-MM-DD)".to_string()); + } + out +} + +/// Whether an entry was last read more than [`MAX_AGE_DAYS`] before +/// `today` (YYYY-MM-DD). An unreadable date counts as stale. +pub fn is_stale(e: &Entry, today: &str) -> bool { + let (Ok(read), Ok(now)) = ( + NaiveDate::parse_from_str(&e.reviewed_on, "%Y-%m-%d"), + NaiveDate::parse_from_str(today, "%Y-%m-%d"), + ) else { + return true; + }; + (now - read).num_days() > MAX_AGE_DAYS +} + +/// The stale entries of a store. +pub fn stale<'a>(entries: &'a [Entry], today: &str) -> Vec<&'a Entry> { + entries.iter().filter(|e| is_stale(e, today)).collect() +} + +/// What is asked of the store. +#[derive(Debug, Clone, Default)] +pub struct Query<'a> { + pub service: &'a str, + pub action: &'a str, + /// `terraform`, `cloudformation`, `cdk`, or empty for a runbook. + pub tool: &'a str, + /// What is known of the resource (`major`, `scope`). + pub facts: BTreeMap, +} + +impl Query<'_> { + fn takes(&self, e: &Entry) -> bool { + (e.service == self.service || e.service == "any") + && (e.action == self.action || e.action == "any") + && (e.tool == "any" || (!self.tool.is_empty() && e.tool == self.tool)) + && e.when + .iter() + .all(|(k, v)| self.facts.get(k).is_none_or(|have| have == v)) + } +} + +/// The entries of one section for a query, in file order, from `entries`. +pub fn section_in<'a>(entries: &'a [Entry], q: &Query, section: &str) -> Vec<&'a Entry> { + entries + .iter() + .filter(|e| e.section == section && q.takes(e)) + .collect() +} + +/// The entries of one section for a query, from the shipped store. +pub fn section(q: &Query, section: &str) -> Vec<&'static Entry> { + section_in(store(), q, section) +} + +/// The tool key guidance uses for a location's tool: SAM and Serverless +/// Framework deploy through CloudFormation and share its entries; OpenTofu +/// shares Terraform's. +pub fn tool_key(tool: &str) -> &'static str { + match tool { + "terraform" | "opentofu" => "terraform", + "cloudformation" | "sam" | "serverless" => "cloudformation", + "cdk" => "cdk", + _ => "", + } +} + +/// Fills an entry's placeholders (`{arn}`, `{region}`) from `vars`. A +/// placeholder with no value is left as written, so a gap is seen and not +/// silently emptied. +pub fn fill(template: &str, vars: &BTreeMap<&str, String>) -> String { + let mut out = template.to_string(); + for (k, v) in vars { + if !v.is_empty() { + out = out.replace(&format!("{{{k}}}"), v); + } + } + out +} + +/// A source as a card or pull request shows it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Cited { + pub url: String, + pub reviewed_on: String, + /// Not re-read within [`MAX_AGE_DAYS`]. + #[serde(default)] + pub stale: bool, +} + +/// The distinct sources of some entries, in order. +pub fn cited(entries: &[&Entry], today: &str) -> Vec { + let mut out: Vec = Vec::new(); + for e in entries { + if let Some(c) = out.iter_mut().find(|c| c.url == e.source) { + c.stale |= is_stale(e, today); + if e.reviewed_on < c.reviewed_on { + c.reviewed_on = e.reviewed_on.clone(); + } + continue; + } + out.push(Cited { + url: e.source.clone(), + reviewed_on: e.reviewed_on.clone(), + stale: is_stale(e, today), + }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_entry_has_a_source_and_a_review_date() { + let mut ids = std::collections::BTreeSet::new(); + for e in store() { + assert_eq!(problems(e), Vec::::new(), "{}", e.id); + assert!(ids.insert(e.id.clone()), "{} is listed twice", e.id); + } + assert!(store().len() > 100, "{}", store().len()); + } + + #[test] + fn an_entry_without_a_source_or_a_date_is_refused() { + let ok = store()[0].clone(); + let mut no_source = ok.clone(); + no_source.source = String::new(); + assert!(problems(&no_source).contains(&"no source link".to_string())); + let mut not_a_link = ok.clone(); + not_a_link.source = "the RDS user guide".into(); + assert!(problems(¬_a_link).contains(&"no source link".to_string())); + let mut no_date = ok.clone(); + no_date.reviewed_on = "last week".into(); + assert!(problems(&no_date) + .iter() + .any(|p| p.starts_with("no review date"))); + let mut odd = ok; + odd.section = "musings".into(); + assert!(problems(&odd).iter().any(|p| p.contains("unknown section"))); + // A file with a missing field does not load at all. + assert!(parse(r#"[{"id":"x","service":"rds"}]"#).is_err()); + } + + #[test] + fn an_entry_not_re_read_in_time_is_flagged() { + let e = &store()[0]; + assert!(!is_stale(e, &e.reviewed_on)); + let read = NaiveDate::parse_from_str(&e.reviewed_on, "%Y-%m-%d").unwrap(); + let edge = (read + chrono::Duration::days(MAX_AGE_DAYS)) + .format("%Y-%m-%d") + .to_string(); + let late = (read + chrono::Duration::days(MAX_AGE_DAYS + 1)) + .format("%Y-%m-%d") + .to_string(); + assert!(!is_stale(e, &edge)); + assert!(is_stale(e, &late)); + assert!(is_stale(e, "not a day")); + assert_eq!(stale(store(), &e.reviewed_on).len(), 0); + assert_eq!(stale(store(), "2099-01-01").len(), store().len()); + let c = cited(&[e], &late); + assert!(c[0].stale && c[0].url == e.source); + } + + fn q<'a>(service: &'a str, action: &'a str, tool: &'a str) -> Query<'a> { + Query { + service, + action, + tool, + facts: BTreeMap::new(), + } + } + + /// RDS and Aurora are covered in full: every part of a runbook for + /// each update a person applies, and every part of a pull request for + /// each tool. + #[test] + fn rds_and_aurora_cover_every_part_of_a_runbook_and_a_pull_request() { + let runbook = [ + "what", + "in_code", + "cve", + "interruption", + "permissions", + "precheck", + "backup", + "console", + "apply", + "validation", + "rollback", + "if_nothing", + ]; + for (service, action) in [ + ("rds", "os_update"), + ("rds", "engine_upgrade"), + ("aurora", "os_update"), + ("aurora", "engine_patch"), + ("aurora", "engine_upgrade"), + ] { + for s in runbook { + assert!( + !section(&q(service, action, ""), s).is_empty(), + "{service} {action} has no `{s}`" + ); + } + } + for service in ["rds", "aurora"] { + for tool in ["terraform", "cloudformation", "cdk"] { + for s in ["attribute", "takes_effect", "replacement", "plan"] { + assert!( + !section(&q(service, "engine_upgrade", tool), s).is_empty(), + "{service} engine_upgrade with {tool} has no `{s}`" + ); + } + } + assert!(!section(&q(service, "engine_upgrade", "terraform"), "trap").is_empty()); + } + } + + #[test] + fn the_other_services_have_what_a_person_or_a_pull_request_needs() { + for (service, action) in [ + ("elasticache", "service_update"), + ("opensearch", "service_software"), + ] { + for s in [ + "what", + "in_code", + "interruption", + "apply", + "validation", + "rollback", + ] { + assert!( + !section(&q(service, action, ""), s).is_empty(), + "{service} {action} has no `{s}`" + ); + } + } + for (service, action) in [ + ("elasticache", "engine_upgrade"), + ("opensearch", "engine_upgrade"), + ("eks_nodegroup", "nodegroup_release"), + ("ami", "ami_replace"), + ("lambda_runtime", "runtime_change"), + ] { + assert!( + !section(&q(service, action, "terraform"), "attribute").is_empty(), + "{service}" + ); + assert!( + !section(&q(service, action, ""), "rollback").is_empty(), + "{service}" + ); + } + // The OpenSearch trap: a version change replaces the domain + // unless the update policy is there. + let r = section( + &q("opensearch", "engine_upgrade", "cloudformation"), + "replacement", + ); + assert_eq!(r[0].requires, "EnableVersionUpgrade"); + } + + #[test] + fn a_query_takes_its_tool_and_what_holds_for_any() { + let tf = section(&q("aurora", "engine_upgrade", "terraform"), "attribute"); + assert_eq!(tf.len(), 1); + assert!(tf[0] + .text + .contains("Never raise it on an `aws_rds_cluster_instance`")); + // A runbook asks with no tool: tool entries stay out. + assert!(section(&q("aurora", "engine_upgrade", ""), "attribute").is_empty()); + // `when` leaves an entry out only when a known fact contradicts it. + let mut minor = q("rds", "engine_upgrade", ""); + let all = section(&minor, "precheck").len(); + minor.facts.insert("major".into(), "false".into()); + assert_eq!(section(&minor, "precheck").len(), all - 1); + assert_eq!(tool_key("sam"), "cloudformation"); + assert_eq!(tool_key("opentofu"), "terraform"); + assert_eq!(tool_key("pulumi"), ""); + } + + #[test] + fn placeholders_take_the_resources_own_identifiers() { + let mut v = BTreeMap::new(); + v.insert( + "arn", + "arn:aws:rds:us-east-1:111122223333:db:orders-1".to_string(), + ); + v.insert("region", "us-east-1".to_string()); + v.insert("action", "system-update".to_string()); + v.insert("target", String::new()); + let e = section(&q("rds", "os_update", ""), "apply")[0]; + let c = fill(&e.cli, &v); + assert_eq!(c, "aws rds apply-pending-maintenance-action --resource-identifier arn:aws:rds:us-east-1:111122223333:db:orders-1 --apply-action system-update --opt-in-type next-maintenance --region us-east-1"); + // A value that is not known stays visible. + assert_eq!(fill("to {target}", &v), "to {target}"); + } +} diff --git a/services/common/src/infra_vuln/guidance/aurora.json b/services/common/src/infra_vuln/guidance/aurora.json new file mode 100644 index 000000000..22d7ecf96 --- /dev/null +++ b/services/common/src/infra_vuln/guidance/aurora.json @@ -0,0 +1,59 @@ +[ +{"id":"aurora.os_update.what","service":"aurora","action":"os_update","tool":"any","section":"what","text":"An operating system update. On the cluster ARN the action is `os-upgrade`: it updates the operating systems of all DB instances in the cluster with rolling upgrades. On an instance ARN the action is `system-update`: it updates the operating system of that one instance; AWS keeps it for backward compatibility and recommends the cluster-level action. The description tells the two kinds apart: \"New Operating System upgrade is available\" is a move to a new Amazon Linux major version and is mandatory; \"New Operating System patch is available\" is a patch.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.in_code","service":"aurora","action":"os_update","tool":"any","section":"in_code","text":"This cannot be expressed in code. The Terraform `aws_rds_cluster` and `aws_rds_cluster_instance`, CloudFormation `AWS::RDS::DBCluster` and CDK resources have a maintenance window, auto minor version upgrade and an engine version, and no argument that applies a pending maintenance action. No code change is needed and none causes drift.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/rds_cluster.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.cve","service":"aurora","action":"os_update","tool":"any","section":"cve","text":"AWS publishes no CVE list for this action: it returns the action, its dates and a generic description.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.interruption","service":"aurora","action":"os_update","tool":"any","section":"interruption","text":"The cluster-level `os-upgrade` preserves read availability: Aurora updates a few reader instances at a time and the writer last, so there is one writer failover. Zero-downtime patching does not apply to operating system patches and upgrades. With the instance-level action, update the readers first and the writer last; each instance restarts in its own maintenance window.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.if_nothing","service":"aurora","action":"os_update","tool":"any","section":"if_nothing","text":"An action with an apply date is applied by AWS in the maintenance window after that date (cluster-level updates use the cluster's window, instance-level ones each instance's window). Operating system distribution upgrades are mandatory. An action without a date is not applied automatically.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.permissions","service":"aurora","action":"os_update","tool":"any","section":"permissions","text":"The person running this needs `rds:DescribePendingMaintenanceActions`, `rds:ApplyPendingMaintenanceAction`, `rds:DescribeDBClusters`, `rds:DescribeDBInstances`, `rds:DescribeEvents` and `rds:CreateDBClusterSnapshot` on this cluster and its instances.","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.precheck.pending","service":"aurora","action":"os_update","tool":"any","section":"precheck","text":"Confirm what is pending on the cluster and on each instance, and read the dates.","cli":"aws rds describe-pending-maintenance-actions --filters Name=db-cluster-id,Values={cluster} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.precheck.members","service":"aurora","action":"os_update","tool":"any","section":"precheck","text":"Read which instance is the writer and that the cluster is `available`. If the cluster-level `os-upgrade` is offered, use it instead of patching instances one by one.","cli":"aws rds describe-db-clusters --db-cluster-identifier {cluster} --region {region} --query \"DBClusters[0].{Status:Status,Window:PreferredMaintenanceWindow,Members:DBClusterMembers[*].{Id:DBInstanceIdentifier,Writer:IsClusterWriter}}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.backup","service":"aurora","action":"os_update","tool":"any","section":"backup","text":"An `immediate` opt-in can't be undone. Take a manual cluster snapshot first so there is a known restore point.","cli":"aws rds create-db-cluster-snapshot --db-cluster-identifier {cluster} --db-cluster-snapshot-identifier {snapshot} --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.console","service":"aurora","action":"os_update","tool":"any","section":"console","text":"RDS console, Region {region} > Databases > select `{id}` > Actions > Patch at next window (or Patch now). Defer upgrade stays available until the update starts.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.apply.window","service":"aurora","action":"os_update","tool":"any","section":"apply","text":"Schedule it for the next maintenance window. Run it once per ARN listed under Scope, readers before the writer when the action is instance-level.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type next-maintenance --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.apply.now","service":"aurora","action":"os_update","tool":"any","section":"apply","text":"Or apply it now, in a quiet period. An immediate opt-in can't be undone.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type immediate --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.validation","service":"aurora","action":"os_update","tool":"any","section":"validation","text":"The action leaves the pending list once applied. The list is eventually consistent: poll with backoff, starting at a couple of seconds, for up to five minutes. Then check every instance is `available` and the application reconnected after the writer failover.","cli":"aws rds describe-pending-maintenance-actions --filters Name=db-cluster-id,Values={cluster} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.os_update.rollback","service":"aurora","action":"os_update","tool":"any","section":"rollback","text":"A scheduled update that has not started can be cancelled with `undo-opt-in`. Once it has started it can't be deferred, and an immediate opt-in can't be undone. AWS documents no way to remove an applied operating system update.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type undo-opt-in --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, + +{"id":"aurora.engine_patch.what","service":"aurora","action":"engine_patch","tool":"any","section":"what","text":"An Aurora PostgreSQL engine patch. On a cluster ARN `system-update` means \"patch the DB engine for Aurora PostgreSQL\" (AWS's example description: \"Upgrade to Aurora PostgreSQL 3.3.2\"). The same action name on an instance ARN means an operating system update.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.in_code","service":"aurora","action":"engine_patch","tool":"any","section":"in_code","text":"This cannot be expressed in code. The Aurora PostgreSQL engine version in the API, and so in Terraform, CloudFormation and CDK, is major.minor (for example `16.4`). The patch is a third digit that only `SELECT aurora_version();` shows, and it arrives as this pending action. No code change is needed and none causes drift. (Aurora MySQL 2 and 3 differ: their version string includes the patch level, so a patch there changes the engine version.)","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.VersionPolicy.Versioning.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.cve","service":"aurora","action":"engine_patch","tool":"any","section":"cve","text":"The pending action carries no CVE list. A CVE is named here only when an AWS bulletin ties it to this engine and the patch's version.","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.interruption","service":"aurora","action":"engine_patch","tool":"any","section":"interruption","text":"With zero-downtime patching (Aurora PostgreSQL 10.21, 11.16, 12.11, 13.7, 14.3, 15.3, 16.1 and higher) the writer keeps most connections: a drop in throughput that typically lasts a few seconds, at most about one minute. Connections are still dropped when long-running queries or transactions, DDL, temporary tables or table locks, sessions listening on notification channels, `WITH HOLD` cursors or TLSv1.1 are in use. Zero-downtime patching does not cover reader instances: they restart. Without it the database is shut down and every connection and transaction in progress is lost.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MinorUpgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.if_nothing","service":"aurora","action":"engine_patch","tool":"any","section":"if_nothing","text":"An action with an apply date is applied by AWS in the cluster's maintenance window after that date. With auto minor version upgrade on, Aurora also applies patches on its own schedule. An action without a date waits until someone applies it.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.permissions","service":"aurora","action":"engine_patch","tool":"any","section":"permissions","text":"The person running this needs `rds:DescribePendingMaintenanceActions`, `rds:ApplyPendingMaintenanceAction`, `rds:DescribeDBClusters`, `rds:DescribeEvents` and `rds:CreateDBClusterSnapshot` on this cluster, and a database login to run `SELECT aurora_version();`.","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.precheck.pending","service":"aurora","action":"engine_patch","tool":"any","section":"precheck","text":"Confirm the patch is still pending and read its description and dates.","cli":"aws rds describe-pending-maintenance-actions --resource-identifier {arn} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.precheck.quiet","service":"aurora","action":"engine_patch","tool":"any","section":"precheck","text":"Pick a low-traffic period, and clear parameter changes that are in a `pending` state first: they interfere with zero-downtime patching. Clients should retry with exponential backoff and jitter.","cli":"aws rds describe-db-clusters --db-cluster-identifier {cluster} --region {region} --query \"DBClusters[0].{Status:Status,EngineVersion:EngineVersion,Window:PreferredMaintenanceWindow,Pending:PendingModifiedValues,Global:GlobalClusterIdentifier}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MinorUpgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.precheck.global","service":"aurora","action":"engine_patch","tool":"any","section":"precheck","text":"If the cluster is in an Aurora global database, apply pending maintenance on the secondary clusters before the primary. Managed cross-Region switchover and failover have patch level requirements across the member clusters.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-upgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.backup","service":"aurora","action":"engine_patch","tool":"any","section":"backup","text":"Aurora takes its own pre-upgrade snapshot for major version upgrades only, not for minor versions or patches. Take a manual cluster snapshot first.","cli":"aws rds create-db-cluster-snapshot --db-cluster-identifier {cluster} --db-cluster-snapshot-identifier {snapshot} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.console","service":"aurora","action":"engine_patch","tool":"any","section":"console","text":"RDS console, Region {region} > Databases > select the cluster `{cluster}` > Actions > Patch at next window (or Patch now).","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.apply.window","service":"aurora","action":"engine_patch","tool":"any","section":"apply","text":"Schedule the patch for the cluster's next maintenance window.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type next-maintenance --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.apply.now","service":"aurora","action":"engine_patch","tool":"any","section":"apply","text":"Or apply it now, in a quiet period. An immediate opt-in can't be undone.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type immediate --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.validation","service":"aurora","action":"engine_patch","tool":"any","section":"validation","text":"The engine version string stays the same; the patch shows in `SELECT aurora_version();` (three numbers). The action leaves the pending list (eventually consistent: poll with backoff for up to five minutes). Check the cluster is `available` and the application reconnected.","cli":"aws rds describe-pending-maintenance-actions --resource-identifier {arn} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Updates.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_patch.rollback","service":"aurora","action":"engine_patch","tool":"any","section":"rollback","text":"A scheduled patch that has not started can be cancelled with `undo-opt-in`; an immediate opt-in can't be undone. AWS documents no way back from an applied patch, and Aurora PostgreSQL does not support restoring a snapshot, or a point in time, to a previous minor version.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type undo-opt-in --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, + +{"id":"aurora.engine_upgrade.what","service":"aurora","action":"engine_upgrade","tool":"any","section":"what","text":"An engine version upgrade of the cluster (`db-upgrade`, or a new minor version). It has a code equivalent: the cluster's engine version.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MinorUpgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.in_code","service":"aurora","action":"engine_upgrade","tool":"any","section":"in_code","text":"This has a code equivalent: the engine version of the cluster resource. Applying it in AWS instead leaves a version pinned in code behind the live one.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/rds_cluster.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cve","service":"aurora","action":"engine_upgrade","tool":"any","section":"cve","text":"The pending action carries no CVE list. A CVE is named here only when an AWS bulletin ties it to this engine and target version. For Aurora MySQL, AWS publishes which version first fixed each CVE.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.CVE_list.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.tf.attribute","service":"aurora","action":"engine_upgrade","tool":"terraform","section":"attribute","text":"Change `engine_version` on the `aws_rds_cluster` (or the module input or variable that feeds it). Never raise it on an `aws_rds_cluster_instance`: the provider says an upgrade must be done on the cluster and trying it on the instance will not update the version. A major version jump also needs `allow_major_version_upgrade = true`, and `db_cluster_parameter_group_name` and `db_instance_parameter_group_name` of the new family. A member of an `aws_rds_global_cluster` is upgraded through the global cluster, with `lifecycle { ignore_changes = [engine_version] }` on the member.","attributes":["engine_version"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/rds_cluster_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.tf.takes_effect","service":"aurora","action":"engine_upgrade","tool":"terraform","section":"takes_effect","text":"`apply_immediately` defaults to `false`: after apply the upgrade is queued for the cluster's next maintenance window and the plan keeps showing a difference until it runs. With `apply_immediately = true` the outage happens at apply time. The provider notes that updating `engine_version` results in an outage.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/rds_cluster.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.tf.replacement","service":"aurora","action":"engine_upgrade","tool":"terraform","section":"replacement","text":"`engine_version` updates in place. The provider documents these as forcing a new cluster: `cluster_identifier`, `cluster_identifier_prefix`, `cluster_scalability_type`, `publicly_accessible`, `availability_zones`; and on a cluster instance: `availability_zone`, `cluster_identifier`, `db_subnet_group_name`, `engine`, `identifier`, `identifier_prefix`. CoderHelm also refuses a change to `snapshot_identifier` or `global_cluster_identifier` in an upgrade change.","attributes":["cluster_identifier","cluster_identifier_prefix","cluster_scalability_type","publicly_accessible","availability_zones","availability_zone","db_subnet_group_name","engine","identifier","identifier_prefix","snapshot_identifier","global_cluster_identifier"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/rds_cluster.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.tf.trap.behind","service":"aurora","action":"engine_upgrade","tool":"terraform","section":"trap","text":"Never set a value below the live version: a pinned version behind the live one makes the next apply a downgrade attempt, which RDS refuses. Aurora MySQL 2 and 3 version strings include the patch level (`8.0.mysql_aurora.3.08.2`), so a fully pinned value falls behind whenever AWS patches; Aurora PostgreSQL values are major.minor, so only minor versions move. The running version is `engine_version_actual`.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Updates.Versions.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cfn.attribute","service":"aurora","action":"engine_upgrade","tool":"cloudformation","section":"attribute","text":"Change `EngineVersion` on the `AWS::RDS::DBCluster` (Update requires: Some interruptions; in place). Not on a member `AWS::RDS::DBInstance`: for Aurora the property is not applicable there, the cluster manages it. If the cluster is a member of a global database, do not use this property: set `EngineVersion` on the `AWS::RDS::GlobalCluster`.","attributes":["EngineVersion"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbcluster.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cfn.takes_effect","service":"aurora","action":"engine_upgrade","tool":"cloudformation","section":"takes_effect","text":"CloudFormation cannot schedule cluster modifications for the maintenance window: the upgrade starts when the stack update runs. To upgrade in the maintenance window instead, AWS says to use `modify-db-cluster` or the console, and then the template must be raised to match.","source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_rds-readme.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cfn.replacement","service":"aurora","action":"engine_upgrade","tool":"cloudformation","section":"replacement","text":"`EngineVersion` is not a replacement property. `DBClusterIdentifier`, `SnapshotIdentifier` and `EngineMode` are (removing `SnapshotIdentifier` from a cluster that was restored from one creates an empty cluster and deletes the original). Changing the logical id of the resource replaces it too. The default `DeletionPolicy` of a DB cluster is `Snapshot`.","attributes":["DBClusterIdentifier","SnapshotIdentifier","EngineMode"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbcluster.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cfn.trap.template","service":"aurora","action":"engine_upgrade","tool":"cloudformation","section":"trap","text":"CloudFormation compares templates, not live values. For Aurora MySQL the version string changes when AWS patches the cluster, and AWS warns that this change in `EngineVersion` can trigger actions by CloudFormation. Set the template to at least the live version; never below it.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Updates.Versions.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cdk.attribute","service":"aurora","action":"engine_upgrade","tool":"cdk","section":"attribute","text":"Change the engine version on the cluster's `engine` (for example `rds.AuroraPostgresEngineVersion.VER_16_1` or `rds.AuroraMysqlEngineVersion.VER_3_07_0`; use the class's static `of(...)` when the library has no constant for the target). CDK passes it to the cluster's `EngineVersion`, an in-place update.","attributes":["version","engine"],"source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_rds-readme.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cdk.takes_effect","service":"aurora","action":"engine_upgrade","tool":"cdk","section":"takes_effect","text":"The upgrade starts when the stack deploys: CloudFormation does not support scheduling cluster modifications for the maintenance window. The default instance update behaviour is BULK, where all instances might be unavailable at the same time; `instanceUpdateBehaviour: rds.InstanceUpdateBehaviour.ROLLING` updates one instance at a time.","source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_rds-readme.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.cdk.replacement","service":"aurora","action":"engine_upgrade","tool":"cdk","section":"replacement","text":"Changing a construct id changes the logical id, and CloudFormation then replaces the resource. Keep every construct id and the cluster identifier as they are. The default `removalPolicy` is SNAPSHOT.","attributes":["clusterIdentifier","snapshotIdentifier"],"source":"https://docs.aws.amazon.com/cdk/v2/guide/identifiers.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.interruption","service":"aurora","action":"engine_upgrade","tool":"any","section":"interruption","text":"A minor version upgrade restarts the cluster. Aurora PostgreSQL with zero-downtime patching keeps most writer connections (a drop in throughput of a few seconds to about one minute) and restarts the readers; without it every connection is lost. Aurora MySQL zero-downtime patching is best effort and the length of the outage varies with workload, cluster size and binary log data. Zero-downtime patching does not apply to major version upgrades: after the writer is upgraded each reader has a brief outage.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MinorUpgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.permissions","service":"aurora","action":"engine_upgrade","tool":"any","section":"permissions","text":"The person running this needs `rds:DescribeDBEngineVersions`, `rds:DescribeDBClusters`, `rds:CreateDBClusterSnapshot`, `rds:ModifyDBCluster` and `rds:DescribeEvents` on this cluster.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.precheck.target","service":"aurora","action":"engine_upgrade","tool":"any","section":"precheck","text":"Confirm the target is a valid upgrade from the running version.","cli":"aws rds describe-db-engine-versions --engine {engine} --engine-version {from} --region {region} --query \"DBEngineVersions[*].ValidUpgradeTarget[*].{EngineVersion:EngineVersion,AutoUpgrade:AutoUpgrade,Major:IsMajorVersionUpgrade}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.precheck.state","service":"aurora","action":"engine_upgrade","tool":"any","section":"precheck","text":"The cluster must be `available`. Clear pending parameter changes (they interfere with zero-downtime patching). If the cluster is in a global database, upgrade the secondary clusters before the primary, or upgrade the global cluster.","cli":"aws rds describe-db-clusters --db-cluster-identifier {cluster} --region {region} --query \"DBClusters[0].{Status:Status,EngineVersion:EngineVersion,Window:PreferredMaintenanceWindow,Pending:PendingModifiedValues,Global:GlobalClusterIdentifier,AutoMinor:AutoMinorVersionUpgrade}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-upgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.precheck.copy","service":"aurora","action":"engine_upgrade","tool":"any","section":"precheck","text":"Test the upgrade on a copy first: restore a recent snapshot or clone the cluster, upgrade the copy and run the application's tests. New minor versions can change query plans.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MinorUpgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.precheck.major","service":"aurora","action":"engine_upgrade","tool":"any","section":"precheck","when":{"major":"true"},"text":"For a major upgrade of Aurora PostgreSQL: prepare a DB cluster parameter group and a DB parameter group for the new version; no open prepared transactions; logical replication slots block the upgrade on source versions before 17; update extensions such as PostGIS and pgRouting first.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.backup","service":"aurora","action":"engine_upgrade","tool":"any","section":"backup","text":"Take a manual cluster snapshot before the upgrade. Aurora takes its own pre-upgrade snapshot for major version upgrades only, not for minor versions.","cli":"aws rds create-db-cluster-snapshot --db-cluster-identifier {cluster} --db-cluster-snapshot-identifier {snapshot} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.console","service":"aurora","action":"engine_upgrade","tool":"any","section":"console","text":"RDS console, Region {region} > Databases > select the cluster `{cluster}` > Modify > DB engine version: {target} > Continue > choose Apply during the next scheduled maintenance window (or Apply immediately) > Modify cluster.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MinorUpgrade.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.apply.window","service":"aurora","action":"engine_upgrade","tool":"any","section":"apply","text":"Upgrade the cluster in its next maintenance window. Add `--allow-major-version-upgrade` for a major version jump; use `--apply-immediately` to upgrade now.","cli":"aws rds modify-db-cluster --db-cluster-identifier {cluster} --engine-version {target} --no-apply-immediately --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.validation","service":"aurora","action":"engine_upgrade","tool":"any","section":"validation","text":"The cluster is `available` again and its engine version is the target; `SELECT aurora_version();` shows the full version. Check the application reconnected and watch for query plan regressions.","cli":"aws rds describe-db-clusters --db-cluster-identifier {cluster} --region {region} --query \"DBClusters[0].{Status:Status,EngineVersion:EngineVersion}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Updates.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.rollback","service":"aurora","action":"engine_upgrade","tool":"any","section":"rollback","text":"Upgrades are one-way. Aurora PostgreSQL does not support restoring a snapshot, or a point in time, to a previous minor version, so there is no way back from a minor upgrade; test on a clone first. After a major upgrade the pre-upgrade snapshot can restore the previous version into a new cluster. Reverting the version in code is not a rollback: it asks for a downgrade. Aurora rolls back by itself only when a major upgrade fails.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.html","reviewed_on":"2026-11-13"}, +{"id":"aurora.engine_upgrade.if_nothing","service":"aurora","action":"engine_upgrade","tool":"any","section":"if_nothing","text":"Aurora minor versions are available for at least 12 months. After that Aurora may upgrade the cluster to the default minor version in a maintenance window even when auto minor version upgrade is off, with a reminder and cluster event `RDS-EVENT-0156` beforehand. Aurora global databases do not get automatic minor version upgrades.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.VersionPolicy.Versioning.html","reviewed_on":"2026-11-13"} +] diff --git a/services/common/src/infra_vuln/guidance/compute.json b/services/common/src/infra_vuln/guidance/compute.json new file mode 100644 index 000000000..adfb02ee3 --- /dev/null +++ b/services/common/src/infra_vuln/guidance/compute.json @@ -0,0 +1,35 @@ +[ +{"id":"eks_nodegroup.release.what","service":"eks_nodegroup","action":"nodegroup_release","tool":"any","section":"what","text":"A new AMI release for an EKS managed node group. With an EKS optimized AMI the latest security patches and operating system updates come with the latest AMI release version, and only when an update of the node group is started.","source":"https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.tf.attribute","service":"eks_nodegroup","action":"nodegroup_release","tool":"terraform","section":"attribute","text":"Set `release_version` on the `aws_eks_node_group` (or the module input that feeds it, for example `ami_release_version` in terraform-aws-modules/eks). It is an in-place update. When `release_version` is omitted the node group gets the latest AMI only at creation or at the next Kubernetes version change.","attributes":["release_version"],"source":"https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/eks_node_group.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.cfn.attribute","service":"eks_nodegroup","action":"nodegroup_release","tool":"cloudformation","section":"attribute","text":"Set `ReleaseVersion` on the `AWS::EKS::Nodegroup` (Update requires: No interruption). No other property of the node group may change in the same update.","attributes":["ReleaseVersion"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-eks-nodegroup.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.cdk.attribute","service":"eks_nodegroup","action":"nodegroup_release","tool":"cdk","section":"attribute","text":"Set `releaseVersion` in the node group's options. `forceUpdate` defaults to true in CDK: after the 15-minute drain timeout the update ignores pod disruption budgets unless the code sets `forceUpdate: false`.","attributes":["releaseVersion"],"source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_eks.NodegroupOptions.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.takes_effect","service":"eks_nodegroup","action":"nodegroup_release","tool":"any","section":"takes_effect","text":"The update starts when the change is applied or the stack deploys; there is no maintenance window. EKS creates a new launch template version, scales up, then replaces the nodes.","source":"https://docs.aws.amazon.com/eks/latest/userguide/managed-node-update-behavior.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.interruption","service":"eks_nodegroup","action":"nodegroup_release","tool":"any","section":"interruption","text":"Every node is replaced, `maxUnavailable` at a time (default one node). Pods are drained and pod disruption budgets are honoured unless the update is forced. If pods don't leave a node within 15 minutes the update fails with `PodEvictionFailure`; a node that takes more than 15 minutes to join makes it time out.","source":"https://docs.aws.amazon.com/eks/latest/userguide/managed-node-update-behavior.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.replacement","service":"eks_nodegroup","action":"nodegroup_release","tool":"cloudformation","section":"replacement","text":"These properties replace the whole node group: `AmiType`, `CapacityType`, `ClusterName`, `DiskSize`, `InstanceTypes`, `NodegroupName`, `NodeRole`, `RemoteAccess`, `Subnets`. A move from an AL2 to an AL2023 AMI type is such a replacement, not a release bump.","attributes":["AmiType","CapacityType","ClusterName","DiskSize","InstanceTypes","NodegroupName","NodeRole","RemoteAccess","Subnets"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-eks-nodegroup.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.precheck","service":"eks_nodegroup","action":"nodegroup_release","tool":"any","section":"precheck","text":"The node group's version can't be greater than the control plane's. Check pod disruption budgets allow a node to drain, and that there is capacity for the extra nodes the update launches.","cli":"aws eks describe-nodegroup --cluster-name {cluster} --nodegroup-name {id} --region {region} --query \"nodegroup.{Status:status,Release:releaseVersion,Version:version,Update:updateConfig}\"","source":"https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.rollback","service":"eks_nodegroup","action":"nodegroup_release","tool":"any","section":"rollback","text":"A failed update leaves a mixed group. To go back, update the node group again to the previous release version; nodes are replaced the same way.","cli":"aws eks update-nodegroup-version --cluster-name {cluster} --nodegroup-name {id} --release-version {from} --region {region}","source":"https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html","reviewed_on":"2026-11-13"}, +{"id":"eks_nodegroup.release.trap.al2","service":"eks_nodegroup","action":"nodegroup_release","tool":"any","section":"trap","text":"EKS stopped publishing Amazon Linux 2 EKS optimized AMIs on November 26, 2025, and Kubernetes 1.32 is the last version with them. An AL2 node group has no newer release to move to: it needs AL2023 or Bottlerocket, which for a node group without a custom-AMI launch template is a new node group, not this change.","source":"https://docs.aws.amazon.com/eks/latest/userguide/eks-ami-deprecation-faqs.html","reviewed_on":"2026-11-13"}, + +{"id":"ami.replace.what","service":"ami","action":"ami_replace","tool":"any","section":"what","text":"The instances run an AMI that predates the fix. The code change is a newer AMI in a new launch template version; the instances get it only when they are replaced.","source":"https://docs.aws.amazon.com/autoscaling/ec2/userguide/instance-refresh-overview.html","reviewed_on":"2026-11-13"}, +{"id":"ami.replace.tf.attribute","service":"ami","action":"ami_replace","tool":"terraform","section":"attribute","text":"Change only `image_id` on the launch template. Resolving AWS's public AMI parameter with `data \"aws_ssm_parameter\"` puts a concrete AMI id in a new launch template version at plan time, which keeps instance refresh, skip matching and rollback working. If the AMI comes from `data \"aws_ami\"` with `most_recent = true` the code is already current: change nothing and say so.","attributes":["image_id"],"source":"https://docs.aws.amazon.com/autoscaling/ec2/userguide/using-systems-manager-parameters.html","reviewed_on":"2026-11-13"}, +{"id":"ami.replace.tf.takes_effect","service":"ami","action":"ami_replace","tool":"terraform","section":"takes_effect","text":"An AMI change rolls instances only when the Auto Scaling group has an `instance_refresh` block and its launch template `version` is a number or a computed value, not the literal `$Latest`. Without the block, running instances keep the old AMI until they are replaced for another reason. Terraform does not wait for the refresh to finish, and a second apply cancels a running refresh.","source":"https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/autoscaling_group.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"ami.replace.cfn.takes_effect","service":"ami","action":"ami_replace","tool":"cloudformation","section":"takes_effect","text":"CloudFormation refreshes instances only when the group's `LaunchTemplate` property changes and the group has an `UpdatePolicy` (`AutoScalingInstanceRefresh` or `AutoScalingRollingUpdate`). A rolling update does not honour the group's instance maintenance policy and does not launch before terminating.","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-updatepolicy.html","reviewed_on":"2026-11-13"}, +{"id":"ami.replace.interruption","service":"ami","action":"ami_replace","tool":"any","section":"interruption","text":"An instance refresh replaces instances in batches. With the default 90 percent minimum healthy and 100 percent maximum, 10 percent of capacity is replaced at a time and instances are terminated before new ones launch, so a small group loses an instance at a time. Minimum and maximum both at 100 percent launches before terminating.","source":"https://docs.aws.amazon.com/autoscaling/ec2/userguide/instance-refresh-overview.html","reviewed_on":"2026-11-13"}, +{"id":"ami.replace.rollback","service":"ami","action":"ami_replace","tool":"any","section":"rollback","text":"An instance refresh can be rolled back only while it is in progress, only when it was started with a desired configuration, and not when the group uses the `$Latest` or `$Default` launch template version or an AMI alias from Parameter Store. After it finishes, start a new refresh with the previous launch template version.","cli":"aws autoscaling rollback-instance-refresh --auto-scaling-group-name {id} --region {region}","source":"https://docs.aws.amazon.com/autoscaling/ec2/userguide/instance-refresh-rollback.html","reviewed_on":"2026-11-13"}, +{"id":"ami.replace.trap.al2","service":"ami","action":"ami_replace","tool":"any","section":"trap","text":"Amazon Linux 2 reached its end of support on 2026-06-30 and no longer receives standard security updates: for an AL2 AMI the fix is a move to Amazon Linux 2023, which is a migration, not an AMI bump. An AL2023 AMI is locked to a repository version and does not pick up updates by itself.","source":"https://aws.amazon.com/amazon-linux-2/faqs/","reviewed_on":"2026-11-13"}, + +{"id":"lambda_runtime.change.what","service":"lambda_runtime","action":"runtime_change","tool":"any","section":"what","text":"The function runs a deprecated runtime: Lambda may no longer apply security updates to it. Patch-level runtime updates are applied by Lambda automatically; moving to a new major language version means changing the runtime identifier, which AWS never does for you.","source":"https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.tf.attribute","service":"lambda_runtime","action":"runtime_change","tool":"terraform","section":"attribute","text":"Change `runtime` on the `aws_lambda_function`. If an `aws_lambda_runtime_management_config` sets `update_runtime_on = \"Manual\"` for the function, the runtime can't be updated until that mode changes.","attributes":["runtime"],"source":"https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/lambda_runtime_management_config.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.cfn.attribute","service":"lambda_runtime","action":"runtime_change","tool":"cloudformation","section":"attribute","text":"Change `Runtime` on the `AWS::Lambda::Function` (Update requires: No interruption). In Serverless Framework the runtime is `provider.runtime` or the function's own `runtime`.","attributes":["Runtime"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-lambda-function.html","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.takes_effect","service":"lambda_runtime","action":"runtime_change","tool":"any","section":"takes_effect","text":"The change applies to `$LATEST` as soon as it is deployed. CloudFormation updates configuration and code with two calls in sequence, so invocations between them can fail; invoking through a version or alias avoids that.","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-lambda-function.html","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.replacement","service":"lambda_runtime","action":"runtime_change","tool":"cloudformation","section":"replacement","text":"`Runtime` is not a replacement property. `FunctionName` and `PackageType` are.","attributes":["FunctionName","PackageType"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-lambda-function.html","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.precheck","service":"lambda_runtime","action":"runtime_change","tool":"any","section":"precheck","text":"AWS does not guarantee backward compatibility between major language versions. Check the handler code, dependencies packaged with the function, and every layer: a layer built for one language version or operating system needs a new version built for the target runtime, and the function's layer list changes in the same pull request.","source":"https://docs.aws.amazon.com/lambda/latest/dg/runtimes-update.html","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.rollback","service":"lambda_runtime","action":"runtime_change","tool":"any","section":"rollback","text":"Before the old runtime's block-update date, setting the runtime back works. After it, a function can still move to a supported runtime and can't go back. AWS recommends function versions and aliases so a rollback is repointing the alias.","source":"https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html","reviewed_on":"2026-11-13"}, +{"id":"lambda_runtime.change.if_nothing","service":"lambda_runtime","action":"runtime_change","tool":"any","section":"if_nothing","text":"A function on a deprecated runtime keeps running, without security updates. After the block-create date new functions can't use the runtime, and after the block-update date the function's code and configuration can't be updated without also changing the runtime.","source":"https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html","reviewed_on":"2026-11-13"}, + +{"id":"any.order.nonproduction_first","service":"any","action":"any","tool":"any","section":"order","text":"Non-production first: AWS Well-Architected says patching should not be performed on production systems without first testing in a safe environment.","source":"https://docs.aws.amazon.com/wellarchitected/latest/framework/ops_dev_integ_patch_mgmt.html","reviewed_on":"2026-11-13"}, +{"id":"any.plan.terraform","service":"any","action":"any","tool":"terraform","section":"plan","text":"CoderHelm ran no plan: it holds no cloud credentials. In the plan JSON a replacement shows as `change.actions` of `[\"delete\",\"create\"]` or `[\"create\",\"delete\"]`, with `replace_paths` naming the attribute. The plan for this change must show an in-place update of the one resource and nothing destroyed. If it shows \"must be replaced\" or a destroy, do not apply.","source":"https://developer.hashicorp.com/terraform/internals/json-format","reviewed_on":"2026-11-13"}, +{"id":"any.plan.cloudformation","service":"any","action":"any","tool":"cloudformation","section":"plan","text":"CoderHelm created no change set: it holds no cloud credentials. In a change set a replacement shows as `Replacement: True` (or `Conditional`), and `PolicyAction` says what happens to the old resource. An update that needs \"Some interruptions\" shows `Replacement: False` and still restarts the resource. If the change set shows a replacement or a removal, do not execute it.","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ResourceChange.html","reviewed_on":"2026-11-13"}, +{"id":"any.plan.cdk","service":"any","action":"any","tool":"cdk","section":"plan","text":"CoderHelm ran no `cdk diff`: it holds no cloud credentials. `cdk diff` creates a change set to show accurate replacement information (or falls back to a template comparison that over-reports replacements). If it shows the resource being replaced or removed, do not deploy.","source":"https://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cmd-diff.html","reviewed_on":"2026-11-13"}, +{"id":"any.pipeline.merge","service":"any","action":"any","tool":"any","section":"pipeline","text":"Find out how this repository applies changes before merging. Some pipelines apply on merge (a push workflow, HCP Terraform, CloudFormation Git sync, CDK Pipelines), where the plan seen in review is advisory and is recomputed; Atlantis applies from the pull request before merge. CoderHelm opens the pull request and stops there: it never applies.","source":"https://www.runatlantis.io/docs/command-requirements","reviewed_on":"2026-11-13"} +] diff --git a/services/common/src/infra_vuln/guidance/elasticache.json b/services/common/src/infra_vuln/guidance/elasticache.json new file mode 100644 index 000000000..5c0437681 --- /dev/null +++ b/services/common/src/infra_vuln/guidance/elasticache.json @@ -0,0 +1,29 @@ +[ +{"id":"elasticache.service_update.what","service":"elasticache","action":"service_update","tool":"any","section":"what","text":"An ElastiCache service update for a node-based cluster: a patch AWS makes available under a name. Its type is `security-update`, `engine-update` (patches or minor engine updates for the current engine version) or `engine-major-version-update`. Service updates are cumulative: the latest one includes any not yet applied.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.in_code","service":"elasticache","action":"service_update","tool":"any","section":"in_code","text":"This cannot be expressed in code. A service update is applied with `batch-apply-update-action` or by ElastiCache in the maintenance window; Terraform and CloudFormation have no argument for it. From Valkey 7.2 and Redis OSS 6.0 ElastiCache manages the patch version itself, so the code's engine version (major.minor) does not change and nothing drifts.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement-upgrade-considerations.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.cve","service":"elasticache","action":"service_update","tool":"any","section":"cve","text":"A CVE is named here only when an AWS security bulletin names this service update. Otherwise the update's own severity (critical, important, medium, low) is what AWS gives.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.interruption","service":"elasticache","action":"service_update","tool":"any","section":"interruption","text":"Nodes are updated in turn. With replicas the cluster stays available for reads, and writes pause for the few seconds of each failover; existing client connections are terminated, so clients must reconnect with retries and exponential backoff. A single node, or a group without Multi-AZ, is unavailable while its primary is updated. On Memcached, engine version upgrades clear all cache data; AWS does not say on the pages read whether a service update on Memcached nodes does.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement-upgrade-considerations.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.if_nothing","service":"elasticache","action":"service_update","tool":"any","section":"if_nothing","text":"Each update has a Recommended Apply By Date (critical: within 14 days, important: 30, medium: 60, low: 90). When its \"Auto-update after due date\" is Yes, ElastiCache schedules it in the cluster's maintenance window after that date; when it is No it is never applied automatically. ElastiCache reserves the right to patch on your behalf for a critical security vulnerability.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.permissions","service":"elasticache","action":"service_update","tool":"any","section":"permissions","text":"The person running this needs `elasticache:DescribeServiceUpdates`, `elasticache:DescribeUpdateActions`, `elasticache:BatchApplyUpdateAction`, `elasticache:DescribeReplicationGroups` and `elasticache:CreateSnapshot` on this replication group.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.precheck.status","service":"elasticache","action":"service_update","tool":"any","section":"precheck","text":"Only an update with status available or scheduled can be applied. Read its severity, type and whether it auto-applies after the due date.","cli":"aws elasticache describe-update-actions --replication-group-ids {id} --service-update-name {update} --region {region}","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.precheck.group","service":"elasticache","action":"service_update","tool":"any","section":"precheck","text":"The replication group must be `available`. Read whether Multi-AZ and automatic failover are on, how many replicas each shard has, and the maintenance window. Apply in a period of low write traffic.","cli":"aws elasticache describe-replication-groups --replication-group-id {id} --region {region} --query \"ReplicationGroups[0].{Status:Status,MultiAZ:MultiAZ,Failover:AutomaticFailover,Snapshots:SnapshotRetentionLimit}\"","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement-upgrade-considerations.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.backup","service":"elasticache","action":"service_update","tool":"any","section":"backup","text":"Automatic backups are off unless the snapshot retention limit is above zero. Take a manual backup first (Valkey and Redis OSS; Memcached has no persistence).","cli":"aws elasticache create-snapshot --replication-group-id {id} --snapshot-name {snapshot} --region {region}","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.console","service":"elasticache","action":"service_update","tool":"any","section":"console","text":"ElastiCache console, Region {region} > Service updates > select `{update}` > select the cluster `{id}` > Apply now.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.apply","service":"elasticache","action":"service_update","tool":"any","section":"apply","text":"Apply the service update to the replication group.","cli":"aws elasticache batch-apply-update-action --service-update-name {update} --replication-group-ids {id} --region {region}","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.validation","service":"elasticache","action":"service_update","tool":"any","section":"validation","text":"The update action's status goes from in-progress to complete (shown for 7 days). Check the replication group is `available` and clients reconnected.","cli":"aws elasticache describe-update-actions --replication-group-ids {id} --service-update-name {update} --region {region}","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.service_update.rollback","service":"elasticache","action":"service_update","tool":"any","section":"rollback","text":"A running update can be stopped: nodes already in progress finish, the others are left on the old version and the update can be resumed later. Nodes that were updated can't be reverted.","cli":"aws elasticache batch-stop-update-action --service-update-name {update} --replication-group-ids {id} --region {region}","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Self-Service-Updates.html","reviewed_on":"2026-11-13"}, + +{"id":"elasticache.engine_upgrade.what","service":"elasticache","action":"engine_upgrade","tool":"any","section":"what","text":"An engine version upgrade of the cache (a new major or minor version, or the move from Redis OSS to Valkey). ElastiCache never starts one by itself while a version is supported: it is started by changing the engine version.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.in_code","service":"elasticache","action":"engine_upgrade","tool":"any","section":"in_code","text":"This has a code equivalent: the engine version of the replication group (and the engine, for Redis OSS to Valkey).","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/elasticache_replication_group.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.tf.attribute","service":"elasticache","action":"engine_upgrade","tool":"terraform","section":"attribute","text":"Change `engine_version` on the `aws_elasticache_replication_group`. For version 7 and higher write major.minor (`7.2`), never a patch version; for 6 write `6.2` or `6.x`. A major version jump also needs a compatible `parameter_group_name`. Moving to Valkey sets `engine = \"valkey\"` together with an explicit `engine_version`. `aws_elasticache_cluster` accepts only `memcached` and `redis`.","attributes":["engine_version"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/elasticache_replication_group.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.tf.takes_effect","service":"elasticache","action":"engine_upgrade","tool":"terraform","section":"takes_effect","text":"`apply_immediately` defaults to `false`: the upgrade waits for the next maintenance window and the plan keeps showing a difference until it runs. Any attribute change that re-creates the resource is applied immediately whatever `apply_immediately` says.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/elasticache_replication_group.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.tf.replacement","service":"elasticache","action":"engine_upgrade","tool":"terraform","section":"replacement","text":"An `engine_version` increase is in place. A decrease is not: the provider re-creates the replication group when the version is lowered, which destroys the data. Never lower the version to roll back. CoderHelm also refuses a change to `replication_group_id`, `subnet_group_name`, `at_rest_encryption_enabled`, `kms_key_id` or `port` in an upgrade change.","attributes":["replication_group_id","subnet_group_name","at_rest_encryption_enabled","kms_key_id","port"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/internal/service/elasticache/engine_version.go","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.cfn.attribute","service":"elasticache","action":"engine_upgrade","tool":"cloudformation","section":"attribute","text":"Change `EngineVersion` on the `AWS::ElastiCache::ReplicationGroup` (Update requires: No interruption, meaning no replacement; the service still fails over). Moving to Valkey sets `Engine: valkey` and needs a parameter group. `AWS::ElastiCache::CacheCluster` accepts only `memcached` and `redis`, and changing its `Engine` is a replacement.","attributes":["EngineVersion"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.cfn.takes_effect","service":"elasticache","action":"engine_upgrade","tool":"cloudformation","section":"takes_effect","text":"These resources have no `ApplyImmediately` property. AWS does not say on the pages read whether a version change from CloudFormation applies at once or in the maintenance window: plan for it to start when the stack update runs.","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.cfn.replacement","service":"elasticache","action":"engine_upgrade","tool":"cloudformation","section":"replacement","text":"Replacement properties include `AtRestEncryptionEnabled`, `KmsKeyId`, `CacheSubnetGroupName`, `Port`, `ReplicationGroupId`, `SnapshotName`, `NetworkType` and `DataTieringEnabled`. Changing `NumNodeGroups` or `NodeGroupConfiguration` without `UpdatePolicy: UseOnlineResharding: true` replaces the whole replication group.","attributes":["AtRestEncryptionEnabled","KmsKeyId","CacheSubnetGroupName","Port","ReplicationGroupId","SnapshotName","NetworkType","DataTieringEnabled","NumNodeGroups","NodeGroupConfiguration"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.interruption","service":"elasticache","action":"engine_upgrade","tool":"any","section":"interruption","text":"From Redis OSS 5.0.6 the cluster stays available for reads during the upgrade and for writes except during each failover, which lasts a few seconds; existing client connections are terminated. A single node, or a group without Multi-AZ, has its primary unavailable during the upgrade. A Memcached version upgrade always clears all cache data.","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement-upgrade-considerations.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.precheck","service":"elasticache","action":"engine_upgrade","tool":"any","section":"precheck","text":"A pending scale-up blocks an engine upgrade. A single node or non-Multi-AZ group needs enough free memory for a snapshot. A major version jump needs a parameter group compatible with the new version. An encrypted group can't move to a version without encryption support.","cli":"aws elasticache describe-replication-groups --replication-group-id {id} --region {region} --query \"ReplicationGroups[0].{Status:Status,MultiAZ:MultiAZ,Failover:AutomaticFailover,Pending:PendingModifiedValues,Snapshots:SnapshotRetentionLimit}\"","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement.HowTo.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.backup","service":"elasticache","action":"engine_upgrade","tool":"any","section":"backup","text":"The upgrade makes a best effort to keep the data. Automatic backups are off unless the snapshot retention limit is above zero: take a manual backup first.","cli":"aws elasticache create-snapshot --replication-group-id {id} --snapshot-name {snapshot} --region {region}","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement-upgrade-considerations.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.apply","service":"elasticache","action":"engine_upgrade","tool":"any","section":"apply","text":"Upgrade the replication group in its next maintenance window (use `--apply-immediately` to upgrade now).","cli":"aws elasticache modify-replication-group --replication-group-id {id} --engine-version {target} --no-apply-immediately --region {region}","source":"https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/VersionManagement.HowTo.html","reviewed_on":"2026-11-13"}, +{"id":"elasticache.engine_upgrade.rollback","service":"elasticache","action":"engine_upgrade","tool":"any","section":"rollback","text":"You can't downgrade to an earlier engine version: the only way is to delete the group and create it again on the earlier version, restoring a backup. The one exception AWS documents is rolling Valkey 7.2 back to Redis OSS 7.1.","source":"https://docs.aws.amazon.com/cli/latest/reference/elasticache/modify-replication-group.html","reviewed_on":"2026-11-13"} +] diff --git a/services/common/src/infra_vuln/guidance/opensearch.json b/services/common/src/infra_vuln/guidance/opensearch.json new file mode 100644 index 000000000..0a5306e96 --- /dev/null +++ b/services/common/src/infra_vuln/guidance/opensearch.json @@ -0,0 +1,29 @@ +[ +{"id":"opensearch.service_software.what","service":"opensearch","action":"service_software","tool":"any","section":"what","text":"An OpenSearch Service software update: a new release of the service's own software for the domain (releases ending in `-P` and a number are patches). It is not an engine version upgrade. Required updates generally carry critical security fixes; most updates are optional.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.in_code","service":"opensearch","action":"service_software","tool":"any","section":"in_code","text":"This cannot be expressed in code. Terraform, CloudFormation and CDK can only switch automatic software updates on (`auto_software_update_enabled`, `SoftwareUpdateOptions`, `enableAutoSoftwareUpdate`) and set the off-peak window; none can apply a given release. The engine version in code does not change.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/opensearch_domain.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.cve","service":"opensearch","action":"service_software","tool":"any","section":"cve","text":"A CVE is named here only when an AWS security bulletin names this service software release. AWS's examples of required updates are Log4j CVEs and enforcing IMDSv2.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.interruption","service":"opensearch","action":"service_software","tool":"any","section":"interruption","text":"Service software updates use a blue/green deployment: the domain stays available while the node count temporarily rises, often doubling, with possible higher latency and rejected requests, and extra load on dedicated master nodes. Updates typically complete within minutes and can take hours or days under heavy load.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/managedomains-configuration-changes.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.if_nothing","service":"opensearch","action":"service_software","tool":"any","section":"if_nothing","text":"An optional update is never forced. A required update is installed by AWS in the off-peak window once its deadline passes. AWS's current pages state the deadline two ways (typically 14 days from availability, and a 30-day rule); the date on this card is the one the API returned for this domain. AWS also states that a domain left without a required update is first isolated (all network access removed) and later permanently deleted with its data.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.permissions","service":"opensearch","action":"service_software","tool":"any","section":"permissions","text":"The person running this needs `es:DescribeDomain`, `es:StartServiceSoftwareUpdate` and `es:CancelServiceSoftwareUpdate` on this domain.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.precheck","service":"opensearch","action":"service_software","tool":"any","section":"precheck","text":"Read the update's state in `ServiceSoftwareOptions` (`UpdateAvailable`, `NewVersion`, `OptionalDeployment`, `AutomatedUpdateDate`). A domain that is processing a change, has a red cluster status, a high error rate or split brain is not eligible. Check there is headroom for the temporary extra nodes.","cli":"aws opensearch describe-domain --domain-name {id} --region {region} --query \"DomainStatus.{Processing:Processing,Software:ServiceSoftwareOptions,OffPeak:OffPeakWindowOptions}\"","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.backup","service":"opensearch","action":"service_software","tool":"any","section":"backup","text":"OpenSearch Service takes hourly automated snapshots. Take a manual snapshot to a repository you control if you need a restore point of your own.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/opensearch_domain.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.console","service":"opensearch","action":"service_software","tool":"any","section":"console","text":"OpenSearch Service console, Region {region} > Domains > select `{id}` > Actions > Update > choose Apply update now or Schedule it in off-peak window > Confirm.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.apply.window","service":"opensearch","action":"service_software","tool":"any","section":"apply","text":"Schedule the update for the domain's off-peak window.","cli":"aws opensearch start-service-software-update --domain-name {id} --schedule-at OFF_PEAK_WINDOW --region {region}","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.apply.now","service":"opensearch","action":"service_software","tool":"any","section":"apply","text":"Or start the update now, outside the off-peak window.","cli":"aws opensearch start-service-software-update --domain-name {id} --schedule-at NOW --region {region}","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.validation","service":"opensearch","action":"service_software","tool":"any","section":"validation","text":"`UpdateStatus` goes from `PENDING_UPDATE` to `IN_PROGRESS` to `COMPLETED` and `CurrentVersion` becomes the new release. Check the cluster is green.","cli":"aws opensearch describe-domain --domain-name {id} --region {region} --query \"DomainStatus.ServiceSoftwareOptions\"","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.rollback","service":"opensearch","action":"service_software","tool":"any","section":"rollback","text":"An update can be cancelled only in the `PENDING_UPDATE` state. For updates applied on or after April 24, 2026 a rollback is supported for 15 days, once per update, unless a configuration change was made after the update, AWS applied a mandatory update after its deadline, or the update rode along with another blue/green change.","cli":"aws opensearch cancel-service-software-update --domain-name {id} --region {region}","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.service_software.trap","service":"opensearch","action":"service_software","tool":"any","section":"trap","text":"By default any change to the domain that causes a blue/green deployment (instance type, security groups, advanced settings and others) also installs the latest service software (`UseLatestServiceSoftwareForBlueGreen`), and an update installed that way can't be rolled back. An unrelated infrastructure change can therefore apply this update.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/service-software.html","reviewed_on":"2026-11-13"}, + +{"id":"opensearch.engine_upgrade.what","service":"opensearch","action":"engine_upgrade","tool":"any","section":"what","text":"An engine version upgrade of the domain (OpenSearch or Elasticsearch version). The in-place upgrade runs as a blue/green deployment and can't be paused, cancelled or rolled back.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/version-migration.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.in_code","service":"opensearch","action":"engine_upgrade","tool":"any","section":"in_code","text":"This has a code equivalent: the engine version of the domain (`OpenSearch_X.Y` or `Elasticsearch_X.Y`).","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/opensearch_domain.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.tf.attribute","service":"opensearch","action":"engine_upgrade","tool":"terraform","section":"attribute","text":"Change `engine_version` on the `aws_opensearch_domain` (`OpenSearch_X.Y` or `Elasticsearch_X.Y`). The provider documentation does not say whether this is an in-place upgrade or a replacement: read the plan before merging, and stop if it says the domain must be replaced.","attributes":["engine_version"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/opensearch_domain.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.tf.replacement","service":"opensearch","action":"engine_upgrade","tool":"terraform","section":"replacement","text":"The provider documents these as forcing a new domain: adding or removing `vpc_options`, and `advanced_security_options.enabled` going from true to false. CoderHelm also refuses a change to `domain_name` in an upgrade change.","attributes":["domain_name","vpc_options"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/opensearch_domain.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.cfn.attribute","service":"opensearch","action":"engine_upgrade","tool":"cloudformation","section":"attribute","text":"Change `EngineVersion` on the `AWS::OpenSearchService::Domain`, and only with the `UpdatePolicy: EnableVersionUpgrade: true` attribute on the resource. With the policy the version updates without replacement.","attributes":["EngineVersion"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-opensearchservice-domain.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.cfn.replacement","service":"opensearch","action":"engine_upgrade","tool":"cloudformation","section":"replacement","requires":"EnableVersionUpgrade","text":"Without `UpdatePolicy: EnableVersionUpgrade: true` (or with it false), changing `EngineVersion` makes CloudFormation replace the whole domain: a new empty domain is created and the old one is deleted with its data. The policy must be on the resource before, or in the same change as, the version change. `DomainName` and `EngineMode` are replacement properties, changing `EncryptionAtRestOptions` re-creates the domain, and switching `AWS::Elasticsearch::Domain` to `AWS::OpenSearchService::Domain` in a template deletes the domain.","attributes":["DomainName","EngineMode","EncryptionAtRestOptions"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-updatepolicy.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.cdk.attribute","service":"opensearch","action":"engine_upgrade","tool":"cdk","section":"attribute","text":"Change the `version` of the `opensearchservice.Domain`, and only with `enableVersionUpgrade: true` on the domain (it defaults to false). On an L1 `CfnDomain`, set `cfnOptions.updatePolicy = { enableVersionUpgrade: true }`.","attributes":["version"],"source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_opensearchservice.Domain.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.cdk.replacement","service":"opensearch","action":"engine_upgrade","tool":"cdk","section":"replacement","requires":"enableVersionUpgrade","text":"`enableVersionUpgrade` defaults to false, and without it a version change replaces the whole domain with an empty one. Changing a construct id or the domain name replaces it too. The default `removalPolicy` is RETAIN.","attributes":["domainName"],"source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_opensearchservice.Domain.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.interruption","service":"opensearch","action":"engine_upgrade","tool":"any","section":"interruption","text":"The upgrade takes from 15 minutes to several hours. The domain stays available, write performance can degrade, and OpenSearch Dashboards might be unavailable for some or all of it.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/version-migration.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.precheck","service":"opensearch","action":"engine_upgrade","tool":"any","section":"precheck","text":"Check the upgrade path is supported (OpenSearch 1.3 or 2.x must reach 2.19 before 3.x; indexes created on old versions may need reindexing first). The service runs pre-upgrade checks and does not proceed unless they pass: green cluster, disk usage below 90%, JVM memory pressure below 75%, fewer than 1,000 shards per node, no snapshot in progress, plugins available on the target. With managed disaster recovery, upgrade the secondary domain first.","cli":"aws opensearch describe-domain --domain-name {id} --region {region} --query \"DomainStatus.{EngineVersion:EngineVersion,Processing:Processing,UpgradeProcessing:UpgradeProcessing}\"","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/version-migration.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.backup","service":"opensearch","action":"engine_upgrade","tool":"any","section":"backup","text":"Take a manual snapshot before upgrading. The service takes its own pre-upgrade snapshot and uses it only to restore the cluster if the upgrade fails.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/version-migration.html","reviewed_on":"2026-11-13"}, +{"id":"opensearch.engine_upgrade.rollback","service":"opensearch","action":"engine_upgrade","tool":"any","section":"rollback","text":"An in-place engine upgrade can't be rolled back. To return to the earlier version, restore a manual snapshot on a new domain. Snapshots taken on OpenSearch 1.x and Elasticsearch 7.10 or earlier are incompatible with OpenSearch 3.x.","source":"https://docs.aws.amazon.com/opensearch-service/latest/developerguide/version-migration.html","reviewed_on":"2026-11-13"} +] diff --git a/services/common/src/infra_vuln/guidance/rds.json b/services/common/src/infra_vuln/guidance/rds.json new file mode 100644 index 000000000..bdc351342 --- /dev/null +++ b/services/common/src/infra_vuln/guidance/rds.json @@ -0,0 +1,46 @@ +[ +{"id":"rds.os_update.what","service":"rds","action":"os_update","tool":"any","section":"what","text":"An operating system update for the DB instance (`system-update` on an instance ARN). It does not change the DB engine version or the DB instance class.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.in_code","service":"rds","action":"os_update","tool":"any","section":"in_code","text":"This cannot be expressed in code. The Terraform `aws_db_instance`, CloudFormation `AWS::RDS::DBInstance` and CDK resources have a maintenance window, auto minor version upgrade and an engine version, and no argument that applies a pending maintenance action. No code change is needed and none causes drift: the operating system level is not an attribute of the resource.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.cve","service":"rds","action":"os_update","tool":"any","section":"cve","text":"AWS publishes no CVE list for this action: it returns the action, its dates and a generic description. AWS says operating system updates most often occur for security issues and recommends applying them as soon as possible.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.interruption","service":"rds","action":"os_update","tool":"any","section":"interruption","text":"Operating system updates typically take about 10 minutes. On a Multi-AZ DB instance deployment RDS patches the standby, promotes it, then patches the old primary: one failover that typically lasts less than a minute. A Single-AZ instance is offline while it is patched.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.if_nothing","service":"rds","action":"os_update","tool":"any","section":"if_nothing","text":"An optional update has no apply date and RDS never applies it automatically. A mandatory update has an apply date: after it RDS applies the update in a maintenance window, and moving the window does not avoid it (after the mandatory date RDS can apply it outside the preferred window).","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.permissions","service":"rds","action":"os_update","tool":"any","section":"permissions","text":"The person running this needs `rds:DescribePendingMaintenanceActions`, `rds:ApplyPendingMaintenanceAction`, `rds:DescribeDBInstances`, `rds:DescribeEvents` and `rds:CreateDBSnapshot` on this instance, and AWS CLI access to the account and Region.","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.precheck.pending","service":"rds","action":"os_update","tool":"any","section":"precheck","text":"Confirm the action is still pending and read its dates (a mandatory update has `AutoAppliedAfterDate` and `CurrentApplyDate`; an optional one has neither).","cli":"aws rds describe-pending-maintenance-actions --resource-identifier {arn} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.precheck.status","service":"rds","action":"os_update","tool":"any","section":"precheck","text":"The instance must be `available`. Read whether it is Multi-AZ and when its maintenance window is. Changes waiting for the window are in `PendingModifiedValues`, not in the pending maintenance list.","cli":"aws rds describe-db-instances --db-instance-identifier {id} --region {region} --query \"DBInstances[0].{Status:DBInstanceStatus,MultiAZ:MultiAZ,Window:PreferredMaintenanceWindow,Pending:PendingModifiedValues}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.backup","service":"rds","action":"os_update","tool":"any","section":"backup","text":"An `immediate` opt-in can't be undone. Take a manual snapshot first so there is a known restore point.","cli":"aws rds create-db-snapshot --db-instance-identifier {id} --db-snapshot-identifier {snapshot} --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.console","service":"rds","action":"os_update","tool":"any","section":"console","text":"RDS console, Region {region} > Databases > select `{id}` > Actions > Patch at next window (or Patch now). Defer upgrade stays available until the update starts.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.apply.window","service":"rds","action":"os_update","tool":"any","section":"apply","text":"Schedule it for the next maintenance window.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type next-maintenance --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.apply.now","service":"rds","action":"os_update","tool":"any","section":"apply","text":"Or apply it now, in a quiet period. An immediate opt-in can't be undone.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type immediate --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.validation","service":"rds","action":"os_update","tool":"any","section":"validation","text":"The action leaves the pending list once applied. The list is eventually consistent: right after applying it can still show the action. Poll with backoff, starting at a couple of seconds, for up to five minutes, then check the instance is `available` again.","cli":"aws rds describe-pending-maintenance-actions --resource-identifier {arn} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.os_update.rollback","service":"rds","action":"os_update","tool":"any","section":"rollback","text":"A scheduled update that has not started can be cancelled with `undo-opt-in`. Once it has started it can't be deferred, and an immediate opt-in can't be undone. AWS documents no way to remove an applied operating system update; the restore point is the snapshot.","cli":"aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {action} --opt-in-type undo-opt-in --region {region}","source":"https://docs.aws.amazon.com/cli/latest/reference/rds/apply-pending-maintenance-action.html","reviewed_on":"2026-11-13"}, + +{"id":"rds.engine_upgrade.what","service":"rds","action":"engine_upgrade","tool":"any","section":"what","text":"An engine version upgrade (`db-upgrade`). It is the one pending maintenance action with a code equivalent: raising the engine version in code does the same thing and keeps the code and the database aligned.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.in_code","service":"rds","action":"engine_upgrade","tool":"any","section":"in_code","text":"This has a code equivalent: the engine version attribute of the database resource. Applying it in AWS instead leaves a version pinned in code behind the live one.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cve","service":"rds","action":"engine_upgrade","tool":"any","section":"cve","text":"The pending action carries no CVE list. A CVE is named here only when an AWS bulletin ties it to this engine and target version.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.tf.attribute","service":"rds","action":"engine_upgrade","tool":"terraform","section":"attribute","text":"Change `engine_version` on the `aws_db_instance` (or the module input or variable that feeds it). It is an in-place update. A major version jump also needs `allow_major_version_upgrade = true` and a parameter group of the new family in `parameter_group_name`.","attributes":["engine_version"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.tf.takes_effect","service":"rds","action":"engine_upgrade","tool":"terraform","section":"takes_effect","text":"`apply_immediately` defaults to `false`: after apply the upgrade is queued for the next maintenance window, and the plan keeps showing a difference until it runs. With `apply_immediately = true` the outage happens at apply time, which in an apply-on-merge pipeline is at merge.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.tf.replacement","service":"rds","action":"engine_upgrade","tool":"terraform","section":"replacement","text":"`engine_version` updates in place. The provider documents `backup_target`, `nchar_character_set_name`, `restore_to_point_in_time` and `multi_tenant` (true to false) as forcing a new resource. CoderHelm also refuses a change to `identifier`, `identifier_prefix` or `snapshot_identifier` in an upgrade change, to stay on the safe side: check the plan for \"must be replaced\".","attributes":["backup_target","nchar_character_set_name","restore_to_point_in_time","multi_tenant","identifier","identifier_prefix","snapshot_identifier"],"source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.tf.trap.behind","service":"rds","action":"engine_upgrade","tool":"terraform","section":"trap","text":"If the live version is already ahead of the pinned `engine_version` (auto minor version upgrade defaults to `true`), the next apply asks RDS for a lower version and RDS refuses it (`InvalidParameterCombination`: cannot upgrade from the higher version to the lower one), which blocks every apply of that root. Never set a value below the live version. The provider fix for `aws_db_instance` was still an open pull request on the review date.","source":"https://github.com/hashicorp/terraform-provider-aws/pull/49496","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.tf.trap.prefix","service":"rds","action":"engine_upgrade","tool":"terraform","section":"trap","text":"With auto minor version upgrade enabled the provider accepts a version prefix (`8.0` for `8.0.36`) and reports the running version as `engine_version_actual`. A prefix that already covers the target needs no code change; keep the prefix rather than replacing it with a full version.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.tf.option.bluegreen","service":"rds","action":"engine_upgrade","tool":"terraform","section":"option","text":"`blue_green_update { enabled = true }` performs the update through an RDS Blue/Green deployment (MySQL, MariaDB and PostgreSQL only, not with replicas, backups must be enabled). Switchover downtime is usually under one minute. Do not add it as part of this change unless the team asks: it changes how every later update of the instance is applied.","source":"https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/db_instance.html.markdown","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cfn.attribute","service":"rds","action":"engine_upgrade","tool":"cloudformation","section":"attribute","text":"Change `EngineVersion` on the `AWS::RDS::DBInstance` (or the parameter that feeds it). Update requires: Some interruptions (in place, not a replacement). A major version jump also needs `AllowMajorVersionUpgrade: true`.","attributes":["EngineVersion"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbinstance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cfn.takes_effect","service":"rds","action":"engine_upgrade","tool":"cloudformation","section":"takes_effect","text":"CloudFormation applies DB instance updates immediately by default (`ApplyImmediately` defaults to `true`): the outage happens when the stack update runs. With `ApplyImmediately: false` the change waits for the next maintenance window and the instance stays in a drift state until then.","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbinstance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cfn.replacement","service":"rds","action":"engine_upgrade","tool":"cloudformation","section":"replacement","text":"`EngineVersion` is not a replacement property. `DBInstanceIdentifier`, `DBClusterIdentifier` and `DBSnapshotIdentifier` are: CloudFormation creates a replacement instance, then deletes the old one and its automated snapshots. Changing the logical id of the resource replaces it too.","attributes":["DBInstanceIdentifier","DBClusterIdentifier","DBSnapshotIdentifier"],"source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbinstance.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cfn.trap.template","service":"rds","action":"engine_upgrade","tool":"cloudformation","section":"trap","text":"CloudFormation compares the new template with the previous template, not with the live database. If AWS already moved the version forward, the stale template value is invisible until someone edits it. Set the value to at least the live version. A version prefix (`16`, `8.0`) is matched by prefix during drift detection.","source":"https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cfn.trap.bluegreen","service":"rds","action":"engine_upgrade","tool":"cloudformation","section":"trap","text":"RDS Blue/Green Deployments are not supported with CloudFormation. Do not propose one for a stack-managed database.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-considerations.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cdk.attribute","service":"rds","action":"engine_upgrade","tool":"cdk","section":"attribute","text":"Change the engine version on the instance's `engine` (for example `rds.PostgresEngineVersion.VER_17_7` or `rds.MysqlEngineVersion.VER_8_0_39`; use the class's static `of(...)` when the library has no constant for the target). CDK passes it to `EngineVersion`, an in-place update. A major version jump also needs `allowMajorVersionUpgrade: true` (default false).","attributes":["version","engine"],"source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_rds-readme.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cdk.takes_effect","service":"rds","action":"engine_upgrade","tool":"cdk","section":"takes_effect","text":"The change applies when the stack deploys. To schedule instance modifications for the next maintenance window set `applyImmediately: false` on the instance.","source":"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_rds-readme.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.cdk.replacement","service":"rds","action":"engine_upgrade","tool":"cdk","section":"replacement","text":"Changing a construct id changes the logical id, and CloudFormation then replaces the resource. Keep every construct id and the instance identifier as they are. The default `removalPolicy` is SNAPSHOT.","attributes":["instanceIdentifier","snapshotIdentifier"],"source":"https://docs.aws.amazon.com/cdk/v2/guide/identifiers.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.interruption","service":"rds","action":"engine_upgrade","tool":"any","section":"interruption","text":"Engine upgrades require downtime. Multi-AZ does not avoid it for a DB instance deployment: primary and standby are upgraded at the same time and both are unavailable, and a minor upgrade can last several minutes. A Multi-AZ DB cluster typically limits a minor upgrade to about 35 seconds (one second or less behind RDS Proxy). A Single-AZ instance is offline for the length of the upgrade; AWS gives no figure. RDS for MySQL major upgrades typically complete in about 10 minutes.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.MySQL.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.permissions","service":"rds","action":"engine_upgrade","tool":"any","section":"permissions","text":"The person running this needs `rds:DescribeDBEngineVersions`, `rds:DescribeDBInstances`, `rds:CreateDBSnapshot`, `rds:ModifyDBInstance` (or `rds:ApplyPendingMaintenanceAction`) and `rds:DescribeEvents` on this instance.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.precheck.target","service":"rds","action":"engine_upgrade","tool":"any","section":"precheck","text":"Confirm the target is a valid upgrade from the running version (the row with `AutoUpgrade` true is the version RDS moves to on its own).","cli":"aws rds describe-db-engine-versions --engine {engine} --engine-version {from} --region {region} --query \"DBEngineVersions[*].ValidUpgradeTarget[*].{EngineVersion:EngineVersion,AutoUpgrade:AutoUpgrade,Major:IsMajorVersionUpgrade}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.precheck.replicas","service":"rds","action":"engine_upgrade","tool":"any","section":"precheck","text":"Read replicas change the order. RDS for MySQL: upgrade every read replica before the source instance. RDS for PostgreSQL major upgrade: in-Region replicas are upgraded together with the primary and can lengthen its downtime. Multi-AZ DB cluster read replicas: for a minor upgrade, upgrade the replicas first or the upgrade is blocked.","cli":"aws rds describe-db-instances --db-instance-identifier {id} --region {region} --query \"DBInstances[0].{Replicas:ReadReplicaDBInstanceIdentifiers,ReplicaOf:ReadReplicaSourceDBInstanceIdentifier,Backups:BackupRetentionPeriod,MultiAZ:MultiAZ,Window:PreferredMaintenanceWindow,AutoMinor:AutoMinorVersionUpgrade}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.MySQL.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.precheck.major","service":"rds","action":"engine_upgrade","tool":"any","section":"precheck","when":{"major":"true"},"text":"For a major upgrade: have a parameter group of the new family ready; apply pending operating system updates first; PostgreSQL needs no open prepared transactions, no logical replication slots on source versions before 17, and extensions that the target supports; MySQL goes one major version at a time (5.7 to 8.0, then 8.0 to 8.4) and runs mandatory prechecks that cancel the upgrade before the instance stops (details in `PrePatchCompatibility.log`).","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.PostgreSQL.MajorVersion.Process.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.precheck.copy","service":"rds","action":"engine_upgrade","tool":"any","section":"precheck","text":"Test the upgrade on a copy first: restore a snapshot into a new instance, upgrade that instance and run the application's tests against it.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/MySQL.Concepts.VersionMgmt.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.backup","service":"rds","action":"engine_upgrade","tool":"any","section":"backup","text":"Take a manual snapshot before the upgrade. RDS takes its own snapshots before and after an upgrade only when the backup retention period is greater than 0.","cli":"aws rds create-db-snapshot --db-instance-identifier {id} --db-snapshot-identifier {snapshot} --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.MySQL.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.console","service":"rds","action":"engine_upgrade","tool":"any","section":"console","text":"RDS console, Region {region} > Databases > select `{id}` > Modify > DB engine version: {target} > Continue > choose Apply during the next scheduled maintenance window (or Apply immediately) > Modify DB instance.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.apply.window","service":"rds","action":"engine_upgrade","tool":"any","section":"apply","text":"Upgrade in the next maintenance window. Add `--allow-major-version-upgrade` for a major version jump; use `--apply-immediately` to upgrade now.","cli":"aws rds modify-db-instance --db-instance-identifier {id} --engine-version {target} --no-apply-immediately --region {region}","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.validation","service":"rds","action":"engine_upgrade","tool":"any","section":"validation","text":"During the upgrade the status is `upgrading` and the instance can't be modified. Afterwards the status is `available` and the engine version is the target. After a PostgreSQL major upgrade run `ANALYZE VERBOSE;` in every database and update extensions with `ALTER EXTENSION name UPDATE`.","cli":"aws rds describe-db-instances --db-instance-identifier {id} --region {region} --query \"DBInstances[0].{Status:DBInstanceStatus,EngineVersion:EngineVersion,Pending:PendingModifiedValues}\"","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.rollback","service":"rds","action":"engine_upgrade","tool":"any","section":"rollback","text":"Upgrades are one-way: after the upgrade you can't revert to the previous engine version. The way back is restoring the pre-upgrade snapshot into a new DB instance, which loses every write since the snapshot. Reverting the version in code is not a rollback: it asks RDS for a downgrade, which RDS refuses. RDS rolls back by itself only when the upgrade fails.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.MySQL.html","reviewed_on":"2026-11-13"}, +{"id":"rds.engine_upgrade.if_nothing","service":"rds","action":"engine_upgrade","tool":"any","section":"if_nothing","text":"With auto minor version upgrade on, RDS upgrades in the maintenance window to the version it has flagged for automatic upgrade. With it off, RDS still upgrades for critical security issues or when the version reaches its end of support, and after a mandatory date it can do so outside the preferred window.","source":"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html","reviewed_on":"2026-11-13"} +] diff --git a/services/common/src/infra_vuln/hcl.rs b/services/common/src/infra_vuln/hcl.rs new file mode 100644 index 000000000..e29e3f1f5 --- /dev/null +++ b/services/common/src/infra_vuln/hcl.rs @@ -0,0 +1,528 @@ +//! Just enough of HCL to find where a value is set: the blocks of a +//! Terraform or OpenTofu file (`resource`, `module`, `variable`, `locals`), +//! their attributes with the line each is on, and the simple expressions a +//! value is usually written as (a literal, `var.x`, `local.x`, a string +//! with `${...}` in it). Anything else is kept as its text and treated as +//! unknown; nothing is evaluated. + +/// One attribute: `name = expr`, and the 1-based line it starts on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Attr { + pub name: String, + pub expr: String, + pub line: u32, +} + +/// One block: `kind "label" "label" { ... }`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Block { + pub kind: String, + pub labels: Vec, + pub line: u32, + pub end_line: u32, + pub attrs: Vec, + pub blocks: Vec, +} + +impl Block { + pub fn attr(&self, name: &str) -> Option<&Attr> { + self.attrs.iter().find(|a| a.name == name) + } + pub fn label(&self, i: usize) -> &str { + self.labels.get(i).map(String::as_str).unwrap_or("") + } + pub fn child(&self, kind: &str) -> Option<&Block> { + self.blocks.iter().find(|b| b.kind == kind) + } +} + +struct P<'a> { + s: &'a [u8], + i: usize, + line: u32, + /// Inside `{ k = v, k2: v2 }`: commas end a value, `:` assigns. + object: bool, +} + +impl P<'_> { + fn peek(&self) -> Option { + self.s.get(self.i).copied() + } + fn at(&self, t: &str) -> bool { + self.s[self.i..].starts_with(t.as_bytes()) + } + fn bump(&mut self) -> Option { + let c = self.peek()?; + if c == b'\n' { + self.line += 1; + } + self.i += 1; + Some(c) + } + fn skip_line(&mut self) { + while let Some(c) = self.peek() { + if c == b'\n' { + break; + } + self.i += 1; + } + } + fn skip_block_comment(&mut self) { + while self.peek().is_some() && !self.at("*/") { + self.bump(); + } + self.i = (self.i + 2).min(self.s.len()); + } + /// Whitespace, newlines and comments. In an object, commas too. + fn skip_space(&mut self, newlines: bool) { + loop { + match self.peek() { + Some(b' ' | b'\t' | b'\r') => self.i += 1, + Some(b',') if self.object => self.i += 1, + Some(b'\n') if newlines => { + self.bump(); + } + Some(b'#') => self.skip_line(), + Some(b'/') if self.at("//") => self.skip_line(), + Some(b'/') if self.at("/*") => self.skip_block_comment(), + _ => break, + } + } + } + fn ident(&mut self) -> Option { + let start = self.i; + while let Some(c) = self.peek() { + if c.is_ascii_alphanumeric() || c == b'_' || c == b'-' || c == b'.' { + self.i += 1; + } else { + break; + } + } + (self.i > start).then(|| String::from_utf8_lossy(&self.s[start..self.i]).to_string()) + } + /// At `"`: through the closing quote, `${ ... }` and escapes included. + fn string(&mut self) { + self.bump(); + while let Some(c) = self.peek() { + match c { + b'\\' => { + self.bump(); + self.bump(); + } + b'"' => { + self.bump(); + return; + } + b'$' | b'%' if self.at("${") || self.at("%{") => { + self.i += 2; + let mut depth = 1; + while let Some(c) = self.peek() { + match c { + b'"' => { + self.string(); + continue; + } + b'{' => depth += 1, + b'}' => { + depth -= 1; + if depth == 0 { + self.bump(); + break; + } + } + _ => {} + } + self.bump(); + } + } + _ => { + self.bump(); + } + } + } + } + fn heredoc(&mut self) { + self.i += 2; + if self.peek() == Some(b'-') { + self.i += 1; + } + let Some(tag) = self.ident() else { + return; + }; + self.skip_line(); + while self.peek().is_some() { + self.bump(); + let start = self.i; + self.skip_line(); + let l = String::from_utf8_lossy(&self.s[start..self.i]); + if l.trim() == tag { + return; + } + } + } + /// A value: to the end of the line at depth 0 (or a comma or the + /// closing brace of an object). + fn expr(&mut self) -> String { + let start = self.i; + let mut depth = 0i32; + while let Some(c) = self.peek() { + match c { + b'"' => { + self.string(); + continue; + } + b'<' if self.at("<<") && depth == 0 => { + self.heredoc(); + continue; + } + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + if depth == 0 { + break; + } + depth -= 1; + } + b'\n' if depth == 0 => break, + b',' if depth == 0 && self.object => break, + b'#' if depth == 0 => break, + b'/' if depth == 0 && (self.at("//") || self.at("/*")) => break, + _ => {} + } + self.bump(); + } + String::from_utf8_lossy(&self.s[start..self.i]) + .trim() + .to_string() + } + fn body(&mut self, top: bool) -> (Vec, Vec) { + let mut attrs = Vec::new(); + let mut blocks = Vec::new(); + loop { + self.skip_space(true); + match self.peek() { + None => break, + Some(b'}') => { + if !top { + self.bump(); + break; + } + self.bump(); + continue; + } + _ => {} + } + let line = self.line; + let name = if self.peek() == Some(b'"') { + let start = self.i; + self.string(); + String::from_utf8_lossy(&self.s[start..self.i]) + .trim_matches('"') + .to_string() + } else { + match self.ident() { + Some(n) => n, + None => { + // Not something this reader knows: next line. + self.bump(); + self.skip_line(); + continue; + } + } + }; + self.skip_space(false); + let assigns = match self.peek() { + Some(b'=') => !self.at("=="), + Some(b':') => self.object, + _ => false, + }; + if assigns { + self.bump(); + self.skip_space(false); + let expr = self.expr(); + attrs.push(Attr { name, expr, line }); + continue; + } + let mut labels = Vec::new(); + loop { + self.skip_space(false); + match self.peek() { + Some(b'"') => { + let start = self.i; + self.string(); + labels.push( + String::from_utf8_lossy(&self.s[start..self.i]) + .trim_matches('"') + .to_string(), + ); + } + Some(c) if c.is_ascii_alphabetic() || c == b'_' => { + if let Some(l) = self.ident() { + labels.push(l); + } + } + _ => break, + } + } + if self.peek() == Some(b'{') { + self.bump(); + let (a, b) = self.body(false); + blocks.push(Block { + kind: name, + labels, + line, + end_line: self.line, + attrs: a, + blocks: b, + }); + } else { + self.skip_line(); + } + } + (attrs, blocks) + } +} + +/// The blocks of a `.tf` file. Text that is not HCL gives no blocks. +pub fn parse(src: &str) -> Vec { + let mut p = P { + s: src.as_bytes(), + i: 0, + line: 1, + object: false, + }; + p.body(true).1 +} + +/// The assignments of a `.tfvars` file (or any file's top level). +pub fn assignments(src: &str) -> Vec { + let mut p = P { + s: src.as_bytes(), + i: 0, + line: 1, + object: false, + }; + p.body(true).0 +} + +/// The entries of an object value (`{ Name = "orders", Env = "prod" }`), +/// each with its line counted from `first_line`. +pub fn object(expr: &str, first_line: u32) -> Vec { + let t = expr.trim(); + let Some(inner) = t.strip_prefix('{').and_then(|x| x.strip_suffix('}')) else { + return Vec::new(); + }; + let mut p = P { + s: inner.as_bytes(), + i: 0, + line: first_line, + object: true, + }; + p.body(true).0 +} + +/// One piece of a string with `${...}` in it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Part { + Text(String), + /// What stands between `${` and `}`. + Ref(String), +} + +/// A value as it is usually written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Value { + /// `"orders"`, `16`, `true`. + Lit(String), + /// `var.name`. + Var(String), + /// `local.name`. + Local(String), + /// `each.key`, `each.value.engine_version`, `count.index`. + Each(String), + /// `"${var.env}-orders"`. + Template(Vec), + /// Anything else, as written. + Other(String), +} + +fn word(s: &str) -> bool { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +fn reference(t: &str) -> Value { + if let Some(v) = t.strip_prefix("var.").filter(|v| word(v)) { + return Value::Var(v.to_string()); + } + if let Some(v) = t.strip_prefix("local.").filter(|v| word(v)) { + return Value::Local(v.to_string()); + } + if t.starts_with("each.") || t.starts_with("count.") { + return Value::Each(t.to_string()); + } + Value::Other(t.to_string()) +} + +/// Reads an expression's text. +pub fn value(expr: &str) -> Value { + let t = expr.trim(); + if let Some(inner) = t + .strip_prefix('"') + .and_then(|x| x.strip_suffix('"')) + .filter(|x| !x.contains('"') || x.contains("${")) + { + if !inner.contains("${") { + return Value::Lit(inner.to_string()); + } + let mut parts = Vec::new(); + let mut rest = inner; + while let Some(at) = rest.find("${") { + if at > 0 { + parts.push(Part::Text(rest[..at].to_string())); + } + let after = &rest[at + 2..]; + let mut depth = 1; + let mut end = after.len(); + for (i, c) in after.char_indices() { + match c { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + end = i; + break; + } + } + _ => {} + } + } + parts.push(Part::Ref(after[..end].trim().to_string())); + rest = after.get(end + 1..).unwrap_or(""); + } + if !rest.is_empty() { + parts.push(Part::Text(rest.to_string())); + } + // "${var.x}" alone is the reference itself. + if let [Part::Ref(r)] = parts.as_slice() { + return reference(r); + } + return Value::Template(parts); + } + if t == "true" + || t == "false" + || (!t.is_empty() && t.chars().all(|c| c.is_ascii_digit() || c == '.')) + { + return Value::Lit(t.to_string()); + } + reference(t) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TF: &str = r#" +# The orders database. +resource "aws_db_instance" "orders" { + identifier_prefix = "orders-" + engine = "postgres" # pinned + engine_version = var.db_engine_version + tags = { + Name = "orders" + Environment = var.env + } + lifecycle { + ignore_changes = [password] + } + user_data = <<-EOT + echo "resource \"nope\" {" + EOT +} + +/* a module call */ +module "aurora" { + source = "../../modules/aurora" + name = "${var.env}-ledger" + version_pin = "16.4" + for_each = toset(["a", "b"]) +} + +variable "db_engine_version" { + type = string + default = "16.4" +} + +locals { + env = "prod" +} +"#; + + #[test] + fn blocks_and_attributes_come_with_their_lines() { + let b = parse(TF); + let kinds: Vec<&str> = b.iter().map(|x| x.kind.as_str()).collect(); + assert_eq!(kinds, vec!["resource", "module", "variable", "locals"]); + let db = &b[0]; + assert_eq!(db.labels, vec!["aws_db_instance", "orders"]); + assert_eq!(db.line, 3); + assert_eq!(db.attr("engine").unwrap().expr, "\"postgres\""); + let ev = db.attr("engine_version").unwrap(); + assert_eq!((ev.expr.as_str(), ev.line), ("var.db_engine_version", 6)); + assert!(db.child("lifecycle").is_some()); + // A heredoc that looks like a block is text, not a block. + assert_eq!(b.len(), 4); + assert!(db.attr("user_data").is_some()); + let tags = db.attr("tags").unwrap(); + let t = object(&tags.expr, tags.line); + assert_eq!(t.len(), 2); + assert_eq!( + (t[0].name.as_str(), t[0].expr.as_str(), t[0].line), + ("Name", "\"orders\"", 8) + ); + assert_eq!(b[1].label(0), "aurora"); + assert_eq!(b[1].attr("for_each").unwrap().expr, "toset([\"a\", \"b\"])"); + assert_eq!(b[2].attr("default").unwrap().expr, "\"16.4\""); + } + + #[test] + fn values_are_read_as_written() { + assert_eq!(value("\"orders\""), Value::Lit("orders".into())); + assert_eq!(value("16"), Value::Lit("16".into())); + assert_eq!(value("var.env"), Value::Var("env".into())); + assert_eq!(value("\"${var.env}\""), Value::Var("env".into())); + assert_eq!(value("local.name"), Value::Local("name".into())); + assert_eq!( + value("each.value.engine_version"), + Value::Each("each.value.engine_version".into()) + ); + assert_eq!( + value("\"${var.env}-ledger\""), + Value::Template(vec![ + Part::Ref("var.env".into()), + Part::Text("-ledger".into()) + ]) + ); + assert!(matches!(value("coalesce(var.a, \"x\")"), Value::Other(_))); + assert!(matches!(value("var.map[\"k\"]"), Value::Other(_))); + } + + #[test] + fn tfvars_and_one_line_objects_read_too() { + let v = assignments( + "env = \"prod\"\ndb_engine_version = \"16.4\" # live\nsizes = { a = 1, b = 2 }\n", + ); + assert_eq!(v.len(), 3); + assert_eq!( + (v[1].name.as_str(), v[1].expr.as_str(), v[1].line), + ("db_engine_version", "\"16.4\"", 2) + ); + let o = object(&v[2].expr, v[2].line); + assert_eq!( + o.iter().map(|a| a.name.as_str()).collect::>(), + vec!["a", "b"] + ); + assert!(parse("not hcl at all {{{").len() <= 1); + assert!(parse("").is_empty()); + } +} diff --git a/services/common/src/infra_vuln/inventory.rs b/services/common/src/infra_vuln/inventory.rs index daccdc8a8..de6b3da54 100644 --- a/services/common/src/infra_vuln/inventory.rs +++ b/services/common/src/infra_vuln/inventory.rs @@ -252,9 +252,10 @@ pub struct Exposure { /// Something AWS has waiting for the resource (applied in AWS, not in code). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Pending { - /// `system-update`, `db-upgrade`, `service-update`, `service-software`. + /// AWS's own name for the action: `system-update`, `os-upgrade`, + /// `db-upgrade`, `service-update`, `service-software`, `health`. pub kind: String, - /// The update's name (`elasticache-20261106-intel`) or description. + /// The update's name (`elasticache-20261106-intel`), or the action's. pub name: String, #[serde(default)] pub description: String, @@ -266,6 +267,30 @@ pub struct Pending { pub auto_applied_after: String, #[serde(default)] pub status: String, + /// What the action does on the ARN it is pending on + /// ([`super::actions::meaning_of`]). + #[serde(default)] + pub meaning: super::actions::Meaning, + /// `cluster` or `instance` for a database action. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub scope: String, + /// Every ARN the action is applied to, in the order to apply it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub arns: Vec, + /// The version it moves to, when AWS's description names it. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub target: String, + /// What else AWS listed that this row stands for. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub merged: Vec, + /// Its place among the actions pending on the same resource (1-based, + /// 0 when it is the only one), and why it is there. + #[serde(default)] + pub step: u8, + #[serde(default)] + pub steps: u8, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub order_why: String, } /// One Amazon Inspector finding on a resource (when the team runs it). @@ -287,19 +312,87 @@ pub struct InspectorHit { pub remediation: String, } -/// Where a resource is defined in the team's code. +/// How sure a location is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum Confidence { + /// More than one place could define it, or only weak signs point here. + /// Never enough for a pull request. + Low, + /// One place fits, without the identifier itself being written there. + #[default] + Medium, + /// AWS's own stack records name it, or the code writes its identifier. + High, +} + +/// The line a version change edits. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Edit { + pub file: String, + #[serde(default)] + pub line: u32, + /// `engine_version`, `EngineVersion`, `release_version`, `runtime`. + pub attribute: String, + /// What is written there now, empty when the attribute is not set. + #[serde(default)] + pub value: String, + /// Where the value lives: `resource`, `module_input`, `tfvars`, + /// `variable_default`, `local`, `template`, `parameter`, `construct`, + /// or `add` when nothing sets it yet. + pub via: String, + /// What else reads the same value, when the edit is not private to + /// this resource. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub shared: String, +} + +/// Where a resource is defined in the team's code, how that was found and +/// how sure it is. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Location { pub repo: String, #[serde(default)] pub file: String, - /// `aws_launch_template.web`, `module.eks.aws_eks_node_group.main`. + /// `aws_launch_template.web`, `module.eks.aws_eks_node_group.main`, a + /// CloudFormation logical id, a CDK construct id. #[serde(default)] pub address: String, #[serde(default)] pub line: u32, - /// How it was found: `tag`, `cloudformation`, `search`. + /// How it was found: `cloudformation_tag`, `cloudformation_lookup`, + /// `cdk_logical_id`, `terraform_name`, `terraform_generated_name`, + /// `terraform_attributes`, `terraform_module`, `repo_tag`, `search`. pub how: String, + /// `terraform`, `opentofu`, `cloudformation`, `sam`, `cdk`, + /// `serverless`, `pulumi`; empty when not known. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub tool: String, + #[serde(default)] + pub confidence: Confidence, + /// What matched, in words, and what makes it unsure. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub evidence: Vec, + /// The line a version change edits, when it was found. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edit: Option, + /// `production`, `staging`, `development`, ...; empty when not known. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub environment: String, + /// The CloudFormation stack, when one made the resource. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub stack: String, + /// The other places that could define it, when unsure + /// (`repo:file address`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub candidates: Vec, +} + +impl Location { + /// Enough to open a pull request against: a file, and not a guess. + pub fn sure(&self) -> bool { + !self.repo.is_empty() && !self.file.is_empty() && self.confidence != Confidence::Low + } } /// One running resource. @@ -323,6 +416,12 @@ pub struct Resource { pub pending: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub defined_in: Option, + /// Settings read from AWS that tell one resource from another in code + /// and say how an update lands (`subnet_group`, `parameter_group`, + /// `instance_class`, `multi_az`, `auto_minor`, `maintenance_window`, + /// `backup_retention`, `replicas`, `writer`, `global`). Never secrets. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub facts: BTreeMap, /// `aws` (read from the account) or `iac` (from the team's code). pub source: String, pub seen_at: String, @@ -418,29 +517,10 @@ pub fn stack_of(tags: &BTreeMap) -> Option<&str> { .map(String::as_str) } -/// The names to search the team's infrastructure code for: the AMI id, -/// the group, the resource's own name, its CloudFormation logical id. +/// The names to search the team's infrastructure code for, strongest +/// first ([`super::locate::search_terms`]). pub fn search_terms(r: &Resource) -> Vec { - let mut out: Vec = Vec::new(); - let mut push = |s: &str| { - let s = s.trim(); - if s.len() >= 4 && !out.iter().any(|x| x == s) { - out.push(s.to_string()); - } - }; - if !r.versions.ami_id.is_empty() { - push(&r.versions.ami_id); - } - // A group that is an ARN ends in an id nobody writes in code. - if !r.group.starts_with("arn:") { - push(&r.group); - } - push(&r.name); - if let Some(l) = r.tags.get("aws:cloudformation:logical-id") { - push(l); - } - out.truncate(4); - out + super::locate::search_terms(r) } /// The Terraform block around `line` (1-based) in a `.tf` file: its @@ -466,55 +546,23 @@ pub fn line_of(content: &str, term: &str) -> Option { .map(|i| i + 1) } -/// Picks where a resource is defined from what was found: a repository a -/// tag names wins; else the first infrastructure file a search found for -/// the earliest term (`files` are `(repo, path, content)`). +/// Where a resource is defined, from the files read (`(repo, path, +/// content)`): see [`super::locate::locate`], which also takes the places +/// a name is mentioned outside infrastructure files. pub fn locate( r: &Resource, team_repos: &[String], files: &[(String, String, String)], ) -> Option { - let tagged = repo_from_tags(&r.tags, team_repos); - for term in search_terms(r) { - for (repo, path, content) in files { - if tagged.as_ref().is_some_and(|t| t != repo) { - continue; - } - let Some(line) = line_of(content, &term) else { - continue; - }; - let (address, line) = if path.ends_with(".tf") { - terraform_address(content, line).unwrap_or((String::new(), line as u32)) - } else { - (String::new(), line as u32) - }; - return Some(Location { - repo: repo.clone(), - file: path.clone(), - address, - line, - how: if tagged.is_some() { - "tag".into() - } else { - "search".into() - }, - }); - } - } - if let Some(repo) = tagged { - return Some(Location { - repo, - how: "tag".into(), - ..Default::default() - }); - } - stack_of(&r.tags).map(|s| Location { - repo: String::new(), - file: String::new(), - address: format!("stack {s}"), - line: 0, - how: "cloudformation".into(), - }) + let files: Vec = files + .iter() + .map(|(repo, path, content)| super::locate::SourceFile { + repo: repo.clone(), + path: path.clone(), + content: content.clone(), + }) + .collect(); + super::locate::locate(r, team_repos, &files, &[]) } /// Lambda functions as the team's Terraform defines them (`aws_lambda_function` @@ -577,7 +625,22 @@ pub fn lambdas_from_terraform( file: path.into(), address: format!("aws_lambda_function.{name}"), line, - how: "search".into(), + how: "terraform_name".into(), + tool: "terraform".into(), + confidence: Confidence::High, + evidence: vec![ + "read from this block: the function is listed from the code itself".into(), + ], + edit: runtime.captures(body).and_then(|c| c.get(1)).map(|m| Edit { + file: path.into(), + line: content[..*start + m.start()].lines().count() as u32, + attribute: "runtime".into(), + value: m.as_str().into(), + via: "resource".into(), + shared: String::new(), + }), + environment: super::locate::environment_of(&[path]), + ..Default::default() }), source: "iac".into(), seen_at: now.into(), @@ -757,14 +820,18 @@ resource "aws_lambda_function" "render" { let l = locate(&r, &["acme/infra".into()], &files).unwrap(); assert_eq!(l.address, "aws_launch_template.web"); assert_eq!(l.file, "envs/prod/web.tf"); - assert_eq!(l.how, "search"); + assert_eq!(l.how, "terraform_attributes"); + assert_eq!(l.confidence, Confidence::High, "{:?}", l.evidence); + assert_eq!(l.edit.as_ref().unwrap().attribute, "image_id"); // Nothing found and no tags: unknown. assert!(locate(&r, &[], &[]).is_none()); // A CloudFormation stack tag says at least which stack. let mut s = r.clone(); s.tags .insert("aws:cloudformation:stack-name".into(), "web-prod".into()); - assert_eq!(locate(&s, &[], &[]).unwrap().how, "cloudformation"); + let stack = locate(&s, &[], &[]).unwrap(); + assert_eq!(stack.how, "cloudformation_tag"); + assert!(!stack.sure(), "a stack name alone is never a pull request"); } #[test] diff --git a/services/common/src/infra_vuln/locate.rs b/services/common/src/infra_vuln/locate.rs new file mode 100644 index 000000000..31ff8f171 --- /dev/null +++ b/services/common/src/infra_vuln/locate.rs @@ -0,0 +1,1426 @@ +//! Where a live resource is defined in a team's code, across every +//! connected repository and layout, with how it was found and how sure +//! that is. +//! +//! In order of certainty: +//! +//! 1. **CloudFormation's own records.** A resource a stack made carries +//! `aws:cloudformation:stack-name` and `logical-id` tags; where tags are +//! not propagated, the worker asks CloudFormation which stack owns the +//! physical id. The logical id is a literal key in a hand-written, SAM +//! or Serverless Framework template, and the readable part of a CDK +//! construct path ([`in_stack`]). +//! 2. **Terraform and OpenTofu**, by resource type and attributes +//! ([`super::terraform`]). +//! 3. **The name written in an infrastructure file** of any tool, as a +//! last resort, graded lower. +//! +//! Files are recognised as infrastructure code by what is in them, not +//! only by their name ([`tool_of`]). What to search a repository for is +//! ranked so every resource gets its strongest name before any gets a +//! second ([`ranked_terms`]). + +use std::collections::BTreeMap; + +use regex::Regex; + +use super::inventory::{Confidence, Edit, Kind, Location, Resource}; +use super::terraform; + +/// One file of a team's repository. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SourceFile { + pub repo: String, + pub path: String, + pub content: String, +} + +/// A place a searched name appears, in any kind of file (a workflow that +/// deploys a stack, a `samconfig.toml`). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Mention { + pub repo: String, + pub path: String, + pub term: String, +} + +fn re(p: &str) -> Regex { + Regex::new(p).expect("a valid pattern") +} + +fn file_name(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +fn ext(path: &str) -> &str { + file_name(path) + .rsplit_once('.') + .map(|(_, e)| e) + .unwrap_or("") +} + +/// Directories whose files are never a team's own infrastructure code. +fn vendored(path: &str) -> bool { + let p = format!("/{}", path.to_ascii_lowercase()); + [ + "/node_modules/", + "/vendor/", + "/.terraform/", + "/cdk.out/", + "/dist/", + "/build/", + "/.serverless/", + "/.aws-sam/", + "/.git/", + "/site-packages/", + ] + .iter() + .any(|d| p.contains(d)) +} + +/// Whether a path could hold infrastructure code, by its name alone: +/// worth reading to find out ([`tool_of`] decides). +pub fn maybe_iac_path(path: &str) -> bool { + if vendored(path) { + return false; + } + let p = path.to_ascii_lowercase(); + let name = file_name(&p); + matches!( + ext(&p), + "tf" | "tofu" + | "tfvars" + | "hcl" + | "yaml" + | "yml" + | "json" + | "ts" + | "js" + | "mjs" + | "py" + | "go" + | "java" + | "cs" + | "toml" + ) && !name.ends_with(".d.ts") + && !name.ends_with(".test.ts") + && !name.ends_with(".spec.ts") + && !matches!( + name, + "package.json" + | "package-lock.json" + | "tsconfig.json" + | "pyproject.toml" + | "cargo.toml" + ) +} + +/// Whether a path names infrastructure code without reading it. +pub fn iac_by_name(path: &str) -> bool { + if vendored(path) { + return false; + } + let p = path.to_ascii_lowercase(); + let name = file_name(&p); + let dirs = format!("/{p}"); + matches!(ext(&p), "tf" | "tofu" | "tfvars" | "hcl") + || p.ends_with(".tf.json") + || matches!( + name, + "serverless.yml" + | "serverless.yaml" + | "serverless.ts" + | "serverless.js" + | "samconfig.toml" + | "samconfig.yaml" + | "cdk.json" + | "pulumi.yaml" + | "pulumi.yml" + ) + || (name.starts_with("pulumi.") && matches!(ext(&p), "yaml" | "yml")) + || (matches!(ext(&p), "yaml" | "yml" | "json") + && (p.contains("cloudformation") + || p.contains("cfn") + || name.contains("template") + || name.contains("stack") + || name.starts_with("sam."))) + || (matches!(ext(&p), "ts" | "js" | "mjs" | "py" | "go" | "java" | "cs") + && (name.contains("stack") + || name.contains("construct") + || [ + "/cdk/", + "/pulumi/", + "/infra/", + "/infrastructure/", + "/iac/", + "/stacks/", + ] + .iter() + .any(|d| dirs.contains(d)))) +} + +/// The tool a file is written for, from its content: `terraform`, +/// `opentofu`, `cloudformation`, `sam`, `serverless`, `cdk`, `pulumi`. +/// `None` when it is not infrastructure code. +pub fn tool_of(path: &str, content: &str) -> Option<&'static str> { + if vendored(path) { + return None; + } + let p = path.to_ascii_lowercase(); + let name = file_name(&p); + match ext(&p) { + "tofu" => return Some("opentofu"), + "tf" | "tfvars" | "hcl" => return Some("terraform"), + _ => {} + } + if p.ends_with(".tf.json") { + return Some("terraform"); + } + if name == "cdk.json" { + return Some("cdk"); + } + if name.starts_with("samconfig.") { + return Some("sam"); + } + if name.starts_with("pulumi.") && matches!(ext(&p), "yaml" | "yml") { + return Some("pulumi"); + } + let has = |w: &str| content.contains(w); + match ext(&p) { + "yaml" | "yml" | "json" => { + if name.starts_with("serverless.") && has("provider") && has("service") { + return Some("serverless"); + } + if has("AWS::Serverless-2016-10-31") { + return Some("sam"); + } + let resources = has("Resources:") || has("\"Resources\""); + let typed = re(r#"["']?Type["']?\s*:\s*["']?(AWS|Custom|Alexa)::"#).is_match(content); + if has("AWSTemplateFormatVersion") || (resources && typed) { + return Some("cloudformation"); + } + if has("provider:") && has("functions:") && has("service:") { + return Some("serverless"); + } + None + } + "ts" | "js" | "mjs" | "py" | "go" | "java" | "cs" => { + if name.starts_with("serverless.") && has("provider") && has("service") { + return Some("serverless"); + } + if [ + "aws-cdk-lib", + "@aws-cdk/", + "aws_cdk", + "software.amazon.awscdk", + "github.com/aws/aws-cdk-go", + "Amazon.CDK", + ] + .iter() + .any(|w| has(w)) + { + return Some("cdk"); + } + if [ + "@pulumi/aws", + "pulumi_aws", + "github.com/pulumi/pulumi-aws", + "Pulumi.Aws", + "com.pulumi.aws", + ] + .iter() + .any(|w| has(w)) + { + return Some("pulumi"); + } + None + } + _ => None, + } +} + +/// What to search a repository for to find its infrastructure code by +/// content, whatever its files are called. +pub const MARKERS: &[&str] = &[ + "AWSTemplateFormatVersion", + "AWS::Serverless-2016-10-31", + "aws-cdk-lib", + "aws_cdk", + "@pulumi/aws", + "pulumi_aws", + "resource \"aws_", + "terraform-aws-modules", +]; + +const ENVS: &[(&str, &[&str])] = &[ + ("production", &["prod", "production", "prd", "live"]), + ( + "staging", + &["staging", "stage", "stg", "preprod", "uat", "preview"], + ), + ( + "development", + &["dev", "development", "sandbox", "sbx", "nonprod"], + ), + ("test", &["test", "testing", "qa", "ci"]), +]; + +/// The environment a name, a path or a tag value speaks of: `production`, +/// `staging`, `development`, `test`, or empty. +pub fn environment_of(words: &[&str]) -> String { + for w in words { + let l = w.to_ascii_lowercase(); + for token in l.split(|c: char| !c.is_ascii_alphanumeric()) { + for (env, names) in ENVS { + if names.contains(&token) { + return (*env).to_string(); + } + } + } + } + String::new() +} + +/// A resource's environment: its environment tag first, then its name. +pub fn environment_of_resource(r: &Resource) -> String { + for (k, v) in &r.tags { + if matches!( + k.to_ascii_lowercase().as_str(), + "environment" | "env" | "stage" | "tier" + ) { + let e = environment_of(&[v]); + if !e.is_empty() { + return e; + } + } + } + environment_of(&[ + &r.name, + r.tags + .get("aws:cloudformation:stack-name") + .map(String::as_str) + .unwrap_or(""), + ]) +} + +/// The stack that made a resource, by AWS's own records. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StackRef { + pub stack: String, + pub logical_id: String, + /// `cloudformation_tag` (the resource's own tags) or + /// `cloudformation_lookup` (CloudFormation asked by physical id). + pub how: &'static str, +} + +/// Tag the worker sets when CloudFormation named the stack by lookup. +pub const LOOKUP_TAG: &str = "coderhelm:cloudformation-lookup"; + +pub fn stack_ref(r: &Resource) -> Option { + let stack = r.tags.get("aws:cloudformation:stack-name")?.clone(); + Some(StackRef { + stack, + logical_id: r + .tags + .get("aws:cloudformation:logical-id") + .cloned() + .unwrap_or_default(), + how: if r.tags.contains_key(LOOKUP_TAG) { + "cloudformation_lookup" + } else { + "cloudformation_tag" + }, + }) +} + +/// What a kind is in a template, the property a version change edits, and +/// the words that name it in a CDK construct class. +struct CfnSpec { + types: &'static [&'static str], + version: &'static str, + classes: &'static [&'static str], +} + +fn cfn_spec(kind: Kind) -> CfnSpec { + match kind { + Kind::RdsInstance => CfnSpec { + types: &["AWS::RDS::DBInstance"], + version: "EngineVersion", + classes: &["databaseinstance", "cfndbinstance", "dbinstance"], + }, + Kind::RdsCluster => CfnSpec { + types: &["AWS::RDS::DBCluster"], + version: "EngineVersion", + classes: &[ + "databasecluster", + "cfndbcluster", + "serverlesscluster", + "dbcluster", + ], + }, + Kind::ElasticacheGroup => CfnSpec { + types: &[ + "AWS::ElastiCache::ReplicationGroup", + "AWS::ElastiCache::CacheCluster", + ], + version: "EngineVersion", + classes: &["cfnreplicationgroup", "cfncachecluster", "replicationgroup"], + }, + Kind::OpensearchDomain => CfnSpec { + types: &[ + "AWS::OpenSearchService::Domain", + "AWS::Elasticsearch::Domain", + ], + version: "EngineVersion", + classes: &["domain", "cfndomain"], + }, + Kind::EksNodegroup => CfnSpec { + types: &["AWS::EKS::Nodegroup"], + version: "ReleaseVersion", + classes: &["nodegroup", "cfnnodegroup"], + }, + Kind::LambdaFunction => CfnSpec { + types: &["AWS::Lambda::Function", "AWS::Serverless::Function"], + version: "Runtime", + classes: &["function"], + }, + Kind::AutoScalingGroup | Kind::Ec2Instance => CfnSpec { + types: &[ + "AWS::AutoScaling::AutoScalingGroup", + "AWS::EC2::LaunchTemplate", + "AWS::EC2::Instance", + ], + version: "ImageId", + classes: &["autoscalinggroup", "launchtemplate", "instance"], + }, + _ => CfnSpec { + types: &[], + version: "", + classes: &[], + }, + } +} + +fn indent(l: &str) -> usize { + l.len() - l.trim_start().len() +} + +/// A logical id's resource in a template: the line of its key, and the +/// lines of the resource (to the next key at the same depth). +pub(crate) fn template_resource<'a>( + lines: &[&'a str], + logical: &str, + types: &[&str], +) -> Option<(usize, Vec<(usize, &'a str)>)> { + let key = re(&format!(r#"^\s*["']?{}["']?\s*:"#, regex::escape(logical))); + for (i, l) in lines.iter().enumerate() { + if !key.is_match(l) { + continue; + } + let base = indent(l); + let body: Vec<(usize, &str)> = lines + .iter() + .enumerate() + .skip(i + 1) + .take_while(|(_, x)| x.trim().is_empty() || indent(x) > base) + .map(|(n, x)| (n, *x)) + .collect(); + let typed = body + .iter() + .take(12) + .any(|(_, x)| types.iter().any(|t| x.contains(t))); + if typed || types.is_empty() { + return Some((i, body)); + } + } + None +} + +fn unquote(s: &str) -> String { + s.trim() + .trim_end_matches(',') + .trim() + .trim_matches(|c| c == '"' || c == '\'') + .to_string() +} + +/// The line that sets `property` for a template resource: the property +/// itself when it is a literal, or the default of the parameter it refers +/// to. +fn template_edit( + path: &str, + lines: &[&str], + body: &[(usize, &str)], + property: &str, +) -> Option { + let prop = re(&format!( + r#"^\s*["']?{}["']?\s*:\s*(.*)$"#, + regex::escape(property) + )); + let (n, value) = body + .iter() + .find_map(|(n, l)| prop.captures(l).map(|c| (*n, c[1].trim().to_string())))?; + let reference = re(r#"(?:!Ref\s+|["']?Ref["']?\s*:\s*)["']?([A-Za-z0-9]+)"#) + .captures(&value) + .map(|c| c[1].to_string()) + .or_else(|| { + // `EngineVersion:` then `Ref: Param` on the next line. + value.is_empty().then(|| { + lines + .get(n + 1) + .and_then(|l| re(r#"["']?Ref["']?\s*:\s*["']?([A-Za-z0-9]+)"#).captures(l)) + .map(|c| c[1].to_string()) + })? + }); + if let Some(param) = reference { + let (_, pbody) = template_resource(lines, ¶m, &[])?; + let default = re(r#"^\s*["']?Default["']?\s*:\s*(.*)$"#); + let (dn, dv) = pbody + .iter() + .find_map(|(n, l)| default.captures(l).map(|c| (*n, unquote(&c[1]))))?; + return Some(Edit { + file: path.to_string(), + line: (dn + 1) as u32, + attribute: param, + value: dv, + via: "parameter".into(), + shared: "the stack may be deployed with a value for this parameter set outside the template (a deploy command, a pipeline, `samconfig.toml`): the default changes nothing where one is".into(), + }); + } + if value.starts_with('!') || value.starts_with('{') || value.is_empty() { + return None; + } + Some(Edit { + file: path.to_string(), + line: (n + 1) as u32, + attribute: property.to_string(), + value: unquote(&value), + via: "template".into(), + shared: String::new(), + }) +} + +/// A construct created in CDK code: its class, id and line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Construct { + pub(crate) class: String, + pub(crate) id: String, + pub(crate) line: usize, +} + +pub(crate) fn constructs(content: &str) -> Vec { + // `new rds.DatabaseCluster(this, 'Orders', ...` and + // `rds.DatabaseCluster(self, "Orders", ...`. + let call = re( + r#"(?:new\s+)?([A-Za-z_][\w.]*)\s*\(\s*(?:this|self|scope|stack|app|[a-z]\w*)\s*,\s*["'`]([^"'`$]+)["'`]"#, + ); + let mut out = Vec::new(); + for (i, l) in content.lines().enumerate() { + for c in call.captures_iter(l) { + out.push(Construct { + class: c[1].to_string(), + id: c[2].to_string(), + line: i, + }); + } + } + out +} + +fn alnum(s: &str) -> String { + s.chars().filter(|c| c.is_ascii_alphanumeric()).collect() +} + +/// The readable part of a CDK logical id (`OrdersDatabase1A2B3C4D` is +/// `OrdersDatabase` and an 8-character hash). `None` for an id a person +/// wrote. +pub fn cdk_readable(logical: &str) -> Option<&str> { + let at = logical.len().checked_sub(8)?; + let (head, tail) = logical.split_at_checked(at)?; + (!head.is_empty() + && tail + .chars() + .all(|c| c.is_ascii_digit() || ('A'..='F').contains(&c)) + && tail.chars().any(|c| c.is_ascii_digit())) + .then_some(head) +} + +/// Everything read of a team's repositories, prepared once for every +/// resource placed against it: each file's tool, and Terraform parsed. +pub struct Code<'a> { + pub files: &'a [SourceFile], + pub mentions: &'a [Mention], + tools: Vec>, + terraform: terraform::Index<'a>, +} + +impl<'a> Code<'a> { + pub fn new(files: &'a [SourceFile], mentions: &'a [Mention]) -> Code<'a> { + Code { + files, + mentions, + tools: files.iter().map(|f| tool_of(&f.path, &f.content)).collect(), + terraform: terraform::index(files), + } + } + + /// Each file with the tool it is written for. + fn tooled(&self) -> impl Iterator + '_ { + self.files + .iter() + .zip(self.tools.iter()) + .filter_map(|(f, t)| t.map(|t| (f, t))) + } +} + +/// The resource a stack made, in the team's code. +pub fn in_stack( + r: &Resource, + stack: &StackRef, + files: &[SourceFile], + mentions: &[Mention], +) -> Option { + in_stack_of(r, stack, &Code::new(files, mentions)) +} + +fn in_stack_of(r: &Resource, stack: &StackRef, code: &Code) -> Option { + let (files, mentions) = (code.files, code.mentions); + let spec = cfn_spec(r.kind); + let names_stack = |repo: &str| { + mentions + .iter() + .any(|m| m.repo == repo && m.term == stack.stack) + || files + .iter() + .any(|f| f.repo == repo && f.content.contains(&stack.stack)) + }; + let env = { + let e = environment_of(&[&stack.stack]); + if e.is_empty() { + environment_of_resource(r) + } else { + e + } + }; + let base = |f: &SourceFile, tool: &str| Location { + repo: f.repo.clone(), + file: f.path.clone(), + how: stack.how.into(), + tool: tool.to_string(), + stack: stack.stack.clone(), + environment: env.clone(), + ..Default::default() + }; + if stack.logical_id.is_empty() { + return None; + } + // A template that has the logical id as a key, with the right type. + let mut found: Vec = Vec::new(); + for (f, tool) in code.tooled() { + if !matches!(tool, "cloudformation" | "sam" | "serverless") { + continue; + } + let lines: Vec<&str> = f.content.lines().collect(); + let Some((at, body)) = template_resource(&lines, &stack.logical_id, spec.types) else { + continue; + }; + let mut l = base(f, tool); + l.address = stack.logical_id.clone(); + l.line = (at + 1) as u32; + l.edit = template_edit(&f.path, &lines, &body, spec.version); + l.evidence.push(format!( + "stack `{}` made it as `{}` ({}), and this template defines a resource with that logical id", + stack.stack, + stack.logical_id, + if stack.how == "cloudformation_tag" { + "its CloudFormation tags" + } else { + "CloudFormation's answer for its physical id" + } + )); + found.push(l); + } + if !found.is_empty() { + let named: Vec = found + .iter() + .enumerate() + .filter(|(_, l)| names_stack(&l.repo)) + .map(|(i, _)| i) + .collect(); + let pick = match (found.len(), named.len()) { + (1, _) => 0, + (_, 1) => named[0], + _ => { + let mut l = found[0].clone(); + l.confidence = Confidence::Low; + l.evidence.push(format!( + "{} templates define a resource with that logical id; CoderHelm cannot tell which one the stack was deployed from", + found.len() + )); + l.candidates = found + .iter() + .skip(1) + .take(5) + .map(|c| format!("{}:{} {}", c.repo, c.file, c.address)) + .collect(); + return Some(l); + } + }; + let mut l = found.swap_remove(pick); + if names_stack(&l.repo) { + l.confidence = Confidence::High; + l.evidence + .push(format!("the repository names the stack `{}`", stack.stack)); + } else { + l.confidence = Confidence::Medium; + l.evidence.push(format!( + "the stack name `{}` is not written in the repository: the template is the only one that fits", + stack.stack + )); + } + if l.edit.is_none() { + l.evidence.push(format!( + "the template does not set `{}` as a plain value CoderHelm can read", + spec.version + )); + } + return Some(l); + } + // CDK: the logical id is the construct path's ids and a hash. + let readable = cdk_readable(&stack.logical_id)?; + let want = readable.to_ascii_lowercase(); + let mut best: Option<(i32, &SourceFile, Construct)> = None; + let mut ties = 0; + for (f, tool) in code.tooled() { + if tool != "cdk" { + continue; + } + for c in constructs(&f.content) { + let id = alnum(&c.id).to_ascii_lowercase(); + if id.len() < 3 || !want.contains(&id) { + continue; + } + let class = c + .class + .rsplit('.') + .next() + .unwrap_or("") + .to_ascii_lowercase(); + let right_class = spec.classes.iter().any(|k| class.contains(k)); + let score = (if want == id { + 60 + } else if want.ends_with(&id) || want.starts_with(&id) { + 40 + } else { + 20 + }) + if right_class { 40 } else { 0 } + + id.len().min(20) as i32; + match &best { + Some((s, _, _)) if *s > score => {} + Some((s, _, _)) if *s == score => ties += 1, + _ => { + ties = 0; + best = Some((score, f, c)); + } + } + } + } + let (score, f, c) = best?; + let mut l = base(f, "cdk"); + l.how = "cdk_logical_id".into(); + l.address = c.id.clone(); + l.line = (c.line + 1) as u32; + l.evidence.push(format!( + "stack `{}` made it as `{}`; CDK builds that id from construct ids and a hash, and `{}` creates the construct `{}` here", + stack.stack, stack.logical_id, c.class, c.id + )); + // The version the construct is given: within the call. + let lines: Vec<&str> = f.content.lines().collect(); + let version = re( + r#"((?:[A-Za-z_]\w*\.)*[A-Za-z]*(?:EngineVersion|KubernetesVersion|Runtime)\.[A-Za-z0-9_]+(?:\([^)]*\))?)"#, + ); + l.edit = lines + .iter() + .enumerate() + .skip(c.line) + .take(60) + .find_map(|(n, x)| version.captures(x).map(|m| (n, m[1].to_string()))) + .map(|(n, v)| Edit { + file: f.path.clone(), + line: (n + 1) as u32, + attribute: "version".into(), + value: v, + via: "construct".into(), + shared: String::new(), + }); + let stack_named = names_stack(&f.repo); + l.confidence = if ties > 0 || score < 60 { + l.evidence.push( + "more than one construct fits that id about as well, or the construct is not of the expected kind".into(), + ); + Confidence::Low + } else if stack_named && score >= 80 { + l.evidence + .push(format!("the repository names the stack `{}`", stack.stack)); + Confidence::High + } else { + l.evidence.push(format!( + "the stack name `{}` is not written in the repository", + stack.stack + )); + Confidence::Medium + }; + Some(l) +} + +/// What to search a repository for, for one resource, strongest first. +pub fn search_terms(r: &Resource) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |s: &str| { + let s = s.trim(); + if s.len() >= 4 && !out.iter().any(|x| x == s) { + out.push(s.to_string()); + } + }; + if let Some(l) = r.tags.get("aws:cloudformation:logical-id") { + push(l); + if let Some(readable) = cdk_readable(l) { + push(readable); + } + } + if let Some(s) = r.tags.get("aws:cloudformation:stack-name") { + push(s); + } + if !r.versions.ami_id.is_empty() { + push(&r.versions.ami_id); + } + match terraform::generated_prefix(&r.name) { + // A generated name is written nowhere; its prefix may be. + Some(p) if p != "terraform-" => push(p.trim_end_matches('-')), + Some(_) => {} + None => push(&r.name), + } + // A group that is an ARN ends in an id nobody writes in code. + if !r.group.starts_with("arn:") && terraform::generated_prefix(&r.group).is_none() { + push(&r.group); + } + if let Some(lt) = r.tags.get("coderhelm:launch-template") { + push(lt); + } + for k in ["subnet_group", "parameter_group", "cluster"] { + if let Some(v) = r.facts.get(k) { + if !v.starts_with("default") { + push(v); + } + } + } + out +} + +/// The names to search for across a team's resources, at most `cap`: +/// resources with something pending first, and every resource's strongest +/// name before any resource's second. +pub fn ranked_terms(resources: &[Resource], cap: usize) -> Vec { + let mut order: Vec<&Resource> = resources.iter().collect(); + order.sort_by_key(|r| { + ( + r.pending.is_empty(), + !matches!( + r.kind, + Kind::AutoScalingGroup | Kind::Ec2Instance | Kind::EksNodegroup + ), + r.id.clone(), + ) + }); + let per: Vec> = order.iter().map(|r| search_terms(r)).collect(); + let mut out: Vec = Vec::new(); + let deepest = per.iter().map(Vec::len).max().unwrap_or(0); + 'all: for rank in 0..deepest { + for terms in &per { + if let Some(t) = terms.get(rank) { + if !out.contains(t) { + if out.len() >= cap { + break 'all; + } + out.push(t.clone()); + } + } + } + } + out +} + +/// The repository a tag names (`org/repo` or a GitHub URL), when it is +/// one of the team's. +fn tagged_repo(r: &Resource, team_repos: &[String]) -> Option { + super::inventory::repo_from_tags(&r.tags, team_repos) +} + +/// The name written in an infrastructure file: the last resort. +fn by_name(r: &Resource, code: &Code) -> Option { + let spec = cfn_spec(r.kind); + let tf = terraform::spec(r.kind); + let mut hits: Vec = Vec::new(); + for term in search_terms(r) { + for (f, tool) in code.tooled() { + let Some(line) = super::inventory::line_of(&f.content, &term) else { + continue; + }; + let mut l = Location { + repo: f.repo.clone(), + file: f.path.clone(), + line: line as u32, + how: "search".into(), + tool: tool.into(), + environment: environment_of(&[&f.path]), + ..Default::default() + }; + let mut fits = false; + if matches!(tool, "terraform" | "opentofu") && f.path.ends_with(".tfvars") { + continue; + } + if matches!(tool, "terraform" | "opentofu") { + if let Some((address, at)) = super::inventory::terraform_address(&f.content, line) { + fits = tf.as_ref().is_some_and(|s| { + s.types + .iter() + .any(|t| address.starts_with(&format!("{t}."))) + }); + l.address = address; + l.line = at; + } + } else if matches!(tool, "cloudformation" | "sam" | "serverless") { + // The resource the line is in: the nearest key above it + // whose body names one of the kind's types. + let lines: Vec<&str> = f.content.lines().collect(); + let key = re(r#"^\s*["']?([A-Za-z0-9]+)["']?\s*:\s*\{?\s*$"#); + for i in (0..line.min(lines.len())).rev() { + let Some(c) = key.captures(lines[i]) else { + continue; + }; + if let Some((at, body)) = template_resource(&lines, &c[1], spec.types) { + if at == i && !spec.types.is_empty() { + fits = true; + l.address = c[1].to_string(); + l.line = (at + 1) as u32; + l.edit = template_edit(&f.path, &lines, &body, spec.version); + break; + } + } + } + } + l.evidence.push(format!("`{term}` is written in this file")); + l.confidence = if fits { + Confidence::Medium + } else { + l.evidence.push( + "CoderHelm could not tell that the code around it defines this resource".into(), + ); + Confidence::Low + }; + hits.push(l); + } + if !hits.is_empty() { + break; + } + } + hits.sort_by_key(|h| std::cmp::Reverse(h.confidence)); + let mut best = hits.first()?.clone(); + let same: Vec<&Location> = hits + .iter() + .skip(1) + .filter(|h| h.confidence == best.confidence) + .collect(); + if !same.is_empty() { + best.confidence = Confidence::Low; + best.evidence.push(format!( + "the name is written in {} files; CoderHelm cannot tell which defines it", + same.len() + 1 + )); + best.candidates = same + .iter() + .take(5) + .map(|c| { + format!("{}:{} {}", c.repo, c.file, c.address) + .trim() + .to_string() + }) + .collect(); + } + Some(best) +} + +/// Where a resource is defined, from everything read: the files of the +/// team's repositories and the places its names are mentioned. +pub fn locate( + r: &Resource, + team_repos: &[String], + files: &[SourceFile], + mentions: &[Mention], +) -> Option { + locate_in(r, team_repos, &Code::new(files, mentions)) +} + +/// [`locate`] against code prepared once ([`Code::new`]) for a whole read. +pub fn locate_in(r: &Resource, team_repos: &[String], code: &Code) -> Option { + let tagged = tagged_repo(r, team_repos); + // A repository its tag names: only that repository's files count. + let scoped: Vec; + let narrowed: Code; + let code: &Code = match &tagged { + Some(t) => { + scoped = code + .files + .iter() + .filter(|f| &f.repo == t) + .cloned() + .collect(); + narrowed = Code::new(&scoped, code.mentions); + &narrowed + } + None => code, + }; + let stack = stack_ref(r); + let mut found: Vec = Vec::new(); + if let Some(s) = &stack { + found.extend(in_stack_of(r, s, code)); + } + found.extend(terraform::locate_in( + &terraform::Live::of(r), + &code.terraform, + )); + if found.iter().all(|l| l.confidence == Confidence::Low) { + found.extend(by_name(r, code)); + } + found.sort_by_key(|l| std::cmp::Reverse(l.confidence)); + if let Some(mut l) = found.into_iter().next() { + if tagged.is_some() { + l.evidence + .push(format!("its repository tag names `{}`", l.repo)); + } + if l.environment.is_empty() { + l.environment = environment_of_resource(r); + } + if let Some(s) = &stack { + l.stack = s.stack.clone(); + } + return Some(l); + } + if let Some(repo) = tagged { + return Some(Location { + repo, + how: "repo_tag".into(), + confidence: Confidence::Low, + evidence: vec![ + "its repository tag names this repository; CoderHelm did not find the file that defines it there".into(), + ], + environment: environment_of_resource(r), + ..Default::default() + }); + } + stack.map(|s| Location { + how: s.how.into(), + tool: "cloudformation".into(), + address: s.logical_id.clone(), + confidence: Confidence::Low, + evidence: vec![format!( + "CloudFormation stack `{}` made it{}; no connected repository has a template or CDK construct for it", + s.stack, + if s.logical_id.is_empty() { + String::new() + } else { + format!(" as `{}`", s.logical_id) + } + )], + environment: environment_of_resource(r), + stack: s.stack, + ..Default::default() + }) +} + +/// A sentence's first letter in upper case. +pub fn sentence(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => String::new(), + } +} + +/// What a location says in one line, for a card or a ticket. +pub fn describe(l: &Location) -> String { + let how = match l.how.as_str() { + "cloudformation_tag" => "its CloudFormation stack tags", + "cloudformation_lookup" => "CloudFormation's record of the stack that owns it", + "cdk_logical_id" => "its CloudFormation logical id, matched to a CDK construct", + "terraform_name" => "its identifier in Terraform", + "terraform_generated_name" => "its Terraform-generated name's prefix and its settings", + "terraform_attributes" => "its type and settings in Terraform", + "terraform_module" => "a Terraform module call and its inputs", + "repo_tag" => "its repository tag", + _ => "its name in the code", + }; + let sure = match l.confidence { + Confidence::High => "high", + Confidence::Medium => "medium", + Confidence::Low => "low", + }; + format!("Found by {how} (confidence: {sure}).") +} + +/// Facts about a set of resources that say which are the same thing in +/// different environments: the name with its environment word removed. +pub fn sibling_key(r: &Resource) -> String { + let name = match terraform::generated_prefix(&r.name) { + Some(p) => p, + None => &r.name, + }; + let words: Vec = name + .to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|t| !t.is_empty() && !ENVS.iter().any(|(_, names)| names.contains(t))) + .map(String::from) + .collect(); + format!("{:?}:{}:{}", r.kind, r.versions.engine, words.join("-")) +} + +/// Tags a resource carries, as a map, for tests and callers that build one. +pub fn tags(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::infra_vuln::inventory::Versions; + + fn file(repo: &str, path: &str, content: &str) -> SourceFile { + SourceFile { + repo: repo.into(), + path: path.into(), + content: content.into(), + } + } + + fn db(name: &str, t: &[(&str, &str)]) -> Resource { + Resource { + id: format!("arn:aws:rds:us-east-1:111122223333:db:{name}"), + kind: Kind::RdsInstance, + name: name.into(), + group: format!("arn:aws:rds:us-east-1:111122223333:db:{name}"), + versions: Versions { + engine: "postgres".into(), + engine_version: "16.4".into(), + ..Default::default() + }, + tags: tags(t), + ..Default::default() + } + } + + const CFN: &str = r#"AWSTemplateFormatVersion: "2010-09-09" +Parameters: + DbVersion: + Type: String + Default: "16.4" +Resources: + Queue: + Type: AWS::SQS::Queue + Database: + Type: AWS::RDS::DBInstance + DeletionPolicy: Snapshot + Properties: + Engine: postgres + EngineVersion: "16.4" + DBInstanceClass: db.t4g.medium + Replica: + Type: AWS::RDS::DBInstance + Properties: + EngineVersion: !Ref DbVersion +"#; + + #[test] + fn files_are_recognised_by_what_is_in_them() { + // CloudFormation at a neutral path. + assert_eq!(tool_of("deploy/api.yaml", CFN), Some("cloudformation")); + assert_eq!( + tool_of("app.yml", "Transform: AWS::Serverless-2016-10-31\nResources:\n Fn:\n Type: AWS::Serverless::Function\n"), + Some("sam") + ); + assert_eq!( + tool_of("services/api/serverless.yml", "service: api\nprovider:\n name: aws\n runtime: nodejs22.x\nfunctions:\n a:\n handler: a.h\n"), + Some("serverless") + ); + // CDK next to application code, not named a stack. + assert_eq!( + tool_of( + "src/database.ts", + "import * as rds from 'aws-cdk-lib/aws-rds';\n" + ), + Some("cdk") + ); + assert_eq!( + tool_of("app/storage.py", "from aws_cdk import aws_rds as rds\n"), + Some("cdk") + ); + assert_eq!( + tool_of("index.ts", "import * as aws from '@pulumi/aws';\n"), + Some("pulumi") + ); + assert_eq!( + tool_of("__main__.py", "import pulumi_aws as aws\n"), + Some("pulumi") + ); + assert_eq!(tool_of("main.tofu", ""), Some("opentofu")); + assert_eq!(tool_of("envs/prod.tfvars", ""), Some("terraform")); + // Not infrastructure code, whatever it is called. + assert_eq!( + tool_of("docker-compose.yml", "services:\n web:\n image: x\n"), + None + ); + assert_eq!( + tool_of("src/app/page.tsx", "export default function Page() {}"), + None + ); + assert_eq!(tool_of("openapi.yaml", "openapi: 3.0.0\npaths: {}\n"), None); + assert_eq!( + tool_of("node_modules/aws-cdk-lib/x.ts", "aws-cdk-lib"), + None + ); + assert!(maybe_iac_path("src/database.ts") && !maybe_iac_path("src/database.test.ts")); + assert!(iac_by_name("serverless.yml") && iac_by_name("Pulumi.prod.yaml")); + assert!(iac_by_name("samconfig.toml") && iac_by_name("infra/app.py")); + assert!(!iac_by_name("src/app/page.tsx") && !iac_by_name("docker-compose.yml")); + } + + #[test] + fn a_stack_tag_and_logical_id_lead_to_the_template_and_the_line() { + let r = db( + "api-prod-database-abc123", + &[ + ("aws:cloudformation:stack-name", "api-prod"), + ("aws:cloudformation:logical-id", "Database"), + ], + ); + let files = vec![ + file("acme/api", "deploy/api.yaml", CFN), + file( + "acme/api", + ".github/deploy.sh", + "aws cloudformation deploy --stack-name api-prod", + ), + ]; + let l = locate(&r, &["acme/api".into()], &files, &[]).unwrap(); + assert_eq!( + (l.how.as_str(), l.tool.as_str()), + ("cloudformation_tag", "cloudformation") + ); + assert_eq!(l.confidence, Confidence::High); + assert_eq!( + (l.file.as_str(), l.address.as_str(), l.line), + ("deploy/api.yaml", "Database", 9) + ); + assert_eq!(l.stack, "api-prod"); + assert_eq!(l.environment, "production"); + let e = l.edit.unwrap(); + assert_eq!( + ( + e.attribute.as_str(), + e.value.as_str(), + e.line, + e.via.as_str() + ), + ("EngineVersion", "16.4", 14, "template") + ); + // The physical name is nowhere in the template. + assert!(!CFN.contains("api-prod-database-abc123")); + } + + #[test] + fn a_lookup_by_physical_id_works_where_tags_are_missing_and_a_parameter_is_followed() { + let mut r = db("api-prod-replica-zz9", &[]); + assert!(stack_ref(&r).is_none()); + // What the worker adds after asking CloudFormation. + r.tags + .insert("aws:cloudformation:stack-name".into(), "api-prod".into()); + r.tags + .insert("aws:cloudformation:logical-id".into(), "Replica".into()); + r.tags.insert(LOOKUP_TAG.into(), "true".into()); + let files = vec![file("acme/api", "deploy/api.yaml", CFN)]; + let l = locate(&r, &["acme/api".into()], &files, &[]).unwrap(); + assert_eq!(l.how, "cloudformation_lookup"); + assert_eq!( + l.confidence, + Confidence::Medium, + "the stack name is not in the repository" + ); + let e = l.edit.unwrap(); + assert_eq!( + ( + e.via.as_str(), + e.attribute.as_str(), + e.line, + e.value.as_str() + ), + ("parameter", "DbVersion", 5, "16.4") + ); + assert!(e.shared.contains("outside the template")); + // A mention of the stack name in a workflow makes it sure. + let m = vec![Mention { + repo: "acme/api".into(), + path: ".github/workflows/deploy.yml".into(), + term: "api-prod".into(), + }]; + assert_eq!( + locate(&r, &["acme/api".into()], &files, &m) + .unwrap() + .confidence, + Confidence::High + ); + } + + #[test] + fn two_templates_with_the_same_logical_id_are_low_and_listed() { + let r = db( + "x", + &[ + ("aws:cloudformation:stack-name", "billing"), + ("aws:cloudformation:logical-id", "Database"), + ], + ); + let files = vec![ + file("acme/api", "deploy/api.yaml", CFN), + file("acme/billing", "template.yaml", CFN), + ]; + let l = locate(&r, &[], &files, &[]).unwrap(); + assert_eq!(l.confidence, Confidence::Low); + assert_eq!(l.candidates.len(), 1); + assert!(!l.sure()); + // No template anywhere: the stack is named, with no file. + let none = locate(&r, &[], &[], &[]).unwrap(); + assert_eq!((none.stack.as_str(), none.file.as_str()), ("billing", "")); + assert!(!none.sure()); + assert!(none.evidence[0].contains("no connected repository")); + } + + const CDK: &str = r#"import * as cdk from 'aws-cdk-lib'; +import * as rds from 'aws-cdk-lib/aws-rds'; + +export class DataTier extends cdk.Stack { + constructor(scope: cdk.App, id: string) { + super(scope, id); + const vpc = new ec2.Vpc(this, 'Network'); + new rds.DatabaseCluster(this, 'Ledger', { + engine: rds.DatabaseClusterEngine.auroraPostgres({ + version: rds.AuroraPostgresEngineVersion.VER_16_4, + }), + vpc, + }); + } +} +"#; + + #[test] + fn a_cdk_logical_id_leads_to_the_construct_in_a_file_not_named_a_stack() { + assert_eq!(cdk_readable("LedgerB7C4D2E1"), Some("Ledger")); + assert_eq!(cdk_readable("Database"), None); + let r = Resource { + kind: Kind::RdsCluster, + name: "datatier-ledgerb7c4d2e1-k3j2h1".into(), + tags: tags(&[ + ("aws:cloudformation:stack-name", "DataTierProd"), + ("aws:cloudformation:logical-id", "LedgerB7C4D2E1"), + ]), + ..Default::default() + }; + let files = vec![ + file("acme/app", "src/data-tier.ts", CDK), + file( + "acme/app", + "bin/app.ts", + "import 'aws-cdk-lib';\nnew DataTier(app, 'DataTierProd');\n", + ), + ]; + let l = locate(&r, &[], &files, &[]).unwrap(); + assert_eq!((l.how.as_str(), l.tool.as_str()), ("cdk_logical_id", "cdk")); + assert_eq!( + (l.file.as_str(), l.address.as_str(), l.line), + ("src/data-tier.ts", "Ledger", 8) + ); + assert_eq!(l.confidence, Confidence::High); + let e = l.edit.unwrap(); + assert_eq!((e.line, e.via.as_str()), (10, "construct")); + assert_eq!(e.value, "rds.AuroraPostgresEngineVersion.VER_16_4"); + } + + #[test] + fn terms_are_ranked_so_no_resource_is_starved() { + let mut many: Vec = (0..40) + .map(|i| { + let mut r = db(&format!("aaa-instance-{i:02}"), &[]); + r.kind = Kind::Ec2Instance; + r.group = format!("aaa-group-{i:02}"); + r.versions.ami_id = format!("ami-0000000000000{i:04}"); + r + }) + .collect(); + // Sorted alphabetically, this one's names came after the cap. + let mut late = db( + "zeta-orders", + &[("aws:cloudformation:logical-id", "ZetaOrders")], + ); + late.pending.push(Default::default()); + many.push(late); + let t = ranked_terms(&many, 30); + assert_eq!(t.len(), 30); + assert!(t.contains(&"ZetaOrders".to_string()), "{t:?}"); + // A Terraform-generated name is not searched for; its prefix is. + let gen = db("orders-20240311094512345600000001", &[]); + assert_eq!(search_terms(&gen), vec!["orders"]); + assert!(search_terms(&db("terraform-20240311094512345600000001", &[])).is_empty()); + } + + #[test] + fn a_name_in_a_file_is_the_last_resort_and_graded() { + // Pulumi: recognised, searched by name, never sure enough alone. + let r = db("reports-prod", &[]); + let files = vec![file( + "acme/app", + "infra/index.ts", + "import * as aws from '@pulumi/aws';\nnew aws.rds.Instance('reports', { identifier: 'reports-prod', engineVersion: '16.4' });\n", + )]; + let l = locate(&r, &[], &files, &[]).unwrap(); + assert_eq!((l.how.as_str(), l.tool.as_str()), ("search", "pulumi")); + assert_eq!(l.confidence, Confidence::Low); + assert!(!l.sure()); + // A template that writes the identifier, with no stack records. + let t = "Resources:\n Reports:\n Type: AWS::RDS::DBInstance\n Properties:\n DBInstanceIdentifier: reports-prod\n EngineVersion: \"16.4\"\n"; + let l = locate(&r, &[], &[file("acme/app", "db.yaml", t)], &[]).unwrap(); + assert_eq!( + (l.address.as_str(), l.confidence), + ("Reports", Confidence::Medium) + ); + assert_eq!(l.edit.unwrap().line, 6); + assert!(locate(&r, &[], &[], &[]).is_none()); + } + + #[test] + fn environments_and_siblings_are_read_from_names_and_tags() { + assert_eq!(environment_of(&["envs/prod/main.tf"]), "production"); + assert_eq!(environment_of(&["orders-staging"]), "staging"); + assert_eq!( + environment_of(&["product-catalog"]), + "", + "a word that only starts like one" + ); + let p = db("orders-prod", &[]); + let s = db("orders-staging", &[("Environment", "Staging")]); + assert_eq!(environment_of_resource(&p), "production"); + assert_eq!(environment_of_resource(&s), "staging"); + assert_eq!(sibling_key(&p), sibling_key(&s)); + assert_ne!(sibling_key(&p), sibling_key(&db("billing-prod", &[]))); + } +} diff --git a/services/common/src/infra_vuln/matching.rs b/services/common/src/infra_vuln/matching.rs index 8a8d31f85..f06e93d02 100644 --- a/services/common/src/infra_vuln/matching.rs +++ b/services/common/src/infra_vuln/matching.rs @@ -23,8 +23,10 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; +use super::actions::{self, Meaning, Tie}; use super::feeds::{Advisory, Bulletin, Distro, LatestImage, Runtime, Who}; -use super::inventory::{Exposure, Kind, Location, Os, Resource}; +use super::inventory::{Exposure, Kind, Location, Os, Pending, Resource}; +use super::runbook::{self, PrNotes, Runbook}; use crate::security_fixes::Tier; /// What kind of fix a finding has. @@ -71,6 +73,33 @@ pub struct Fix { /// Why nothing is needed (aws), in the bulletin's words. #[serde(default)] pub reason: String, + /// Why this is a pull request, or why it is a runbook, in words. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub decision: String, + /// What a pending action means on the ARN it is on. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub meaning: Option, + /// The whole runbook, when a person applies the update in AWS. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub runbook: Option, + /// What a pull request must say and check, for the tool that defines + /// the resource. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub notes: Option, + /// What to do in the code once the update is applied in AWS. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub code_note: String, + /// Its place among related work: the other actions on the same + /// resource, and non-production before production. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub order: Vec, + /// The findings that go first (their ids). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub after: Vec, + /// What is said about advisories: why none is named, or that one is + /// only related. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub advisory_note: String, } /// One infrastructure finding: one fix for one group of resources. @@ -100,6 +129,9 @@ pub struct InfraFinding { /// replace CoderHelm's own matching for the resource. #[serde(default, skip_serializing_if = "Option::is_none")] pub inspector: Option, + /// `production`, `staging`, ...; empty when not known. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub environment: String, } /// Amazon Inspector's facts on a finding. @@ -242,6 +274,22 @@ impl Hits { self.severity("important"); } } + /// A bulletin with only the CVEs that tie to the action (none for a + /// bulletin that is only related). + fn bulletin_with(&mut self, b: &Bulletin, cves: &[String], kev: &BTreeMap) { + if !self.sources.iter().any(|s| s.id == b.id) { + self.sources.push(Source { + id: b.id.clone(), + kind: "bulletin".into(), + url: b.url.clone(), + severity: b.severity.clone(), + }); + } + self.add_cves(cves, kev); + if b.severity == "important" && !cves.is_empty() { + self.severity("important"); + } + } fn advisory(&mut self, a: &Advisory, kev: &BTreeMap) { if !self.sources.iter().any(|s| s.id == a.id) { self.sources.push(Source { @@ -291,13 +339,65 @@ fn finding(r: &Resource, key: &str, title: String, hits: Hits, fix: Fix) -> Infr exposure: r.exposure.clone(), fix, inspector: None, + environment: r + .defined_in + .as_ref() + .map(|l| l.environment.clone()) + .filter(|e| !e.is_empty()) + .unwrap_or_else(|| super::locate::environment_of_resource(r)), } } +/// The place to open a pull request against: found, with a file, and not +/// a guess. fn iac(r: &Resource) -> Option { - r.defined_in - .clone() - .filter(|l| !l.repo.is_empty() && !l.file.is_empty()) + r.defined_in.clone().filter(Location::sure) +} + +/// Why there is no pull request for a change that has a code equivalent. +fn not_in_code(r: &Resource) -> String { + match &r.defined_in { + None => "This change has a code equivalent, but CoderHelm did not find this resource in any connected repository, so it is a runbook. If it is defined in code somewhere else, change it there too, or the next apply may undo this.".to_string(), + Some(l) => format!( + "This change has a code equivalent, but CoderHelm is not sure where this resource is defined, so it opens no pull request. {} {}", + super::locate::describe(l), + l.evidence.join(". ") + ) + .trim() + .to_string(), + } +} + +/// A code fix for a resource: a pull request where the code was found for +/// sure, with the guidance's notes for its tool; a runbook otherwise. +fn code_fix(r: &Resource, feeds: &Feeds, mut fix: Fix) -> Fix { + let service = runbook::service_of(r.kind, &r.versions.engine); + let action = runbook::action_of(r.kind); + match iac(r) { + Some(l) => { + let v = runbook::vars(r, None, &fix.from, &fix.to, feeds.today); + fix.notes = Some(runbook::pr_notes( + service, + action, + &l.tool, + BTreeMap::new(), + &v, + feeds.today, + )); + fix.decision = format!( + "A pull request: this change has a code equivalent and the code that defines the resource was found. {}", + super::locate::describe(&l) + ); + fix.kind = Some(FixKind::Pr); + fix.location = Some(l); + } + None => { + fix.kind = Some(FixKind::Runbook); + fix.decision = not_in_code(r); + fix.location = r.defined_in.clone(); + } + } + fix } /// An AMI-based group (Auto Scaling group, instance, ECS container hosts). @@ -404,9 +504,9 @@ fn match_ami(r: &Resource, feeds: &Feeds, out: &mut Vec) { } else { format!("AWS's latest AL2023 AMI in {} is {latest}", r.region) }, - apply_by: String::new(), - reason: String::new(), + ..Default::default() }; + let fix = code_fix(r, feeds, fix); out.push(finding( r, &format!("ami:{to}"), @@ -481,9 +581,9 @@ fn match_nodegroup(r: &Resource, feeds: &Feeds, out: &mut Vec) { r.name, r.region )], console: format!("EKS > Clusters > {cluster} > Compute > {} > Update now", r.name), - apply_by: String::new(), - reason: String::new(), + ..Default::default() }; + let fix = code_fix(r, feeds, fix); out.push(finding( r, &format!("nodegroup:{to}"), @@ -610,6 +710,7 @@ fn match_lambda(r: &Resource, feeds: &Feeds, out: &mut Vec) { apply_by: runtime.block_update.clone(), ..Default::default() }; + let fix = code_fix(r, feeds, fix); out.push(finding( r, &format!("runtime:{rt}"), @@ -635,75 +736,318 @@ fn match_lambda(r: &Resource, feeds: &Feeds, out: &mut Vec) { } } -fn runbook( - r: &Resource, - pending: &super::inventory::Pending, - cli: String, - console: String, - service: &str, - feeds: &Feeds, - out: &mut Vec, -) { +/// What a stored pending row means: its own reading, or, for a row saved +/// before meanings were kept, what its kind says. +fn meaning(r: &Resource, p: &Pending) -> Meaning { + if p.meaning != Meaning::Unknown { + return p.meaning; + } + match (r.kind, p.kind.as_str()) { + (_, "health") => Meaning::Health, + (Kind::ElasticacheGroup, "service-update") => Meaning::ServiceUpdate, + (Kind::OpensearchDomain, "service-software") => Meaning::ServiceSoftware, + (Kind::RdsInstance, k) => actions::meaning_of(k, "instance", &r.versions.engine), + (Kind::RdsCluster, k) => match p.arns.first() { + Some(a) => actions::meaning_of(k, actions::scope_of(a), &r.versions.engine), + // Which ARN it was on was not kept: only names that mean one + // thing on both are read. + None => match k { + "db-upgrade" | "os-upgrade" => actions::meaning_of(k, "cluster", ""), + _ => Meaning::Unknown, + }, + }, + _ => Meaning::Unknown, + } +} + +/// The severity an update's own words give, when no advisory does. +fn own_severity(m: Meaning, description: &str) -> &'static str { + let d = description.to_ascii_lowercase(); + for s in ["critical", "important", "medium", "low"] { + if d.split(|c: char| !c.is_ascii_alphabetic()).any(|w| w == s) { + return s; + } + } + if m == Meaning::OsUpdate || d.contains("security") { + "important" + } else { + "medium" + } +} + +/// Whether the code's value for a version already allows `target`: the +/// same version, a later one, or a prefix of it (`16` for `16.6`). +fn code_covers(code: &str, target: &str) -> bool { + !code.is_empty() + && !target.is_empty() + && (code == target || target.starts_with(&format!("{code}.")) || !version_lt(code, target)) +} + +/// One pending update of a database, cache or search domain: a pull +/// request when the update has a code equivalent and the code was found +/// for sure, a runbook otherwise, and in both cases why. +fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) { + let m = meaning(r, p); + let service = runbook::service_of(r.kind, &r.versions.engine); + let action = m.guidance_action(); + let from = r.versions.engine_version.clone(); + let mut p = p.clone(); + p.meaning = m; + if p.arns.is_empty() { + p.arns = vec![r.id.clone()]; + } + + // Advisories: only what ties to this action. let mut hits = Hits::new(); hits.sources.push(Source { - id: format!("{}:{}", pending.kind, pending.name), + id: format!("{}:{}", p.kind, p.name), kind: "maintenance".into(), url: String::new(), severity: String::new(), }); - // A bulletin that says the customer applies it in AWS names the CVEs. - for (b, row) in bulletin_rows(feeds, service) { - if row.who == Who::CustomerInAws { - hits.bulletin(b, feeds.kev); + let bulletin_service = match r.kind { + Kind::RdsCluster | Kind::RdsInstance => "rds", + Kind::ElasticacheGroup => "elasticache", + Kind::OpensearchDomain => "opensearch", + _ => "", + }; + let target = actions::Target { + meaning: m, + engine: &r.versions.engine, + running: &from, + target: &p.target, + name: &p.name, + today: feeds.today, + }; + let mut advisory_note = String::new(); + for (b, row) in bulletin_rows(feeds, bulletin_service) { + match actions::tie(b, row, &target) { + Ok(Tie::Exact { cves, .. }) => hits.bulletin_with(b, &cves, feeds.kev), + Ok(Tie::Related { why }) => { + hits.bulletin_with(b, &[], feeds.kev); + advisory_note = why; + } + Err(_) => {} } } + let q = super::guidance::Query { + service, + action, + tool: "", + facts: BTreeMap::new(), + }; + let first = |section: &str| { + super::guidance::section(&q, section) + .first() + .map(|e| e.text.clone()) + .unwrap_or_default() + }; + if hits.cves.is_empty() && advisory_note.is_empty() { + advisory_note = first("cve"); + } if hits.severity.is_empty() { - hits.severity( - if pending.kind == "system-update" - || pending - .description - .to_ascii_lowercase() - .contains("security") - { - "important" + hits.severity(own_severity(m, &p.description)); + } + + // Pull request or runbook. + let located = r.defined_in.clone(); + let sure = located.clone().filter(Location::sure); + let where_it_is = |l: &Location| { + format!( + "`{}`{} in {}", + l.file, + if l.address.is_empty() { + String::new() } else { - "medium" + format!(" (`{}`)", l.address) }, - ); + l.repo + ) + }; + let mut kind = FixKind::Runbook; + let mut notes = None; + let mut code_note = String::new(); + let decision = if m == Meaning::Unknown { + format!( + "A runbook: AWS documents the `{}` action on a cluster only for Aurora PostgreSQL (an engine patch) and on an instance as an operating system update. On this {} ({}) AWS does not say what it does, so CoderHelm does not either: read AWS's description of the action before applying it.", + p.kind, + r.kind.label(), + r.versions.engine + ) + } else if !m.in_code() { + let mut d = first("in_code"); + if d.is_empty() { + d = "This is applied in AWS; nothing in infrastructure code does it.".into(); + } + if let Some(l) = &sure { + d.push_str(&format!( + " The resource is defined in {}; nothing there changes for this update.", + where_it_is(l) + )); + } + d + } else if p.target.is_empty() { + "This update has a code equivalent, but AWS's description of the action does not name the version it moves to, so CoderHelm cannot write the change. Read the valid targets with the first check below.".to_string() + } else { + match (&sure, sure.as_ref().and_then(|l| l.edit.as_ref())) { + (Some(_), Some(e)) if e.value.is_empty() => { + code_note = format!( + "The code that defines this resource sets no `{}` ({}), so no version there holds this back and there is nothing to change.", + e.attribute, e.file + ); + "A runbook: the code that defines this resource does not pin a version, so the upgrade is not a code change. Apply it in AWS, or let AWS apply it in the maintenance window.".to_string() + } + (Some(_), Some(e)) if code_covers(&e.value, &p.target) => { + code_note = format!( + "The code already allows {}: {} sets `{}` to `{}` (line {}). No code change is needed.", + p.target, e.file, e.attribute, e.value, e.line + ); + format!( + "A runbook: the code that defines this resource already allows version {} ({} is `{}`), so there is nothing to change there. The upgrade has not run yet: it is waiting for the maintenance window or for the change to be applied.", + p.target, e.attribute, e.value + ) + } + (Some(l), Some(_)) => { + kind = FixKind::Pr; + let mut facts = BTreeMap::new(); + if let Some(major) = actions::is_major(&r.versions.engine, &from, &p.target) { + facts.insert("major".to_string(), major.to_string()); + } + let v = runbook::vars(r, Some(&p), &from, &p.target, feeds.today); + notes = Some(runbook::pr_notes( + service, + action, + &l.tool, + facts, + &v, + feeds.today, + )); + format!( + "A pull request: an engine version change has a code equivalent, and the code that defines this resource was found. {}", + super::locate::describe(l) + ) + } + _ => { + code_note = "If this resource is defined in code, raise its pinned version there to the new version once this is applied. A version pinned behind the live one makes the next apply a downgrade attempt, which the service refuses.".into(); + not_in_code(r) + } + } + }; + + // Built for a pull request too: if the replacement guard gives up on + // the code change, the finding falls back to it. + let rb = Some(runbook::build(r, &p, feeds.today)); + let (cli, console) = match rb.as_ref().filter(|_| kind == FixKind::Runbook) { + Some(rb) => ( + rb.steps + .iter() + .filter(|s| !s.cli.is_empty()) + .map(|s| s.cli.clone()) + .take(p.arns.len().max(1)) + .collect(), + rb.console.first().cloned().unwrap_or_default(), + ), + None => (Vec::new(), String::new()), + }; + let what = if m == Meaning::Unknown { + format!("AWS action `{}`", p.kind) + } else if p.target.is_empty() { + m.label().to_string() + } else { + format!("{} to {}", m.label(), p.target) + }; + let summary = match (kind, &sure) { + (FixKind::Pr, Some(l)) => { + let e = l.edit.as_ref(); + format!( + "Raise `{}` to {} in {}", + e.map(|e| e.attribute.as_str()) + .unwrap_or("the engine version"), + p.target, + e.map(|e| e.file.as_str()).unwrap_or(l.file.as_str()) + ) + } + _ => format!("Apply the {what} in AWS (`{}`)", p.kind), + }; + let mut order = Vec::new(); + if !p.order_why.is_empty() { + order.push(p.order_why.clone()); + } + for x in &p.merged { + order.push(format!("{}.", super::locate::sentence(x))); } + let fix = Fix { + kind: Some(kind), + summary, + location: if kind == FixKind::Pr { sure } else { located }, + from, + to: p.target.clone(), + cli, + console, + apply_by: p.apply_by.clone(), + reason: p.description.clone(), + decision, + meaning: Some(m), + runbook: rb, + notes, + code_note, + order, + after: Vec::new(), + advisory_note, + }; + out.push(finding( + r, + &format!("{}:{}", p.kind, p.name), + format!("{} {}: {what} pending", r.kind.label(), r.name), + hits, + fix, + )); +} + +/// An AWS Health event on a resource: a card that says where to read it. +fn health(r: &Resource, p: &Pending, out: &mut Vec) { + let mut hits = Hits::new(); + hits.sources.push(Source { + id: format!("{}:{}", p.kind, p.name), + kind: "maintenance".into(), + url: String::new(), + severity: String::new(), + }); + hits.severity(own_severity(Meaning::Health, &p.description)); let fix = Fix { kind: Some(FixKind::Runbook), - summary: format!( - "Apply {} {} in AWS", - pending.kind.replace('-', " "), - if pending.name == pending.kind { - String::new() + summary: format!("Act on the AWS Health event {}", p.name), + from: r.versions.engine_version.clone(), + cli: vec![format!( + "aws health describe-events --filter eventTypeCodes={} --region us-east-1", + p.name + )], + console: format!( + "AWS Health Dashboard > Your account health > {}", + if p.auto_applied_after.is_empty() { + "Open and recent issues" } else { - pending.name.clone() + "Scheduled changes" } - ) - .replace(" ", " ") - .trim() - .to_string(), - location: None, - from: r.versions.engine_version.clone(), - to: String::new(), - cli: vec![cli], - console, - apply_by: pending.apply_by.clone(), - reason: pending.description.clone(), + ), + apply_by: p.apply_by.clone(), + reason: p.description.clone(), + decision: "A runbook: an AWS Health event says what to do in its own words; read the event for the steps.".into(), + meaning: Some(Meaning::Health), + advisory_note: "AWS Health events carry an action type and dates, not a CVE list.".into(), + ..Default::default() }; out.push(finding( r, - &format!("{}:{}", pending.kind, pending.name), + &format!("{}:{}", p.kind, p.name), format!( "{} {}: {}", r.kind.label(), r.name, - if pending.description.is_empty() { - pending.name.clone() + if p.description.is_empty() { + p.name.clone() } else { - pending.description.clone() + p.description.clone() } ), hits, @@ -713,56 +1057,96 @@ fn runbook( fn match_managed(r: &Resource, feeds: &Feeds, out: &mut Vec) { for p in &r.pending { - match r.kind { - Kind::RdsCluster | Kind::RdsInstance - if matches!(p.kind.as_str(), "system-update" | "db-upgrade") => + match meaning(r, p) { + Meaning::Health => health(r, p, out), + Meaning::OsUpdate + | Meaning::EnginePatch + | Meaning::EngineUpgrade + | Meaning::ServiceUpdate + | Meaning::ServiceSoftware => update(r, p, feeds, out), + // An update action AWS does not document for this ARN (a + // cluster-level `system-update` on an engine other than Aurora + // PostgreSQL): shown, named as AWS names it, with no meaning + // made up for it. + Meaning::Unknown + if matches!(r.kind, Kind::RdsCluster | Kind::RdsInstance) + && matches!( + p.kind.as_str(), + "system-update" | "os-upgrade" | "db-upgrade" + ) => { - let cli = format!( - "aws rds apply-pending-maintenance-action --resource-identifier {} --apply-action {} --opt-in-type next-maintenance --region {}", - r.id, p.kind, r.region - ); - let console = format!( - "RDS > Databases > {} > Maintenance & backups > Pending maintenance > Apply", - r.name - ); - runbook(r, p, cli, console, "rds", feeds, out); - } - Kind::ElasticacheGroup if p.kind == "service-update" => { - let cli = format!( - "aws elasticache batch-apply-update-action --service-update-name {} --replication-group-ids {} --region {}", - p.name, r.name, r.region - ); - let console = format!("ElastiCache > Service updates > {} > Apply now", p.name); - runbook(r, p, cli, console, "elasticache", feeds, out); - } - _ if p.kind == "health" => { - let cli = format!( - "aws health describe-events --filter eventTypeCodes={} --region us-east-1", - p.name - ); - let console = format!( - "AWS Health Dashboard > Your account health > {}", - if p.auto_applied_after.is_empty() { - "Open and recent issues" - } else { - "Scheduled changes" - } - ); - runbook(r, p, cli, console, "", feeds, out); - } - Kind::OpensearchDomain if p.kind == "service-software" => { - let cli = format!("aws opensearch start-service-software-update --domain-name {} --schedule-at OFF_PEAK_WINDOW --region {}", r.name, r.region); - let console = format!( - "OpenSearch Service > Domains > {} > Actions > Update", - r.name - ); - runbook(r, p, cli, console, "opensearch", feeds, out); + update(r, p, feeds, out) } + // Hardware maintenance, certificate rotation and the + // serverless platform version are not security updates + // CoderHelm describes: they are not made into findings. _ => {} } } } +/// The same resource in more than one environment: the non-production +/// one goes first, and both rows say so. +fn order_environments(found: &mut [InfraFinding], siblings: &[(usize, String)]) { + let rule = super::guidance::section( + &super::guidance::Query { + service: "any", + action: "any", + tool: "", + facts: BTreeMap::new(), + }, + "order", + ) + .first() + .map(|e| e.text.clone()) + .unwrap_or_default(); + let mut groups: BTreeMap<(String, Option, String), Vec> = BTreeMap::new(); + for (i, key) in siblings { + let f = &found[*i]; + if f.fix.kind == Some(FixKind::Aws) { + continue; + } + groups + .entry((key.clone(), f.fix.meaning, f.fix.to.clone())) + .or_default() + .push(*i); + } + for members in groups.values() { + let prod: Vec = members + .iter() + .copied() + .filter(|i| found[*i].environment == "production") + .collect(); + let first: Vec = members + .iter() + .copied() + .filter(|i| !found[*i].environment.is_empty() && found[*i].environment != "production") + .collect(); + if prod.is_empty() || first.is_empty() { + continue; + } + let names = |ids: &[usize]| { + ids.iter() + .map(|i| format!("`{}` ({})", found[*i].name, found[*i].environment)) + .collect::>() + .join(", ") + }; + let (before, after_names) = (names(&first), names(&prod)); + let ids: Vec = first.iter().map(|i| found[*i].id.clone()).collect(); + for i in &prod { + found[*i].fix.after = ids.clone(); + found[*i].fix.order.push(format!( + "This is production. The same update is open on {before}: do that first, check it, then this one. {rule}" + )); + } + for i in &first { + found[*i].fix.order.push(format!( + "This is the non-production copy of {after_names}: do this one first. {rule}" + )); + } + } +} + fn inspector_rank(s: &str) -> &'static str { match s.to_ascii_uppercase().as_str() { "CRITICAL" => "critical", @@ -820,7 +1204,9 @@ fn with_inspector(r: &Resource, own: Vec, feeds: &Feeds) -> Vec { for s in hit_sources.sources.drain(..) { @@ -891,7 +1277,27 @@ fn with_inspector(r: &Resource, own: Vec, feeds: &Feeds) -> Vec Vec { let mut out = Vec::new(); + let mut siblings: Vec<(usize, String)> = Vec::new(); for r in resources { + let start = out.len(); + match_one(r, feeds, &mut out); + let key = super::locate::sibling_key(r); + siblings.extend((start..out.len()).map(|i| (i, key.clone()))); + } + order_environments(&mut out, &siblings); + out.sort_by(|a, b| { + (a.tier.is_none(), a.tier, a.fix.kind, a.title.as_str()).cmp(&( + b.tier.is_none(), + b.tier, + b.fix.kind, + b.title.as_str(), + )) + }); + out +} + +fn match_one(r: &Resource, feeds: &Feeds, out: &mut Vec) { + { if !r.inspector.is_empty() && matches!( r.kind, @@ -910,30 +1316,21 @@ pub fn findings(resources: &[Resource], feeds: &Feeds) -> Vec { _ => {} } out.extend(with_inspector(r, own, feeds)); - match_managed(r, feeds, &mut out); - continue; + match_managed(r, feeds, out); + return; } match r.kind { - Kind::AutoScalingGroup | Kind::Ec2Instance => match_ami(r, feeds, &mut out), - Kind::EksNodegroup => match_nodegroup(r, feeds, &mut out), - Kind::EcsFargateService => match_fargate(r, feeds, &mut out), - Kind::LambdaFunction => match_lambda(r, feeds, &mut out), + Kind::AutoScalingGroup | Kind::Ec2Instance => match_ami(r, feeds, out), + Kind::EksNodegroup => match_nodegroup(r, feeds, out), + Kind::EcsFargateService => match_fargate(r, feeds, out), + Kind::LambdaFunction => match_lambda(r, feeds, out), Kind::RdsCluster | Kind::RdsInstance | Kind::ElasticacheGroup - | Kind::OpensearchDomain => match_managed(r, feeds, &mut out), + | Kind::OpensearchDomain => match_managed(r, feeds, out), Kind::EksCluster | Kind::ContainerImage => {} } } - out.sort_by(|a, b| { - (a.tier.is_none(), a.tier, a.fix.kind, a.title.as_str()).cmp(&( - b.tier.is_none(), - b.tier, - b.fix.kind, - b.title.as_str(), - )) - }); - out } /// Whether a finding is still open after a new read of the account: its @@ -1075,13 +1472,44 @@ mod tests { // The Aurora runbook card: exact CLI, console path, AWS's date. let db = runbooks[0]; assert_eq!(db.kind, Some(Kind::RdsCluster)); - assert!(db.fix.cli[0].starts_with("aws rds apply-pending-maintenance-action --resource-identifier arn:aws:rds:us-east-1:111122223333:cluster:orders --apply-action system-update")); - assert!(db.fix.console.contains("Pending maintenance")); + // The action is pending on the instance ARN, where `system-update` + // is an operating system update: the command names that ARN. + assert!(db.fix.cli[0].starts_with("aws rds apply-pending-maintenance-action --resource-identifier arn:aws:rds:us-east-1:111122223333:db:orders-1 --apply-action system-update"), "{:?}", db.fix.cli); + assert!( + db.fix.console.contains("Patch at next window"), + "{}", + db.fix.console + ); assert_eq!(db.fix.apply_by, "2026-12-01"); + assert_eq!(db.fix.meaning, Some(Meaning::OsUpdate)); + assert!(db.title.contains("operating system update"), "{}", db.title); + // AWS publishes no CVE list for an OS update: the bulletin that + // tells RDS customers to patch the database OS is shown as + // related, and its CVE is not put on the action. + assert!(db.cves.is_empty(), "{:?}", db.cves); assert!( db.sources.iter().any(|s| s.id == "2026-160-AWS"), - "the bulletin says RDS customers apply it" + "the bulletin says RDS customers patch the database OS" + ); + assert!( + db.fix.advisory_note.contains("no CVE list"), + "{}", + db.fix.advisory_note ); + // The cluster is in the team's Terraform, and it is still a + // runbook, because an OS update cannot be expressed in code. + assert!( + db.fix.decision.contains("cannot be expressed in code"), + "{}", + db.fix.decision + ); + assert!( + db.fix.decision.contains("aws_rds_cluster.orders"), + "{}", + db.fix.decision + ); + let rb = db.fix.runbook.as_ref().expect("a full runbook"); + assert!(!rb.prechecks.is_empty() && !rb.backup.is_empty() && !rb.rollback.is_empty()); // AWS-managed rows, never counted as open. let fargate = aws @@ -1181,8 +1609,15 @@ mod tests { .unwrap(); assert_eq!( ng.fix.kind, - Some(FixKind::Pr), - "CoderHelm's node group fix is kept" + Some(FixKind::Runbook), + "CoderHelm's node group fix is kept; not found in code, it is a runbook" + ); + assert!(ng.fix.to.ends_with("20261031"), "{}", ng.fix.to); + assert!(ng.fix.cli[0].starts_with("aws eks update-nodegroup-version")); + assert!( + ng.fix.decision.contains("did not find this resource"), + "{}", + ng.fix.decision ); assert!(ng.sources.iter().any(|s| s.kind == "inspector")); let facts = ng.inspector.as_ref().unwrap(); @@ -1268,6 +1703,15 @@ mod tests { package_type: "Zip".into(), ..Default::default() }, + defined_in: Some(Location { + repo: "acme/infra".into(), + file: "lambda.tf".into(), + address: "aws_lambda_function.thumbs".into(), + how: "terraform_name".into(), + tool: "terraform".into(), + confidence: inventory::Confidence::High, + ..Default::default() + }), ..Default::default() }; let kev = BTreeMap::new(); @@ -1294,5 +1738,454 @@ mod tests { .unwrap() .deprecated ); + let notes = f[0].fix.notes.as_ref().expect("the guidance for Terraform"); + assert!(notes.attribute[0].contains("`runtime` on the `aws_lambda_function`")); + assert!(notes.rollback[0].contains("block-update date")); + } + + fn feeds_with<'a>( + bulletins: &'a [Bulletin], + kev: &'a BTreeMap, + latest: &'a BTreeMap, + ) -> Feeds<'a> { + Feeds { + advisories: &[], + bulletins, + runtimes: &[], + latest: &[], + kev, + latest_al2023: latest, + today: "2026-11-13", + } + } + + fn database(name: &str, engine: &str, version: &str, lines: &[(&str, &str, &str)]) -> Resource { + let cluster = engine.starts_with("aurora"); + let arn = format!( + "arn:aws:rds:us-east-1:111122223333:{}:{name}", + if cluster { "cluster" } else { "db" } + ); + let lines: Vec = lines + .iter() + .map(|(action, description, by)| actions::Line { + arn: arn.clone(), + action: action.to_string(), + description: description.to_string(), + apply_by: by.to_string(), + ..Default::default() + }) + .collect(); + Resource { + id: arn.clone(), + kind: if cluster { + Kind::RdsCluster + } else { + Kind::RdsInstance + }, + name: name.into(), + account: "111122223333".into(), + region: "us-east-1".into(), + group: arn, + versions: inventory::Versions { + engine: engine.into(), + engine_version: version.into(), + ..Default::default() + }, + pending: actions::reconcile(engine, version, &lines), + count: 1, + ..Default::default() + } + } + + fn in_terraform( + file: &str, + address: &str, + value: &str, + confidence: inventory::Confidence, + ) -> Location { + Location { + repo: "acme/infra".into(), + file: file.into(), + address: address.into(), + line: 3, + how: "terraform_name".into(), + tool: "terraform".into(), + confidence, + edit: Some(inventory::Edit { + file: file.into(), + line: 5, + attribute: "engine_version".into(), + value: value.into(), + via: "resource".into(), + shared: String::new(), + }), + ..Default::default() + } + } + + fn one(r: Resource, bulletins: &[Bulletin]) -> Vec { + let (kev, latest) = (BTreeMap::new(), BTreeMap::new()); + findings(&[r], &feeds_with(bulletins, &kev, &latest)) + } + + #[test] + fn an_engine_upgrade_is_a_pull_request_when_the_code_is_found_for_sure() { + let mut r = database( + "billing-prod", + "mysql", + "8.0.36", + &[("db-upgrade", "Upgrade to 8.0.40", "2026-12-10")], + ); + r.defined_in = Some(in_terraform( + "db/main.tf", + "aws_db_instance.billing", + "8.0.36", + inventory::Confidence::High, + )); + let f = one(r.clone(), &[]); + assert_eq!(f.len(), 1); + let x = &f[0]; + assert_eq!(x.fix.kind, Some(FixKind::Pr)); + assert_eq!( + (x.fix.from.as_str(), x.fix.to.as_str()), + ("8.0.36", "8.0.40") + ); + assert_eq!( + x.fix.summary, + "Raise `engine_version` to 8.0.40 in db/main.tf" + ); + assert!( + x.fix.decision.starts_with("A pull request"), + "{}", + x.fix.decision + ); + // The runbook is kept behind the pull request, for a fallback; the + // card's own commands stay empty while it is a pull request. + assert!(x + .fix + .runbook + .as_ref() + .is_some_and(|rb| !rb.steps.is_empty())); + assert!(x.fix.cli.is_empty()); + let n = x.fix.notes.as_ref().unwrap(); + assert!(n.takes_effect[0].contains("`apply_immediately` defaults to `false`")); + assert!(n.interruption[0].contains("Engine upgrades require downtime")); + assert!(n.rollback[0].contains("one-way")); + assert!(n.never_change.contains(&"identifier".to_string())); + assert!(n + .traps + .iter() + .any(|t| t.contains("Never set a value below the live version"))); + assert!( + x.cves.is_empty(), + "the action names no CVE and no bulletin ties one to it" + ); + assert_eq!(x.fix.apply_by, "2026-12-10"); + + // The same update, the code found but not for sure: a runbook + // that says what was found and why it is unsure. + let mut unsure = r.clone(); + let mut l = in_terraform( + "db/main.tf", + "aws_db_instance.billing", + "8.0.36", + inventory::Confidence::Low, + ); + l.evidence = vec!["2 other places fit about as well".into()]; + unsure.defined_in = Some(l); + let x = &one(unsure, &[])[0]; + assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert!( + x.fix + .decision + .contains("is not sure where this resource is defined"), + "{}", + x.fix.decision + ); + assert!( + x.fix.decision.contains("2 other places fit"), + "{}", + x.fix.decision + ); + assert!(x.fix.location.is_some(), "what was found is still shown"); + assert!(x.fix.runbook.as_ref().unwrap().steps[0].cli.contains( + "modify-db-instance --db-instance-identifier billing-prod --engine-version 8.0.40" + )); + assert!(x.fix.code_note.contains("raise its pinned version")); + + // Not in any repository: a runbook. + let mut nowhere = r.clone(); + nowhere.defined_in = None; + let x = &one(nowhere, &[])[0]; + assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert!(x + .fix + .decision + .contains("did not find this resource in any connected repository")); + + // The code already allows the target (a prefix): nothing to change. + let mut prefix = r.clone(); + prefix.defined_in = Some(in_terraform( + "db/main.tf", + "aws_db_instance.billing", + "8.0", + inventory::Confidence::High, + )); + let x = &one(prefix, &[])[0]; + assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert!( + x.fix.decision.contains("already allows version 8.0.40"), + "{}", + x.fix.decision + ); + + // The code pins no version at all: nothing to change there. + let mut unpinned = r.clone(); + let mut l = in_terraform( + "db/main.tf", + "aws_db_instance.billing", + "", + inventory::Confidence::High, + ); + if let Some(e) = l.edit.as_mut() { + e.via = "add".into(); + } + unpinned.defined_in = Some(l); + let x = &one(unpinned, &[])[0]; + assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert!( + x.fix.decision.contains("does not pin a version"), + "{}", + x.fix.decision + ); + + // AWS's description names no version: no change can be written. + let mut vague = database( + "billing-prod", + "mysql", + "8.0.36", + &[("db-upgrade", "A new engine version is available", "")], + ); + vague.defined_in = r.defined_in.clone(); + let x = &one(vague, &[])[0]; + assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert!(x.fix.decision.contains("does not name the version")); + } + + #[test] + fn what_cannot_be_expressed_in_code_stays_a_runbook_even_when_the_resource_is_in_code() { + for (engine, version, action, description, meaning) in [ + ( + "postgres", + "16.4", + "system-update", + "New Operating System update is available", + Meaning::OsUpdate, + ), + ( + "aurora-postgresql", + "16.4", + "system-update", + "Upgrade to Aurora PostgreSQL 16.4.3", + Meaning::EnginePatch, + ), + ( + "aurora-postgresql", + "16.4", + "os-upgrade", + "New Operating System patch is available", + Meaning::OsUpdate, + ), + ] { + let mut r = database("orders", engine, version, &[(action, description, "")]); + r.defined_in = Some(in_terraform( + "main.tf", + "aws_rds_cluster.orders", + version, + inventory::Confidence::High, + )); + let f = one(r, &[]); + assert_eq!(f.len(), 1, "{action} on {engine}"); + let x = &f[0]; + assert_eq!(x.fix.meaning, Some(meaning)); + assert_eq!(x.fix.kind, Some(FixKind::Runbook), "{action} on {engine}"); + assert!( + x.fix.decision.contains("cannot be expressed in code"), + "{}", + x.fix.decision + ); + assert!( + x.fix + .decision + .contains("nothing there changes for this update"), + "{}", + x.fix.decision + ); + assert!(x.fix.notes.is_none()); + assert!(x.cves.is_empty()); + } + // Hardware maintenance is not made into a finding. An update + // action AWS does not document for this ARN is shown under AWS's + // own name, with no meaning made up for it. + let r = database( + "orders", + "aurora-mysql", + "8.0.mysql_aurora.3.08.2", + &[ + ("hardware-maintenance", "", ""), + ("system-update", "something", "2026-12-01"), + ], + ); + let f = one(r, &[]); + assert_eq!(f.len(), 1); + assert_eq!(f[0].fix.meaning, Some(Meaning::Unknown)); + assert!( + f[0].title.contains("AWS action `system-update` pending"), + "{}", + f[0].title + ); + assert!( + f[0].fix.decision.contains("AWS does not say what it does"), + "{}", + f[0].fix.decision + ); + assert!( + f[0].fix.cli[0].contains("--apply-action system-update --opt-in-type next-maintenance"), + "{:?}", + f[0].fix.cli + ); + assert!(f[0].cves.is_empty()); + } + + #[test] + fn an_advisory_is_attached_only_where_it_applies() { + let b = Bulletin { + id: "2026-170-AWS".into(), + severity: "important".into(), + published: "2026-11-01".into(), + url: "u".into(), + cves: vec!["CVE-2026-11111".into()], + services: vec![feeds::ServiceStatus { + service: "rds".into(), + who: Who::CustomerInAws, + reason: "Customers should upgrade to Aurora PostgreSQL 16.4.3 or RDS for MySQL version 8.0.40.".into(), + ..Default::default() + }], + ..Default::default() + }; + let bs = std::slice::from_ref(&b); + // The OS update on any database: never the CVE. + let os = one( + database( + "a", + "postgres", + "16.4", + &[( + "system-update", + "New Operating System update is available", + "", + )], + ), + bs, + ); + assert!(os[0].cves.is_empty() && !os[0].sources.iter().any(|s| s.id == b.id)); + // The Aurora PostgreSQL patch to the fixed version: the CVE. + let patch = one( + database( + "b", + "aurora-postgresql", + "16.4", + &[("system-update", "Upgrade to Aurora PostgreSQL 16.4.3", "")], + ), + bs, + ); + assert_eq!(patch[0].cves, vec!["CVE-2026-11111"]); + assert_eq!(patch[0].severity, "important"); + // A MySQL upgrade that stops short of the fix: not the CVE. + let short = one( + database( + "c", + "mysql", + "8.0.36", + &[("db-upgrade", "Upgrade to 8.0.39", "")], + ), + bs, + ); + assert!(short[0].cves.is_empty()); + // A MySQL upgrade that reaches it: the CVE. + let reach = one( + database( + "d", + "mysql", + "8.0.36", + &[("db-upgrade", "Upgrade to 8.0.40", "")], + ), + bs, + ); + assert_eq!(reach[0].cves, vec!["CVE-2026-11111"]); + // MariaDB is not named by the bulletin. + let other = one( + database( + "e", + "mariadb", + "10.11.6", + &[("db-upgrade", "Upgrade to 10.11.9", "")], + ), + bs, + ); + assert!(other[0].cves.is_empty()); + assert!( + other[0].fix.advisory_note.contains("no CVE list"), + "{}", + other[0].fix.advisory_note + ); + } + + #[test] + fn the_non_production_copy_goes_first_and_both_rows_say_so() { + let up = [("db-upgrade", "Upgrade to 16.6", "2027-01-15")]; + let mut prod = database("orders-prod", "postgres", "16.4", &up); + prod.defined_in = Some(in_terraform( + "envs/prod/main.tf", + "aws_db_instance.orders", + "16.4", + inventory::Confidence::High, + )); + let mut staging = database("orders-staging", "postgres", "16.4", &up); + staging.defined_in = Some(in_terraform( + "envs/staging/main.tf", + "aws_db_instance.orders", + "16.4", + inventory::Confidence::High, + )); + let other = database("billing-prod", "postgres", "16.4", &up); + let (kev, latest) = (BTreeMap::new(), BTreeMap::new()); + let f = findings(&[prod, staging, other], &feeds_with(&[], &kev, &latest)); + let by = |n: &str| f.iter().find(|x| x.name == n).unwrap(); + let (p, s, o) = (by("orders-prod"), by("orders-staging"), by("billing-prod")); + assert_eq!( + (p.environment.as_str(), s.environment.as_str()), + ("production", "staging") + ); + assert_eq!(p.fix.after, vec![s.id.clone()]); + assert!( + p.fix + .order + .iter() + .any(|x| x.contains("`orders-staging` (staging): do that first")), + "{:?}", + p.fix.order + ); + assert!(s.fix.after.is_empty()); + assert!( + s.fix.order.iter().any(|x| x.contains("do this one first")), + "{:?}", + s.fix.order + ); + assert!(s.fix.order.iter().any(|x| x.contains("Well-Architected"))); + assert!( + o.fix.after.is_empty() && o.fix.order.is_empty(), + "no copy of it elsewhere" + ); } } diff --git a/services/common/src/infra_vuln/mod.rs b/services/common/src/infra_vuln/mod.rs index d475d151e..9c40c3b85 100644 --- a/services/common/src/infra_vuln/mod.rs +++ b/services/common/src/infra_vuln/mod.rs @@ -15,18 +15,40 @@ //! the optional "Infrastructure vulnerabilities" permissions of its //! CoderHelmLogReader role (`RES#` records in the AWS insights table). //! +//! - [`locate`], [`terraform`] and [`hcl`]: where each resource is defined +//! in the team's code, in whatever tool and layout, with how it was +//! found and how sure that is. +//! +//! - [`actions`]: what a pending action means on its ARN, which advisories +//! apply to it, and one ordered set of rows per resource. +//! //! - [`matching`] and [`records`]: one finding per fix (a PR, a runbook //! step in AWS, or AWS-managed), closed only when a new read of the -//! account shows the fix running. +//! account shows the fix running. A fix is a pull request when the +//! update has a code equivalent and the code was found for sure; else a +//! runbook that says why. +//! +//! - [`guidance`]: what AWS and each tool say about applying an update, +//! as dated, sourced data. [`runbook`] writes the runbook and the pull +//! request's notes from it; [`guard`] refuses a change that would +//! replace or destroy a data resource. //! -//! Nothing here calls a model: every match is a version comparison. +//! Nothing here calls a model: every match is a comparison. +pub mod actions; pub mod feeds; +pub mod guard; +pub mod guidance; +pub mod hcl; pub mod inventory; +pub mod locate; pub mod matching; pub mod raw; pub mod records; +pub mod runbook; +pub mod stacks; pub mod store; +pub mod terraform; /// Global records live under the same partition as the CISA list. pub const GLOBAL_PK: &str = crate::security_fixes::GLOBAL_PK; diff --git a/services/common/src/infra_vuln/raw.rs b/services/common/src/infra_vuln/raw.rs index 3dcca4663..61093e87b 100644 --- a/services/common/src/infra_vuln/raw.rs +++ b/services/common/src/infra_vuln/raw.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; +use super::actions::{self, Line, Meaning}; use super::inventory::{self as inv, AmiInfo, Exposure, Kind, Pending, Resource, Versions}; #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -110,6 +111,13 @@ pub struct RawDatabase { /// An instance of this cluster (its own record is the cluster's). pub cluster: String, pub tags: Vec<(String, String)>, + /// An instance that is its cluster's writer. + pub writer: bool, + /// Settings that tell it apart in code and say how an update lands + /// (`subnet_group`, `parameter_group`, `instance_class`, `multi_az`, + /// `auto_minor`, `maintenance_window`, `backup_retention`, `replicas`, + /// `global`). Never credentials. + pub facts: BTreeMap, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -275,13 +283,14 @@ impl RawAccount { out } - fn pending_for(&self, arn: &str) -> Vec { + /// What AWS lists as pending on one ARN. + fn lines_for(&self, arn: &str, writer: bool) -> Vec { self.pending .iter() .filter(|p| p.resource_arn == arn) - .map(|p| Pending { - kind: p.action.clone(), - name: p.action.clone(), + .map(|p| Line { + arn: arn.to_string(), + action: p.action.clone(), description: p.description.clone(), apply_by: [&p.forced_apply, &p.auto_applied_after, &p.current_apply] .into_iter() @@ -289,7 +298,7 @@ impl RawAccount { .map(|d| d.chars().take(10).collect()) .unwrap_or_default(), auto_applied_after: p.auto_applied_after.chars().take(10).collect(), - status: "pending".into(), + writer, }) .collect() } @@ -528,15 +537,26 @@ impl RawAccount { "not publicly accessible".into() }, }; - let mut pending = self.pending_for(&d.arn); + // Everything pending on the cluster and on its instances, as + // one row per meaning (the same action name means different + // things on the two kinds of ARN). + let mut lines = self.lines_for(&d.arn, false); for m in &members { - for p in self.pending_for(&m.arn) { - if !pending.iter().any(|x| x.kind == p.kind) { - pending.push(p); - } - } + lines.extend(self.lines_for(&m.arn, m.writer)); + } + r.pending = actions::reconcile(&d.engine, &d.engine_version, &lines); + r.facts = d.facts.clone(); + r.facts.insert( + "members".into(), + members + .iter() + .map(|m| m.id.as_str()) + .collect::>() + .join(","), + ); + if let Some(w) = members.iter().find(|m| m.writer) { + r.facts.insert("writer".into(), w.id.clone()); } - r.pending = pending; out.push(r); } for d in self.db_instances.iter().filter(|i| i.cluster.is_empty()) { @@ -551,7 +571,9 @@ impl RawAccount { "not publicly accessible".into() }, }; - r.pending = self.pending_for(&d.arn); + r.pending = + actions::reconcile(&d.engine, &d.engine_version, &self.lines_for(&d.arn, false)); + r.facts = d.facts.clone(); out.push(r); } @@ -580,6 +602,9 @@ impl RawAccount { apply_by: u.apply_by.chars().take(10).collect(), auto_applied_after: String::new(), status: u.status.clone(), + meaning: Meaning::ServiceUpdate, + arns: vec![g.to_string()], + ..Default::default() }) .collect(); out.push(r); @@ -611,6 +636,9 @@ impl RawAccount { apply_by: d.automated_update_date.chars().take(10).collect(), auto_applied_after: d.automated_update_date.chars().take(10).collect(), status: "available".into(), + meaning: Meaning::ServiceSoftware, + arns: vec![d.arn.clone()], + ..Default::default() }); } out.push(r); @@ -662,6 +690,8 @@ impl RawAccount { String::new() }, status: e.status.clone(), + meaning: Meaning::Health, + ..Default::default() }); } } @@ -702,6 +732,10 @@ pub const CALLS: &[(&str, &str)] = &[ "elasticache:DescribeServiceUpdates", ), ("DescribeUpdateActions", "elasticache:DescribeUpdateActions"), + ( + "DescribeStackResources", + "cloudformation:DescribeStackResources", + ), ("ListDomainNames", "es:ListDomainNames"), ("DescribeDomains", "es:DescribeDomains"), ("DescribeImageScanFindings", "ecr:DescribeImageScanFindings"), diff --git a/services/common/src/infra_vuln/records.rs b/services/common/src/infra_vuln/records.rs index 55e0c14eb..2369f74ab 100644 --- a/services/common/src/infra_vuln/records.rs +++ b/services/common/src/infra_vuln/records.rs @@ -91,6 +91,22 @@ pub struct Record { pub updated_at: String, #[serde(default)] pub fixed_at: Option, + /// Why the replacement guard refused the change a fix run made + /// ([`super::guard`]): each offending line. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub refused: Vec, + /// How many times in a row the guard tripped on this finding's + /// change: 1 while the one fix round runs, 2 once it gave up. + #[serde(default)] + pub guard_attempts: u8, + /// The guard tripped twice: the pull request is a draft and the + /// finding is applied by its runbook. + #[serde(default)] + pub drafted: bool, + /// What the refused change was for ([`guard_sig`]): no new fix run + /// starts by itself while the finding still asks for the same. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub guard_sig: String, /// A line for the timeline when something changed (not stored). #[serde(skip)] pub event: Option, @@ -116,6 +132,10 @@ impl Record { first_seen_at: now.into(), updated_at: now.into(), fixed_at: None, + refused: Vec::new(), + guard_attempts: 0, + drafted: false, + guard_sig: String::new(), } } @@ -135,6 +155,22 @@ impl Record { o.insert("fixed_at".into(), json!(self.fixed_at)); // The fix's kind as the contract names it. o["fix"]["kind"] = json!(self.finding.fix.kind); + if !self.refused.is_empty() { + o.insert("refused".into(), json!(self.refused)); + o.insert("drafted".into(), json!(self.drafted)); + 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); + o["fix"]["decision"] = json!(format!( + "A runbook: CoderHelm's own code change for this update would have replaced or destroyed a resource that holds data, twice, so its pull request is a draft and the update is applied in AWS. {}", + GUARD_STOPPED + )); + o.insert("note".into(), json!(GUARD_DRAFT_NOTE)); + } else { + o.insert("note".into(), json!(GUARD_ROUND_NOTE)); + } + } if self.status == Status::PrOpen && self.pr.as_ref().is_some_and(|p| p.state == "merged") { @@ -145,6 +181,87 @@ impl Record { } } +/// What the page says while the one fix round after a tripped guard runs. +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."; +/// 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."; + +/// What a finding's code change is for: the target and the line it +/// edits. A guard refusal holds for as long as this stays the same. +pub fn guard_sig(f: &InfraFinding) -> String { + let l = f.fix.location.as_ref(); + let e = l.and_then(|l| l.edit.as_ref()); + format!( + "{}|{}|{}|{}|{}|{}", + f.fix.to, + l.map(|l| l.repo.as_str()).unwrap_or(""), + l.map(|l| l.address.as_str()).unwrap_or(""), + e.map(|e| e.file.as_str()).unwrap_or(""), + e.map(|e| e.attribute.as_str()).unwrap_or(""), + e.map(|e| e.value.as_str()).unwrap_or(""), + ) +} + +/// What happens after the guard read a fix run's pull request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GuardStep { + /// Nothing to object to: the pull request stands. + Passed, + /// First trip: one fix round, told each offending line. + FixRound, + /// Second trip: the pull request becomes a draft, the finding falls + /// back to its runbook, and no further attempt starts by itself. + Draft, +} + +impl Record { + fn clear_guard(&mut self) { + self.refused.clear(); + self.guard_attempts = 0; + self.drafted = false; + self.guard_sig.clear(); + } + + /// Records what the guard found on this finding's pull request and + /// says what happens next. Pure: the caller does it. + pub fn guard_step(&mut self, reasons: &[String]) -> GuardStep { + if reasons.is_empty() { + self.clear_guard(); + return GuardStep::Passed; + } + self.refused = reasons.to_vec(); + self.guard_sig = guard_sig(&self.finding); + self.guard_attempts = self.guard_attempts.saturating_add(1); + if self.guard_attempts == 1 { + GuardStep::FixRound + } else { + self.drafted = true; + GuardStep::Draft + } + } + + /// The guard refused this finding's change and the finding still asks + /// for the same change: no fix run starts by itself. + pub fn guard_blocks(&self) -> bool { + !self.refused.is_empty() && self.guard_sig == guard_sig(&self.finding) + } + + /// Before a new fix run for this finding: an old refusal about a + /// change the finding no longer asks for (its code or its target + /// changed), or one a person now overrides, is forgotten. + pub fn start_over(&mut self) { + self.clear_guard(); + } +} + +/// 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 { + format!("{}{}", ticket_body(r), super::guard::fix_round(&r.refused)) +} + /// A new read's findings against the stored ones: the records that /// changed (new, updated, or fixed). Dismissed ones stay dismissed while /// they still match. @@ -167,6 +284,7 @@ pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime r2.fixed_at = None; r2.pr = None; r2.ticket.clear(); + r2.clear_guard(); r2.event = Some("Found again in the latest read".into()); } if r2 != *r { @@ -262,42 +380,138 @@ pub fn insights(records: &[Record], now: DateTime) -> Value { }) } -/// The fix run's ticket: exactly what to change, where, and how to roll it -/// out. The run edits only the file named. +/// A production fix waits for its non-production copy unless AWS's date +/// is this close. +pub const HOLD_UNLESS_DUE_DAYS: i64 = 7; + +/// Why a fix run for this finding must not start yet: the same update is +/// still open on the non-production copy of the resource, which goes +/// first. `None` when nothing holds it, or when AWS's own date is within +/// [`HOLD_UNLESS_DUE_DAYS`] (then waiting would let AWS apply it unplanned). +pub fn held(r: &Record, all: &[Record], today: &str) -> Option { + let first: Vec<&Record> = all + .iter() + .filter(|x| r.finding.fix.after.contains(&x.finding.id) && x.status.is_open()) + .collect(); + if first.is_empty() { + return None; + } + let day = |s: &str| chrono::NaiveDate::parse_from_str(s.get(..10)?, "%Y-%m-%d").ok(); + if let (Some(by), Some(now)) = (day(&r.finding.fix.apply_by), day(today)) { + if (by - now).num_days() <= HOLD_UNLESS_DUE_DAYS { + return None; + } + } + Some(format!( + "Waiting for the non-production copy first: {}", + first + .iter() + .map(|x| format!("{} ({})", x.finding.name, x.finding.environment)) + .collect::>() + .join(", ") + )) +} + +fn where_line(l: &super::inventory::Location) -> String { + format!( + "Where: `{}`{}{}\n", + l.file, + if l.address.is_empty() { + String::new() + } else { + format!(", `{}`", l.address) + }, + if l.line > 0 { + format!(" (line {})", l.line) + } else { + String::new() + } + ) +} + +/// The fix run's ticket: exactly what to change, where, and what must not +/// change. The run edits only the file named. What the guidance says for +/// the tool that defines the resource is part of it. pub fn ticket_body(r: &Record) -> String { + use super::inventory::Kind; let f = &r.finding; let mut out = format!("{}\n\n", f.title); out.push_str(&format!("Fix: {}\n", f.fix.summary)); if let Some(l) = &f.fix.location { - out.push_str(&format!( - "Where: `{}`{}{}\n", - l.file, - if l.address.is_empty() { - String::new() - } else { - format!(", `{}`", l.address) - }, - if l.line > 0 { - format!(" (line {})", l.line) - } else { - String::new() + out.push_str(&where_line(l)); + if let Some(e) = &l.edit { + out.push_str(&format!( + "The value to change: `{}` in `{}`{}{}.\n", + e.attribute, + e.file, + if e.line > 0 { + format!(", line {}", e.line) + } else { + String::new() + }, + match (e.via.as_str(), e.value.is_empty()) { + ("add", _) => " (nothing sets it yet: add it)".to_string(), + (_, true) => String::new(), + (via, false) => format!( + " (now `{}`, set through {})", + e.value, + via.replace('_', " ") + ), + } + )); + if !e.shared.is_empty() { + out.push_str(&format!( + "This value is shared: {}. Say so in the description.\n", + e.shared + )); } - )); + } + out.push_str(&format!("{}\n", super::locate::describe(l))); } out.push_str(&format!("From `{}` to `{}`.\n\n", f.fix.from, f.fix.to)); + let managed = matches!( + f.kind, + Some( + Kind::RdsCluster | Kind::RdsInstance | Kind::ElasticacheGroup | Kind::OpensearchDomain + ) + ); match f.kind { - Some(super::inventory::Kind::AutoScalingGroup) - | Some(super::inventory::Kind::Ec2Instance) => { + Some(Kind::AutoScalingGroup) | Some(Kind::Ec2Instance) => { out.push_str("Change only the AMI. Prefer AWS's public parameter over a fixed AMI ID, so the next release is picked up too: in Terraform, `data \"aws_ssm_parameter\" \"al2023\" { name = \"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64\" }` and `image_id = data.aws_ssm_parameter.al2023.value` (the matching `-arm64` parameter for Graviton). Keep the launch template's other settings as they are. If the AMI comes from `data \"aws_ami\"` with `most_recent = true`, the code is already current: change nothing and say so; rolling the instances is the fix.\n"); } - Some(super::inventory::Kind::EksNodegroup) => { + Some(Kind::EksNodegroup) => { out.push_str(&format!("Set `release_version` on the node group (or the module input that feeds it) to `{}`. Change nothing else.\n", f.fix.to)); } - Some(super::inventory::Kind::LambdaFunction) => { + Some(Kind::LambdaFunction) => { out.push_str(&format!("Set `runtime` to `{}`, and check the handler code for anything the newer runtime changed.\n", f.fix.to)); } _ => {} } + if let Some(n) = &f.fix.notes { + if managed { + for a in &n.attribute { + out.push_str(&format!("{a}\n")); + } + out.push_str(&format!( + "\nSet the value to `{}` and change nothing else. If the value already allows `{}` (a prefix such as `16` for `16.6`), change nothing and say so.\n", + f.fix.to, f.fix.to + )); + } + if !n.never_change.is_empty() { + out.push_str(&format!( + "\nThis change must be in place. Never change any of these, on this or any other resource: {}. Never rename, move or remove a resource, a logical id or a construct id. Never lower a version. A change that would replace or destroy a resource that holds data is refused and its pull request is closed.\n", + n.never_change + .iter() + .map(|a| format!("`{a}`")) + .collect::>() + .join(", ") + )); + } + for t in n.replacement.iter().chain(n.traps.iter()) { + out.push_str(&format!("- {t}\n")); + } + out.push_str("\nNever run an apply, a deploy or a change set: open the pull request and stop. CoderHelm writes the rollout notes (when it takes effect, the interruption, pre-checks, rollback) into the description itself.\n"); + } if !f.cves.is_empty() { out.push_str(&format!("\nFixes: {}.\n", f.cves.join(", "))); } @@ -327,8 +541,28 @@ pub fn pr_body(r: &Record, change: &str) -> String { }, f.exposure.why )); + if !f.fix.apply_by.is_empty() { + out.push_str(&format!("AWS's date for this: {}.\n\n", f.fix.apply_by)); + } + for o in &f.fix.order { + out.push_str(&format!("{o}\n\n")); + } out.push_str("## Changes\n\n"); out.push_str(&format!("{change}\n\n")); + if let Some(l) = &f.fix.location { + out.push_str(&format!( + "How the code was found: {} {}\n\n", + super::locate::describe(l), + l.evidence + .iter() + .map(|e| format!("{}.", super::locate::sentence(e))) + .collect::>() + .join(" ") + )); + if let Some(e) = l.edit.as_ref().filter(|e| !e.shared.is_empty()) { + out.push_str(&format!("Shared value: {}.\n\n", e.shared)); + } + } out.push_str("## Advisories\n\n"); for s in &f.sources { if s.url.is_empty() { @@ -340,12 +574,29 @@ pub fn pr_body(r: &Record, change: &str) -> String { if !f.cves.is_empty() { out.push_str(&format!("\nCVEs: {}\n", f.cves.join(", "))); } + if !f.fix.advisory_note.is_empty() { + out.push_str(&format!("\n{}\n", f.fix.advisory_note)); + } + if let Some(n) = &f.fix.notes { + let notes = super::runbook::pr_notes_markdown(n); + if !notes.trim().is_empty() { + out.push_str("\n## Rollout\n"); + out.push_str(¬es); + } + } if !f.fix.cli.is_empty() { out.push_str("\n## After merge\n\nThe new version runs only once the resources roll. CoderHelm closes this finding when it reads the account again and sees it running.\n\n```\n"); for c in &f.fix.cli { out.push_str(&format!("{c}\n")); } out.push_str("```\n"); + } else if f.fix.notes.is_some() { + out.push_str("\n## After merge\n\nCoderHelm never applies this. It closes the finding when it reads the account again and sees the new version running.\n"); + } + // The guard gave up on this change: every rebuild of the description + // keeps the reason at its top, which keeps the pull request a draft. + if r.drafted && !r.refused.is_empty() { + return super::guard::put_hold(&out, &r.refused); } out } @@ -497,6 +748,7 @@ mod tests { address: "aws_launch_template.web".into(), line: 3, how: "search".into(), + ..Default::default() }); x.fix.cli = vec!["aws autoscaling start-instance-refresh --auto-scaling-group-name web-asg".into()]; @@ -509,4 +761,250 @@ mod tests { assert!(b.contains("## After merge")); assert!(!b.contains('\u{2192}')); } + + fn upgrade(id: &str, name: &str, env: &str, by: &str) -> InfraFinding { + use crate::infra_vuln::inventory::{Confidence, Edit, Kind, Location}; + let mut x = f(id, FixKind::Pr); + x.kind = Some(Kind::RdsCluster); + x.name = name.into(); + x.environment = env.into(); + x.title = format!("Aurora cluster {name}: engine version upgrade to 16.6 pending"); + x.fix.summary = "Raise `engine_version` to 16.6 in envs/prod/main.tf".into(); + x.fix.from = "16.4".into(); + x.fix.to = "16.6".into(); + x.fix.apply_by = by.into(); + x.fix.location = Some(Location { + repo: "acme/infra".into(), + file: "modules/aurora/main.tf".into(), + address: "module.ledger.aws_rds_cluster.this".into(), + line: 6, + how: "terraform_module".into(), + tool: "terraform".into(), + confidence: Confidence::High, + evidence: vec!["`cluster_identifier` is `ledger-prod-aurora`, the live name".into()], + edit: Some(Edit { + file: "envs/prod/main.tf".into(), + line: 4, + attribute: "engine_version".into(), + value: "16.4".into(), + via: "module_input".into(), + shared: String::new(), + }), + environment: env.into(), + ..Default::default() + }); + let v = std::collections::BTreeMap::new(); + x.fix.notes = Some(crate::infra_vuln::runbook::pr_notes( + "aurora", + "engine_upgrade", + "terraform", + std::collections::BTreeMap::new(), + &v, + "2026-11-13", + )); + x + } + + #[test] + fn a_database_upgrade_ticket_names_the_edit_and_what_must_never_change() { + let r = Record::new( + upgrade("a", "ledger-prod-aurora", "production", "2027-01-15"), + "t", + ); + let t = ticket_body(&r); + assert!(t.contains("The value to change: `engine_version` in `envs/prod/main.tf`, line 4 (now `16.4`, set through module input)"), "{t}"); + assert!( + t.contains("Never raise it on an `aws_rds_cluster_instance`"), + "{t}" + ); + assert!(t.contains("Never change any of these"), "{t}"); + assert!(t.contains("`cluster_identifier`"), "{t}"); + assert!(t.contains("Never lower a version"), "{t}"); + assert!(t.contains("Never run an apply"), "{t}"); + assert!( + t.contains("a Terraform module call and its inputs (confidence: high)"), + "{t}" + ); + let b = pr_body( + &r, + "Raised the ledger cluster's engine version input to 16.6.", + ); + for part in [ + "## Summary", + "## Changes", + "## Rollout", + "**When it takes effect**", + "**Expected interruption**", + "**Replacement**", + "**What the plan must show**", + "**Before applying**", + "**Rollback**", + "**Known traps**", + "**Sources**", + "AWS's date for this: 2027-01-15.", + "How the code was found:", + "CoderHelm never applies this", + ] { + assert!(b.contains(part), "the description has no {part}:\n{b}"); + } + assert!(b.contains("(read 2026-11-13)")); + for arrow in ['\u{2192}', '\u{21d2}', '\u{279c}'] { + assert!(!b.contains(arrow) && !t.contains(arrow)); + } + } + + #[test] + fn production_waits_for_its_non_production_copy_unless_aws_is_about_to_apply_it() { + let staging = Record::new( + upgrade("s", "ledger-staging-aurora", "staging", "2027-01-15"), + "t", + ); + let mut p = upgrade("p", "ledger-prod-aurora", "production", "2027-01-15"); + p.fix.after = vec!["s".into()]; + let prod = Record::new(p, "t"); + let all = vec![staging.clone(), prod.clone()]; + let why = held(&prod, &all, "2026-11-13").expect("held"); + assert!(why.contains("ledger-staging-aurora (staging)"), "{why}"); + assert_eq!(held(&staging, &all, "2026-11-13"), None); + // Staging is done (a read no longer finds it): production goes. + let mut done = staging.clone(); + done.status = Status::Fixed; + assert_eq!(held(&prod, &[done, prod.clone()], "2026-11-13"), None); + // AWS's date is a week away: waiting would let AWS apply it unplanned. + assert_eq!(held(&prod, &all, "2027-01-10"), None); + } + + const LINE: &str = + "modules/aurora/main.tf, line 5: `aws_rds_cluster.this` changes `cluster_identifier`, which replaces the resource"; + + #[test] + fn a_first_trip_is_one_fix_round_told_the_offending_line() { + let mut r = Record::new(upgrade("a", "ledger-prod-aurora", "production", ""), "t"); + assert!(r.view().get("refused").is_none()); + assert_eq!(r.guard_step(&[LINE.to_string()]), GuardStep::FixRound); + assert_eq!((r.guard_attempts, r.drafted), (1, false)); + let t = fix_round_body(&r); + // The ticket's own words, then the line and the in-place change. + assert!( + t.contains("The value to change: `engine_version` in `envs/prod/main.tf`, line 4"), + "{t}" + ); + assert!(t.contains(&format!("- {LINE}")), "{t}"); + assert!( + t.contains("make the in-place change this ticket asks for"), + "{t}" + ); + // Still a pull request on the page, with what is happening. + let v = r.view(); + assert_eq!(v["fix"]["kind"], "pr"); + assert_eq!(v["drafted"], false); + assert_eq!(v["note"], GUARD_ROUND_NOTE); + // The description is not marked while the round runs. + assert!(crate::infra_vuln::guard::hold(&pr_body(&r, "Raised it.")).is_none()); + } + + #[test] + fn a_fix_round_that_passes_the_guard_clears_the_refusal() { + let mut r = Record::new(upgrade("a", "ledger-prod-aurora", "production", ""), "t"); + r.guard_step(&[LINE.to_string()]); + assert_eq!(r.guard_step(&[]), GuardStep::Passed); + assert!(r.refused.is_empty() && !r.drafted && r.guard_attempts == 0); + assert!(!r.guard_blocks()); + assert!(r.view().get("refused").is_none()); + } + + #[test] + fn a_second_trip_drafts_the_pull_request_and_falls_back_to_the_runbook() { + let mut r = Record::new(upgrade("a", "ledger-prod-aurora", "production", ""), "t"); + r.finding.fix.runbook = Some(crate::infra_vuln::runbook::Runbook { + steps: vec![crate::infra_vuln::runbook::Step { + text: "Upgrade the cluster in its next maintenance window.".into(), + cli: "aws rds modify-db-cluster --db-cluster-identifier ledger-prod-aurora --engine-version 16.6".into(), + }], + ..Default::default() + }); + r.guard_step(&[LINE.to_string()]); + assert_eq!(r.guard_step(&[LINE.to_string()]), GuardStep::Draft); + assert!(r.drafted && r.guard_attempts == 2); + // On the finding: the reason, a runbook, and why. + let v = r.view(); + assert_eq!(v["refused"][0], LINE); + assert_eq!(v["drafted"], true); + assert_eq!(v["fix"]["kind"], "runbook"); + assert!(v["fix"]["decision"] + .as_str() + .unwrap() + .contains("its pull request is a draft")); + assert!(v["fix"]["decision"] + .as_str() + .unwrap() + .contains("no further attempt until the code")); + assert!(v["fix"]["runbook"]["steps"][0]["cli"] + .as_str() + .unwrap() + .contains("modify-db-cluster")); + assert_eq!(v["note"], GUARD_DRAFT_NOTE); + // The stored finding is unchanged: it is still a code fix, should + // its code or target change. + assert_eq!(r.finding.fix.kind, Some(FixKind::Pr)); + } + + #[test] + fn a_draft_stays_a_draft_through_later_description_rebuilds() { + use crate::infra_vuln::guard; + let mut r = Record::new(upgrade("a", "ledger-prod-aurora", "production", ""), "t"); + r.guard_step(&[LINE.to_string()]); + r.guard_step(&[LINE.to_string()]); + for change in ["Raised it.", "Raised it again, after a later run.", ""] { + let b = pr_body(&r, change); + assert!(b.starts_with(crate::security_fixes::MARKER), "{b}"); + assert_eq!(b.matches(guard::HOLD_START).count(), 1); + assert!( + guard::hold(&b).is_some(), + "a rebuilt description lost the hold" + ); + let top = &b[..b.find("## Summary").unwrap()]; + assert!( + top.contains("This pull request is a draft") && top.contains(LINE), + "{top}" + ); + } + // Once the guard passes a later change, the section goes. + r.guard_step(&[]); + assert!(guard::hold(&pr_body(&r, "Raised it.")).is_none()); + } + + #[test] + fn no_further_attempt_until_the_code_or_the_target_changes() { + let mut r = Record::new(upgrade("a", "ledger-prod-aurora", "production", ""), "t"); + assert!(!r.guard_blocks()); + r.guard_step(&[LINE.to_string()]); + r.guard_step(&[LINE.to_string()]); + assert!(r.guard_blocks()); + // A new read with the same finding: still blocked. + let same = reconcile(&[r.clone()], vec![r.finding.clone()], now()); + assert!(same.is_empty(), "{same:?}"); + // The target changes. + let mut target = r.clone(); + target.finding.fix.to = "16.8".into(); + assert!(!target.guard_blocks()); + // The code changes (the line that sets the value moved or changed). + let mut code = r.clone(); + if let Some(e) = code + .finding + .fix + .location + .as_mut() + .and_then(|l| l.edit.as_mut()) + { + e.value = "16.5".into(); + } + assert!(!code.guard_blocks()); + code.start_over(); + assert!(code.refused.is_empty() && !code.drafted && code.guard_attempts == 0); + // Found again after being fixed: the refusal belongs to the past. + r.status = Status::Fixed; + let again = reconcile(&[r.clone()], vec![r.finding.clone()], now()); + assert!(again[0].refused.is_empty() && !again[0].drafted); + } } diff --git a/services/common/src/infra_vuln/runbook.rs b/services/common/src/infra_vuln/runbook.rs new file mode 100644 index 000000000..1e8776ce4 --- /dev/null +++ b/services/common/src/infra_vuln/runbook.rs @@ -0,0 +1,673 @@ +//! The runbook a person follows when an update is applied in AWS, and the +//! notes a pull request carries when it is applied through code. Both are +//! written from the guidance store ([`super::guidance`]) with the +//! resource's own identifiers filled in; no service fact lives here. +//! +//! CoderHelm never runs a runbook: it is a card for a person. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::actions::{self, Meaning}; +use super::guidance::{self, Cited, Entry, Query}; +use super::inventory::{Kind, Pending, Resource}; + +/// One thing to do or check, with its command when there is one. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Step { + pub text: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub cli: String, +} + +/// A complete runbook for one update of one resource. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Runbook { + /// The account, Region and exact identifiers it applies to. + pub scope: Vec, + /// What the update is and what it fixes. + pub what: Vec, + pub interruption: Vec, + /// Permissions and tools the person needs. + pub prerequisites: Vec, + pub prechecks: Vec, + pub backup: Vec, + /// The console path, step by step. + pub console: Vec, + /// The commands that apply it. + pub steps: Vec, + pub validation: Vec, + pub rollback: Vec, + /// AWS's apply-by date (YYYY-MM-DD), and what AWS does after it. + pub apply_by: String, + pub if_nothing: Vec, + /// Order among other pending work, traps, what to do in code after. + pub notes: Vec, + /// The pages the facts came from, with the day each was last read. + pub sources: Vec, + /// A fact here was not re-read within the guidance store's limit. + pub stale: bool, +} + +/// The guidance store's service for a resource. +pub fn service_of(kind: Kind, engine: &str) -> &'static str { + match kind { + Kind::RdsCluster if engine.starts_with("aurora") => "aurora", + // A Multi-AZ DB cluster (a cluster that is not Aurora) has rules + // of its own that the store does not hold yet. + Kind::RdsCluster => "", + Kind::RdsInstance => "rds", + Kind::ElasticacheGroup => "elasticache", + Kind::OpensearchDomain => "opensearch", + Kind::EksNodegroup => "eks_nodegroup", + Kind::AutoScalingGroup | Kind::Ec2Instance => "ami", + Kind::LambdaFunction => "lambda_runtime", + _ => "", + } +} + +/// The guidance store's action for a kind of finding with no pending +/// action of its own (an AMI, a node group release, a runtime). +pub fn action_of(kind: Kind) -> &'static str { + match kind { + Kind::EksNodegroup => "nodegroup_release", + Kind::AutoScalingGroup | Kind::Ec2Instance => "ami_replace", + Kind::LambdaFunction => "runtime_change", + _ => "any", + } +} + +fn tail(arn: &str) -> &str { + arn.rsplit([':', '/']).next().unwrap_or(arn) +} + +/// The values a guidance entry's placeholders take for this resource. +pub fn vars( + r: &Resource, + p: Option<&Pending>, + from: &str, + target: &str, + today: &str, +) -> BTreeMap<&'static str, String> { + let arn = p + .and_then(|p| p.arns.first().cloned()) + .unwrap_or_else(|| r.id.clone()); + let cluster = match r.kind { + Kind::RdsCluster => r.name.clone(), + _ => r + .tags + .get("coderhelm:cluster") + .or(r.facts.get("cluster")) + .cloned() + .unwrap_or_default(), + }; + let action = p.map(|p| p.kind.clone()).unwrap_or_default(); + let mut v = BTreeMap::new(); + v.insert("arn", arn.clone()); + // The identifier a command takes: the resource the ARN names (an + // instance of a cluster has its own), else the record's name. + v.insert( + "id", + if arn.starts_with("arn:aws:rds:") { + tail(&arn).to_string() + } else { + r.name.clone() + }, + ); + v.insert("cluster", cluster); + v.insert("region", r.region.clone()); + v.insert("account", r.account.clone()); + v.insert("engine", r.versions.engine.clone()); + v.insert("from", from.to_string()); + v.insert("target", target.to_string()); + v.insert("update", p.map(|p| p.name.clone()).unwrap_or_default()); + v.insert( + "snapshot", + format!( + "{}-before-{}-{}", + r.name, + if action.is_empty() { "update" } else { &action }, + today.replace('-', "") + ), + ); + v.insert("action", action); + v +} + +fn texts(entries: &[&Entry], v: &BTreeMap<&str, String>) -> Vec { + entries.iter().map(|e| guidance::fill(&e.text, v)).collect() +} + +fn steps(entries: &[&Entry], v: &BTreeMap<&str, String>) -> Vec { + entries + .iter() + .map(|e| Step { + text: guidance::fill(&e.text, v), + cli: guidance::fill(&e.cli, v), + }) + .collect() +} + +/// The runbook for a pending action on a resource. +pub fn build(r: &Resource, p: &Pending, today: &str) -> Runbook { + let service = service_of(r.kind, &r.versions.engine); + let action = p.meaning.guidance_action(); + let from = &r.versions.engine_version; + let mut facts = BTreeMap::new(); + if let Some(major) = actions::is_major(&r.versions.engine, from, &p.target) { + facts.insert("major".to_string(), major.to_string()); + } + if !p.scope.is_empty() { + facts.insert("scope".to_string(), p.scope.clone()); + } + let q = Query { + service, + action, + tool: "", + facts, + }; + let v = vars(r, Some(p), from, &p.target, today); + let mut used: Vec<&Entry> = Vec::new(); + let mut take = |section: &str| -> Vec<&'static Entry> { + let e = if service.is_empty() || action == "any" { + Vec::new() + } else { + guidance::section(&q, section) + }; + used.extend(e.iter().copied()); + e + }; + + let mut scope = vec![format!("AWS account {}, Region {}.", r.account, r.region)]; + scope.push(format!("{} `{}` ({}).", r.kind.label(), r.name, r.id)); + if p.arns.len() > 1 { + scope.push(format!( + "The action is pending on {} ARNs; apply it to each, in this order: {}.", + p.arns.len(), + p.arns.join(", ") + )); + } else if let Some(a) = p.arns.first().filter(|a| *a != &r.id) { + scope.push(format!("The action is pending on {a}.")); + } + scope.push(format!( + "AWS action `{}`{}: {}{}.", + p.kind, + if p.name != p.kind && !p.name.is_empty() && p.meaning != Meaning::EnginePatch { + format!(" `{}`", p.name) + } else { + String::new() + }, + p.meaning.label(), + if p.description.is_empty() { + String::new() + } else { + format!(" (AWS's description: \"{}\")", p.description) + } + )); + if !from.is_empty() { + scope.push(format!( + "It runs {} {}{}.", + r.versions.engine, + from, + if p.target.is_empty() { + String::new() + } else { + format!("; the action moves it to {}", p.target) + } + )); + } + for m in &p.merged { + scope.push(format!("Note: {m}.")); + } + + let mut what = texts(&take("what"), &v); + what.extend(texts(&take("cve"), &v)); + let interruption = texts(&take("interruption"), &v); + let mut prerequisites = texts(&take("permissions"), &v); + prerequisites.push(format!( + "AWS CLI v2 signed in to account {} with Region {}, and a change window agreed with the people who own what uses this resource.", + r.account, r.region + )); + let prechecks = steps(&take("precheck"), &v); + let backup = steps(&take("backup"), &v); + let console = texts(&take("console"), &v); + + // Apply: once per ARN the action is pending on. + let apply = take("apply"); + let mut do_steps = Vec::new(); + for e in &apply { + if p.arns.len() > 1 && e.cli.contains("{arn}") { + for (n, arn) in p.arns.iter().enumerate() { + let mut one = v.clone(); + one.insert("arn", arn.clone()); + one.insert("id", tail(arn).to_string()); + do_steps.push(Step { + text: format!( + "{} ({} of {}: {})", + guidance::fill(&e.text, &one), + n + 1, + p.arns.len(), + tail(arn) + ), + cli: guidance::fill(&e.cli, &one), + }); + } + } else { + do_steps.push(Step { + text: guidance::fill(&e.text, &v), + cli: guidance::fill(&e.cli, &v), + }); + } + } + // No reviewed guidance for this resource or action: the command AWS + // documents for any pending maintenance action still applies. + let mut notes = Vec::new(); + if do_steps.is_empty() && r.id.starts_with("arn:aws:rds:") { + for arn in &p.arns { + do_steps.push(Step { + text: "Schedule the pending action for the next maintenance window.".into(), + cli: format!( + "aws rds apply-pending-maintenance-action --resource-identifier {arn} --apply-action {} --opt-in-type next-maintenance --region {}", + p.kind, r.region + ), + }); + } + notes.push("CoderHelm has no reviewed guidance for this action on this kind of resource: read AWS's description of the action and the service's documentation before applying it.".to_string()); + } + let validation = steps(&take("validation"), &v); + let rollback = steps(&take("rollback"), &v); + let if_nothing = texts(&take("if_nothing"), &v); + if !p.order_why.is_empty() { + notes.push(p.order_why.clone()); + } + notes.extend(texts(&take("trap"), &v)); + notes.extend(texts(&take("order"), &v)); + + let sources = guidance::cited(&used, today); + let stale = sources.iter().any(|s| s.stale); + Runbook { + scope, + what, + interruption, + prerequisites, + prechecks, + backup, + console, + steps: do_steps, + validation, + rollback, + apply_by: p.apply_by.clone(), + if_nothing, + notes, + sources, + stale, + } +} + +/// What a pull request for a code change must say and check, from the +/// guidance for the tool that defines the resource. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PrNotes { + /// Which attribute to change, for this tool. + pub attribute: Vec, + pub takes_effect: Vec, + pub interruption: Vec, + /// What replaces the resource, and so what the change must not touch. + pub replacement: Vec, + /// The attributes whose change replaces the resource. + pub never_change: Vec, + pub prechecks: Vec, + pub backup: Vec, + pub rollback: Vec, + pub traps: Vec, + /// What the plan or change set must show, since CoderHelm runs none. + pub plan: Vec, + pub pipeline: Vec, + pub order: Vec, + pub validation: Vec, + pub sources: Vec, + pub stale: bool, +} + +/// The notes for a code change to `service`'s `action` with `tool` +/// (`terraform`, `cloudformation`, `cdk`, or a tool that shares one of +/// those: see [`guidance::tool_key`]). +pub fn pr_notes( + service: &str, + action: &str, + tool: &str, + facts: BTreeMap, + v: &BTreeMap<&str, String>, + today: &str, +) -> PrNotes { + let q = Query { + service, + action, + tool: guidance::tool_key(tool), + facts, + }; + let mut used: Vec<&Entry> = Vec::new(); + let mut take = |section: &str| -> Vec<&'static Entry> { + let e = guidance::section(&q, section); + used.extend(e.iter().copied()); + e + }; + let replacement = take("replacement"); + let mut never_change: Vec = replacement + .iter() + .flat_map(|e| e.attributes.iter().cloned()) + .collect(); + never_change.dedup(); + let mut traps = texts(&take("trap"), v); + traps.extend(texts(&take("option"), v)); + let out = PrNotes { + attribute: texts(&take("attribute"), v), + takes_effect: texts(&take("takes_effect"), v), + interruption: texts(&take("interruption"), v), + replacement: texts(&replacement, v), + never_change, + prechecks: steps(&take("precheck"), v), + backup: steps(&take("backup"), v), + rollback: texts(&take("rollback"), v), + traps, + plan: texts(&take("plan"), v), + pipeline: texts(&take("pipeline"), v), + order: texts(&take("order"), v), + validation: steps(&take("validation"), v), + sources: Vec::new(), + stale: false, + }; + let sources = guidance::cited(&used, today); + PrNotes { + stale: sources.iter().any(|s| s.stale), + sources, + ..out + } +} + +fn bullets(out: &mut String, title: &str, items: &[String]) { + if items.is_empty() { + return; + } + out.push_str(&format!("\n**{title}**\n\n")); + for i in items { + out.push_str(&format!("- {i}\n")); + } +} + +fn step_list(out: &mut String, title: &str, items: &[Step]) { + if items.is_empty() { + return; + } + out.push_str(&format!("\n**{title}**\n\n")); + for s in items { + out.push_str(&format!("- {}\n", s.text)); + if !s.cli.is_empty() { + out.push_str(&format!("\n ```\n {}\n ```\n", s.cli)); + } + } +} + +/// The sources line every card and pull request ends with. +pub fn sources_line(sources: &[Cited]) -> String { + if sources.is_empty() { + return String::new(); + } + let mut out = String::from("\n**Sources**\n\n"); + for s in sources { + out.push_str(&format!( + "- {} (read {}{})\n", + s.url, + s.reviewed_on, + if s.stale { + format!( + "; not re-read in over {} days: check the page before relying on it", + guidance::MAX_AGE_DAYS + ) + } else { + String::new() + } + )); + } + out +} + +/// The notes as Markdown, for a pull request's description. +pub fn pr_notes_markdown(n: &PrNotes) -> String { + let mut out = String::new(); + bullets(&mut out, "When it takes effect", &n.takes_effect); + bullets(&mut out, "Expected interruption", &n.interruption); + bullets(&mut out, "Replacement", &n.replacement); + bullets(&mut out, "What the plan must show", &n.plan); + step_list(&mut out, "Before applying", &n.prechecks); + step_list(&mut out, "Backup", &n.backup); + bullets(&mut out, "Rollback", &n.rollback); + bullets(&mut out, "Known traps", &n.traps); + step_list(&mut out, "After it is applied", &n.validation); + bullets(&mut out, "How this repository applies changes", &n.pipeline); + out.push_str(&sources_line(&n.sources)); + out +} + +/// The runbook as Markdown (a card's long form, a notification, a doc). +pub fn markdown(rb: &Runbook) -> String { + let mut out = String::new(); + bullets(&mut out, "Scope", &rb.scope); + bullets(&mut out, "What it is", &rb.what); + bullets(&mut out, "Expected interruption", &rb.interruption); + bullets(&mut out, "You need", &rb.prerequisites); + step_list(&mut out, "Check first", &rb.prechecks); + step_list(&mut out, "Backup", &rb.backup); + bullets(&mut out, "In the console", &rb.console); + step_list(&mut out, "With the CLI", &rb.steps); + step_list(&mut out, "Check after", &rb.validation); + step_list(&mut out, "Rollback", &rb.rollback); + if !rb.apply_by.is_empty() || !rb.if_nothing.is_empty() { + let mut d = rb.if_nothing.clone(); + if !rb.apply_by.is_empty() { + d.insert(0, format!("AWS's date for this action: {}.", rb.apply_by)); + } + bullets(&mut out, "If nothing is done", &d); + } + bullets(&mut out, "Notes", &rb.notes); + out.push_str(&sources_line(&rb.sources)); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::infra_vuln::actions::Line; + use crate::infra_vuln::inventory::Versions; + + const CLUSTER: &str = "arn:aws:rds:us-east-1:111122223333:cluster:orders"; + + fn aurora() -> Resource { + Resource { + id: CLUSTER.into(), + kind: Kind::RdsCluster, + name: "orders".into(), + account: "111122223333".into(), + region: "us-east-1".into(), + versions: Versions { + engine: "aurora-postgresql".into(), + engine_version: "16.4".into(), + ..Default::default() + }, + ..Default::default() + } + } + + fn pending(lines: &[(&str, &str, &str, &str)]) -> Vec { + let l: Vec = lines + .iter() + .map(|(arn, action, d, by)| Line { + arn: arn.to_string(), + action: action.to_string(), + description: d.to_string(), + apply_by: by.to_string(), + writer: arn.ends_with("orders-1"), + ..Default::default() + }) + .collect(); + actions::reconcile("aurora-postgresql", "16.4", &l) + } + + #[test] + fn an_engine_patch_runbook_has_every_section_with_the_real_identifiers() { + let p = &pending(&[( + CLUSTER, + "system-update", + "Upgrade to Aurora PostgreSQL 16.4.3", + "2026-12-01", + )])[0]; + let rb = build(&aurora(), p, "2026-11-13"); + for (name, n) in [ + ("scope", rb.scope.len()), + ("what", rb.what.len()), + ("interruption", rb.interruption.len()), + ("prerequisites", rb.prerequisites.len()), + ("prechecks", rb.prechecks.len()), + ("backup", rb.backup.len()), + ("console", rb.console.len()), + ("steps", rb.steps.len()), + ("validation", rb.validation.len()), + ("rollback", rb.rollback.len()), + ("if_nothing", rb.if_nothing.len()), + ("sources", rb.sources.len()), + ] { + assert!(n > 0, "the runbook has no {name}"); + } + assert_eq!(rb.apply_by, "2026-12-01"); + assert!(rb.scope[0].contains("111122223333") && rb.scope[0].contains("us-east-1")); + assert_eq!( + rb.steps[0].cli, + format!("aws rds apply-pending-maintenance-action --resource-identifier {CLUSTER} --apply-action system-update --opt-in-type next-maintenance --region us-east-1") + ); + assert_eq!( + rb.backup[0].cli, + "aws rds create-db-cluster-snapshot --db-cluster-identifier orders --db-cluster-snapshot-identifier orders-before-system-update-20261113 --region us-east-1" + ); + assert!(rb + .what + .iter() + .any(|w| w.contains("patch the DB engine for Aurora PostgreSQL"))); + assert!(rb.rollback.iter().any(|s| s.cli.contains("undo-opt-in"))); + assert!(rb + .validation + .iter() + .any(|s| s.text.contains("aurora_version()"))); + // Nothing left unfilled. + let text = markdown(&rb); + assert!( + !regex::Regex::new(r"\{[a-z_]+\}").unwrap().is_match(&text), + "{text}" + ); + assert!(text.contains("(read 2026-11-13)")); + assert!(!rb.stale); + // The same runbook read long after the review date says so. + let late = build(&aurora(), p, "2027-11-13"); + assert!(late.stale); + assert!(markdown(&late).contains("not re-read in over 180 days")); + } + + #[test] + fn an_instance_level_os_update_is_one_command_per_instance_in_order() { + let w = "arn:aws:rds:us-east-1:111122223333:db:orders-1"; + let rd = "arn:aws:rds:us-east-1:111122223333:db:orders-2"; + let p = &pending(&[ + ( + w, + "system-update", + "New Operating System patch is available", + "", + ), + ( + rd, + "system-update", + "New Operating System patch is available", + "", + ), + ])[0]; + let rb = build(&aurora(), p, "2026-11-13"); + let window: Vec<&Step> = rb + .steps + .iter() + .filter(|s| s.cli.contains("next-maintenance")) + .collect(); + assert_eq!(window.len(), 2); + assert!( + window[0].cli.contains("db:orders-2"), + "the reader first: {}", + window[0].cli + ); + assert!(window[1].cli.contains("db:orders-1")); + assert!(rb.scope.iter().any(|s| s.contains("in this order"))); + assert!(rb.what.iter().any(|w| w.contains("no CVE list"))); + } + + #[test] + fn pull_request_notes_differ_by_tool() { + let v = vars(&aurora(), None, "16.4", "16.6", "2026-11-13"); + let tf = pr_notes( + "aurora", + "engine_upgrade", + "terraform", + BTreeMap::new(), + &v, + "2026-11-13", + ); + assert!(tf.attribute[0].contains("`engine_version` on the `aws_rds_cluster`")); + assert!(tf.takes_effect[0].contains("`apply_immediately` defaults to `false`")); + assert!(tf.never_change.contains(&"cluster_identifier".to_string())); + assert!(tf + .traps + .iter() + .any(|t| t.contains("Never set a value below the live version"))); + assert!(tf.rollback[0].contains("one-way")); + assert!(tf.plan[0].contains("ran no plan")); + assert!(tf.order[0].contains("Non-production first")); + let cfn = pr_notes( + "aurora", + "engine_upgrade", + "sam", + BTreeMap::new(), + &v, + "2026-11-13", + ); + assert!(cfn.takes_effect[0].contains("cannot schedule cluster modifications")); + assert!(cfn + .never_change + .contains(&"DBClusterIdentifier".to_string())); + let md = pr_notes_markdown(&tf); + assert!(md.contains("**When it takes effect**") && md.contains("**Rollback**")); + assert!( + md.contains("--engine aurora-postgresql --engine-version 16.4"), + "{md}" + ); + // OpenSearch on CloudFormation: the replacement trap leads. + let os = pr_notes( + "opensearch", + "engine_upgrade", + "cloudformation", + BTreeMap::new(), + &v, + "2026-11-13", + ); + assert!(os.replacement[0].contains("replace the whole domain")); + } + + #[test] + fn services_map_to_the_guidance_store() { + assert_eq!(service_of(Kind::RdsCluster, "aurora-mysql"), "aurora"); + // A Multi-AZ DB cluster is not Aurora and not a DB instance: no + // guidance is borrowed for it. + assert_eq!(service_of(Kind::RdsCluster, "postgres"), ""); + assert_eq!(service_of(Kind::RdsInstance, "mysql"), "rds"); + assert_eq!(service_of(Kind::EksCluster, ""), ""); + assert_eq!(action_of(Kind::LambdaFunction), "runtime_change"); + } +} diff --git a/services/common/src/infra_vuln/stacks.rs b/services/common/src/infra_vuln/stacks.rs new file mode 100644 index 000000000..09003e7cc --- /dev/null +++ b/services/common/src/infra_vuln/stacks.rs @@ -0,0 +1,143 @@ +//! Which CloudFormation stack made a resource, asked of CloudFormation +//! itself: `DescribeStackResources` with the resource's physical id. +//! +//! CloudFormation does not put its `aws:cloudformation:*` tags on every +//! resource type, so the tags alone miss resources a stack made. This +//! lookup does not depend on tags. It returns the stack's name and the +//! resource's logical id and nothing else: no template, no parameters, no +//! outputs. +//! +//! It needs `cloudformation:DescribeStackResources` in the read role's +//! "Infrastructure vulnerabilities" permissions. A role without it gets +//! [`Owner::Denied`] once, the read notes the permission, and resources +//! are placed by their tags and by the code alone. + +use crate::live::aws::Session; + +/// What CloudFormation said. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Owner { + /// A stack made it. + Stack { stack: String, logical_id: String }, + /// No stack owns this physical id. + None, + /// The role may not ask (the permission is not granted yet). + Denied(String), + /// The call failed for another reason. + Failed(String), +} + +/// What an error from the call means. +pub fn read_error(code: Option<&str>, message: &str) -> Owner { + let c = code.unwrap_or(""); + if c.contains("AccessDenied") || c == "UnauthorizedOperation" { + return Owner::Denied(crate::truncate_str(message, 240).to_string()); + } + // "Stack for does not exist". + if c == "ValidationError" && message.contains("does not exist") { + return Owner::None; + } + Owner::Failed(format!("{c}: {}", crate::truncate_str(message, 200))) +} + +/// The physical id CloudFormation knows a resource by, when it is one the +/// lookup works for: a database's identifier, a cache's replication group +/// id, a domain's name, an Auto Scaling group's name. +pub fn physical_id(r: &super::inventory::Resource) -> Option { + use super::inventory::Kind; + match r.kind { + Kind::RdsCluster + | Kind::RdsInstance + | Kind::ElasticacheGroup + | Kind::OpensearchDomain + | Kind::AutoScalingGroup => Some(r.name.clone()).filter(|n| !n.is_empty()), + _ => None, + } +} + +/// Asks CloudFormation which stack owns `physical_id`. +pub async fn owner_of(s: &Session, physical_id: &str) -> Owner { + use aws_sdk_cloudformation::config::{BehaviorVersion, Credentials, Region}; + use aws_sdk_cloudformation::error::ProvideErrorMetadata; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + let cfn = aws_sdk_cloudformation::Client::from_conf( + aws_sdk_cloudformation::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(s.region.clone())) + .credentials_provider(creds) + .build(), + ); + match cfn + .describe_stack_resources() + .physical_resource_id(physical_id) + .send() + .await + { + Ok(o) => o + .stack_resources() + .iter() + .find(|r| r.physical_resource_id() == Some(physical_id)) + .map(|r| Owner::Stack { + stack: r.stack_name().unwrap_or("").to_string(), + logical_id: r.logical_resource_id().unwrap_or("").to_string(), + }) + .unwrap_or(Owner::None), + Err(e) => match e.as_service_error() { + Some(se) => read_error(se.code(), se.message().unwrap_or("")), + None => Owner::Failed("AWS didn't answer".into()), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::infra_vuln::inventory::{Kind, Resource}; + + #[test] + fn a_refusal_names_itself_and_a_resource_no_stack_made_is_not_an_error() { + assert!(matches!( + read_error( + Some("AccessDenied"), + "User is not authorized to perform: cloudformation:DescribeStackResources" + ), + Owner::Denied(_) + )); + assert_eq!( + read_error( + Some("ValidationError"), + "Stack for orders-prod does not exist" + ), + Owner::None + ); + assert!(matches!( + read_error(Some("Throttling"), "Rate exceeded"), + Owner::Failed(_) + )); + } + + #[test] + fn the_lookup_is_asked_only_for_kinds_whose_physical_id_is_their_name() { + let r = |kind| Resource { + kind, + name: "orders".into(), + ..Default::default() + }; + assert_eq!( + physical_id(&r(Kind::RdsInstance)).as_deref(), + Some("orders") + ); + assert_eq!( + physical_id(&r(Kind::OpensearchDomain)).as_deref(), + Some("orders") + ); + assert_eq!(physical_id(&r(Kind::EksNodegroup)), None); + assert_eq!(physical_id(&r(Kind::LambdaFunction)), None); + } +} diff --git a/services/common/src/infra_vuln/terraform.rs b/services/common/src/infra_vuln/terraform.rs new file mode 100644 index 000000000..c95ea46d1 --- /dev/null +++ b/services/common/src/infra_vuln/terraform.rs @@ -0,0 +1,1427 @@ +//! Finding the Terraform or OpenTofu code that defines a live resource +//! without Terraform's state: by resource type and attributes, never by +//! the literal name alone. +//! +//! - Every directory of `.tf` files is read as a module. A directory is +//! seen once per way it is used: once per module call that points at it +//! (with the caller's inputs), or, for a root, once per environment +//! variable file (`prod.tfvars`, `envs/staging.tfvars`). +//! - A resource block of the right type is scored against the live +//! resource in each of those: its identifier (a literal, a variable +//! resolved through the call or the variable file, a prefix with +//! Terraform's generated suffix), engine, version, tags, subnet group. +//! A literal that contradicts the live resource rules the block out. +//! - The edit target is where the value is written, which may not be the +//! resource block: a module call's input, a line of a variable file, a +//! variable's default. A value several resources share is said so. +//! - A module whose source is a registry or a git address is matched on +//! the call's own inputs; its resource block cannot be edited. +//! +//! State would answer this exactly (`terraform state list -id=...`), and +//! CoderHelm does not read state: what this finds is graded, and a low +//! grade never becomes a pull request. + +use std::collections::BTreeMap; + +use regex::Regex; + +use super::hcl::{self, Attr, Block, Part, Value}; +use super::inventory::{Confidence, Edit, Kind, Location, Resource}; +use super::locate::{environment_of, SourceFile}; + +/// What is matched: the live resource's own values. +#[derive(Debug, Clone, Default)] +pub struct Live { + pub kind: Kind, + /// The names it may carry in code (its own, its launch template's). + pub names: Vec, + pub engine: String, + pub engine_version: String, + pub ami_id: String, + pub tags: BTreeMap, + pub facts: BTreeMap, +} + +impl Live { + pub fn of(r: &Resource) -> Live { + let mut names = vec![r.name.clone()]; + if let Some(lt) = r.tags.get("coderhelm:launch-template") { + names.push(lt.clone()); + } + names.retain(|n| !n.is_empty()); + Live { + kind: r.kind, + names, + engine: r.versions.engine.clone(), + engine_version: r.versions.engine_version.clone(), + ami_id: r.versions.ami_id.clone(), + tags: r + .tags + .iter() + .filter(|(k, _)| !k.starts_with("aws:") && !k.starts_with("coderhelm:")) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + facts: r.facts.clone(), + } + } +} + +/// What a kind of resource looks like in Terraform. +pub struct Spec { + pub types: &'static [&'static str], + /// Attributes that hold its identifier, and a prefix of it. + pub names: &'static [&'static str], + pub prefixes: &'static [&'static str], + /// The attribute a version change edits. + pub version: &'static str, + /// Words in a module's source that say it makes this kind. + pub module_words: &'static [&'static str], +} + +pub fn spec(kind: Kind) -> Option { + Some(match kind { + Kind::RdsInstance => Spec { + types: &["aws_db_instance"], + names: &["identifier"], + prefixes: &["identifier_prefix"], + version: "engine_version", + module_words: &["rds", "db", "postgres", "mysql", "database"], + }, + Kind::RdsCluster => Spec { + types: &["aws_rds_cluster"], + names: &["cluster_identifier"], + prefixes: &["cluster_identifier_prefix"], + version: "engine_version", + module_words: &["aurora", "rds", "cluster", "database"], + }, + Kind::ElasticacheGroup => Spec { + types: &[ + "aws_elasticache_replication_group", + "aws_elasticache_cluster", + ], + names: &["replication_group_id", "cluster_id"], + prefixes: &[], + version: "engine_version", + module_words: &["elasticache", "redis", "valkey", "cache"], + }, + Kind::OpensearchDomain => Spec { + types: &["aws_opensearch_domain", "aws_elasticsearch_domain"], + names: &["domain_name"], + prefixes: &[], + version: "engine_version", + module_words: &["opensearch", "elasticsearch"], + }, + Kind::EksNodegroup => Spec { + types: &["aws_eks_node_group"], + names: &["node_group_name"], + prefixes: &["node_group_name_prefix"], + version: "release_version", + module_words: &["eks", "node"], + }, + Kind::LambdaFunction => Spec { + types: &["aws_lambda_function"], + names: &["function_name"], + prefixes: &[], + version: "runtime", + module_words: &["lambda"], + }, + Kind::AutoScalingGroup | Kind::Ec2Instance => Spec { + types: &[ + "aws_launch_template", + "aws_autoscaling_group", + "aws_instance", + ], + names: &["name"], + prefixes: &["name_prefix"], + version: "image_id", + module_words: &["autoscaling", "asg", "ec2"], + }, + _ => return None, + }) +} + +fn re(p: &str) -> Regex { + Regex::new(p).expect("a valid pattern") +} + +/// The prefix of a name Terraform generated: the provider appends a +/// timestamp and a counter, 26 characters, to `terraform-` or to the +/// `*_prefix` argument. `None` for a name a person chose. +pub fn generated_prefix(name: &str) -> Option<&str> { + let at = name.len().checked_sub(26)?; + let (prefix, tail) = name.split_at_checked(at)?; + re(r"^\d{18}[0-9a-f]{8}$") + .is_match(tail) + .then_some(prefix) + .filter(|p| !p.is_empty()) +} + +#[derive(Debug, Clone)] +struct Origin { + file: String, + line: u32, + /// The name the value is written under there. + name: String, + via: &'static str, +} + +#[derive(Debug, Clone)] +enum Val { + /// A value read all the way to a literal, and where the literal is. + Known(String, Origin), + /// A string with parts that could not be read: a pattern the live + /// value must fit, and the text as written. + Pattern(String, String), + Unknown(String), +} + +/// One directory of `.tf` files. +struct Dir<'a> { + repo: &'a str, + dir: String, + files: Vec<(&'a str, Vec)>, + /// Variable files in or under the directory. + tfvars: Vec<(&'a str, Vec)>, +} + +impl Dir<'_> { + fn blocks(&self) -> impl Iterator { + self.files + .iter() + .flat_map(|(p, bs)| bs.iter().map(move |b| (*p, b))) + } + fn variable_default(&self, name: &str) -> Option<(&str, &Attr)> { + self.blocks() + .filter(|(_, b)| b.kind == "variable" && b.label(0) == name) + .find_map(|(p, b)| b.attr("default").map(|a| (p, a))) + } + fn local(&self, name: &str) -> Option<(&str, &Attr)> { + self.blocks() + .filter(|(_, b)| b.kind == "locals") + .find_map(|(p, b)| b.attr(name).map(|a| (p, a))) + } + /// How many resource and module blocks read `var.`. + fn readers(&self, name: &str) -> usize { + let needle = format!("var.{name}"); + let word = re(&format!(r"\bvar\.{}\b", regex::escape(name))); + self.blocks() + .filter(|(_, b)| matches!(b.kind.as_str(), "resource" | "module")) + .filter(|(_, b)| { + fn any(b: &Block, needle: &str, word: &Regex) -> bool { + b.attrs + .iter() + .any(|a| a.expr.contains(needle) && word.is_match(&a.expr)) + || b.blocks.iter().any(|c| any(c, needle, word)) + } + any(b, &needle, &word) + }) + .count() + } +} + +/// One way a directory is used. +#[derive(Debug, Clone, Default)] +struct Ctx { + vars: BTreeMap, + /// `module.db.` for a module called as `db`. + prefix: String, + env: String, + /// The variable file or call chain, for the evidence. + label: String, + /// The module is called more than once, or with `for_each`. + repeated: bool, +} + +fn dir_of(path: &str) -> String { + path.rsplit_once('/') + .map(|(d, _)| d) + .unwrap_or("") + .to_string() +} + +/// `a/b` + `../c` is `a/c`. +fn join(dir: &str, rel: &str) -> String { + let mut parts: Vec<&str> = dir.split('/').filter(|p| !p.is_empty()).collect(); + for p in rel.split('/') { + match p { + "" | "." => {} + ".." => { + parts.pop(); + } + x => parts.push(x), + } + } + parts.join("/") +} + +fn is_tf(path: &str) -> bool { + path.ends_with(".tf") || path.ends_with(".tofu") +} + +fn is_tfvars(path: &str) -> bool { + path.ends_with(".tfvars") +} + +fn dirs<'a>(files: &'a [SourceFile]) -> Vec> { + let mut out: Vec> = Vec::new(); + for f in files.iter().filter(|f| is_tf(&f.path)) { + let d = dir_of(&f.path); + let blocks = hcl::parse(&f.content); + match out.iter_mut().find(|x| x.repo == f.repo && x.dir == d) { + Some(x) => x.files.push((&f.path, blocks)), + None => out.push(Dir { + repo: &f.repo, + dir: d, + files: vec![(&f.path, blocks)], + tfvars: Vec::new(), + }), + } + } + // A variable file belongs to the nearest directory of `.tf` files at + // or above it. + for f in files.iter().filter(|f| is_tfvars(&f.path)) { + let mut d = dir_of(&f.path); + loop { + if let Some(x) = out.iter_mut().find(|x| x.repo == f.repo && x.dir == d) { + x.tfvars.push((&f.path, hcl::assignments(&f.content))); + break; + } + if d.is_empty() { + break; + } + d = dir_of(&d); + } + } + out +} + +#[allow(clippy::too_many_arguments)] +fn resolve( + expr: &str, + file: &str, + line: u32, + name: &str, + via: &'static str, + ctx: &Ctx, + dir: &Dir, + depth: u8, +) -> Val { + if depth > 6 { + return Val::Unknown(expr.to_string()); + } + match hcl::value(expr) { + Value::Lit(s) => Val::Known( + s, + Origin { + file: file.to_string(), + line, + name: name.to_string(), + via, + }, + ), + Value::Var(v) => match ctx.vars.get(&v) { + Some(x) => x.clone(), + None => match dir.variable_default(&v) { + Some((p, a)) => resolve( + &a.expr, + p, + a.line, + &v, + "variable_default", + ctx, + dir, + depth + 1, + ), + None => Val::Unknown(expr.to_string()), + }, + }, + Value::Local(v) => match dir.local(&v) { + Some((p, a)) => resolve(&a.expr, p, a.line, &v, "local", ctx, dir, depth + 1), + None => Val::Unknown(expr.to_string()), + }, + Value::Template(parts) => { + let mut text = String::new(); + let mut pattern = String::from("^"); + let mut known = true; + for p in parts { + match p { + Part::Text(t) => { + text.push_str(&t); + pattern.push_str(®ex::escape(&t)); + } + Part::Ref(r) => match resolve(&r, file, line, name, via, ctx, dir, depth + 1) { + Val::Known(v, _) => { + text.push_str(&v); + pattern.push_str(®ex::escape(&v)); + } + _ => { + known = false; + pattern.push_str(".+"); + } + }, + } + } + if known { + Val::Known( + text, + Origin { + file: file.to_string(), + line, + name: name.to_string(), + via, + }, + ) + } else { + pattern.push('$'); + Val::Pattern(pattern, expr.to_string()) + } + } + Value::Each(t) | Value::Other(t) => Val::Unknown(t), + } +} + +const META: &[&str] = &[ + "source", + "version", + "count", + "for_each", + "providers", + "depends_on", +]; + +/// Every way `dirs[at]` is used: per module call that points at it, or per +/// environment variable file when nothing calls it. +fn contexts(dirs: &[Dir], at: usize, depth: u8) -> Vec { + let me = &dirs[at]; + let mut out = Vec::new(); + if depth < 4 { + for (ci, c) in dirs.iter().enumerate().filter(|(_, c)| c.repo == me.repo) { + for (file, m) in c.blocks().filter(|(_, b)| b.kind == "module") { + let Some(Value::Lit(src)) = m.attr("source").map(|a| hcl::value(&a.expr)) else { + continue; + }; + if !(src.starts_with("./") || src.starts_with("../")) + || join(&c.dir, &src) != me.dir + { + continue; + } + if ci == at { + continue; + } + let many = m.attr("for_each").is_some() || m.attr("count").is_some(); + for cc in contexts(dirs, ci, depth + 1) { + let mut vars = BTreeMap::new(); + for a in m.attrs.iter().filter(|a| !META.contains(&a.name.as_str())) { + vars.insert( + a.name.clone(), + resolve(&a.expr, file, a.line, &a.name, "module_input", &cc, c, 0), + ); + } + let env = if cc.env.is_empty() { + environment_of(&[m.label(0), &c.dir]) + } else { + cc.env.clone() + }; + out.push(Ctx { + vars, + prefix: format!("{}module.{}.", cc.prefix, m.label(0)), + env, + label: if cc.label.is_empty() { + format!("module `{}` in {file}", m.label(0)) + } else { + format!("module `{}` in {file}, with {}", m.label(0), cc.label) + }, + repeated: many || cc.repeated, + }); + } + } + } + } + if !out.is_empty() { + let n = out.len(); + if n > 1 { + // Several calls of one module: an edit inside the module is + // shared by all of them. + for c in out.iter_mut() { + c.repeated = true; + } + } + return out; + } + // A root: what its variable files set. + let set = |path: &str, attrs: &[Attr], into: &mut BTreeMap| { + for a in attrs { + let v = match hcl::value(&a.expr) { + Value::Lit(s) => Val::Known( + s, + Origin { + file: path.to_string(), + line: a.line, + name: a.name.clone(), + via: "tfvars", + }, + ), + _ => Val::Unknown(a.expr.clone()), + }; + into.insert(a.name.clone(), v); + } + }; + let always = |p: &str| { + dir_of(p) == me.dir && (p.ends_with("terraform.tfvars") || p.ends_with(".auto.tfvars")) + }; + let mut base = BTreeMap::new(); + for (p, attrs) in me.tfvars.iter().filter(|(p, _)| always(p)) { + set(p, attrs, &mut base); + } + let per_env: Vec<&(&str, Vec)> = me.tfvars.iter().filter(|(p, _)| !always(p)).collect(); + if per_env.is_empty() { + return vec![Ctx { + vars: base, + env: environment_of(&[&me.dir]), + ..Default::default() + }]; + } + per_env + .into_iter() + .map(|(p, attrs)| { + let mut vars = base.clone(); + set(p, attrs, &mut vars); + Ctx { + vars, + env: environment_of(&[p]), + label: (*p).to_string(), + ..Default::default() + } + }) + .collect() +} + +/// One place that could define the resource. +#[derive(Debug, Clone)] +pub struct Candidate { + pub score: i32, + pub location: Location, +} + +struct Scored { + score: i32, + evidence: Vec, + how: &'static str, +} + +fn starts_with_version(live: &str, code: &str) -> bool { + !code.is_empty() + && (live == code || live.starts_with(&format!("{code}.")) || live.starts_with(code)) +} + +/// Scores the attributes `get` returns against the live resource. `None` +/// when a literal contradicts it. +#[allow(clippy::too_many_arguments)] +fn score( + live: &Live, + sp: &Spec, + names: &[&str], + prefixes: &[&str], + get: &dyn Fn(&str) -> Option, + has: &dyn Fn(&str) -> bool, + repeated_block: bool, + tags: &[(String, Val)], +) -> Option { + // An instance group's blocks (launch template, group) each carry a + // name of their own: a name that differs rules nothing out there. + let strict = !matches!(live.kind, Kind::AutoScalingGroup | Kind::Ec2Instance); + let repeated_block = repeated_block || !strict; + let mut s = Scored { + score: 0, + evidence: Vec::new(), + how: "terraform_attributes", + }; + let gen = live.names.iter().find_map(|n| generated_prefix(n)); + let mut named = false; + for n in names { + match get(n) { + Some(Val::Known(v, o)) => { + if live.names.iter().any(|x| x == &v) { + s.score += 100; + s.how = "terraform_name"; + s.evidence.push(format!( + "`{n}` is `{v}`, the live name ({})", + if o.via == "resource" { + "written in the block".to_string() + } else { + format!("from `{}` in {}", o.name, o.file) + } + )); + named = true; + } else if !repeated_block { + return None; + } + } + Some(Val::Pattern(p, text)) => { + let fits = Regex::new(&p) + .ok() + .is_some_and(|r| live.names.iter().any(|x| r.is_match(x))); + if fits { + s.score += 40; + s.evidence.push(format!( + "`{n}` is written as `{text}`, which the live name fits; part of it is set somewhere CoderHelm did not read" + )); + named = true; + } else if !repeated_block { + return None; + } + } + Some(Val::Unknown(text)) => { + if !strict { + } else if text.starts_with("each.") || text.starts_with("count.") || repeated_block + { + s.score += 15; + s.evidence.push(format!( + "`{n}` comes from `{text}`: the block creates several resources and CoderHelm cannot tell which one is this" + )); + } else { + s.evidence + .push(format!("`{n}` is `{text}`, which CoderHelm could not read")); + } + } + None => {} + } + } + for n in prefixes { + match (get(n), gen) { + (Some(Val::Known(v, _)), Some(g)) if v == g => { + s.score += 90; + s.how = "terraform_generated_name"; + s.evidence.push(format!( + "`{n}` is `{v}`, and the live name is that prefix plus the suffix Terraform generates" + )); + named = true; + } + (Some(Val::Known(_, _)), _) if !repeated_block => return None, + (Some(Val::Pattern(p, text)), Some(g)) + if Regex::new(&p).ok().is_some_and(|r| r.is_match(g)) => + { + s.score += 35; + s.how = "terraform_generated_name"; + s.evidence.push(format!( + "`{n}` is written as `{text}`, which the generated live name's prefix fits" + )); + named = true; + } + _ => {} + } + } + let sets_name = names.iter().chain(prefixes.iter()).any(|n| has(n)); + if !named && !sets_name && gen == Some("terraform-") { + s.score += 30; + s.how = "terraform_generated_name"; + s.evidence.push( + "the live name is one Terraform generated (`terraform-` and a timestamp), and this block sets no identifier".into(), + ); + } else if !named && !sets_name && gen.is_none() && !repeated_block { + // A name a person chose, and a block that would get a generated one. + return None; + } + if !live.engine.is_empty() { + if let Some(Val::Known(v, _)) = get("engine") { + if v == live.engine { + s.score += 15; + s.evidence.push(format!("`engine` is `{v}`")); + } else { + return None; + } + } + } + if !live.engine_version.is_empty() && sp.version == "engine_version" { + if let Some(Val::Known(v, _)) = get("engine_version") { + if starts_with_version(&live.engine_version, &v) { + s.score += 10; + s.evidence.push(format!( + "`engine_version` is `{v}` (it runs {})", + live.engine_version + )); + } else { + s.evidence.push(format!( + "`engine_version` is `{v}` while it runs {}", + live.engine_version + )); + } + } + } + if !live.ami_id.is_empty() { + if let Some(Val::Known(v, _)) = get("image_id") { + if v == live.ami_id { + s.score += 100; + s.how = "terraform_attributes"; + s.evidence + .push(format!("`image_id` is `{v}`, the AMI that runs")); + } + } + } + for (fact, attr, points) in [ + ("subnet_group", "db_subnet_group_name", 15), + ("subnet_group", "subnet_group_name", 15), + ("parameter_group", "parameter_group_name", 10), + ("parameter_group", "db_cluster_parameter_group_name", 10), + ("instance_class", "instance_class", 5), + ("cluster", "cluster_name", 15), + ] { + let Some(want) = live.facts.get(fact) else { + continue; + }; + if let Some(Val::Known(v, _)) = get(attr) { + if &v == want { + s.score += points; + s.evidence.push(format!("`{attr}` is `{v}`")); + } else if points >= 15 { + s.score -= 20; + s.evidence + .push(format!("`{attr}` is `{v}`, the live one is `{want}`")); + } + } + } + let mut tag_points = 0; + for (k, v) in tags { + let Some(want) = live.tags.get(k) else { + continue; + }; + if let Val::Known(v, _) = v { + if v == want { + if tag_points < 30 { + tag_points += 10; + s.evidence.push(format!("tag `{k}` is `{v}`")); + } + } else { + s.score -= 20; + s.evidence + .push(format!("tag `{k}` is `{v}`, the live tag is `{want}`")); + } + } + } + s.score += tag_points; + (s.score >= 30).then_some(s) +} + +fn edit_from( + val: Option, + file: &str, + line: u32, + attribute: &str, + evidence: &mut Vec, +) -> Option { + match val { + Some(Val::Known(v, o)) => Some(Edit { + file: o.file, + line: o.line, + attribute: o.name, + value: v, + via: o.via.to_string(), + shared: String::new(), + }), + Some(Val::Pattern(_, text)) | Some(Val::Unknown(text)) => { + evidence.push(format!( + "`{attribute}` is `{text}`: CoderHelm could not follow it to the line that sets the value" + )); + None + } + None => Some(Edit { + file: file.to_string(), + line, + attribute: attribute.to_string(), + value: String::new(), + via: "add".into(), + shared: String::new(), + }), + } +} + +fn tags_of(b: &Block, file: &str, ctx: &Ctx, dir: &Dir) -> Vec<(String, Val)> { + let Some(t) = b.attr("tags") else { + return Vec::new(); + }; + hcl::object(&t.expr, t.line) + .into_iter() + .map(|a| { + let v = resolve(&a.expr, file, a.line, &a.name, "resource", ctx, dir, 0); + (a.name, v) + }) + .collect() +} + +/// Every place in `files` that could define the live resource, best first. +pub fn candidates(live: &Live, files: &[SourceFile]) -> Vec { + candidates_in(live, &index(files)) +} + +/// A team's Terraform files, parsed once for every resource placed +/// against them. +pub struct Index<'a> { + dirs: Vec>, +} + +/// Parses the Terraform and OpenTofu files among `files`. +pub fn index(files: &[SourceFile]) -> Index<'_> { + Index { dirs: dirs(files) } +} + +/// Every place in a parsed set of files that could define the live +/// resource, best first. +pub fn candidates_in(live: &Live, index: &Index) -> Vec { + let Some(sp) = spec(live.kind) else { + return Vec::new(); + }; + let dirs = &index.dirs; + let mut out: Vec = Vec::new(); + for (at, d) in dirs.iter().enumerate() { + let wanted: Vec<(&str, &Block)> = d + .blocks() + .filter(|(_, b)| b.kind == "resource" && sp.types.contains(&b.label(0))) + .collect(); + let remote: Vec<(&str, &Block)> = d + .blocks() + .filter(|(_, b)| b.kind == "module") + .filter(|(_, b)| { + matches!(b.attr("source").map(|a| hcl::value(&a.expr)), + Some(Value::Lit(s)) if !(s.starts_with("./") || s.starts_with("../")) + && sp.module_words.iter().any(|w| s.to_ascii_lowercase().contains(w))) + }) + .collect(); + if wanted.is_empty() && remote.is_empty() { + continue; + } + let ctxs = contexts(dirs, at, 0); + let opentofu = d.files.iter().any(|(p, _)| p.ends_with(".tofu")); + for ctx in &ctxs { + for (file, b) in &wanted { + let many = b.attr("for_each").is_some() || b.attr("count").is_some(); + let get = |n: &str| { + b.attr(n) + .map(|a| resolve(&a.expr, file, a.line, n, "resource", ctx, d, 0)) + }; + let has = |n: &str| b.attr(n).is_some(); + let tags = tags_of(b, file, ctx, d); + let Some(mut s) = score(live, &sp, sp.names, sp.prefixes, &get, &has, many, &tags) + else { + continue; + }; + let version = if b.label(0) == "aws_elasticsearch_domain" { + "elasticsearch_version" + } else { + sp.version + }; + let mut edit = edit_from(get(version), file, b.line, version, &mut s.evidence); + if let Some(e) = edit.as_mut() { + e.shared = shared_note(e, b, many, ctx, d); + } + if !ctx.prefix.is_empty() { + s.how = "terraform_module"; + } + if !ctx.label.is_empty() { + s.evidence.push(format!("read through {}", ctx.label)); + } + out.push(Candidate { + score: s.score, + location: Location { + repo: d.repo.to_string(), + file: (*file).to_string(), + address: format!("{}{}.{}", ctx.prefix, b.label(0), b.label(1)), + line: b.line, + how: s.how.into(), + tool: if opentofu { "opentofu" } else { "terraform" }.into(), + confidence: Confidence::Low, + evidence: s.evidence, + edit, + environment: ctx.env.clone(), + ..Default::default() + }, + }); + } + for (file, m) in &remote { + let many = m.attr("for_each").is_some() || m.attr("count").is_some(); + let get = |n: &str| { + m.attr(n) + .map(|a| resolve(&a.expr, file, a.line, n, "module_input", ctx, d, 0)) + }; + let has = |n: &str| m.attr(n).is_some(); + let mut names: Vec<&str> = sp.names.to_vec(); + for n in ["name", "identifier", "cluster_name"] { + if !names.contains(&n) { + names.push(n); + } + } + let tags = tags_of(m, file, ctx, d); + // A module may turn its name into a prefix; a call that + // sets a name is never ruled out for lacking a prefix. + let Some(mut s) = score( + live, + &sp, + &names, + &[], + &get, + &|n| has(n) || names.iter().any(|x| has(x)), + many, + &tags, + ) + .or_else(|| prefix_through_module(live, &names, &get)) else { + continue; + }; + let source = match m.attr("source").map(|a| hcl::value(&a.expr)) { + Some(Value::Lit(x)) => x, + _ => String::new(), + }; + s.how = "terraform_module"; + s.evidence.push(format!( + "defined through the module `{source}`: the resource block is inside the module, so the edit is this call's input" + )); + let version = [ + sp.version, + "engine_version", + "ami_release_version", + "cluster_version", + ] + .into_iter() + .find(|v| m.attr(v).is_some()) + .unwrap_or(sp.version); + let mut edit = edit_from(get(version), file, m.line, version, &mut s.evidence); + if let Some(e) = edit.as_mut() { + if e.via == "add" { + e.via = "module_input".into(); + s.evidence.push(format!( + "the call does not set `{version}`: the module's own default applies; check the module's inputs for the name it uses" + )); + } + e.shared = shared_note(e, m, many, ctx, d); + } + out.push(Candidate { + score: s.score.min(95), + location: Location { + repo: d.repo.to_string(), + file: (*file).to_string(), + address: format!("{}module.{}", ctx.prefix, m.label(0)), + line: m.line, + how: s.how.into(), + tool: if opentofu { "opentofu" } else { "terraform" }.into(), + confidence: Confidence::Low, + evidence: s.evidence, + edit, + environment: if ctx.env.is_empty() { + environment_of(&[m.label(0)]) + } else { + ctx.env.clone() + }, + ..Default::default() + }, + }); + } + } + } + out.sort_by_key(|c| std::cmp::Reverse(c.score)); + out +} + +/// A registry module that is given a name and makes it a prefix: the live +/// name is the call's name, a dash, and Terraform's generated suffix. +fn prefix_through_module( + live: &Live, + names: &[&str], + get: &dyn Fn(&str) -> Option, +) -> Option { + let g = live.names.iter().find_map(|n| generated_prefix(n))?; + for n in names { + if let Some(Val::Known(v, _)) = get(n) { + if g == v || g.trim_end_matches('-') == v { + return Some(Scored { + score: 70, + evidence: vec![format!( + "the call's `{n}` is `{v}`, and the live name is that name plus the suffix Terraform generates" + )], + how: "terraform_module", + }); + } + } + } + None +} + +fn shared_note(e: &Edit, block: &Block, many: bool, ctx: &Ctx, d: &Dir) -> String { + match e.via.as_str() { + "tfvars" | "variable_default" => { + let n = d.readers(&e.attribute); + let mut s = String::new(); + if n > 1 { + s = format!("{n} blocks read `var.{}`: the change reaches all of them", e.attribute); + } + if e.via == "variable_default" { + if !s.is_empty() { + s.push_str(". "); + } + s.push_str("A variable's default applies wherever nothing else sets it"); + if ctx.repeated { + s.push_str(", in every use of this module"); + } + } + s + } + "resource" if many => format!( + "`{}.{}` creates several resources (`for_each` or `count`): a value written in the block applies to every one", + block.label(0), + block.label(1) + ), + "resource" | "add" if ctx.repeated => { + "the block is inside a module used more than once: a value written here applies to every use".into() + } + "module_input" if many => { + "the module call creates several copies (`for_each` or `count`): this input applies to every one".into() + } + _ => String::new(), + } +} + +/// The place that defines the live resource, graded. `None` when nothing +/// fits. A tie between places, or weak signs only, is `Low`, with the +/// other places listed. +pub fn locate(live: &Live, files: &[SourceFile]) -> Option { + locate_in(live, &index(files)) +} + +/// [`locate`] against files parsed once ([`index`]). +pub fn locate_in(live: &Live, index: &Index) -> Option { + let all = candidates_in(live, index); + let best = all.first()?; + let rivals: Vec<&Candidate> = all + .iter() + .skip(1) + .filter(|c| c.score > best.score - 30) + .collect(); + let mut loc = best.location.clone(); + loc.confidence = if best.score >= 90 && rivals.is_empty() { + Confidence::High + } else if best.score >= 50 && rivals.is_empty() { + Confidence::Medium + } else { + Confidence::Low + }; + if !rivals.is_empty() { + loc.evidence.push(format!( + "{} other place{} fit{} about as well; CoderHelm cannot tell them apart without Terraform's state", + rivals.len(), + if rivals.len() == 1 { "" } else { "s" }, + if rivals.len() == 1 { "s" } else { "" }, + )); + loc.candidates = rivals + .iter() + .take(5) + .map(|c| { + format!( + "{}:{} {}{}", + c.location.repo, + c.location.file, + c.location.address, + if c.location.environment.is_empty() { + String::new() + } else { + format!(" ({})", c.location.environment) + } + ) + }) + .collect(); + } else if loc.confidence == Confidence::Low { + loc.evidence.push( + "only the resource type and a few settings fit; the identifier is not written in the code CoderHelm read".into(), + ); + } + if loc.edit.is_none() { + // Found, but not the line to change: not enough for a pull request. + loc.confidence = loc.confidence.min(Confidence::Low); + } + Some(loc) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(path: &str, content: &str) -> SourceFile { + SourceFile { + repo: "acme/infra".into(), + path: path.into(), + content: content.into(), + } + } + + fn db(name: &str, engine: &str, version: &str) -> Live { + Live { + kind: Kind::RdsInstance, + names: vec![name.into()], + engine: engine.into(), + engine_version: version.into(), + ..Default::default() + } + } + + #[test] + fn a_resource_written_with_its_identifier_is_found_with_the_line_to_edit() { + let f = file( + "db/main.tf", + r#" +resource "aws_db_instance" "billing" { + identifier = "billing-prod" + engine = "mysql" + engine_version = "8.0.36" +} + +resource "aws_db_instance" "reports" { + identifier = "reports-prod" + engine = "mysql" + engine_version = "8.0.36" +} +"#, + ); + let l = locate(&db("billing-prod", "mysql", "8.0.36"), &[f]).unwrap(); + assert_eq!(l.address, "aws_db_instance.billing"); + assert_eq!( + (l.how.as_str(), l.confidence), + ("terraform_name", Confidence::High) + ); + assert_eq!(l.tool, "terraform"); + let e = l.edit.unwrap(); + assert_eq!( + ( + e.file.as_str(), + e.line, + e.attribute.as_str(), + e.value.as_str(), + e.via.as_str() + ), + ("db/main.tf", 5, "engine_version", "8.0.36", "resource") + ); + assert!( + l.candidates.is_empty(), + "a block naming another database is ruled out" + ); + } + + #[test] + fn a_generated_identifier_is_matched_by_prefix_and_attributes_not_by_name() { + let live_name = "orders-20240311094512345600000001"; + assert_eq!(generated_prefix(live_name), Some("orders-")); + assert_eq!( + generated_prefix("terraform-20240311094512345600000001"), + Some("terraform-") + ); + assert_eq!(generated_prefix("orders-prod"), None); + let f = file( + "main.tf", + r#" +resource "aws_db_instance" "orders" { + identifier_prefix = "orders-" + engine = "postgres" + engine_version = "16.4" + tags = { Team = "payments" } +} +resource "aws_db_instance" "audit" { + identifier_prefix = "audit-" + engine = "postgres" + engine_version = "16.4" +} +"#, + ); + let mut live = db(live_name, "postgres", "16.4"); + live.tags.insert("Team".into(), "payments".into()); + let l = locate(&live, std::slice::from_ref(&f)).unwrap(); + assert_eq!(l.address, "aws_db_instance.orders"); + assert_eq!( + (l.how.as_str(), l.confidence), + ("terraform_generated_name", Confidence::High) + ); + assert!( + l.evidence + .iter() + .any(|e| e.contains("suffix Terraform generates")), + "{:?}", + l.evidence + ); + // The literal live name is nowhere in the file. + assert!(!f.content.contains(live_name)); + } + + #[test] + fn a_default_generated_name_with_two_blocks_that_fit_is_low_and_says_why() { + let f = file( + "main.tf", + r#" +resource "aws_db_instance" "a" { + engine = "postgres" + engine_version = "16.4" +} +resource "aws_db_instance" "b" { + engine = "postgres" + engine_version = "16.4" +} +"#, + ); + let l = locate( + &db("terraform-20240311094512345600000001", "postgres", "16.4"), + &[f], + ) + .unwrap(); + assert_eq!(l.confidence, Confidence::Low); + assert!(!l.sure(), "never a pull request"); + assert_eq!(l.candidates.len(), 1); + assert!( + l.evidence + .iter() + .any(|e| e.contains("cannot tell them apart")), + "{:?}", + l.evidence + ); + // One block that fits, with the engine and version too: medium. + let one = file( + "main.tf", + "resource \"aws_db_instance\" \"a\" {\n engine = \"postgres\"\n engine_version = \"16.4\"\n}\n", + ); + let l = locate( + &db("terraform-20240311094512345600000001", "postgres", "16.4"), + &[one], + ) + .unwrap(); + assert_eq!(l.confidence, Confidence::Medium); + // Another engine: ruled out. + let other = file( + "main.tf", + "resource \"aws_db_instance\" \"a\" {\n engine = \"mysql\"\n}\n", + ); + assert!(locate( + &db("terraform-20240311094512345600000001", "postgres", "16.4"), + &[other] + ) + .is_none()); + } + + const MODULE: &str = r#" +variable "name" {} +variable "engine_version" { + default = "16.4" +} +resource "aws_rds_cluster" "this" { + cluster_identifier = "${var.name}-aurora" + engine = "aurora-postgresql" + engine_version = var.engine_version +} +resource "aws_rds_cluster_instance" "this" { + count = 2 + cluster_identifier = aws_rds_cluster.this.id + engine_version = aws_rds_cluster.this.engine_version +} +"#; + + fn cluster(name: &str) -> Live { + Live { + kind: Kind::RdsCluster, + names: vec![name.into()], + engine: "aurora-postgresql".into(), + engine_version: "16.4".into(), + ..Default::default() + } + } + + #[test] + fn a_cluster_defined_through_a_local_module_edits_the_callers_input() { + let files = vec![ + file("modules/aurora/main.tf", MODULE), + file( + "envs/prod/main.tf", + "module \"ledger\" {\n source = \"../../modules/aurora\"\n name = \"ledger-prod\"\n engine_version = \"16.4\"\n}\n", + ), + file( + "envs/staging/main.tf", + "module \"ledger\" {\n source = \"../../modules/aurora\"\n name = \"ledger-staging\"\n engine_version = \"16.4\"\n}\n", + ), + ]; + let l = locate(&cluster("ledger-prod-aurora"), &files).unwrap(); + assert_eq!(l.address, "module.ledger.aws_rds_cluster.this"); + assert_eq!( + (l.how.as_str(), l.confidence), + ("terraform_module", Confidence::High) + ); + assert_eq!(l.environment, "production"); + // The edit is the caller's input, not the module's resource block + // and never the cluster instance. + let e = l.edit.unwrap(); + assert_eq!( + ( + e.file.as_str(), + e.line, + e.attribute.as_str(), + e.via.as_str() + ), + ("envs/prod/main.tf", 4, "engine_version", "module_input") + ); + let s = locate(&cluster("ledger-staging-aurora"), &files).unwrap(); + assert_eq!(s.environment, "staging"); + assert_eq!(s.edit.unwrap().file, "envs/staging/main.tf"); + } + + #[test] + fn a_module_default_is_shared_and_the_note_says_so() { + let files = vec![ + file("modules/aurora/main.tf", MODULE), + file( + "envs/prod/main.tf", + "module \"ledger\" {\n source = \"../../modules/aurora\"\n name = \"ledger-prod\"\n}\nmodule \"audit\" {\n source = \"../../modules/aurora\"\n name = \"audit-prod\"\n}\n", + ), + ]; + let l = locate(&cluster("ledger-prod-aurora"), &files).unwrap(); + let e = l.edit.unwrap(); + assert_eq!( + (e.file.as_str(), e.via.as_str()), + ("modules/aurora/main.tf", "variable_default") + ); + assert!( + e.shared.contains("every use of this module"), + "{}", + e.shared + ); + } + + #[test] + fn a_registry_module_is_matched_on_the_calls_inputs() { + let f = file( + "main.tf", + r#" +module "db" { + source = "terraform-aws-modules/rds/aws" + version = "~> 6.0" + + identifier = "orders" + instance_use_identifier_prefix = true + engine = "postgres" + engine_version = "16.4" + family = "postgres16" +} +"#, + ); + let l = locate( + &db("orders-20240311094512345600000001", "postgres", "16.4"), + &[f], + ) + .unwrap(); + assert_eq!(l.address, "module.db"); + assert_eq!(l.how, "terraform_module"); + assert_eq!( + l.confidence, + Confidence::Medium, + "a module's inside is not read" + ); + let e = l.edit.unwrap(); + assert_eq!( + (e.line, e.attribute.as_str(), e.via.as_str()), + (9, "engine_version", "module_input") + ); + assert!( + l.evidence.iter().any(|e| e.contains("inside the module")), + "{:?}", + l.evidence + ); + } + + const ROOT: &str = r#" +variable "env" {} +variable "db_engine_version" {} +resource "aws_db_instance" "app" { + identifier = "app-${var.env}" + engine = "postgres" + engine_version = var.db_engine_version +} +"#; + + #[test] + fn a_variable_file_per_environment_is_the_edit_target() { + let files = vec![ + file("stack/main.tf", ROOT), + file( + "stack/envs/prod.tfvars", + "env = \"prod\"\ndb_engine_version = \"16.4\"\n", + ), + file( + "stack/envs/staging.tfvars", + "env = \"staging\"\ndb_engine_version = \"16.6\"\n", + ), + ]; + let l = locate(&db("app-prod", "postgres", "16.4"), &files).unwrap(); + assert_eq!(l.confidence, Confidence::High); + assert_eq!(l.environment, "production"); + let e = l.edit.unwrap(); + assert_eq!( + ( + e.file.as_str(), + e.line, + e.attribute.as_str(), + e.value.as_str(), + e.via.as_str() + ), + ( + "stack/envs/prod.tfvars", + 2, + "db_engine_version", + "16.4", + "tfvars" + ) + ); + // Without the variable files the name only fits a pattern: medium, + // and no line to edit means no pull request. + let alone = locate(&db("app-prod", "postgres", "16.4"), &files[..1]).unwrap(); + assert!(!alone.sure()); + assert!( + alone + .evidence + .iter() + .any(|e| e.contains("could not follow")), + "{:?}", + alone.evidence + ); + } + + #[test] + fn for_each_and_count_say_the_value_is_shared() { + let f = file( + "main.tf", + r#" +resource "aws_db_instance" "tenant" { + for_each = var.tenants + identifier = each.key + engine = "postgres" + engine_version = "16.4" +} +"#, + ); + let l = locate(&db("tenant-a", "postgres", "16.4"), &[f]).unwrap(); + assert_eq!( + l.confidence, + Confidence::Low, + "which instance it is cannot be read" + ); + assert!(l + .edit + .as_ref() + .unwrap() + .shared + .contains("applies to every one")); + assert!( + l.evidence + .iter() + .any(|e| e.contains("creates several resources")), + "{:?}", + l.evidence + ); + } + + #[test] + fn paths_join_and_other_kinds_have_their_attribute() { + assert_eq!(join("envs/prod", "../../modules/aurora"), "modules/aurora"); + assert_eq!(join("", "./db"), "db"); + assert_eq!(spec(Kind::EksNodegroup).unwrap().version, "release_version"); + assert_eq!(spec(Kind::LambdaFunction).unwrap().version, "runtime"); + assert!(spec(Kind::ContainerImage).is_none()); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 7a8f53f26..0ff95c341 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -43,11 +43,14 @@ pub mod deliveries_rollup; /// bisect, resumable state. pub mod dep_audit; pub mod dep_fix; +pub mod dep_head; +pub mod description_handoff; /// The shared dead-letter queue: whose each failed message is, whether the /// worker can read it, and when the cleanup archives it. pub mod dlq; /// One DNS TXT lookup through the system resolver (the email check's DMARC). pub mod dns_txt; +pub mod file_claims; /// Hybrid self-hosting: CoderHelm addresses, the event relay, the token /// broker and the signatures between an install and the hosted side. pub mod hybrid; diff --git a/services/common/src/live/iam_resource_types.json b/services/common/src/live/iam_resource_types.json index b0dab3f24..78aa1e3e4 100644 --- a/services/common/src/live/iam_resource_types.json +++ b/services/common/src/live/iam_resource_types.json @@ -87,6 +87,9 @@ "cloudformation:ListStackResources": [ "stack" ], + "cloudformation:DescribeStackResources": [ + "stack" + ], "ecr:BatchGetImage": [ "repository" ], diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index 94b7f5e31..13a4b0048 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -175,7 +175,7 @@ pub const ABILITIES: &[Ability] = &[ Ability { key: "infra", name: "Infrastructure vulnerabilities", - why: "Reads which versions run in the account so they can be matched against security advisories: EC2 instances and their AMIs, Auto Scaling groups and the load balancers in front of them, EKS clusters and node groups, RDS and Aurora pending maintenance, ElastiCache service updates, OpenSearch software updates, ECR scan results, kernels from SSM inventory, and AWS's public latest-AMI parameters. Only when the stack's InfrastructureVulnerabilities parameter is on. Never Lambda function settings, launch template user data or environment variables, and nothing is changed.", + why: "Reads which versions run in the account so they can be matched against security advisories: EC2 instances and their AMIs, Auto Scaling groups and the load balancers in front of them, EKS clusters and node groups, RDS and Aurora pending maintenance, ElastiCache service updates, OpenSearch software updates, ECR scan results, kernels from SSM inventory, AWS's public latest-AMI parameters, and which CloudFormation stack made a resource (the stack's name and the resource's logical id, so the fix goes to the code that defines it). Only when the stack's InfrastructureVulnerabilities parameter is on. Never Lambda function settings, launch template user data or environment variables, and nothing is changed.", actions: &[ "ec2:DescribeInstances", "ec2:DescribeImages", @@ -194,6 +194,7 @@ pub const ABILITIES: &[Ability] = &[ "es:ListDomainNames", "es:DescribeDomains", "ecr:DescribeImageScanFindings", + "cloudformation:DescribeStackResources", "ssm:ListInventoryEntries", "ssm:GetParameters", ], @@ -815,8 +816,8 @@ mod tests { assert!(checked.contains(&"logs:StartQuery")); // Knowledge bases (6), imports (4), copying into Bedrock (6 more: // its Get calls are the knowledge bases' too) and infrastructure - // reads (19), Inspector (3) and Health (3). - assert_eq!(checked.len() + 41, all_actions().len()); + // reads (20), Inspector (3) and Health (3). + assert_eq!(checked.len() + 42, all_actions().len()); assert!(!checked.contains(&"bedrock:IngestKnowledgeBaseDocuments")); // Copying into Bedrock rides along as its own parameter and stack. let sync = ["arn:aws:bedrock:us-east-1:111122223333:knowledge-base/SYNC123456".to_string()]; diff --git a/services/common/src/prose.rs b/services/common/src/prose.rs index eb96b0018..401275ff3 100644 --- a/services/common/src/prose.rs +++ b/services/common/src/prose.rs @@ -52,6 +52,24 @@ pub fn sentence_ends(text: &str) -> Vec { ends } +/// The sentences of `text`, each with its byte range: every stretch up to a +/// sentence end ([`sentence_ends`]), and what is left after the last one. +/// Leading whitespace belongs to the sentence it precedes. +pub fn sentence_spans(text: &str) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut start = 0; + for end in sentence_ends(text) { + if !text[start..end].trim().is_empty() { + out.push((start, end)); + } + start = end; + } + if !text[start..].trim().is_empty() { + out.push((start, text.len())); + } + out +} + /// At most `max_sentences` whole sentences and about `max_bytes`. A first /// sentence longer than `max_bytes` is kept whole: the cap never splits it. /// Text with no sentence end is returned as it is. diff --git a/services/common/src/reachability.rs b/services/common/src/reachability.rs index a6c9185c7..81c462e42 100644 --- a/services/common/src/reachability.rs +++ b/services/common/src/reachability.rs @@ -1303,6 +1303,192 @@ struct Graph { edges: Vec>, /// (direct dependency name, its node) roots: Vec<(String, usize)>, + /// The workspace projects the lockfile installs for: each one's folder + /// from the lockfile's folder (`""` for the root) and the nodes it + /// depends on directly. + projects: Vec<(String, Vec)>, + /// (project, a workspace project it depends on), by index in `projects`. + project_links: Vec<(usize, usize)>, +} + +/// `rel` from the folder `base`, with `.` and `..` resolved (`apps/web` and +/// `../studio` is `apps/studio`). +fn join_rel(base: &str, rel: &str) -> String { + let mut parts: Vec<&str> = base.split('/').filter(|p| !p.is_empty()).collect(); + for seg in rel.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// One workspace project of a lockfile, and which of the packages asked +/// about its dependencies bring in. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct LockProject { + /// Its folder, from the lockfile's folder (`""`: the lockfile's own). + pub dir: String, + /// The packages asked about that it installs, directly or through a + /// dependency or another workspace project, as `name@version`. + pub uses: Vec, +} + +fn graph_of(path: &str, text: &str, manifests: &[(String, String)]) -> Option { + let name = path.rsplit('/').next().unwrap_or(path); + match name { + "pnpm-lock.yaml" => pnpm_graph(text), + "package-lock.json" | "npm-shrinkwrap.json" => npm_graph(text), + "yarn.lock" => yarn_projects(text, manifests), + _ => None, + } +} + +/// Every installed copy a lockfile resolves, as (name, version). `None` for +/// a lockfile this can't read: the caller then says the versions are not +/// known, never a guess. +pub fn lock_copies(path: &str, text: &str) -> Option> { + let name = path.rsplit('/').next().unwrap_or(path); + let mut out: Vec<(String, String)> = match name { + "pnpm-lock.yaml" | "package-lock.json" | "npm-shrinkwrap.json" | "yarn.lock" => { + graph_of(path, text, &[])?.nodes + } + "Cargo.lock" | "poetry.lock" | "uv.lock" => toml_copies(text), + "Gemfile.lock" => gem_copies(text), + _ => return None, + }; + out.retain(|(n, v)| !n.is_empty() && !v.is_empty()); + out.sort(); + out.dedup(); + (!out.is_empty()).then_some(out) +} + +/// The `[[package]]` tables of a TOML lockfile (`Cargo.lock`, `poetry.lock`, +/// `uv.lock`): each one's `name` and `version`. +fn toml_copies(text: &str) -> Vec<(String, String)> { + let mut out = vec![]; + let mut cur: Option<(String, String)> = None; + let value = |l: &str, key: &str| -> Option { + let rest = l.strip_prefix(key)?.trim_start().strip_prefix('=')?; + Some(rest.trim().trim_matches('"').to_string()) + }; + for line in text.lines() { + let t = line.trim(); + if t.starts_with('[') { + if let Some(c) = cur.take() { + out.push(c); + } + if t == "[[package]]" { + cur = Some((String::new(), String::new())); + } + continue; + } + if let Some(c) = cur.as_mut() { + if let Some(v) = value(t, "name") { + c.0 = v; + } else if let Some(v) = value(t, "version") { + c.1 = v; + } + } + } + out.extend(cur); + out +} + +/// The gems a `Gemfile.lock` resolves: the `name (version)` lines of its +/// `specs:` lists (a dependency's own requirements sit deeper and carry a +/// range, never a single version). +fn gem_copies(text: &str) -> Vec<(String, String)> { + let mut out = vec![]; + for line in text.lines() { + let Some(rest) = line.strip_prefix(" ") else { + continue; + }; + if rest.starts_with(' ') { + continue; + } + let Some((name, ver)) = rest.split_once(" (") else { + continue; + }; + let ver = ver.trim_end_matches(')'); + if ver.chars().next().is_some_and(|c| c.is_ascii_digit()) && !ver.contains(' ') { + out.push((name.to_string(), ver.to_string())); + } + } + out +} + +/// The workspace projects of a lockfile, each with the packages of `asked` +/// (name and a version on the line asked about) that its dependencies bring +/// in: the projects a change to those packages can break. `manifests`: each +/// workspace project's folder (from the lockfile's folder) and its +/// `package.json`; only `yarn.lock`, which does not list its projects, +/// needs them. `None` for a lockfile this can't read. +pub fn lock_projects( + path: &str, + text: &str, + manifests: &[(String, String)], + asked: &[(String, String)], +) -> Option> { + let g = graph_of(path, text, manifests)?; + if g.projects.is_empty() { + return None; + } + let mut out = vec![]; + for (pi, (dir, _)) in g.projects.iter().enumerate() { + // This project and every workspace project it depends on. + let mut mine = vec![pi]; + let mut i = 0; + while i < mine.len() { + for (from, to) in &g.project_links { + if *from == mine[i] && !mine.contains(to) { + mine.push(*to); + } + } + i += 1; + } + let mut seen: HashSet = HashSet::new(); + let mut queue: VecDeque = VecDeque::new(); + for p in &mine { + for n in &g.projects[*p].1 { + if seen.insert(*n) { + queue.push_back(*n); + } + } + } + while let Some(n) = queue.pop_front() { + for to in &g.edges[n] { + if seen.insert(*to) { + queue.push_back(*to); + } + } + } + let mut uses: Vec = seen + .iter() + .map(|n| &g.nodes[*n]) + .filter(|(name, ver)| { + asked.iter().any(|(an, av)| { + an == name + && !ver.is_empty() + && crate::security_fixes::version_line(av) + == crate::security_fixes::version_line(ver) + }) + }) + .map(|(name, ver)| format!("{name}@{ver}")) + .collect(); + uses.sort(); + uses.dedup(); + out.push(LockProject { + dir: dir.clone(), + uses, + }); + } + out.sort_by(|a, b| a.dir.cmp(&b.dir)); + Some(out) } impl Graph { @@ -1454,13 +1640,18 @@ fn pnpm_graph(text: &str) -> Option { } } // The direct dependencies: each importer's, or the top level's. - let mut importers: Vec<&serde_yaml::Value> = vec![]; + let mut importers: Vec<(String, &serde_yaml::Value)> = vec![]; if let Some(m) = doc.get("importers") { - importers.extend(yaml_map(m).into_iter().map(|(_, v)| v)); + importers.extend(yaml_map(m)); } else { - importers.push(&doc); - } - for imp in importers { + importers.push((".".to_string(), &doc)); + } + // (project, the folder of the workspace project it links to) + let mut links: Vec<(usize, String)> = vec![]; + for (key, imp) in importers { + let dir = join_rel("", &key); + let pi = g.projects.len(); + g.projects.push((dir.clone(), vec![])); for field in ["dependencies", "devDependencies", "optionalDependencies"] { let Some(m) = imp.get(field) else { continue }; for (dn, dv) in yaml_map(m) { @@ -1469,14 +1660,24 @@ fn pnpm_graph(text: &str) -> Option { other => yaml_str(other), }; let Some(value) = value else { continue }; + if let Some(to) = value.strip_prefix("link:") { + links.push((pi, join_rel(&dir, to))); + continue; + } if let Some(t) = pnpm_target(&dn, &value, v5) { if let Some(n) = node(&mut g, &t) { g.roots.push((dn.clone(), n)); + g.projects[pi].1.push(n); } } } } } + for (from, dir) in links { + if let Some(to) = g.projects.iter().position(|(d, _)| *d == dir) { + g.project_links.push((from, to)); + } + } Some(g) } @@ -1521,18 +1722,92 @@ fn npm_graph(text: &str) -> Option { } } } + // The workspace projects: every location outside `node_modules`. A + // dependency that resolves to a link is another workspace project. + let project_locs: Vec<&str> = packages + .keys() + .map(String::as_str) + .filter(|l| !l.contains("node_modules/")) + .collect(); + let mut loc_of: Vec<&str> = vec![""; g.nodes.len()]; + for (loc, i) in &index { + loc_of[*i] = loc; + } + for loc in &project_locs { + let pi = g.projects.len(); + g.projects.push((loc.to_string(), vec![])); + for to in g.edges[index[*loc]].clone() { + match packages.get(loc_of[to]) { + Some(p) if p["link"].as_bool() == Some(true) => { + let dir = p["resolved"].as_str().unwrap_or("").trim_matches('/'); + if let Some(at) = project_locs.iter().position(|l| *l == dir) { + g.project_links.push((pi, at)); + } + } + _ => g.projects[pi].1.push(to), + } + } + } Some(g) } +fn yarn_spec(name: &str, range: &str) -> String { + let r = range.trim().trim_matches('"'); + let r = r.strip_prefix("npm:").unwrap_or(r); + format!("{name}@{r}") +} + fn yarn_graph(text: &str, direct_names: &[String]) -> Option { + let (mut g, _) = yarn_parse(text)?; + // The project's own dependencies: every copy of a name it lists. + for d in direct_names { + for (i, (n, _)) in g.nodes.iter().enumerate() { + if n == d { + g.roots.push((d.clone(), i)); + } + } + } + Some(g) +} + +/// A `yarn.lock` with its workspace projects, which the lockfile itself +/// does not list: each project's `package.json` names what it depends on, +/// and the lockfile says which copy each range resolves to. +fn yarn_projects(text: &str, manifests: &[(String, String)]) -> Option { + let (mut g, spec_to) = yarn_parse(text)?; + let parsed: Vec<(String, Value)> = manifests + .iter() + .filter_map(|(dir, t)| Some((join_rel("", dir), serde_json::from_str::(t).ok()?))) + .collect(); + for (dir, _) in &parsed { + g.projects.push((dir.clone(), vec![])); + } + for (pi, (_, m)) in parsed.iter().enumerate() { + for field in ["dependencies", "devDependencies", "optionalDependencies"] { + for (dep, range) in m[field].as_object().into_iter().flatten() { + let range = range.as_str().unwrap_or(""); + if let Some(n) = spec_to.get(&yarn_spec(dep, range)) { + g.roots.push((dep.clone(), *n)); + g.projects[pi].1.push(*n); + } else if let Some(to) = parsed + .iter() + .position(|(_, o)| o["name"].as_str() == Some(dep.as_str())) + { + g.project_links.push((pi, to)); + } + } + } + } + Some(g) +} + +/// The copies and edges of a `yarn.lock` (classic and berry), and which +/// copy each `name@range` resolves to. +fn yarn_parse(text: &str) -> Option<(Graph, HashMap)> { let mut g = Graph::default(); let mut spec_to: HashMap = HashMap::new(); let mut pending: Vec<(usize, String, String)> = vec![]; - let norm = |name: &str, range: &str| { - let r = range.trim().trim_matches('"'); - let r = r.strip_prefix("npm:").unwrap_or(r); - format!("{name}@{r}") - }; + let norm = yarn_spec; let split_spec = |spec: &str| -> Option<(String, String)> { let s = spec.trim().trim_matches('"'); let at = s[1..].find('@')? + 1; @@ -1595,18 +1870,10 @@ fn yarn_graph(text: &str, direct_names: &[String]) -> Option { g.edges[from].push(*to); } } - // The project's own dependencies: every copy of a name it lists. - for d in direct_names { - for (i, (n, _)) in g.nodes.iter().enumerate() { - if n == d { - g.roots.push((d.clone(), i)); - } - } - } if g.nodes.is_empty() { return None; } - Some(g) + Some((g, spec_to)) } /// The names a `package.json` lists as dependencies. @@ -1968,6 +2235,144 @@ snapshots: assert_eq!(a.parents.iter().cloned().collect::>(), ["a"]); } + // ── The workspace projects a changed package can break ───────────── + + fn asked() -> Vec<(String, String)> { + vec![ + ("glob-walk".to_string(), "2.3.1".to_string()), + ("path-match".to_string(), "3.1.2".to_string()), + ] + } + + fn uses(projects: &[LockProject]) -> Vec<(&str, Vec<&str>)> { + projects + .iter() + .map(|p| (p.dir.as_str(), p.uses.iter().map(String::as_str).collect())) + .collect() + } + + /// A site, a studio no CI job builds, a shared package the site links, + /// and a docs project that takes neither changed package. + #[test] + fn pnpm_workspace_projects_that_consume_a_changed_line_are_found() { + let lock = "lockfileVersion: '9.0'\nimporters:\n .:\n devDependencies:\n turbo:\n specifier: ^2.0.0\n version: 2.0.1\n apps/web:\n dependencies:\n '@acme/ui':\n specifier: workspace:*\n version: link:../../packages/ui\n next-ish:\n specifier: ^14.0.0\n version: 14.1.0\n apps/studio:\n dependencies:\n studio-kit:\n specifier: ^3.0.0\n version: 3.2.0\n apps/docs:\n dependencies:\n glob-walk:\n specifier: ^4.0.0\n version: 4.0.1\n packages/ui:\n dependencies:\n path-match:\n specifier: ^3.1.0\n version: 3.1.2\npackages:\n glob-walk@2.3.1: {}\n glob-walk@4.0.1: {}\n path-match@3.1.2: {}\n next-ish@14.1.0: {}\n studio-kit@3.2.0: {}\n studio-cli@1.0.0: {}\n turbo@2.0.1: {}\nsnapshots:\n glob-walk@2.3.1: {}\n glob-walk@4.0.1: {}\n path-match@3.1.2: {}\n next-ish@14.1.0: {}\n studio-kit@3.2.0:\n dependencies:\n studio-cli: 1.0.0\n studio-cli@1.0.0:\n dependencies:\n glob-walk: 2.3.1\n turbo@2.0.1: {}\n"; + let projects = lock_projects("pnpm-lock.yaml", lock, &[], &asked()).unwrap(); + assert_eq!( + uses(&projects), + vec![ + ("", vec![]), + // Two levels down, through the studio's tooling. + ("apps/docs", vec![]), + ("apps/studio", vec!["glob-walk@2.3.1"]), + // Through the workspace package it links. + ("apps/web", vec!["path-match@3.1.2"]), + ("packages/ui", vec!["path-match@3.1.2"]), + ], + "the docs project has glob-walk on the 4 line only, which did not change" + ); + let copies = lock_copies("pnpm-lock.yaml", lock).unwrap(); + assert!(copies.contains(&("glob-walk".into(), "2.3.1".into()))); + assert!(copies.contains(&("glob-walk".into(), "4.0.1".into()))); + } + + #[test] + fn npm_workspace_projects_that_consume_a_changed_line_are_found() { + let lock = r#"{"lockfileVersion":3,"packages":{ + "":{"name":"site","workspaces":["apps/*","packages/*"],"devDependencies":{"turbo":"^2.0.0"}}, + "apps/web":{"name":"web","dependencies":{"@acme/ui":"*","next-ish":"^14.0.0"}}, + "apps/studio":{"name":"studio","dependencies":{"studio-kit":"^3.0.0"}}, + "packages/ui":{"name":"@acme/ui","dependencies":{"path-match":"^3.1.0"}}, + "node_modules/@acme/ui":{"resolved":"packages/ui","link":true}, + "node_modules/web":{"resolved":"apps/web","link":true}, + "node_modules/studio":{"resolved":"apps/studio","link":true}, + "node_modules/turbo":{"version":"2.0.1","dev":true}, + "node_modules/next-ish":{"version":"14.1.0"}, + "node_modules/path-match":{"version":"3.1.2"}, + "node_modules/studio-kit":{"version":"3.2.0","dependencies":{"glob-walk":"^2.3.0"}}, + "node_modules/glob-walk":{"version":"4.0.1"}, + "node_modules/studio-kit/node_modules/glob-walk":{"version":"2.3.1"}}}"#; + let projects = lock_projects("package-lock.json", lock, &[], &asked()).unwrap(); + assert_eq!( + uses(&projects), + vec![ + ("", vec![]), + ("apps/studio", vec!["glob-walk@2.3.1"]), + ("apps/web", vec!["path-match@3.1.2"]), + ("packages/ui", vec!["path-match@3.1.2"]), + ] + ); + let copies = lock_copies("package-lock.json", lock).unwrap(); + assert!(copies.contains(&("glob-walk".into(), "2.3.1".into()))); + assert!(!copies.iter().any(|(n, _)| n == "web"), "a link is no copy"); + } + + #[test] + fn yarn_workspace_projects_are_read_from_their_manifests() { + let manifests = vec![ + ( + "".to_string(), + r#"{"name":"site","private":true,"workspaces":["apps/*","packages/*"]}"# + .to_string(), + ), + ( + "apps/web".to_string(), + r#"{"name":"web","dependencies":{"@acme/ui":"*","next-ish":"^14.0.0"}}"# + .to_string(), + ), + ( + "apps/studio".to_string(), + r#"{"name":"studio","devDependencies":{"studio-kit":"^3.0.0"}}"#.to_string(), + ), + ( + "packages/ui".to_string(), + r#"{"name":"@acme/ui","dependencies":{"path-match":"^3.1.0"}}"#.to_string(), + ), + ]; + let classic = "# yarn lockfile v1\n\nglob-walk@^2.3.0:\n version \"2.3.1\"\n\nglob-walk@^4.0.0:\n version \"4.0.1\"\n\nnext-ish@^14.0.0:\n version \"14.1.0\"\n\npath-match@^3.1.0:\n version \"3.1.2\"\n\nstudio-kit@^3.0.0:\n version \"3.2.0\"\n dependencies:\n glob-walk \"^2.3.0\"\n"; + let berry = "__metadata:\n version: 8\n\n\"glob-walk@npm:^2.3.0\":\n version: 2.3.1\n resolution: \"glob-walk@npm:2.3.1\"\n\n\"next-ish@npm:^14.0.0\":\n version: 14.1.0\n resolution: \"next-ish@npm:14.1.0\"\n\n\"path-match@npm:^3.1.0\":\n version: 3.1.2\n resolution: \"path-match@npm:3.1.2\"\n\n\"studio-kit@npm:^3.0.0\":\n version: 3.2.0\n resolution: \"studio-kit@npm:3.2.0\"\n dependencies:\n glob-walk: \"npm:^2.3.0\"\n"; + for lock in [classic, berry] { + let projects = lock_projects("yarn.lock", lock, &manifests, &asked()).unwrap(); + assert_eq!( + uses(&projects), + vec![ + ("", vec![]), + ("apps/studio", vec!["glob-walk@2.3.1"]), + ("apps/web", vec!["path-match@3.1.2"]), + ("packages/ui", vec!["path-match@3.1.2"]), + ], + "{lock}" + ); + } + // Without its projects' manifests a yarn.lock names no project. + assert_eq!(lock_projects("yarn.lock", classic, &[], &asked()), None); + assert_eq!(lock_projects("Cargo.lock", "", &[], &asked()), None); + } + + #[test] + fn the_copies_of_other_lockfiles_are_read_or_said_unreadable() { + let cargo = "version = 3\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.200\"\nsource = \"registry\"\n\n[[package]]\nname = \"time\"\nversion = \"0.3.36\"\n"; + assert_eq!( + lock_copies("Cargo.lock", cargo).unwrap(), + vec![ + ("serde".to_string(), "1.0.200".to_string()), + ("time".to_string(), "0.3.36".to_string()) + ] + ); + let gems = "GEM\n remote: https://rubygems.org/\n specs:\n rack (2.2.8)\n sinatra (3.1.0)\n rack (~> 2.2, >= 2.2.4)\n\nDEPENDENCIES\n sinatra\n"; + assert_eq!( + lock_copies("Gemfile.lock", gems).unwrap(), + vec![ + ("rack".to_string(), "2.2.8".to_string()), + ("sinatra".to_string(), "3.1.0".to_string()) + ] + ); + assert_eq!( + lock_copies("go.sum", "example.com/x v1.0.0 h1:abc=\n"), + None + ); + assert_eq!(lock_copies("pnpm-lock.yaml", "not: [a lockfile"), None); + } + // ── Tiers move with what is learned ─────────────────────────────── use crate::security_fixes::{ diff --git a/services/common/src/runtime_proof.rs b/services/common/src/runtime_proof.rs index d0d5306df..c6fe045ec 100644 --- a/services/common/src/runtime_proof.rs +++ b/services/common/src/runtime_proof.rs @@ -29,6 +29,16 @@ //! - [`report`] writes what ran and what it came to. A part that did not run //! says so with the reason; nothing is claimed that did not run. //! +//! - Every project the bumps can break is built, not only the one with the +//! most bumps. In a workspace, [`add_projects`] adds the build of each +//! project whose dependencies bring in a changed package line (read from +//! the lockfile, `reachability::lock_projects`), whether or not any CI job +//! builds it; [`add_lockfile`] adds the project of every other lockfile +//! the run bumped. A project that is not built, or whose build fails on +//! the base branch too, is named as not proven with the reason +//! ([`unproven_projects`]); a project build that passes on the base +//! branch and fails with the bumps is blamed like any other. +//! //! Everything here is pure; the sandbox run is the worker's //! (`worker::passes::dep_fix`). @@ -49,8 +59,11 @@ pub const PORT: u16 = 38411; pub const COMMON_PORTS: &[u16] = &[3000, 8080, 8000, 5000, 4173, 5173, 4321, 4200]; /// How long the start command gets to answer, in two-second polls. pub const START_POLLS: u32 = 45; -/// Build commands one proof runs. +/// Build commands one proof runs for the main project. pub const MAX_BUILDS: usize = 3; +/// Builds of other affected projects one proof runs beside them: the whole +/// proof is one sandbox run inside one step's time. +pub const MAX_PROJECT_BUILDS: usize = 5; /// The paths requested once the application answers: its root page and the /// health endpoints servers commonly have. pub const PATHS: &[&str] = &["/", "/healthz", "/health", "/api/health"]; @@ -152,6 +165,9 @@ pub struct ProofCmd { pub dir: String, /// Where the command was found, in words (`` `ci.yml`, job `build` ``). pub source: String, + /// The build of another affected project: it is judged on its own and + /// never keeps the main project's start from running. + pub extra: bool, } /// What a proof runs, found once per run. @@ -170,6 +186,246 @@ pub struct ProofPlan { /// Other lockfiles the run bumped packages in, whose projects this /// proof does not build. pub not_covered: Vec, + /// The other projects the bumps can break: each workspace project that + /// takes a changed package line, and the project of each other lockfile + /// with bumps. Each is built, or named as not proven with why. + pub projects: Vec, + /// Why the workspace projects that take the changed packages could not + /// be worked out; empty when they were (or the project is no workspace). + pub projects_unknown: String, +} + +/// One project the bumps can break, beside the main one. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ProjectProof { + /// Its folder from the repository root. + pub dir: String, + /// Why it is affected, in words (`takes glob-walk@2.3.1`). + pub because: String, + /// Its builds, as indices into the plan's `builds`. + pub builds: Vec, + /// Why it is not built here; empty when it is. + pub not_built: String, +} + +/// A workspace project whose dependencies bring in a changed package line. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct AffectedProject { + /// Its folder from the repository root. + pub dir: String, + /// The changed packages it installs, as `name@version`. + pub uses: Vec, + /// Its scripts manifest (`package.json`), when it has one. + pub manifest: Option, +} + +fn because(uses: &[String]) -> String { + let shown: Vec = uses.iter().take(4).map(|u| format!("`{u}`")).collect(); + format!( + "takes {}{}", + shown.join(", "), + if uses.len() > shown.len() { + format!(" and {} more changed packages", uses.len() - shown.len()) + } else { + String::new() + } + ) +} + +fn project_builds(plan: &ProofPlan) -> usize { + plan.projects.iter().map(|p| p.builds.len()).sum() +} + +/// Adds to `plan` (the proof of `lockfile`'s project) every workspace +/// project the bumps can break: a project a build of the plan already runs +/// in is covered by it; one whose manifest declares a `build` script gets +/// that build, whether or not CI builds it; one that declares none is named +/// as not built. The lockfile's own folder is the plan's main project. +pub fn add_projects(plan: &mut ProofPlan, lockfile: &str, projects: &[AffectedProject]) { + let Some(m) = manager_of(lockfile) else { + return; + }; + for p in projects { + if p.dir == plan.dir || plan.projects.iter().any(|x| x.dir == p.dir) { + continue; + } + let mut proof = ProjectProof { + dir: p.dir.clone(), + because: because(&p.uses), + ..Default::default() + }; + let covered: Vec = plan + .builds + .iter() + .enumerate() + .filter(|(_, b)| b.dir == p.dir) + .map(|(i, _)| i) + .collect(); + let scripted = p + .manifest + .as_deref() + .and_then(|t| script_of(t, "build")) + .is_some(); + if !covered.is_empty() { + proof.builds = covered; + } else if !is_plain_path(&p.dir) { + proof.not_built = "its folder can't be named in a sandbox command".into(); + } else if let (true, Some(run), Some(name)) = (scripted, m.run_script, m.scripts_in) { + if project_builds(plan) >= MAX_PROJECT_BUILDS { + proof.not_built = format!( + "one proof builds at most {MAX_PROJECT_BUILDS} projects beside the main one" + ); + } else { + plan.builds.push(ProofCmd { + cmd: format!("{run} build"), + dir: p.dir.clone(), + source: format!("the `build` script of `{}`", under(&p.dir, name)), + extra: true, + }); + proof.builds = vec![plan.builds.len() - 1]; + } + } else { + proof.not_built = match m.scripts_in { + Some(name) => format!("`{}` declares no `build` script", under(&p.dir, name)), + None => format!("{} has no build per project", m.name), + }; + } + plan.projects.push(proof); + } +} + +/// Adds to `plan` the project of another lockfile the run bumped packages +/// in, as `other` (its own [`discover`]) found it: each of its builds runs +/// after that project's own install. A project with no build is named as +/// not built, with why. +pub fn add_lockfile(plan: &mut ProofPlan, lockfile: &str, bumps: usize, other: &ProofPlan) { + let mut proof = ProjectProof { + dir: other.dir.clone(), + because: format!("has its own lockfile `{lockfile}` with {bumps} of the bumps"), + ..Default::default() + }; + if other.builds.is_empty() { + proof.not_built = other.no_build.clone(); + } else if project_builds(plan) + other.builds.len() > MAX_PROJECT_BUILDS { + proof.not_built = + format!("one proof builds at most {MAX_PROJECT_BUILDS} projects beside the main one"); + } else { + for b in &other.builds { + // The project's own install first, in the lockfile's folder. + let install = if b.dir == other.dir { + other.install.clone() + } else { + format!("( cd \"$CH_ROOT\" && {}{} )", cd(&other.dir), other.install) + }; + plan.builds.push(ProofCmd { + cmd: format!("{install} && {}", b.cmd), + dir: b.dir.clone(), + source: format!("{}, after the install of `{lockfile}`", b.source), + extra: true, + }); + proof.builds.push(plan.builds.len() - 1); + } + } + plan.projects.push(proof); +} + +/// The workspace folders a root `package.json` names (`workspaces`, as a +/// list or under `packages`), among the folders of `tree` that hold a +/// `package.json`. `root`: the folder of the root manifest. Folders are +/// returned from `root`. `*` matches one folder name, `**` any depth. +pub fn workspace_dirs(root_manifest: &str, tree: &[String], root: &str) -> Vec { + let Ok(v) = serde_json::from_str::(root_manifest) else { + return vec![]; + }; + let ws = &v["workspaces"]; + let globs: Vec<&str> = ws + .as_array() + .or_else(|| ws["packages"].as_array()) + .map(|a| a.iter().filter_map(|g| g.as_str()).collect()) + .unwrap_or_default(); + fn matches(glob: &[&str], dir: &[&str]) -> bool { + match (glob.first(), dir.first()) { + (None, None) => true, + (Some(&"**"), _) => { + matches(&glob[1..], dir) || (!dir.is_empty() && matches(glob, &dir[1..])) + } + (Some(g), Some(d)) => { + let one = match g.split_once('*') { + Some((pre, post)) => { + d.len() >= pre.len() + post.len() && d.starts_with(pre) && d.ends_with(post) + } + None => g == d, + }; + one && matches(&glob[1..], &dir[1..]) + } + _ => false, + } + } + let prefix = if root.is_empty() { + String::new() + } else { + format!("{root}/") + }; + let mut out: Vec = tree + .iter() + .filter_map(|p| p.strip_prefix(prefix.as_str())) + .filter_map(|p| p.strip_suffix("/package.json")) + .filter(|d| !d.split('/').any(|s| s == "node_modules")) + .filter(|d| { + let segs: Vec<&str> = d.split('/').collect(); + globs.iter().any(|g| { + let g = g.trim_start_matches("./").trim_end_matches('/'); + !g.starts_with('!') && matches(&g.split('/').collect::>(), &segs) + }) + }) + .map(String::from) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// The projects the proof does not prove, each with why: one that is not +/// built, one whose build gave no result, and one whose build fails on the +/// base branch too (the sandbox has no secrets or services, so that says +/// nothing about the bumps). A project whose build passes with the bumps, +/// or fails only with them, is not here: the first is proven, the second +/// is blamed ([`blamed`]). +pub fn unproven_projects( + plan: &ProofPlan, + base: Option<&ProofResult>, + head: Option<&ProofResult>, +) -> Vec<(String, String)> { + let code = |r: Option<&ProofResult>, i: usize| -> Option { + r.filter(|r| r.ran) + .and_then(|r| r.builds.get(i).copied().flatten()) + }; + let mut out = vec![]; + for p in &plan.projects { + if !p.not_built.is_empty() { + out.push((p.dir.clone(), p.not_built.clone())); + continue; + } + let why = p.builds.iter().find_map(|&i| { + let cmd = plan.builds.get(i).map(|b| b.cmd.as_str()).unwrap_or(""); + match (code(base, i), code(head, i)) { + (_, Some(0)) => None, + (Some(0), Some(_)) => None, + (Some(b), Some(_)) => Some(format!( + "its build `{cmd}` fails on the base branch too in the sandbox (exit {b}), which has no secrets or services, so the result says nothing about the bumps" + )), + (None, Some(c)) => Some(format!( + "its build `{cmd}` fails (exit {c}) and did not run on the base branch, so the bumps can't be told from what was already failing" + )), + (_, None) => Some(format!("its build `{cmd}` gave no result in the sandbox")), + } + }); + if let Some(why) = why { + out.push((p.dir.clone(), why)); + } + } + out } impl ProofPlan { @@ -285,6 +541,7 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P } else { format!("the CI workflow `{}`, job `{}`", c.workflow, c.job) }, + extra: false, }); if plan.builds.len() >= MAX_BUILDS { break; @@ -297,6 +554,7 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P cmd: format!("{run} build"), dir: dir.clone(), source: format!("the `build` script of `{}`", under(&dir, name)), + extra: false, }), _ => None, }; @@ -304,6 +562,7 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P cmd: b.to_string(), dir: dir.clone(), source: format!("{}'s own build", m.name), + extra: false, }); match scripted.or(own) { Some(b) => plan.builds.push(b), @@ -328,11 +587,13 @@ pub fn discover(lockfile: &str, ci: &[CiBuild], files: &[(String, String)]) -> P cmd, dir: dir.clone(), source: format!("the `web` entry of `{}`", under(&dir, "Procfile")), + extra: false, }), (None, Some(run), Some(name), Some(text)) => script_of(text, "start").map(|_| ProofCmd { cmd: format!("{run} start"), dir: dir.clone(), source: format!("the `start` script of `{}`", under(&dir, name)), + extra: false, }), _ => None, }; @@ -364,6 +625,9 @@ fn cd(dir: &str) -> String { /// exits 0; the verdict is read from its marker lines. pub fn script(plan: &ProofPlan) -> String { let mut s = String::new(); + if plan.builds.iter().any(|b| b.cmd.contains("$CH_ROOT")) { + s.push_str("export CH_ROOT=\"$(pwd)\"\n"); + } s.push_str(&format!( "( {}{} ) > /tmp/coderhelm-proof-install.log 2>&1; ch_install=$?\n", cd(&plan.dir), @@ -375,10 +639,11 @@ pub fn script(plan: &ProofPlan) -> String { let n = i + 1; s.push_str(&format!( "if [ $ch_install -eq 0 ]; then ( {}{} ) > /tmp/coderhelm-proof-build-{n}.log 2>&1; ch_b{n}=$?; \ - if [ $ch_b{n} -ne 0 ]; then ch_built=1; echo \"--- build {n} failed (exit $ch_b{n}), last output ---\"; tail -c 1200 /tmp/coderhelm-proof-build-{n}.log; echo; fi; \ + if [ $ch_b{n} -ne 0 ]; then {gate}echo \"--- build {n} failed (exit $ch_b{n}), last output ---\"; tail -c 1200 /tmp/coderhelm-proof-build-{n}.log; echo; fi; \ echo \"{STEP_MARK} build {n} $ch_b{n}\"; fi\n", cd(&b.dir), - b.cmd + b.cmd, + gate = if b.extra { "" } else { "ch_built=1; " }, )); } s.push_str("ch_start=skipped; ch_port=0\n"); @@ -623,6 +888,38 @@ pub fn report(plan: &ProofPlan, base: Option<&ProofResult>, head: Option<&ProofR .join(", ") )); } + if !plan.projects_unknown.is_empty() { + s.push_str(&format!( + "- Which workspace projects take the changed packages is not known ({}), so only the builds below were run; a project they don't cover is not proven here.\n", + plan.projects_unknown + )); + } + for p in &plan.projects { + if p.not_built.is_empty() { + s.push_str(&format!( + "- Project `{}` {}: built here ({}).\n", + p.dir, + p.because, + p.builds + .iter() + .filter_map(|&i| plan.builds.get(i)) + .map(|b| format!("`{}`", b.cmd)) + .collect::>() + .join(", ") + )); + } + } + for (dir, why) in unproven_projects(plan, base, head) { + let because = plan + .projects + .iter() + .find(|p| p.dir == dir) + .map(|p| p.because.as_str()) + .unwrap_or(""); + s.push_str(&format!( + "- Project `{dir}` {because}: **not proven here**: {why}. CI on this pull request, or a build by hand, is the check.\n" + )); + } let head = match head { Some(h) if h.ran => h, other => { @@ -751,6 +1048,239 @@ mod tests { )] } + // ── Every project the bumps can break ────────────────────────────── + + fn affected(dir: &str, uses: &[&str], scripts: Option<&str>) -> AffectedProject { + AffectedProject { + dir: dir.into(), + uses: uses.iter().map(|u| u.to_string()).collect(), + manifest: scripts.map(|s| format!("{{\"scripts\":{s}}}")), + } + } + + /// The site is what CI builds; the studio has a build script and no CI + /// job; the shared package declares no build. + fn workspace_plan() -> ProofPlan { + let mut plan = discover( + "pnpm-lock.yaml", + &[ci("pnpm --filter web build", Some("apps/web"), true)], + &pkg(r#"{"dev":"turbo dev"}"#), + ); + add_projects( + &mut plan, + "pnpm-lock.yaml", + &[ + affected( + "apps/web", + &["path-match@3.1.2"], + Some(r#"{"build":"next build"}"#), + ), + affected( + "apps/studio", + &["glob-walk@2.3.1"], + Some(r#"{"build":"studio build"}"#), + ), + affected( + "packages/ui", + &["path-match@3.1.2"], + Some(r#"{"lint":"eslint ."}"#), + ), + ], + ); + plan + } + + #[test] + fn a_project_no_ci_job_builds_is_built_when_its_manifest_declares_a_build() { + let plan = workspace_plan(); + let cmds: Vec<(&str, &str)> = plan + .builds + .iter() + .map(|b| (b.cmd.as_str(), b.dir.as_str())) + .collect(); + assert_eq!( + cmds, + vec![ + ("pnpm --filter web build", "apps/web"), + ("pnpm run build", "apps/studio"), + ] + ); + assert_eq!( + plan.builds[1].source, + "the `build` script of `apps/studio/package.json`" + ); + // The site is covered by the build CI runs in its folder. + assert_eq!(plan.projects[0].builds, vec![0]); + assert_eq!(plan.projects[1].builds, vec![1]); + assert_eq!( + plan.projects[2].not_built, + "`packages/ui/package.json` declares no `build` script" + ); + let sh = script(&plan); + assert!(sh.contains("( cd 'apps/studio' && pnpm run build )")); + // The studio's build failing never keeps the site's start from + // running: only the main project's builds gate it. + let studio = sh.lines().find(|l| l.contains("apps/studio")).unwrap(); + assert!(!studio.contains("ch_built=1"), "{studio}"); + let web = sh.lines().find(|l| l.contains("--filter web")).unwrap(); + assert!(web.contains("ch_built=1"), "{web}"); + } + + #[test] + fn a_project_build_only_the_bumps_break_is_blamed_and_feeds_the_take_out() { + let plan = workspace_plan(); + let base = ProofResult { + ran: true, + builds: vec![Some(0), Some(0)], + start: "skipped".into(), + ..Default::default() + }; + let head = ProofResult { + builds: vec![Some(0), Some(1)], + ..base.clone() + }; + assert_eq!( + blamed(&plan, &base, &head), + vec!["the build `pnpm run build` fails (exit 1)".to_string()] + ); + // Blamed, so not listed as unproven: only the project with no build is. + let open = unproven_projects(&plan, Some(&base), Some(&head)); + assert_eq!(open.len(), 1); + assert_eq!(open[0].0, "packages/ui"); + } + + #[test] + fn a_project_that_cannot_be_built_in_the_sandbox_is_named_as_not_proven() { + let plan = workspace_plan(); + // The studio's build needs a token the sandbox does not have: it + // fails on the base branch too. + let base = ProofResult { + ran: true, + builds: vec![Some(0), Some(1)], + start: "skipped".into(), + ..Default::default() + }; + let head = base.clone(); + assert!( + blamed(&plan, &base, &head).is_empty(), + "never blamed on a bump" + ); + let open = unproven_projects(&plan, Some(&base), Some(&head)); + assert_eq!(open.len(), 2); + assert_eq!(open[0].0, "apps/studio"); + assert!( + open[0].1.contains("fails on the base branch too"), + "{}", + open[0].1 + ); + let r = report(&plan, Some(&base), Some(&head)); + assert!( + r.contains("- Project `apps/studio` takes `glob-walk@2.3.1`: **not proven here**: its build `pnpm run build` fails on the base branch too"), + "{r}" + ); + assert!( + r.contains("- Project `packages/ui` takes `path-match@3.1.2`: **not proven here**: `packages/ui/package.json` declares no `build` script"), + "{r}" + ); + assert!(r.contains("- Project `apps/web` takes `path-match@3.1.2`: built here (`pnpm --filter web build`)."), "{r}"); + // No result at all: every built project is unproven, and said so. + let none = unproven_projects(&plan, Some(&base), None); + assert!(none + .iter() + .any(|(d, w)| d == "apps/web" && w.contains("gave no result"))); + } + + #[test] + fn the_project_of_another_lockfile_is_built_after_its_own_install() { + let mut plan = discover("package-lock.json", &[], &pkg(r#"{"build":"vite build"}"#)); + let studio = discover( + "studio/package-lock.json", + &[], + &[( + "studio/package.json".to_string(), + r#"{"scripts":{"build":"studio build"}}"#.to_string(), + )], + ); + add_lockfile(&mut plan, "studio/package-lock.json", 3, &studio); + let tools = discover("tools/package-lock.json", &[], &[]); + add_lockfile(&mut plan, "tools/package-lock.json", 1, &tools); + assert_eq!(plan.builds.len(), 2); + assert_eq!(plan.builds[1].dir, "studio"); + assert!( + plan.builds[1] + .cmd + .ends_with("npm ci --no-audit --no-fund && npm run build"), + "{}", + plan.builds[1].cmd + ); + assert_eq!( + plan.projects[0].because, + "has its own lockfile `studio/package-lock.json` with 3 of the bumps" + ); + assert!( + plan.projects[1] + .not_built + .contains("`tools/package.json` has no `build` script"), + "{}", + plan.projects[1].not_built + ); + assert!(plan.not_covered.is_empty()); + // The cap is said, never silently dropped. + let mut many = discover("pnpm-lock.yaml", &[], &pkg(r#"{"build":"x"}"#)); + let all: Vec = (0..MAX_PROJECT_BUILDS + 2) + .map(|i| { + affected( + &format!("apps/a{i}"), + &["glob-walk@2.3.1"], + Some(r#"{"build":"x"}"#), + ) + }) + .collect(); + add_projects(&mut many, "pnpm-lock.yaml", &all); + assert_eq!(many.builds.len(), 1 + MAX_PROJECT_BUILDS); + assert_eq!( + many.projects + .iter() + .filter(|p| p.not_built.contains("at most")) + .count(), + 2 + ); + } + + #[test] + fn workspace_folders_are_read_from_the_root_manifest() { + let tree: Vec = [ + "package.json", + "apps/web/package.json", + "apps/studio/package.json", + "apps/web/node_modules/x/package.json", + "packages/ui/package.json", + "packages/deep/inner/package.json", + "tools/release/package.json", + ] + .iter() + .map(|p| p.to_string()) + .collect(); + assert_eq!( + workspace_dirs(r#"{"workspaces":["apps/*","packages/**"]}"#, &tree, ""), + vec![ + "apps/studio", + "apps/web", + "packages/deep/inner", + "packages/ui" + ] + ); + assert_eq!( + workspace_dirs( + r#"{"workspaces":{"packages":["tools/release"]}}"#, + &tree, + "" + ), + vec!["tools/release"] + ); + assert!(workspace_dirs(r#"{"name":"x"}"#, &tree, "").is_empty()); + } + #[test] fn the_build_is_the_one_ci_runs_on_a_pull_request() { let plan = discover( diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index 1bde75999..cb60237be 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -3041,11 +3041,21 @@ fn fmt_num(n: f64) -> String { /// A bundle's table: every package bump with its advisories, reachability /// and due date. pub fn bump_table(unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> String { + bump_table_at(unit, members, None) +} + +/// [`bump_table`] with each Version cell as the head resolves it, when the +/// head was read ([`crate::dep_head`]). +pub fn bump_table_at( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + head: Option<&crate::dep_head::HeadFacts>, +) -> String { let cell = |s: &str| s.replace('|', "\\|").replace('\n', " "); let mut s = String::from( "| Package | Version | Advisories | Reachability | Due |\n| --- | --- | --- | --- | --- |\n", ); - for b in &unit.bumps { + for (i, b) in unit.bumps.iter().enumerate() { let mine: Vec<&Finding> = members .iter() .map(|(f, _)| *f) @@ -3073,11 +3083,9 @@ pub fn bump_table(unit: &FixUnit, members: &[(&Finding, &FindingState)]) -> Stri .unwrap_or_default(); let tier = mine.iter().filter_map(|f| f.tier).min(); s.push_str(&format!( - "| `{}` | {} to {}{} | {} | {} | {}{} |\n", + "| `{}` | {} | {} | {} | {}{} |\n", cell(&b.package), - cell(&b.from), - cell(&b.to), - if b.major { " (major)" } else { "" }, + cell(&version_cell(b, i, head)), cell(&ids.join(", ")), verdict, tier.map(|t| format!("{} ", t.as_str())).unwrap_or_default(), @@ -3152,10 +3160,66 @@ pub fn pr_body_linked( check: &crate::upgrade_notes::WhatToCheck, links: &BodyLinks, ) -> String { - let body = if uses_short_body(unit, members) { - short_body(unit, members, change, check, links) + body_linked(unit, members, change, check, links, None) +} + +/// [`pr_body_linked`] for a pull request that exists or is about to: its +/// table and its first sentences say what the lockfile on the head +/// resolves (`head`, from [`crate::dep_head::resolve`]), never what the run +/// planned. A line that could not be read is shown as a plan and said to be +/// one. +pub fn pr_body_at_head( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, + links: &BodyLinks, + head: &crate::dep_head::HeadFacts, +) -> String { + body_linked(unit, members, change, check, links, Some(head)) +} + +/// The table's Version cell of bump `i`: what the head resolves when it was +/// read, the plan's versions otherwise. +fn version_cell(b: &Bump, i: usize, head: Option<&crate::dep_head::HeadFacts>) -> String { + match head { + Some(h) => h.version_cell(i), + None => format!( + "{} to {}{}", + b.from, + b.to, + if b.major { " (major)" } else { "" } + ), + } +} + +fn body_linked( + unit: &FixUnit, + members: &[(&Finding, &FindingState)], + change: &str, + check: &crate::upgrade_notes::WhatToCheck, + links: &BodyLinks, + head: Option<&crate::dep_head::HeadFacts>, +) -> String { + // Which body is chosen by the plan's size, so it never flips between + // two heads; everything shown comes from the head when it was read. + let short = uses_short_body(unit, members); + let plan = unit; + let at_head = head.map(|h| h.unit_at_head(unit)); + let unit = at_head.as_ref().unwrap_or(unit); + let headline = head.map(|h| h.headline(plan, members)); + let body = if short { + short_body( + unit, + members, + change, + check, + links, + head, + headline.as_deref(), + ) } else { - full_body(unit, members, change, check) + full_body(unit, members, change, check, head, headline.as_deref()) }; let more = if !links.detail.is_empty() { links.detail.as_str() @@ -3173,7 +3237,7 @@ pub fn detail_doc( change: &str, check: &crate::upgrade_notes::WhatToCheck, ) -> String { - let full = full_body(unit, members, change, check); + let full = full_body(unit, members, change, check, None, None); // The description's marker stays in the description only. let full = full.replace(MARKER, ""); format!( @@ -3255,12 +3319,15 @@ fn package_cell(b: &Bump, members: &[(&Finding, &FindingState)], links: &BodyLin /// first, each linked to its finding page), the advisories and evidence /// that matter most, "What to check" for the packages to look at first, /// the rest by tier with counts, Proof and Closes as usual. +#[allow(clippy::too_many_arguments)] fn short_body( unit: &FixUnit, members: &[(&Finding, &FindingState)], change: &str, check: &crate::upgrade_notes::WhatToCheck, links: &BodyLinks, + head: Option<&crate::dep_head::HeadFacts>, + headline: Option<&str>, ) -> String { let mut s = String::new(); let tiers = package_tiers(unit, members); @@ -3290,14 +3357,20 @@ fn short_body( } else { String::new() }; - s.push_str(&format!( - "## Summary\n\nFixes {advisories} advisor{} in {} packages ({majors} major version{}). \ - {}{due}.\n\n{where_all}\n\n", - if advisories == 1 { "y" } else { "ies" }, - unit.bumps.len(), - if majors == 1 { "" } else { "s" }, - top.as_str(), - )); + match headline { + Some(h) => s.push_str(&format!( + "## Summary\n\n{h} {}{due}.\n\n{where_all}\n\n", + top.as_str() + )), + None => s.push_str(&format!( + "## Summary\n\nFixes {advisories} advisor{} in {} packages ({majors} major version{}). \ + {}{due}.\n\n{where_all}\n\n", + if advisories == 1 { "y" } else { "ies" }, + unit.bumps.len(), + if majors == 1 { "" } else { "s" }, + top.as_str(), + )), + } // The table: every bump, most urgent first, ids capped per row. let cell = |s: &str| s.replace('|', "\\|").replace('\n', " "); s.push_str("| Package | Version | Advisories | Reachability | Due |\n| --- | --- | --- | --- | --- |\n"); @@ -3329,11 +3402,9 @@ fn short_body( .map(|d| d.format("%b %-d").to_string()) .unwrap_or_default(); s.push_str(&format!( - "| {} | {} to {}{} | {} | {} | {}{} |\n", + "| {} | {} | {} | {} | {}{} |\n", package_cell(b, members, links), - cell(&b.from), - cell(&b.to), - if b.major { " (major)" } else { "" }, + cell(&version_cell(b, i, head)), cell(&shown_ids), verdict, tiers[i] @@ -3542,13 +3613,7 @@ fn short_body( .take(25) .map(|&i| { let b = &unit.bumps[i]; - format!( - "`{}` {} to {}{}", - b.package, - b.from, - b.to, - if b.major { " (major)" } else { "" } - ) + format!("`{}` {}", b.package, version_cell(b, i, head)) }) .collect(); rest.push_str(&format!( @@ -3676,6 +3741,8 @@ fn full_body( members: &[(&Finding, &FindingState)], change: &str, check: &crate::upgrade_notes::WhatToCheck, + head: Option<&crate::dep_head::HeadFacts>, + headline: Option<&str>, ) -> String { let mut s = String::new(); let top = members @@ -3709,18 +3776,34 @@ fn full_body( ); if unit.bundle { let advisories = primaries(members).len(); - s.push_str(&format!( - "## Summary\n\nFixes {advisories} advisor{} in {} package{}. {when}.\n\n", - if advisories == 1 { "y" } else { "ies" }, - unit.bumps.len(), - if unit.bumps.len() == 1 { "" } else { "s" }, - )); - s.push_str(&bump_table(unit, members)); + match headline { + Some(h) => s.push_str(&format!("## Summary\n\n{h} {when}.\n\n")), + None => s.push_str(&format!( + "## Summary\n\nFixes {advisories} advisor{} in {} package{}. {when}.\n\n", + if advisories == 1 { "y" } else { "ies" }, + unit.bumps.len(), + if unit.bumps.len() == 1 { "" } else { "s" }, + )), + } + s.push_str(&bump_table_at(unit, members, head)); } else { - s.push_str(&format!( - "## Summary\n\nFixes {}. {when}.\n\n", - what.join("; ") - )); + match headline { + // One fix: what it is for, then what the head resolves. + Some(h) => s.push_str(&format!( + "## Summary\n\nFor {}. {h} {when}.\n\n", + what.join("; ") + )), + None => s.push_str(&format!( + "## Summary\n\nFixes {}. {when}.\n\n", + what.join("; ") + )), + } + if let Some(h) = head { + for (i, b) in unit.bumps.iter().enumerate() { + s.push_str(&format!("- `{}` {}\n", b.package, h.version_cell(i))); + } + s.push('\n'); + } } s.push_str("## Advisory\n\n"); for (f, st) in members { @@ -9010,6 +9093,80 @@ mod tests { (unit, fs, check) } + /// The plan called 37 of the bundle's 55 packages major versions. A + /// review round kept each on its line; the description says what the + /// head's lockfile resolves, and where the head can't be read it says + /// so and marks the plan as a plan. + #[test] + fn a_bundles_table_and_headline_come_from_the_head_never_the_plan() { + use crate::dep_head::{resolve, unknown, LockAt}; + let (unit, fs, check) = big_bundle(); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let links = BodyLinks::default(); + let planned = pr_body_linked(&unit, &pairs, "Bumped.", &check, &links); + assert!(planned.contains("(37 major versions)"), "the plan's count"); + let copies = |v: &str| -> Option> { + Some( + unit.bumps + .iter() + .map(|b| (b.package.clone(), v.to_string())) + .collect(), + ) + }; + let lock = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies("1.4.2"), + head: copies("1.4.9"), + why: String::new(), + }; + let head = resolve(&unit, "0123abc4567", &[lock]); + let body = pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let summary = &body[..body.find("## Advisory").unwrap()]; + assert!( + summary.contains("in 55 package version lines (0 cross a major version), read from the lockfile on the head `0123abc`"), + "{summary}" + ); + assert!( + !body.contains("(major)"), + "no line crosses a major on the head" + ); + assert!( + !summary.contains("2.0.1"), + "the plan's target is not what the head installs" + ); + assert!(summary.contains("| 1.4.2 to 1.4.9 |"), "{summary}"); + // Advisories are counted against their patched versions. + let fixed = fs + .iter() + .filter(|(f, _)| head.fixed(&unit, f) == crate::dep_head::Fixed::Yes) + .count(); + assert!( + fixed < fs.len(), + "a finding patched only in 2.0.1 is not fixed at 1.4.9" + ); + assert!(summary.contains("Not fixed on the head:"), "{summary}"); + // Same head, same text. + assert_eq!( + body, + pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head) + ); + // The head could not be read: nothing is counted, the plan is + // shown as a plan. + let blind = unknown(&unit, "`pnpm-lock.yaml` could not be read on the head"); + let body = pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &blind); + let summary = &body[..body.find("## Advisory").unwrap()]; + assert!( + summary.contains("What the head installs is not known"), + "{summary}" + ); + assert!(!summary.contains("Fixes "), "{summary}"); + assert!( + summary.contains("1.4.2 to 2.0.1 planned; not read from the head"), + "{summary}" + ); + assert!(body.chars().count() <= crate::pr_body_fit::GITHUB_BODY_MAX); + } + #[test] fn a_55_package_bundle_fits_and_lists_what_to_look_at_first() { let (unit, fs, check) = big_bundle(); @@ -9018,7 +9175,7 @@ mod tests { "Raised the direct ranges and added overrides for transitive copies. ".repeat(40); // The description before: every advisory, path, piece of evidence // and package note, over GitHub's limit. - let before = full_body(&unit, &pairs, &change, &check); + let before = full_body(&unit, &pairs, &change, &check, None, None); assert!( before.chars().count() > crate::pr_body_fit::GITHUB_BODY_MAX, "{}", diff --git a/services/gateway/src/routes/infra_security.rs b/services/gateway/src/routes/infra_security.rs index c11741dba..1751c5be2 100644 --- a/services/gateway/src/routes/infra_security.rs +++ b/services/gateway/src/routes/infra_security.rs @@ -541,6 +541,79 @@ mod tests { assert_eq!(rv["resources"][0]["findings"][0], "pr"); } + /// What the page reads for a database update: why it is a pull + /// request or a runbook, where the code is and how sure, the whole + /// runbook, and a refusal. + #[test] + fn a_finding_carries_its_decision_location_and_runbook_to_the_page() { + use common::infra_vuln::inventory::{Confidence, Location}; + use common::infra_vuln::matching::{Fix, FixKind, InfraFinding}; + use common::infra_vuln::runbook::{Runbook, Step}; + let now = chrono::Utc::now(); + let f = InfraFinding { + id: "db".into(), + account: "111122223333".into(), + environment: "production".into(), + tier: Some(sec::Tier::P2), + fix: Fix { + kind: Some(FixKind::Runbook), + decision: "This cannot be expressed in code.".into(), + meaning: Some(common::infra_vuln::actions::Meaning::OsUpdate), + advisory_note: "AWS publishes no CVE list for this action.".into(), + order: vec!["2 of 2 pending on this database.".into()], + location: Some(Location { + repo: "acme/infra".into(), + file: "db/main.tf".into(), + how: "terraform_generated_name".into(), + tool: "terraform".into(), + confidence: Confidence::Low, + evidence: vec!["2 other places fit about as well".into()], + candidates: vec!["acme/infra:db/main.tf aws_db_instance.b".into()], + ..Default::default() + }), + runbook: Some(Runbook { + scope: vec!["AWS account 111122223333, Region us-east-1.".into()], + steps: vec![Step { + text: "Schedule it.".into(), + cli: "aws rds apply-pending-maintenance-action".into(), + }], + apply_by: "2026-12-01".into(), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + let mut recs = records::reconcile(&[], vec![f], now); + recs[0].refused = vec!["db/main.tf: `aws_db_instance.a` changes `identifier`".into()]; + let v = findings_view(&recs, vec![], &sec::SecurityConfig::default(), &[], now); + let x = &v["findings"][0]; + assert_eq!(x["environment"], "production"); + assert_eq!(x["fix"]["decision"], "This cannot be expressed in code."); + assert_eq!(x["fix"]["meaning"], "os_update"); + assert_eq!(x["fix"]["location"]["confidence"], "low"); + assert_eq!(x["fix"]["location"]["how"], "terraform_generated_name"); + assert_eq!( + x["fix"]["location"]["candidates"][0], + "acme/infra:db/main.tf aws_db_instance.b" + ); + assert_eq!( + x["fix"]["runbook"]["steps"][0]["cli"], + "aws rds apply-pending-maintenance-action" + ); + assert_eq!(x["fix"]["runbook"]["apply_by"], "2026-12-01"); + assert_eq!(x["fix"]["order"][0], "2 of 2 pending on this database."); + assert_eq!(x["drafted"], false); + assert!(x["refused"][0] + .as_str() + .unwrap() + .contains("changes `identifier`")); + assert!( + x["fix"].get("notes").is_none(), + "nothing is sent that is not there" + ); + } + #[test] fn the_switches_say_what_they_cost_and_the_template_only_receives() { let v = config_view(&records::InfraConfig::default()); diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index dd8b47210..df747d03c 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3795,6 +3795,23 @@ impl GitHubClient { Ok(resp) } + /// Put a pull request back to draft (GraphQL only, like marking ready). + /// The pull request stays open and its branch is untouched. + pub async fn convert_pr_to_draft( + &self, + node_id: &str, + ) -> Result> { + let query = serde_json::json!({ + "query": "mutation($id: ID!) { convertPullRequestToDraft(input: { pullRequestId: $id }) { pullRequest { isDraft } } }", + "variables": { "id": node_id } + }); + let resp = self.post("https://api.github.com/graphql", &query).await?; + if let Some(errors) = resp.get("errors") { + return Err(format!("GraphQL errors: {}", errors).into()); + } + Ok(resp) + } + /// Conversation comments on an issue or PR, oldest first. pub async fn list_issue_comments( &self, diff --git a/services/worker/src/passes/covering.rs b/services/worker/src/passes/covering.rs index f9753e2e3..ef1517173 100644 --- a/services/worker/src/passes/covering.rs +++ b/services/worker/src/passes/covering.rs @@ -532,9 +532,7 @@ impl Cover for GhCover<'_> { } async fn raw_set_body(&self, number: u64, body: &str) -> Result<(), Error> { - self.github - .update_pr_body(self.owner, self.repo, number, body) - .await + crate::passes::description::save(self.github, self.owner, self.repo, number, body).await } } @@ -1235,7 +1233,7 @@ mod tests { assert_eq!(body.matches(".raw_fast_forward(").count(), 1); assert_eq!(body.matches(".raw_set_body(").count(), 1); assert_eq!(body.matches(".fast_forward(self.owner").count(), 1); - assert_eq!(body.matches(".update_pr_body(").count(), 1); + assert_eq!(body.matches("description::save(").count(), 1); let guarded = |name: &str| { let at = body.find(&format!("pub async fn {name}<")).unwrap(); let f = &body[at..]; diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index f3ea8aebe..dcc036bac 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -430,7 +430,11 @@ impl Probe<'_> { /// What the runtime proof of a run runs: the build and start commands of /// the project most of its applied bumps are in, read from the repository's -/// workflows and that project's manifest. +/// workflows and that project's manifest, then the build of every other +/// project the bumps can break: each workspace project whose dependencies +/// bring in a changed package line (read from the lockfile), and the +/// project of every other lockfile the run bumped. A project with no build +/// to run is named as not built, with why. async fn proof_plan(w: &Work<'_>, run: &DepRun) -> rp::ProofPlan { let (o, n, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut by: HashMap<&str, usize> = HashMap::new(); @@ -444,15 +448,141 @@ async fn proof_plan(w: &Work<'_>, run: &DepRun) -> rp::ProofPlan { }; let workflows = checks::read_workflows(w.github, o, n, base).await; let ci = checks::build_commands(&workflows, base); + let mut plan = rp::discover(lockfile, &ci, &proof_files(w, lockfile).await); + if plan.install.is_empty() { + // Not a lockfile CoderHelm builds from: nothing more to add. + plan.not_covered = locks.iter().skip(1).map(|(l, _)| l.to_string()).collect(); + return plan; + } + // The workspace projects that take a changed package line. + let asked: Vec<(String, String)> = run + .applied_bumps() + .iter() + .filter(|b| b.manifest == lockfile) + .map(|b| (b.package.clone(), b.from.clone())) + .collect(); + match affected_projects(w, lockfile, &asked).await { + Ok(projects) => rp::add_projects(&mut plan, lockfile, &projects), + Err(why) => plan.projects_unknown = why, + } + // The projects of the other lockfiles with bumps. + for (other, bumps) in locks.iter().skip(1) { + let found = rp::discover(other, &ci, &proof_files(w, other).await); + rp::add_lockfile(&mut plan, other, *bumps, &found); + } + plan +} + +/// The files [`rp::discover`] reads for a lockfile that exist on the base +/// branch. +async fn proof_files(w: &Work<'_>, lockfile: &str) -> Vec<(String, String)> { + let (o, n, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); let mut files = vec![]; for path in rp::files_to_read(lockfile) { if let Ok(Some(text)) = w.github.read_file_if_exists(o, n, &path, base).await { files.push((path, text)); } } - let mut plan = rp::discover(lockfile, &ci, &files); - plan.not_covered = locks.iter().skip(1).map(|(l, _)| l.to_string()).collect(); - plan + files +} + +/// Workspace manifests one proof reads at most. +const MAX_WORKSPACE_MANIFESTS: usize = 60; + +/// The workspace projects of `lockfile` whose dependencies bring in one of +/// the changed package lines (`asked`: package and the version it had), +/// each with its scripts manifest. `Err` says why they could not be worked +/// out; a lockfile with one project gives none. +async fn affected_projects( + w: &Work<'_>, + lockfile: &str, + asked: &[(String, String)], +) -> Result, String> { + let (o, n, base) = (&w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch); + if !common::reachability::is_lockfile(lockfile) { + // Not a JavaScript workspace lockfile: one project per lockfile. + return Ok(vec![]); + } + let root = lockfile.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + let at = |dir: &str| -> String { + match (root.is_empty(), dir.is_empty()) { + (_, true) => root.to_string(), + (true, false) => dir.to_string(), + (false, false) => format!("{root}/{dir}"), + } + }; + let manifest_path = |dir: &str| -> String { + let d = at(dir); + if d.is_empty() { + "package.json".to_string() + } else { + format!("{d}/package.json") + } + }; + let text = match w.github.read_file_if_exists(o, n, lockfile, base).await { + Ok(Some(t)) => t, + _ => return Err(format!("`{lockfile}` could not be read on the base branch")), + }; + // `yarn.lock` does not list its projects: the root manifest's + // workspaces and each project's manifest do. + let mut manifests: Vec<(String, String)> = vec![]; + if lockfile.ends_with("yarn.lock") { + let Ok(Some(root_manifest)) = w + .github + .read_file_if_exists(o, n, &manifest_path(""), base) + .await + else { + return Err(format!( + "`{}` could not be read to list the workspace", + manifest_path("") + )); + }; + let tree: Vec = match w.github.get_tree(o, n, base).await { + Ok(t) => t.into_iter().map(|e| e.path).collect(), + Err(_) => return Err("the repository's files could not be listed".to_string()), + }; + let dirs = rp::workspace_dirs(&root_manifest, &tree, root); + if dirs.len() > MAX_WORKSPACE_MANIFESTS { + return Err(format!( + "the workspace has {} projects, more than one proof reads", + dirs.len() + )); + } + manifests.push((String::new(), root_manifest)); + for d in dirs { + if let Ok(Some(t)) = w + .github + .read_file_if_exists(o, n, &manifest_path(&d), base) + .await + { + manifests.push((d, t)); + } + } + } + let Some(projects) = common::reachability::lock_projects(lockfile, &text, &manifests, asked) + else { + return Err(format!( + "`{lockfile}` could not be read as a workspace's lockfile" + )); + }; + let mut out = vec![]; + for p in projects.into_iter().filter(|p| !p.uses.is_empty()) { + let manifest = match manifests.iter().find(|(d, _)| *d == p.dir) { + Some((_, t)) => Some(t.clone()), + None => w + .github + .read_file_if_exists(o, n, &manifest_path(&p.dir), base) + .await + .ok() + .flatten(), + }; + out.push(rp::AffectedProject { + dir: at(&p.dir), + uses: p.uses, + manifest, + }); + } + Ok(out) } /// Everything the driver borrows from the run. diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs new file mode 100644 index 000000000..aa442a826 --- /dev/null +++ b/services/worker/src/passes/description.rs @@ -0,0 +1,317 @@ +//! The one place a pull request's description is written from. +//! +//! A dependency run's pull request had the right code after a review round +//! and the wrong description: its table still showed the plan (five packages +//! as major version jumps the final manifest no longer makes), its headline +//! counted advisories nobody had compared with the final lockfile, and the +//! round that fixed the code said it could not edit the description and left +//! the corrections to a person. +//! +//! A description is a function of the head. Three rules keep it one: +//! +//! - [`save`] is the only call of the GitHub client's body write in the +//! pipeline. Every writer (the first description, a section CoderHelm +//! owns, a rewrite) sends its text through it, so no path can write a +//! description this module does not see. A test reads the sources and +//! fails on a call anywhere else. +//! - [`head_moved`] is what every path that moves the head calls (a CI fix, +//! a review fix, feedback, a bump taken out): the description's prose is +//! rewritten from the whole diff, and a dependency pull request's table, +//! headline, "What to check" and Proof are rebuilt from what the lockfile +//! on the head resolves ([`dependency_sections`]). The model is never the +//! source of a version or a count. +//! - A round's account that hands an edit of the description to a person is +//! caught ([`round_account`]): the sentence goes, and the rebuild runs +//! even when the round pushed no code. + +use tracing::warn; + +use crate::agent::provider::ModelProvider; +use crate::clients::github::GitHubClient; +use crate::models::TokenUsage; +use crate::WorkerState; + +type Error = Box; + +/// Writes a pull request's description. The only caller of the client's +/// body write: a sentence that says the description can't be edited, or +/// leaves an edit of it to a person, never reaches a description. +pub async fn save( + github: &GitHubClient, + owner: &str, + repo: &str, + number: u64, + body: &str, +) -> Result<(), Error> { + let body = clean(body); + github.update_pr_body(owner, repo, number, &body).await +} + +/// `body` as [`save`] writes it. +pub fn clean(body: &str) -> std::borrow::Cow<'_, str> { + match common::description_handoff::scrub(body) { + Some(scrubbed) => { + warn!("A description said it could not be edited; that sentence was taken out"); + // The replacement sentence is for a round's account, not for + // the description itself. + std::borrow::Cow::Owned( + scrubbed + .lines() + .filter(|l| { + l.trim().trim_start_matches(['-', '*', '>']).trim() + != common::description_handoff::REBUILT + }) + .map(|l| { + l.replace(common::description_handoff::REBUILT, "") + .trim_end() + .to_string() + }) + .collect::>() + .join("\n"), + ) + } + None => std::borrow::Cow::Borrowed(body), + } +} + +/// The pull request whose head moved. +pub struct Moved<'a> { + pub state: &'a WorkerState, + pub github: &'a GitHubClient, + pub team_id: &'a str, + pub installation_id: u64, + pub owner: &'a str, + pub repo: &'a str, + pub number: u64, + /// The run's ticket: a security ticket's pull request has the sections + /// rebuilt from its lockfiles. + pub ticket_id: &'a str, + pub team_instructions: &'a str, + /// What a person with write access asked to change in the description + /// (empty when nobody asked). + pub requests: &'a [String], +} + +/// The head of an open pull request moved, or a person asked for a change to +/// its description: the description is rebuilt from the branch. Returns +/// what the rewrite changed (see `pr::refresh_description`). +pub async fn head_moved( + m: &Moved<'_>, + provider: &ModelProvider, + usage: &mut TokenUsage, +) -> Option> { + let changed = super::pr::refresh_description( + m.state, + m.github, + (m.team_id, m.installation_id), + m.owner, + m.repo, + m.number, + m.team_instructions, + m.requests, + provider, + usage, + ) + .await; + // After the rewrite, so what the lockfile resolves is the last word on + // every version and count. + dependency_sections( + m.state, + m.github, + m.team_id, + m.owner, + m.repo, + m.number, + m.ticket_id, + ) + .await; + changed +} + +/// A dependency pull request's table, headline, "What to check" and Proof, +/// rebuilt from what the lockfile on its head resolves. Costs no model +/// call. Nothing for any other pull request. +pub async fn dependency_sections( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, + ticket_id: &str, +) { + if !common::security_fixes::is_ticket(ticket_id) { + return; + } + super::security_fixes::rebuild_at_head( + state, + github, + team_id, + &format!("{owner}/{repo}"), + number, + ticket_id, + ) + .await; +} + +/// A round's account, checked: `(the account without any sentence that +/// hands the description to a person, whether there was one)`. A `true` +/// means the description is rebuilt now, whatever the round pushed. +pub fn round_account(account: &str) -> (String, bool) { + match common::description_handoff::scrub(account) { + Some(clean) => (clean, true), + None => (account.to_string(), false), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every source file of the worker, with its path from `src/`. + fn sources() -> Vec<(String, String)> { + fn walk(dir: &std::path::Path, root: &std::path::Path, out: &mut Vec<(String, String)>) { + for e in std::fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, root, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(( + p.strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"), + std::fs::read_to_string(&p).unwrap(), + )); + } + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut out = vec![]; + walk(&root, &root, &mut out); + assert!(out.len() > 100, "the worker's sources were not found"); + out + } + + /// The code of a file: no comment lines, and nothing from its tests on. + fn code(text: &str) -> String { + let end = text.find("#[cfg(test)]").unwrap_or(text.len()); + text[..end] + .lines() + .filter(|l| !l.trim_start().starts_with("//")) + .collect::>() + .join("\n") + } + + /// The guard: a new call site that writes a description some other way + /// fails here. + #[test] + fn the_description_is_written_from_one_place() { + let call = [".update_pr", "_body("].concat(); + let mut calls: Vec = vec![]; + let mut through = 0; + for (path, text) in sources() { + let code = code(&text); + // The client defines the write; it never calls it. + if path != "clients/github.rs" { + for _ in code.matches(&call) { + calls.push(path.clone()); + } + } + // A description sent as a raw request would pass the client's + // method by. + if path != "clients/github.rs" { + for l in code.lines() { + assert!( + !(l.contains("/pulls/") && l.contains(".patch(")), + "{path} patches a pull request itself: {l}" + ); + } + } + through += code.matches("description::save(").count(); + } + assert_eq!( + calls, + vec!["passes/description.rs".to_string()], + "a description is written only through description::save" + ); + assert!(through >= 20, "the writers go through it: {through}"); + // And the client has one method that replaces a description. + let client = include_str!("../clients/github.rs"); + assert_eq!( + client.matches("\n pub async fn update_pr_body(").count(), + 1 + ); + } + + /// Every path that moves a pull request's head rebuilds its + /// description, through this module. + #[test] + fn every_path_that_moves_the_head_rebuilds_the_description() { + let resume = include_str!("resume.rs"); + let round = &resume[resume.find("\nasync fn run_fix_round(").unwrap()..]; + let round = &round[..round[1..].find("\nasync fn ").unwrap()]; + let pushed = round.find("Landed::Pushed { files }").unwrap(); + assert!(round[pushed..].contains("description::head_moved(")); + assert!( + round.contains("description::round_account("), + "a round's account is checked for a handed-off description" + ); + // A bump CI took out. + let revert = &resume[resume.find("\nasync fn revert_dep_commit(").unwrap()..]; + let revert = &revert[..revert[1..].find("\nasync fn ").unwrap_or(revert.len() - 1)]; + assert!(revert.contains("description::dependency_sections(")); + // Feedback from a person or a reviewer. + let feedback = include_str!("feedback.rs"); + assert!(feedback.contains("description::head_moved(")); + assert!(feedback.contains("description::round_account(")); + // Nothing calls the rewrite past this module. + for (path, text) in sources() { + // The incident cases quote the pipeline's source; they call nothing. + if path == "passes/description.rs" + || path == "passes/pr.rs" + || path.starts_with("passes/incidents/") + { + continue; + } + assert!( + !code(&text).contains("pr::refresh_description("), + "{path} rewrites the description past description::head_moved" + ); + } + // The dependency sections come from the head in every writer. + let sec = code(include_str!("security_fixes.rs")); + assert_eq!(sec.matches("sec::pr_body_linked(").count(), 0); + assert!(sec.matches("sec::pr_body_at_head(").count() >= 3); + } + + #[test] + fn a_description_never_says_it_cannot_be_edited() { + let body = "## Summary\n\nKept glob-walk on the 2 line.\n\n## Open items\n- I can't edit the PR description from here.\n- The studio build was not run.\n"; + let out = clean(body); + assert!(!out.contains("can't edit"), "{out}"); + assert!(out.contains("- The studio build was not run."), "{out}"); + assert!(!out.contains(common::description_handoff::REBUILT), "{out}"); + let fine = "## Summary\n\nKept glob-walk on the 2 line.\n"; + assert!(matches!(clean(fine), std::borrow::Cow::Borrowed(_))); + } + + #[test] + fn a_rounds_handoff_becomes_the_rebuild() { + let (account, rebuild) = round_account( + "Scoped the override to the 2 line. I can't edit the PR description from here, so the table still says 4.0.4.", + ); + assert!(rebuild); + assert_eq!( + account, + format!( + "Scoped the override to the 2 line. {}", + common::description_handoff::REBUILT + ) + ); + assert_eq!( + round_account("Scoped the override to the 2 line."), + ("Scoped the override to the 2 line.".to_string(), false) + ); + } +} diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 97e13b26e..4dfae34c8 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -770,10 +770,15 @@ Rules: && github .has_write_access(&msg.repo_owner, &msg.repo_name, msg.trigger_author.trim()) .await; - if !msg.trigger_author.trim().is_empty() { - tools.push(update_description_tool()); - } + // The tool is there in every round: a round with no person behind it + // (CoderHelm's own review, a security follow-up) was told to call a tool + // it did not have, and answered that it could not edit the description. + // There the call asks for the rebuild from the branch. + let person_asked = !msg.trigger_author.trim().is_empty(); + tools.push(update_description_tool()); let mut full_system = system.clone(); + full_system.push_str("\n\n"); + full_system.push_str(common::description_handoff::ROUND_NOTE); // Live systems the team connected for this repo, if any: read-only lookups // so the fix rests on the system's real shape. let live = super::live_sources::LiveSources::load( @@ -968,7 +973,7 @@ Rules: branch: &feedback_round.wip_branch, base_branch: &base, files_modified: std::sync::Mutex::new(false), - description: DescriptionRequests::new(may_edit_description), + description: DescriptionRequests::for_round(may_edit_description, person_asked), scope_guard, history: Some(&history), graphs: Some(&graphs), @@ -1399,24 +1404,75 @@ Rules: // with no code change. What changed goes on the reply. // The round's changes landed above, as one commit in one push. let asked = executor.description.taken(); - let description_note = if fix_pushed || !asked.is_empty() { - let changed = super::pr::refresh_description( + // A sentence the round wrote into a file that says a check passes + // stands only on a recorded result: here, the round's own run of the + // full test suite. Before the description is rebuilt from the branch. + if fix_pushed { + let recorded = super::proof::RunEvidence { + sandbox: super::proof::SandboxRecord { + passed: if suite_passed(&evidence_lines) { + vec![super::checks::CheckKind::Tests] + } else { + vec![] + }, + ..Default::default() + }, + ..Default::default() + }; + let removed = super::file_claims::settle( state, + &run_ticket_message(&msg, &ticket, base.clone()), &github, - (&msg.team_id, msg.installation_id), - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - &team_instructions, - &asked, - &provider, - &mut usage, + &branch, + &recorded, ) .await; - description_reply(&asked, changed.as_deref()) - } else { - String::new() - }; + if !removed.is_empty() { + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &super::file_claims::note(&removed), + ) + .await; + } + } + // A reply that says the description can't be edited, or leaves an edit + // of it to a person, loses that sentence; the rebuild then runs whether + // or not code was pushed. + let (response, handed_off) = super::description::round_account(&response); + if handed_off { + warn!(run_id = %msg.run_id, "A feedback round handed the description to a person; rebuilding it from the branch"); + } + let description_note = + if fix_pushed || !asked.is_empty() || handed_off || executor.description.wants_rebuild() { + let changed = super::description::head_moved( + &super::description::Moved { + state, + github: &github, + team_id: &msg.team_id, + installation_id: msg.installation_id, + owner: &msg.repo_owner, + repo: &msg.repo_name, + number: msg.pr_number, + // A security follow-up names its ticket; any other round's + // ticket is the run's. + ticket_id: if msg.security_ticket.is_empty() { + &ticket.0 + } else { + &msg.security_ticket + }, + team_instructions: &team_instructions, + requests: &asked, + }, + &provider, + &mut usage, + ) + .await; + description_reply(&asked, changed.as_deref()) + } else { + String::new() + }; // Redirects and links the PR changes are checked again after a push // (or when the evidence is a day old) and the description's table @@ -2370,6 +2426,16 @@ fn feedback_tools() -> Vec { ] } +/// Whether the round's evidence records a passing run of the full test +/// suite (the line `review_fix::suite` writes), and no failing one after. +fn suite_passed(evidence: &[String]) -> bool { + evidence + .iter() + .rev() + .find(|l| l.starts_with("Full test suite ")) + .is_some_and(|l| l.starts_with("Full test suite passed")) +} + /// The tool a person's comment reaches the PR description through. fn update_description_tool() -> ToolDefinition { ToolDefinition { @@ -2379,7 +2445,11 @@ fn update_description_tool() -> ToolDefinition { item). Pass the change in the person's words, with every value they gave. \ CoderHelm rewrites the description once you finish (after any code you \ commit), keeps its shape, and adds what changed to your reply. Only people \ - with write access to the repository can have it changed." + with write access to the repository can have it changed to order. When a \ + review finding (not a person) says the description is wrong or out of \ + date, call this too with what is wrong: CoderHelm then rebuilds the \ + description from the branch as it stands. You can always call it; never \ + answer that you cannot edit the description." .to_string(), input_schema: json!({ "type": "object", @@ -2395,23 +2465,53 @@ fn update_description_tool() -> ToolDefinition { /// whether the person who asked may have it changed. struct DescriptionRequests { allowed: bool, + /// A person triggered the round (false: CoderHelm's own review or a + /// follow-up it sent itself). + person: bool, asked: std::sync::Mutex>, + /// The round asked for the description to be rebuilt from the branch. + rebuild: std::sync::atomic::AtomicBool, } impl DescriptionRequests { + #[cfg(test)] fn new(allowed: bool) -> Self { + Self::for_round(allowed, true) + } + + fn for_round(allowed: bool, person: bool) -> Self { Self { allowed, + person, asked: std::sync::Mutex::new(Vec::new()), + rebuild: std::sync::atomic::AtomicBool::new(false), } } + /// The round asked for a rebuild from the branch (no person's words to + /// apply). + fn wants_rebuild(&self) -> bool { + self.rebuild.load(std::sync::atomic::Ordering::Relaxed) + } + /// Records one request and says what happens with it. fn ask(&self, change: &str) -> String { let change = change.split_whitespace().collect::>().join(" "); if change.is_empty() { return "Say what to change in the description.".to_string(); } + if !self.person { + // Nobody's wording to apply: the description is rebuilt from + // the branch, which is what makes it right. + self.rebuild + .store(true, std::sync::atomic::Ordering::Relaxed); + return "Recorded. CoderHelm rebuilds the description from the branch as it stands \ + when you finish (the versions the lockfile resolves, the counts, the changes, \ + the verification and the open items), so the statement you named is replaced \ + by what the branch shows. Fix the code if the code is what is wrong; never \ + write that you cannot edit the description." + .to_string(); + } if !self.allowed { return "Not changed: only people with write access to this repository can have the \ description changed. Tell the person so in your reply, politely; change \ @@ -4281,6 +4381,57 @@ mod description_request_tests { assert!(tool.description.contains("write access")); assert_eq!(tool.input_schema["required"][0], "change"); } + + /// A feedback round's file claims are held to its own suite result. + #[test] + fn a_feedback_rounds_claims_are_checked_against_its_suite_result() { + use super::suite_passed; + let passed = vec![ + "Scope: took out 1 file".to_string(), + "Full test suite passed: `pnpm test` (13 passed)".to_string(), + ]; + assert!(suite_passed(&passed)); + let failed_after = vec![ + "Full test suite passed: `pnpm test` (13 passed)".to_string(), + "Full test suite FAILED (exit 1): `pnpm test` (12 passed, 1 failed)".to_string(), + ]; + assert!(!suite_passed(&failed_after)); + assert!(!suite_passed(&[])); + let src = include_str!("feedback.rs"); + let claims = src.find("super::file_claims::settle(").unwrap(); + let rebuild = src.find("super::description::head_moved(").unwrap(); + assert!( + claims < rebuild, + "claims are settled before the description is rebuilt" + ); + } + + /// A round with no person behind it (CoderHelm's own review) was told + /// to call a tool it did not have and said it could not edit the + /// description. It has the tool now, and the call asks for the rebuild. + #[test] + fn a_round_nobody_asked_can_still_have_the_description_rebuilt() { + let d = DescriptionRequests::for_round(false, false); + assert!(!d.wants_rebuild()); + let out = d + .ask("the table lists glob-walk as 2.3.1 to 4.0.4 (major); the manifest keeps it on 2"); + assert!( + out.starts_with("Recorded. CoderHelm rebuilds the description from the branch"), + "{out}" + ); + assert!(d.wants_rebuild()); + assert!(d.taken().is_empty(), "no person's wording is applied"); + assert!(common::description_handoff::handoffs(&out).is_empty()); + let tool = update_description_tool(); + assert!(tool + .description + .contains("never answer that you cannot edit the description")); + // The round's instructions and the tool are in every round. + let src = include_str!("feedback.rs"); + let run = &src[..src.find("\nfn update_description_tool()").unwrap()]; + assert!(run.contains("tools.push(update_description_tool());\n let mut full_system")); + assert!(run.contains("common::description_handoff::ROUND_NOTE")); + } } #[cfg(test)] diff --git a/services/worker/src/passes/file_claims.rs b/services/worker/src/passes/file_claims.rs new file mode 100644 index 000000000..a2f6eca64 --- /dev/null +++ b/services/worker/src/passes/file_claims.rs @@ -0,0 +1,221 @@ +//! A sentence the run writes into a repository file that says a check +//! passes stands only on a recorded result (`common::file_claims`). +//! +//! The records are the ones the pull request's own sections are written +//! from: the run's last sandbox check (`proof::SandboxRecord`), which says +//! which kinds of check ran and passed. A claim with a passing record +//! stays. One without is taken out of the file before the run finishes, as +//! one commit, and the run page says which sentence and why; the sentence +//! never ships on a guess. + +use common::file_claims::{self as fc, Claim, ClaimKind}; +use tracing::{info, warn}; + +use super::checks::CheckKind; +use super::proof::RunEvidence; +use crate::clients::github::{FileOp, GitHubClient}; +use crate::models::TicketMessage; +use crate::WorkerState; + +/// The kinds of check with a passing result recorded for the branch as the +/// run last checked it. +pub fn proven(evidence: &RunEvidence) -> Vec { + evidence + .sandbox + .passed + .iter() + .filter_map(|k| match k { + CheckKind::Build => Some(ClaimKind::Build), + CheckKind::Tests => Some(ClaimKind::Tests), + CheckKind::Lint => Some(ClaimKind::Lint), + CheckKind::Typecheck => Some(ClaimKind::Typecheck), + _ => None, + }) + .collect() +} + +/// The claims the branch's diff adds to prose files that no recorded +/// passing result covers. +pub fn unproven_in_diff(diff: &serde_json::Value, evidence: &RunEvidence) -> Vec { + let mut claims = vec![]; + for f in diff["files"].as_array().into_iter().flatten() { + if f["status"].as_str() == Some("removed") { + continue; + } + let (Some(path), Some(patch)) = (f["filename"].as_str(), f["patch"].as_str()) else { + continue; + }; + claims.extend(fc::claims_in_patch(path, patch)); + } + fc::unproven(&claims, &proven(evidence)) +} + +/// The run page's line for the claims taken out. +pub fn note(removed: &[Claim]) -> String { + let list: Vec = removed + .iter() + .map(|c| { + format!( + "`{}` line {}: \"{}\" (no passing result is recorded for {})", + c.path, + c.line, + common::truncate_str(&c.sentence, 160), + c.what() + ) + }) + .collect(); + format!( + "Took {} out of the files this run wrote: a sentence that says a check passes stays only \ + when that check has a recorded passing result on this branch. {}", + if removed.len() == 1 { + "one sentence".to_string() + } else { + format!("{} sentences", removed.len()) + }, + list.join("; ") + ) +} + +/// Reads what the branch adds to its prose files and takes out every claim +/// that a check passes with no recorded passing result. Returns the claims +/// taken out. Best effort: a diff that can't be read changes nothing. +pub async fn settle( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + branch: &str, + evidence: &RunEvidence, +) -> Vec { + let (owner, repo) = (&msg.repo_owner, &msg.repo_name); + let Ok(diff) = github.get_diff(owner, repo, &msg.base_branch, branch).await else { + return vec![]; + }; + let open = unproven_in_diff(&diff, evidence); + if open.is_empty() { + return vec![]; + } + let mut paths: Vec<&str> = open.iter().map(|c| c.path.as_str()).collect(); + paths.sort(); + paths.dedup(); + let mut ops = vec![]; + let mut removed: Vec = vec![]; + for path in paths { + let Ok(Some(text)) = github.read_file_if_exists(owner, repo, path, branch).await else { + continue; + }; + if let Some(next) = fc::without(path, &text, &open) { + removed.extend( + open.iter() + .filter(|c| c.path == path && text.contains(c.sentence.as_str())) + .cloned(), + ); + ops.push(FileOp::Write { + path: path.to_string(), + content: next, + }); + } + } + if ops.is_empty() { + return vec![]; + } + let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; + let message = conventions.commit_message( + &super::ticket_tokens(msg), + "Remove claims that a check passes where no result is recorded", + ); + if let Err(e) = github + .batch_write(owner, repo, branch, &message, &ops) + .await + { + warn!(branch, error = %e, "Could not take unproven claims out of the files the run wrote"); + return vec![]; + } + info!( + branch, + removed = removed.len(), + "Took unproven claims out of the run's files" + ); + removed +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::proof::SandboxRecord; + use serde_json::json; + + fn diff() -> serde_json::Value { + json!({"files": [ + {"filename": "README.md", "status": "modified", + "patch": "@@ -4,2 +4,4 @@\n ## Upgrading\n+The build passes with these versions.\n+All tests pass.\n Node 20 or later.\n"}, + {"filename": "src/build.ts", "status": "modified", + "patch": "@@ -1 +1,2 @@\n+// The build passes with these versions.\n"}, + {"filename": "docs/old.md", "status": "removed", + "patch": "@@ -1 +0,0 @@\n-All tests pass.\n"} + ]}) + } + + fn evidence(passed: &[CheckKind]) -> RunEvidence { + RunEvidence { + sandbox: SandboxRecord { + ran: passed.to_vec(), + passed: passed.to_vec(), + ..Default::default() + }, + ..Default::default() + } + } + + #[test] + fn a_claim_needs_the_recorded_result_the_pull_request_is_written_from() { + // Nothing ran: both sentences are unproven. + let open = unproven_in_diff(&diff(), &evidence(&[])); + let got: Vec<(&str, u64, &str)> = open + .iter() + .map(|c| (c.path.as_str(), c.line, c.sentence.as_str())) + .collect(); + assert_eq!( + got, + vec![ + ("README.md", 5, "The build passes with these versions."), + ("README.md", 6, "All tests pass."), + ] + ); + // The tests passed in the sandbox; the build never ran. + let open = unproven_in_diff(&diff(), &evidence(&[CheckKind::Tests, CheckKind::Lint])); + assert_eq!(open.len(), 1); + assert_eq!(open[0].sentence, "The build passes with these versions."); + // Both recorded as passing: the sentences stay. + assert!( + unproven_in_diff(&diff(), &evidence(&[CheckKind::Tests, CheckKind::Build])).is_empty() + ); + let n = note(&open); + assert!( + n.starts_with("Took one sentence out of the files this run wrote"), + "{n}" + ); + assert!( + n.contains("`README.md` line 5") && n.contains("recorded for the build"), + "{n}" + ); + } + + /// Both paths that write files check them before the description is + /// built from the branch. + #[test] + fn the_run_and_its_fix_rounds_settle_their_claims() { + let run = include_str!("mod.rs"); + assert!( + run.matches("file_claims::settle(").count() >= 2, + "both ways a run opens its pull request" + ); + let resume = include_str!("resume.rs"); + let round = &resume[resume.find("\nasync fn run_fix_round(").unwrap()..]; + let claims = round.find("file_claims::settle(").unwrap(); + let rebuild = round.find("description::head_moved(").unwrap(); + assert!( + claims < rebuild, + "claims are settled before the description is rebuilt" + ); + } +} diff --git a/services/worker/src/passes/flaky.rs b/services/worker/src/passes/flaky.rs index 4f922a386..aebdcd43a 100644 --- a/services/worker/src/passes/flaky.rs +++ b/services/worker/src/passes/flaky.rs @@ -249,7 +249,7 @@ pub(crate) async fn note_on_pr( let out = super::completeness::with_section(&body, super::completeness::Section::CiNotes, section); if out != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &out).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr, &out).await { warn!(pr, error = %e, "Flaky checks: could not note the judgement on the pull request"); } } diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 83254243a..fa6604493 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -663,6 +663,14 @@ pub fn section(plan: &PlanResult, f: &PrFacts) -> String { ) } +/// The section as `body` has it, markers included; empty when it has none. +pub fn current_section(body: &str) -> String { + match (body.find(START), body.find(END)) { + (Some(s), Some(e)) if e > s => body[s..e + END.len()].to_string(), + _ => String::new(), + } +} + /// The description with the section in place: replaced where it stands, /// added at the end the first time, taken out when there is none. pub fn shape_body(body: String, section: &str) -> String { diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 3e5ffef7d..52a94c947 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -195,7 +195,8 @@ pub async fn run( let feedback_section = match review_feedback { Some(fb) => format!( - "\n\n## Review Feedback (from previous cycle)\nThe reviewer found issues with the previous implementation. Fix ALL of the following:\n{fb}" + "\n\n## Review Feedback (from previous cycle)\nThe reviewer found issues with the previous implementation. Fix ALL of the following:\n{fb}\n\n## The pull request's description\n{}", + common::description_handoff::ROUND_NOTE ), None => String::new(), }; diff --git a/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs b/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs index 174040774..9a70c9ca1 100644 --- a/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs +++ b/services/worker/src/passes/incidents/ah_dep_run_choice_and_proof.rs @@ -433,7 +433,7 @@ fn the_build_and_the_start_prove_the_bumps_and_what_breaks_them_is_taken_out() { assert!(out < written && written < moved); let plan_src = fn_src(dep, "async fn proof_plan("); assert!(plan_src.contains("checks::build_commands(&workflows, base)")); - assert!(plan_src.contains("rp::discover(lockfile, &ci, &files)")); + assert!(plan_src.contains("rp::discover(lockfile, &ci, &proof_files(w, lockfile).await)")); assert!(worker_dep_fix::proof_waits( Some(std::time::Duration::from_secs(240)), false diff --git a/services/worker/src/passes/incidents/am_description_from_the_head.rs b/services/worker/src/passes/incidents/am_description_from_the_head.rs new file mode 100644 index 000000000..5c46c357a --- /dev/null +++ b/services/worker/src/passes/incidents/am_description_from_the_head.rs @@ -0,0 +1,421 @@ +//! am. A dependency security run's pull request had the right code after a +//! review round and the wrong description: +//! +//! - its table still showed the plan: five packages as major version jumps +//! ("2.3.1 to 4.0.4 (major)") when the final manifest keeps each inside +//! its current major through a scoped override, and a headline that +//! counted twenty major versions; +//! - its count of fixed advisories had never been compared with what the +//! final lockfile installs; +//! - the round that fixed the code wrote "I can't edit the PR description +//! from here" and left the corrections to a person; +//! - the repository's second app, a CMS studio no CI job builds, took a +//! package an override moved to a new major, and nothing built it. +//! +//! Guarantee: the description is a function of the head. A dependency pull +//! request's table and headline are what the lockfile on the head resolves +//! compared with the base branch, an advisory counts as fixed only at or +//! past its patched version, and what can't be read is said as not known. +//! Every write of a description goes through one place, every path that +//! moves the head rebuilds it there, and a round's sentence that hands the +//! description to a person becomes the rebuild. A sentence a run writes +//! into a file that says a check passes needs that check's recorded result. +//! Every workspace project that takes a changed package is built when its +//! manifest declares a build, CI job or not; one that can't be proven is +//! named with why. + +use super::fixture::*; +use crate::passes::{checks::CheckKind, description, file_claims, proof}; +use common::dep_head::{self, Fixed, LockAt}; +use common::runtime_proof as rp; +use common::security_fixes::{self as sec, Advisory, Bump, Finding, FindingState, FixUnit}; + +/// The fixture monorepo's lockfile: the site, the studio no CI job builds, +/// and the studio's tooling bringing in `glob-walk` on the 2 line. +fn lockfile(glob_walk: &str, path_match: &str) -> String { + format!( + "lockfileVersion: '9.0'\nimporters:\n .:\n devDependencies:\n turbo:\n specifier: ^2.0.0\n version: 2.0.1\n apps/web:\n dependencies:\n path-match:\n specifier: ^3.1.0\n version: {path_match}\n apps/studio:\n dependencies:\n studio-kit:\n specifier: ^3.0.0\n version: 3.2.0\npackages:\n glob-walk@{glob_walk}: {{}}\n path-match@{path_match}: {{}}\n studio-kit@3.2.0: {{}}\n turbo@2.0.1: {{}}\nsnapshots:\n glob-walk@{glob_walk}: {{}}\n path-match@{path_match}: {{}}\n studio-kit@3.2.0:\n dependencies:\n glob-walk: {glob_walk}\n turbo@2.0.1: {{}}\n" + ) +} + +fn unit() -> FixUnit { + let bump = |package: &str, from: &str, to: &str| Bump { + package: package.into(), + from: from.into(), + to: to.into(), + major: sec::is_major_bump(from, to), + manifest: "pnpm-lock.yaml".into(), + }; + FixUnit { + repo: format!("{OWNER}/{REPO}"), + ecosystem: "npm".into(), + bundle: true, + // The plan: both as major version jumps. + bumps: vec![ + bump("glob-walk", "2.3.1", "4.0.4"), + bump("path-match", "3.1.2", "11.0.1"), + ], + ..Default::default() + } +} + +fn findings() -> Vec<(Finding, FindingState)> { + let f = |id: &str, package: &str, version: &str, patched: &str| Finding { + id: format!("f-{id}"), + package: package.into(), + version: version.into(), + fixed_version: Some(patched.into()), + manifest: "pnpm-lock.yaml".into(), + advisory: Advisory { + primary: id.into(), + ids: vec![id.into()], + ..Default::default() + }, + ..Default::default() + }; + vec![ + ( + f("GHSA-aaaa-0001", "glob-walk", "2.3.1", "2.3.2"), + FindingState::default(), + ), + ( + f("GHSA-bbbb-0002", "path-match", "3.1.2", "3.1.5"), + FindingState::default(), + ), + ] +} + +fn lock_at(base: &str, head: &str) -> LockAt { + LockAt { + path: "pnpm-lock.yaml".into(), + base: common::reachability::lock_copies("pnpm-lock.yaml", base), + head: common::reachability::lock_copies("pnpm-lock.yaml", head), + why: String::new(), + } +} + +/// The description after the review round kept both packages on their +/// lines: the table and the headline are the head's, not the plan's. +#[test] +fn the_table_and_headline_are_what_the_head_resolves() { + let (unit, fs) = (unit(), findings()); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let check = common::upgrade_notes::WhatToCheck::default(); + let links = sec::BodyLinks::default(); + // What the pull request said: the plan. + let planned = sec::pr_body_linked(&unit, &pairs, "Bumped.", &check, &links); + assert!(planned.contains("2.3.1 to 4.0.4 (major)")); + // The head: scoped overrides keep each on its line. + let head = dep_head::resolve( + &unit, + "5e1f00d7a9", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.5"), + )], + ); + let body = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let mut end = Ending::default(); + end.said(body.clone()); + assert!(end.says("| `glob-walk` | 2.3.1 to 2.3.2 |"), "{body}"); + assert!(end.says("| `path-match` | 3.1.2 to 3.1.5 |"), "{body}"); + assert!( + end.says("Fixes 2 of 2 advisories in 2 package version lines (0 cross a major version), read from the lockfile on the head `5e1f00d`."), + "{body}" + ); + end.never_says("(major)"); + end.never_says("4.0.4"); + end.never_says("11.0.1"); + // A head that stops short of the patch is not counted as a fix. + let short = dep_head::resolve( + &unit, + "0ddba11", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.4"), + )], + ); + assert_eq!(short.fixed(&unit, &fs[1].0), Fixed::No); + let body = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &short); + assert!(body.contains("Fixes 1 of 2 advisories"), "{body}"); + assert!( + body.contains("Not fixed on the head: GHSA-bbbb-0002"), + "{body}" + ); + // A head that can't be read: said, never the plan as a result. + let blind = dep_head::unknown(&unit, "`pnpm-lock.yaml` could not be read on the head"); + let body = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &blind); + assert!( + body.contains("What the head installs is not known"), + "{body}" + ); + assert!( + body.contains("2.3.1 to 4.0.4 planned; not read from the head"), + "{body}" + ); + assert!(!body.contains("Fixes "), "{body}"); +} + +/// The rebuild replaces the stale sections of the open pull request and +/// keeps the rest; a second rebuild on the same head changes nothing. +#[test] +fn a_rebuild_replaces_the_stale_sections_in_place() { + let (unit, fs) = (unit(), findings()); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let check = common::upgrade_notes::WhatToCheck::default(); + let links = sec::BodyLinks::default(); + let open = format!( + "\nDraft: waiting on CI.\n\n\n{}", + sec::pr_body_linked(&unit, &pairs, "Bumped.", &check, &links) + ); + let head = dep_head::resolve( + &unit, + "5e1f00d7a9", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.5"), + )], + ); + let fresh = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let sections = ["## Summary", "## What to check", "## Proof"]; + let rebuilt = common::upgrade_notes::replace_sections(&open, &fresh, §ions); + assert!(rebuilt.starts_with("\nDraft: waiting on CI.")); + assert!(!rebuilt.contains("(major)"), "{rebuilt}"); + assert!(rebuilt.contains("| `glob-walk` | 2.3.1 to 2.3.2 |")); + assert!(rebuilt.contains(sec::MARKER)); + assert_eq!( + common::upgrade_notes::replace_sections(&rebuilt, &fresh, §ions), + rebuilt + ); + // The pipeline rebuilds those sections from the head, in one place. + let src = include_str!("../security_fixes.rs"); + let rebuild = fn_src(src, "pub(crate) async fn rebuild_at_head("); + assert!(rebuild.contains("head_facts(")); + assert!(rebuild.contains("sec::pr_body_at_head(")); + assert!(rebuild.contains("rebuilt_body(body, &fresh)")); + let pure = fn_src(src, "pub(crate) fn rebuilt_body("); + for heading in ["\"## Summary\"", "\"## What to check\"", "\"## Proof\""] { + assert!(pure.contains(heading), "{heading}"); + } + assert!(rebuild.contains("description::save(")); +} + +/// Every section CoderHelm owns elsewhere survives a rebuild word for +/// word, wherever it sits: the draft status, review fixes, the settled +/// items, CI notes, the reviewer guide, open items, and what the run did +/// before and after the code. +#[test] +fn a_rebuild_keeps_every_other_owned_section() { + use crate::passes::completeness::{self, Section}; + use crate::passes::{habits_check, security_fixes}; + let (unit, fs) = (unit(), findings()); + let pairs: Vec<(&Finding, &FindingState)> = fs.iter().map(|(f, s)| (f, s)).collect(); + let check = common::upgrade_notes::WhatToCheck::default(); + let links = sec::BodyLinks::default(); + let mut open = sec::pr_body_linked(&unit, &pairs, "Bumped.", &check, &links); + let sections = [ + (Section::DraftStatus, "Draft: waiting on CI for this head."), + ( + Section::ReviewFixes, + "Round 1: scoped the overrides to their lines.", + ), + ( + Section::Settled, + "Settled here: the audit ran on this head.", + ), + ( + Section::CiNotes, + "The end-to-end job failed once and passed on a rerun: flaky.", + ), + ( + Section::ReviewerGuide, + "Start with package.json, then the lockfile.", + ), + ( + Section::OpenFindings, + "One finding of CoderHelm's own review is open.", + ), + ( + Section::Objections, + "A reviewer's request for changes stands.", + ), + ]; + let mut blocks: Vec = vec![]; + for (section, words) in sections { + let (start, end) = section.markers(); + let block = format!("{start}\n{words}\n{end}"); + open = completeness::with_section(&open, section, block.clone()); + blocks.push(block); + } + let habits = format!( + "{}\n### Before and after the code\n- Reproduced the advisory's path first.\n{}", + habits_check::START, + habits_check::END + ); + open = habits_check::shape_body(open, &habits); + blocks.push(habits); + for b in &blocks { + assert!(open.contains(b.as_str()), "the fixture lost {b}"); + } + let head = dep_head::resolve( + &unit, + "5e1f00d7a9", + &[lock_at( + &lockfile("2.3.1", "3.1.2"), + &lockfile("2.3.2", "3.1.5"), + )], + ); + let fresh = sec::pr_body_at_head(&unit, &pairs, "Bumped.", &check, &links, &head); + let rebuilt = security_fixes::rebuilt_body(&open, &fresh); + assert!( + rebuilt.contains("| `glob-walk` | 2.3.1 to 2.3.2 |"), + "{rebuilt}" + ); + assert!(!rebuilt.contains("(major)"), "{rebuilt}"); + for b in &blocks { + assert_eq!( + rebuilt.matches(b.as_str()).count(), + 1, + "lost or doubled: {b}\n{rebuilt}" + ); + } + assert!(rebuilt.contains(sec::MARKER)); + // The same head again writes nothing new. + assert_eq!(security_fixes::rebuilt_body(&rebuilt, &fresh), rebuilt); + // The model's rewrite keeps them too: the owned sections never reach + // it, and what the run did before and after the code is put back. + let pr = include_str!("../pr.rs"); + let refresh = &pr[pr.find("pub async fn refresh_description(").unwrap()..]; + let refresh = &refresh[..refresh.find("\nasync fn fill_placeholders_once(").unwrap()]; + assert!(refresh.contains("completeness::take_owned(¤t)")); + assert!(refresh.contains("habits_check::current_section(&rest)")); + assert!(refresh.contains("habits_check::shape_body(written, &habits_section)")); +} + +/// "I can't edit the PR description from here" never reaches a person: the +/// round is told the description is rebuilt, its account loses the +/// sentence, and the rebuild runs. +#[test] +fn a_round_never_hands_the_description_to_a_person() { + let account = "Scoped the overrides so glob-walk stays on 2 and path-match on 3.\n\ + I can't edit the PR description from here. Please update the table in the description: it still lists both as major."; + let (clean, rebuild) = description::round_account(account); + assert!(rebuild); + let mut end = Ending::default(); + end.said(clean); + assert!(end.says("Scoped the overrides so glob-walk stays on 2")); + assert!(end.says(common::description_handoff::REBUILT)); + end.never_says("can't edit the PR description"); + end.never_says("Please update the table"); + // Every fix round is told, and has no reason to say it. + let implement = include_str!("../implement.rs"); + assert!(implement.contains("common::description_handoff::ROUND_NOTE")); + assert!(common::description_handoff::ROUND_NOTE.contains("rebuilt from the branch")); + // The description itself never carries such a sentence either. + let body = "## Open items\n- I can't edit the PR description from here.\n"; + assert!(!description::clean(body).contains("can't edit")); +} + +/// The studio no CI job builds takes the changed `glob-walk` line through +/// its tooling: it is found from the lockfile and built from its manifest's +/// build script; when its build can't run in the sandbox, the pull request +/// names it as not proven. +#[test] +fn the_app_no_ci_job_builds_is_built_or_named_as_not_proven() { + let asked = vec![ + ("glob-walk".to_string(), "2.3.1".to_string()), + ("path-match".to_string(), "3.1.2".to_string()), + ]; + let projects = common::reachability::lock_projects( + "pnpm-lock.yaml", + &lockfile("2.3.1", "3.1.2"), + &[], + &asked, + ) + .unwrap(); + let affected: Vec = projects + .into_iter() + .filter(|p| !p.uses.is_empty()) + .map(|p| rp::AffectedProject { + manifest: Some(match p.dir.as_str() { + "apps/studio" => r#"{"scripts":{"build":"studio build"}}"#.to_string(), + _ => r#"{"scripts":{"build":"next build"}}"#.to_string(), + }), + dir: p.dir, + uses: p.uses, + }) + .collect(); + let dirs: Vec<&str> = affected.iter().map(|a| a.dir.as_str()).collect(); + assert_eq!(dirs, vec!["apps/studio", "apps/web"]); + // CI builds the site only. + let ci = [rp::CiBuild { + cmd: "pnpm --filter web build".into(), + dir: Some("apps/web".into()), + workflow: "ci.yml".into(), + job: "build".into(), + on_pull_request: true, + }]; + let mut plan = rp::discover("pnpm-lock.yaml", &ci, &[]); + rp::add_projects(&mut plan, "pnpm-lock.yaml", &affected); + let studio = plan + .builds + .iter() + .position(|b| b.dir == "apps/studio") + .unwrap(); + assert_eq!(plan.builds[studio].cmd, "pnpm run build"); + // The studio's build breaks only with the bumps: blamed, which is what + // the take-out acts on. + let base = rp::ProofResult { + ran: true, + builds: vec![Some(0), Some(0)], + start: "skipped".into(), + ..Default::default() + }; + let mut head = base.clone(); + head.builds[studio] = Some(1); + let blamed = rp::blamed(&plan, &base, &head); + assert_eq!( + blamed, + vec!["the build `pnpm run build` fails (exit 1)".to_string()] + ); + let drive = include_str!("../dep_fix.rs"); + assert!(fn_src(drive, "async fn proof_plan(").contains("affected_projects(")); + assert!(fn_src(drive, "async fn proof_plan(").contains("rp::add_lockfile(")); + // The studio's build needs a token the sandbox lacks: it fails on the + // base branch too, so it is not blamed and is named as not proven. + let mut base_red = base.clone(); + base_red.builds[studio] = Some(1); + assert!(rp::blamed(&plan, &base_red, &head).is_empty()); + let mut end = Ending::default(); + end.said(rp::report(&plan, Some(&base_red), Some(&head))); + assert!(end.says("Project `apps/studio` takes `glob-walk@2.3.1`: **not proven here**")); + assert!(end.says("fails on the base branch too")); + end.never_says("Covers the project of"); +} + +/// A sentence the run wrote into the README says the build passes; only +/// the tests have a recorded passing result. +#[test] +fn a_file_the_run_wrote_claims_only_what_a_check_recorded() { + let diff = serde_json::json!({"files": [{ + "filename": "README.md", "status": "modified", + "patch": "@@ -8,2 +8,4 @@\n ## Security updates\n+The build passes with the new versions.\n+All tests pass.\n Run `pnpm install` after pulling.\n" + }]}); + let evidence = proof::RunEvidence { + sandbox: proof::SandboxRecord { + ran: vec![CheckKind::Tests], + passed: vec![CheckKind::Tests], + ..Default::default() + }, + ..Default::default() + }; + let open = file_claims::unproven_in_diff(&diff, &evidence); + assert_eq!(open.len(), 1); + assert_eq!(open[0].sentence, "The build passes with the new versions."); + let file = "## Security updates\nThe build passes with the new versions.\nAll tests pass.\nRun `pnpm install` after pulling.\n"; + let mut end = Ending::default(); + end.said(common::file_claims::without("README.md", file, &open).unwrap()); + end.never_says("The build passes"); + assert!(end.says("All tests pass.")); + assert!(end.says("Run `pnpm install` after pulling.")); +} diff --git a/services/worker/src/passes/incidents/an_six_database_findings.rs b/services/worker/src/passes/incidents/an_six_database_findings.rs new file mode 100644 index 000000000..e3d50aa38 --- /dev/null +++ b/services/worker/src/passes/incidents/an_six_database_findings.rs @@ -0,0 +1,575 @@ +//! an. Security, Infrastructure showed six database findings for one +//! account. Every one was a runbook with one command and a console path; +//! none had a pull request, although the databases were defined in the +//! team's code. The same CVE stood on all six: on an operating system +//! update, on an Aurora PostgreSQL patch and on a MySQL upgrade. A +//! database Terraform had named (`identifier_prefix` plus its generated +//! suffix) was "not found in code" because its live name is written +//! nowhere. An Aurora cluster defined through a module was not found +//! either. On one cluster a patch and an upgrade were pending at once, as +//! two unrelated rows; an operating system update pending on both of its +//! instances was one row and the other was dropped. An account with more +//! than a hundred databases was read one page deep. +//! +//! Guarantee: an advisory is attached only where it applies (service, +//! engine, version range, kind of action, date), and an action AWS +//! publishes with no CVE list gets none. An action is named for what it +//! means on its ARN. The actions pending on one database are one ordered +//! set of rows, each naming every ARN it applies to. The code that defines +//! a resource is found by what AWS and the code say (stack records, +//! resource type and attributes, module calls, variable files), graded, +//! and a guess never becomes a pull request. An update with a code +//! equivalent is a pull request against the line that sets the value; one +//! that cannot be expressed in code stays a runbook and says so; a runbook +//! is complete. A change that would replace a database is refused. + +use std::collections::BTreeMap; + +use common::infra_vuln::actions::Meaning; +use common::infra_vuln::feeds::{Bulletin, ServiceStatus, Who}; +use common::infra_vuln::inventory::{Confidence, Kind, Resource}; +use common::infra_vuln::locate::{self, SourceFile}; +use common::infra_vuln::matching::{self, Feeds, FixKind, InfraFinding}; +use common::infra_vuln::raw::{RawAccount, RawDatabase, RawPending}; +use common::infra_vuln::records::{self, Record}; + +use crate::passes::infra_findings; + +const ACCOUNT: &str = "111122223333"; +const REGION: &str = "us-east-1"; +const CVE: &str = "CVE-2026-55501"; +/// A name Terraform generated: `identifier_prefix` and 26 characters. +const ORDERS: &str = "orders-20240311094512345600000001"; +const INFRA: &str = "acme/platform-infra"; + +/// What the old cards said, whatever the action. +const OLD_SUMMARY: &str = "Apply system update in AWS"; +const OLD_CONSOLE: &str = "Maintenance & backups > Pending maintenance > Apply"; + +fn arn(kind: &str, name: &str) -> String { + format!("arn:aws:rds:{REGION}:{ACCOUNT}:{kind}:{name}") +} + +fn tags(t: &[(&str, &str)]) -> Vec<(String, String)> { + t.iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} + +fn cluster(name: &str, engine: &str, version: &str) -> RawDatabase { + RawDatabase { + id: name.into(), + arn: arn("cluster", name), + engine: engine.into(), + engine_version: version.into(), + ..Default::default() + } +} + +fn instance(name: &str, engine: &str, version: &str, of: &str, t: &[(&str, &str)]) -> RawDatabase { + RawDatabase { + id: name.into(), + arn: arn("db", name), + engine: engine.into(), + engine_version: version.into(), + cluster: of.into(), + tags: tags(t), + ..Default::default() + } +} + +fn pending(on: &str, action: &str, description: &str, forced: &str) -> RawPending { + RawPending { + resource_arn: on.into(), + action: action.into(), + description: description.into(), + forced_apply: forced.into(), + ..Default::default() + } +} + +/// The account as one read returns it: six things pending, and more +/// databases than one page of a describe call holds. +fn account() -> RawAccount { + let mut writer = instance( + "ledger-prod-aurora-1", + "aurora-postgresql", + "16.4", + "ledger-prod-aurora", + &[], + ); + writer.writer = true; + let reader = instance( + "ledger-prod-aurora-2", + "aurora-postgresql", + "16.4", + "ledger-prod-aurora", + &[], + ); + let mut db_instances = vec![ + writer, + reader, + instance(ORDERS, "postgres", "16.4", "", &[("Team", "payments")]), + instance( + "billing-prod", + "mysql", + "8.0.36", + "", + &[ + ("aws:cloudformation:stack-name", "billing-prod"), + ("aws:cloudformation:logical-id", "BillingDb"), + ], + ), + instance("reports-prod", "mysql", "8.0.36", "", &[]), + ]; + // Past the first hundred: quiet databases with nothing pending. + for i in 0..120 { + db_instances.push(instance( + &format!("quiet-{i:03}"), + "postgres", + "16.6", + "", + &[], + )); + } + let ledger = arn("cluster", "ledger-prod-aurora"); + RawAccount { + account: ACCOUNT.into(), + region: REGION.into(), + read_at: "2026-11-13T09:00:00Z".into(), + db_clusters: vec![cluster("ledger-prod-aurora", "aurora-postgresql", "16.4")], + db_instances, + pending: vec![ + // One cluster, a patch and an upgrade at once. + pending( + &ledger, + "system-update", + "Upgrade to Aurora PostgreSQL 16.4.3", + "", + ), + pending( + &ledger, + "db-upgrade", + "Upgrade to Aurora PostgreSQL 16.6", + "", + ), + // The same action name on its instances: the operating system. + pending( + &arn("db", "ledger-prod-aurora-1"), + "system-update", + "New Operating System patch is available", + "", + ), + pending( + &arn("db", "ledger-prod-aurora-2"), + "system-update", + "New Operating System patch is available", + "", + ), + pending( + &arn("db", ORDERS), + "db-upgrade", + "Upgrade to 16.6", + "2027-01-20T00:00:00Z", + ), + pending( + &arn("db", "billing-prod"), + "system-update", + "New Operating System update is available", + "2026-12-05T00:00:00Z", + ), + pending( + &arn("db", "reports-prod"), + "db-upgrade", + "Upgrade to 8.0.40", + "2026-12-15T00:00:00Z", + ), + ], + ..Default::default() + } +} + +fn file(repo: &str, path: &str, content: &str) -> SourceFile { + SourceFile { + repo: repo.into(), + path: path.into(), + content: content.into(), + } +} + +const AURORA_MODULE: &str = r#"variable "name" {} +variable "engine_version" {} + +resource "aws_rds_cluster" "this" { + cluster_identifier = "${var.name}-aurora" + engine = "aurora-postgresql" + engine_version = var.engine_version +} + +resource "aws_rds_cluster_instance" "this" { + count = 2 + identifier = "${var.name}-aurora-${count.index + 1}" + cluster_identifier = aws_rds_cluster.this.id + engine = aws_rds_cluster.this.engine + engine_version = aws_rds_cluster.this.engine_version +} +"#; + +const PROD: &str = r#"module "ledger" { + source = "../../modules/aurora" + name = "ledger-prod" + engine_version = "16.4" +} +"#; + +const ORDERS_TF: &str = r#"resource "aws_db_instance" "orders" { + identifier_prefix = "orders-" + engine = "postgres" + engine_version = "16.4" + instance_class = "db.r6g.large" + tags = { + Team = "payments" + } +} +"#; + +const BILLING_TEMPLATE: &str = r#"AWSTemplateFormatVersion: "2010-09-09" +Resources: + BillingDb: + Type: AWS::RDS::DBInstance + DeletionPolicy: Snapshot + Properties: + Engine: mysql + EngineVersion: "8.0.36" +"#; + +/// The team's repositories: a Terraform repository (a module, its caller +/// per environment, a root with a generated identifier) and an +/// application repository with its CloudFormation template at a neutral +/// path. +fn code() -> Vec { + vec![ + file(INFRA, "modules/aurora/main.tf", AURORA_MODULE), + file(INFRA, "envs/prod/main.tf", PROD), + file(INFRA, "db/orders.tf", ORDERS_TF), + file("acme/billing", "deploy/stack.yaml", BILLING_TEMPLATE), + file("acme/billing", "scripts/deploy.sh", "aws cloudformation deploy --stack-name billing-prod --template-file deploy/stack.yaml\n"), + ] +} + +/// One bulletin: RDS customers act, and the fix is RDS for MySQL 8.0.40. +fn bulletin() -> Bulletin { + Bulletin { + id: "2026-171-AWS".into(), + title: "Issue with RDS for MySQL".into(), + url: "https://aws.amazon.com/security/security-bulletins/2026-171-AWS/".into(), + severity: "important".into(), + published: "2026-11-02".into(), + updated: "2026-11-02".into(), + cves: vec![CVE.into()], + services: vec![ServiceStatus { + service: "rds".into(), + heading: "RDS/Aurora".into(), + who: Who::CustomerInAws, + reason: "Customers should upgrade to RDS for MySQL version 8.0.40 or later, which is now available.".into(), + ..Default::default() + }], + ..Default::default() + } +} + +struct Scene { + resources: Vec, + findings: Vec, +} + +fn scene() -> Scene { + let raw = account(); + let mut resources = raw.resources(); + let repos = vec![INFRA.to_string(), "acme/billing".to_string()]; + let files = code(); + for r in resources.iter_mut() { + r.defined_in = locate::locate(r, &repos, &files, &[]); + } + let b = bulletin(); + let (kev, latest) = (BTreeMap::new(), BTreeMap::new()); + let findings = matching::findings( + &resources, + &Feeds { + advisories: &[], + bulletins: std::slice::from_ref(&b), + runtimes: &[], + latest: &[], + kev: &kev, + latest_al2023: &latest, + today: "2026-11-13", + }, + ); + Scene { + resources, + findings, + } +} + +fn find<'a>(s: &'a Scene, name: &str, meaning: Meaning) -> &'a InfraFinding { + s.findings + .iter() + .find(|f| f.name == name && f.fix.meaning == Some(meaning)) + .unwrap_or_else(|| panic!("no {meaning:?} finding for {name}")) +} + +#[test] +fn every_page_of_databases_is_kept_and_six_things_are_pending() { + let s = scene(); + // 1 cluster and 123 instances outside it: nothing past the first + // hundred is lost on the way to resources. + let dbs = s + .resources + .iter() + .filter(|r| matches!(r.kind, Kind::RdsCluster | Kind::RdsInstance)) + .count(); + assert_eq!(dbs, 124); + let titles: Vec<&str> = s.findings.iter().map(|f| f.title.as_str()).collect(); + assert_eq!(s.findings.len(), 6, "{titles:#?}"); + let mut ids: Vec<&str> = s.findings.iter().map(|f| f.id.as_str()).collect(); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), 6, "each row is its own finding"); + for f in &s.findings { + assert_ne!(f.fix.summary, OLD_SUMMARY, "{}", f.title); + assert!(!f.fix.console.contains(OLD_CONSOLE), "{}", f.title); + assert!(!f.fix.decision.is_empty(), "{} does not say why", f.title); + } +} + +#[test] +fn the_cve_stands_only_on_the_upgrade_the_bulletin_speaks_of() { + let s = scene(); + let with: Vec<&InfraFinding> = s.findings.iter().filter(|f| !f.cves.is_empty()).collect(); + assert_eq!(with.len(), 1, "the old cards put {CVE} on all six"); + assert_eq!(with[0].name, "reports-prod"); + assert_eq!(with[0].cves, vec![CVE]); + // The operating system updates: no CVE, and the card says AWS + // publishes none. + for name in ["billing-prod", "ledger-prod-aurora"] { + let os = find(&s, name, Meaning::OsUpdate); + assert!(os.cves.is_empty()); + assert!(!os.sources.iter().any(|x| x.kind == "bulletin"), "{name}"); + assert!( + os.fix.advisory_note.contains("no CVE list"), + "{}", + os.fix.advisory_note + ); + } + // The Aurora PostgreSQL patch and upgrade: the bulletin names MySQL. + assert!(find(&s, "ledger-prod-aurora", Meaning::EnginePatch) + .cves + .is_empty()); + assert!(find(&s, "ledger-prod-aurora", Meaning::EngineUpgrade) + .cves + .is_empty()); + assert!(find(&s, ORDERS, Meaning::EngineUpgrade).cves.is_empty()); +} + +#[test] +fn the_cluster_s_three_actions_are_named_for_what_they_mean_and_ordered() { + let s = scene(); + let up = find(&s, "ledger-prod-aurora", Meaning::EngineUpgrade); + let patch = find(&s, "ledger-prod-aurora", Meaning::EnginePatch); + let os = find(&s, "ledger-prod-aurora", Meaning::OsUpdate); + // `system-update` on the cluster ARN is an engine patch; on the + // instance ARNs it is the operating system. + assert!( + patch.title.contains("engine patch to 16.4.3"), + "{}", + patch.title + ); + assert!(os.title.contains("operating system update"), "{}", os.title); + let rb = os.fix.runbook.as_ref().unwrap(); + // One row for both instances, each with its command, the reader first. + let cmds: Vec<&str> = rb + .steps + .iter() + .filter(|x| x.cli.contains("next-maintenance")) + .map(|x| x.cli.as_str()) + .collect(); + assert_eq!(cmds.len(), 2, "{cmds:#?}"); + assert!(cmds[0].contains(":db:ledger-prod-aurora-2 "), "{}", cmds[0]); + assert!(cmds[1].contains(":db:ledger-prod-aurora-1 "), "{}", cmds[1]); + assert!(patch.fix.runbook.as_ref().unwrap().steps[0] + .cli + .contains(":cluster:ledger-prod-aurora --apply-action system-update")); + // An order, and what is not known said plainly. + assert!(up.fix.order[0].starts_with("1 of 3"), "{:?}", up.fix.order); + assert!( + patch.fix.order[0].starts_with("2 of 3"), + "{:?}", + patch.fix.order + ); + assert!(os.fix.order[0].starts_with("3 of 3"), "{:?}", os.fix.order); + assert!(patch.fix.order[0].contains("AWS does not say whether this patch is still offered")); +} + +#[test] +fn a_cluster_defined_through_a_module_gets_a_pull_request_on_the_caller_s_input() { + let s = scene(); + let up = find(&s, "ledger-prod-aurora", Meaning::EngineUpgrade); + assert_eq!(up.fix.kind, Some(FixKind::Pr)); + let l = up.fix.location.as_ref().unwrap(); + assert_eq!( + (l.repo.as_str(), l.how.as_str()), + (INFRA, "terraform_module") + ); + assert_eq!(l.address, "module.ledger.aws_rds_cluster.this"); + assert_eq!(l.confidence, Confidence::High); + assert_eq!(l.environment, "production"); + let e = l.edit.as_ref().unwrap(); + assert_eq!( + ( + e.file.as_str(), + e.line, + e.attribute.as_str(), + e.via.as_str() + ), + ("envs/prod/main.tf", 4, "engine_version", "module_input") + ); + let record = Record::new(up.clone(), "2026-11-13T09:00:00Z"); + let unit = infra_findings::unit_for(&record).expect("a fix unit"); + assert_eq!(unit.repo, INFRA); + let ticket = records::ticket_body(&record); + assert!( + ticket.contains("The value to change: `engine_version` in `envs/prod/main.tf`, line 4"), + "{ticket}" + ); + assert!( + ticket.contains("Never raise it on an `aws_rds_cluster_instance`"), + "{ticket}" + ); + assert!(ticket.contains("Never run an apply"), "{ticket}"); + let body = records::pr_body( + &record, + "Raised the ledger cluster's engine version to 16.6.", + ); + for part in [ + "## Summary", + "## Changes", + "## Rollout", + "`apply_immediately` defaults to `false`", + "Upgrades are one-way", + "Never set a value below the live version", + "CoderHelm ran no plan", + "(read 2026-11-13)", + ] { + assert!( + body.contains(part), + "the description has no `{part}`:\n{body}" + ); + } + // The change the ticket asks for passes the guard; a change that + // would replace the cluster is refused, with the reason. + let raised = vec![( + "envs/prod/main.tf".to_string(), + PROD.to_string(), + PROD.replace("16.4", "16.6"), + )]; + assert!(infra_findings::guard_refusals(&raised).is_empty()); + let replaced = vec![( + "modules/aurora/main.tf".to_string(), + AURORA_MODULE.to_string(), + AURORA_MODULE.replace( + "\"${var.name}-aurora\"\n engine ", + "\"${var.name}-db\"\n engine ", + ), + )]; + let why = infra_findings::guard_refusals(&replaced); + assert!( + why.iter() + .any(|x| x.contains("`cluster_identifier`, which replaces the resource")), + "{why:?}" + ); +} + +#[test] +fn a_generated_identifier_is_found_by_its_prefix_and_settings() { + let s = scene(); + let up = find(&s, ORDERS, Meaning::EngineUpgrade); + assert_eq!(up.fix.kind, Some(FixKind::Pr)); + let l = up.fix.location.as_ref().unwrap(); + assert_eq!(l.address, "aws_db_instance.orders"); + assert_eq!( + (l.how.as_str(), l.confidence), + ("terraform_generated_name", Confidence::High) + ); + assert_eq!(l.edit.as_ref().unwrap().line, 4); + // The live name is written nowhere in the team's code. + assert!(code().iter().all(|f| !f.content.contains(ORDERS))); + assert_eq!( + up.fix.summary, + "Raise `engine_version` to 16.6 in db/orders.tf" + ); + assert_eq!(up.fix.apply_by, "2027-01-20"); +} + +#[test] +fn what_code_cannot_do_or_does_not_hold_is_a_complete_runbook_that_says_why() { + let s = scene(); + // In a CloudFormation template, found by its stack tags, and still a + // runbook: an operating system update cannot be expressed in code. + let billing = find(&s, "billing-prod", Meaning::OsUpdate); + assert_eq!(billing.fix.kind, Some(FixKind::Runbook)); + let l = billing.fix.location.as_ref().unwrap(); + assert_eq!( + (l.how.as_str(), l.file.as_str(), l.address.as_str()), + ("cloudformation_tag", "deploy/stack.yaml", "BillingDb") + ); + assert_eq!(l.confidence, Confidence::High); + assert!( + billing.fix.decision.contains("cannot be expressed in code"), + "{}", + billing.fix.decision + ); + assert!( + billing.fix.decision.contains("deploy/stack.yaml"), + "{}", + billing.fix.decision + ); + assert!(infra_findings::unit_for(&Record::new(billing.clone(), "t")).is_none()); + // Not in any connected repository: a runbook, with everything a + // person needs and the real identifiers. + let reports = find(&s, "reports-prod", Meaning::EngineUpgrade); + assert_eq!(reports.fix.kind, Some(FixKind::Runbook)); + assert!(reports + .fix + .decision + .contains("did not find this resource in any connected repository")); + let rb = reports.fix.runbook.as_ref().unwrap(); + for (part, n) in [ + ("scope", rb.scope.len()), + ("what", rb.what.len()), + ("interruption", rb.interruption.len()), + ("prerequisites", rb.prerequisites.len()), + ("prechecks", rb.prechecks.len()), + ("backup", rb.backup.len()), + ("console", rb.console.len()), + ("steps", rb.steps.len()), + ("validation", rb.validation.len()), + ("rollback", rb.rollback.len()), + ("if_nothing", rb.if_nothing.len()), + ("sources", rb.sources.len()), + ] { + assert!(n > 0, "the runbook has no {part}"); + } + assert_eq!(rb.apply_by, "2026-12-15"); + assert!(rb.scope[0].contains(ACCOUNT) && rb.scope[0].contains(REGION)); + assert_eq!( + rb.steps[0].cli, + format!("aws rds modify-db-instance --db-instance-identifier reports-prod --engine-version 8.0.40 --no-apply-immediately --region {REGION}") + ); + assert!(rb.backup[0] + .cli + .contains("create-db-snapshot --db-instance-identifier reports-prod")); + assert!(rb.rollback[0].text.contains("one-way")); + assert!(reports.fix.code_note.contains("raise its pinned version")); + // CoderHelm never runs it: no fix unit. + assert!(infra_findings::unit_for(&Record::new(reports.clone(), "t")).is_none()); +} diff --git a/services/worker/src/passes/incidents/h_pr_updates.rs b/services/worker/src/passes/incidents/h_pr_updates.rs index d7193e579..e741368a6 100644 --- a/services/worker/src/passes/incidents/h_pr_updates.rs +++ b/services/worker/src/passes/incidents/h_pr_updates.rs @@ -42,7 +42,7 @@ fn the_description_drops_an_older_rounds_failure_when_a_newer_round_lands() { let resume = include_str!("../resume.rs"); let round = fn_src(resume, "\nasync fn run_fix_round("); let pushed = round.find("Landed::Pushed { files }").unwrap(); - assert!(round[pushed..].contains("pr::refresh_description(")); + assert!(round[pushed..].contains("description::head_moved(")); } #[test] diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 2f967f03f..f2c8639ef 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -27,6 +27,8 @@ mod ah_dep_run_choice_and_proof; mod ai_open_items_settled; mod aj_coder_habits; mod al_learning_loop; +mod am_description_from_the_head; +mod an_six_database_findings; mod b_open_pr_retry; mod ba_verdict_on_old_commit; mod bb_flaky_not_broken; diff --git a/services/worker/src/passes/infra_findings.rs b/services/worker/src/passes/infra_findings.rs index e0ef7b2f4..73440e1b7 100644 --- a/services/worker/src/passes/infra_findings.rs +++ b/services/worker/src/passes/infra_findings.rs @@ -203,8 +203,13 @@ fn cadence_due(c: Cadence, daily: bool) -> bool { } } -fn unit_for(r: &Record) -> Option { - let loc = r.finding.fix.location.as_ref()?; +pub(crate) fn unit_for(r: &Record) -> Option { + // A pull request only where the fix is one and the code was found for + // sure: a low-confidence location never becomes a pull request. + if r.finding.fix.kind != Some(FixKind::Pr) { + return None; + } + let loc = r.finding.fix.location.as_ref().filter(|l| l.sure())?; let key = format!("infra:{}", r.finding.id); let to = r.finding.fix.to.clone(); let branch_name = format!( @@ -246,6 +251,50 @@ fn unit_for(r: &Record) -> Option { }) } +/// How long after a tripped guard the one fix round starts: the run that +/// opened the pull request ends first. +const FIX_ROUND_DELAY_SECS: i32 = 300; + +/// Puts one ticket for a fix unit on the ticket queue. +async fn send_ticket( + state: &WorkerState, + team_id: &str, + installation_id: u64, + unit: &FixUnit, + body: String, + base: String, + delay_secs: i32, +) -> Result<(), String> { + let (owner, name) = unit.repo.split_once('/').ok_or("bad repo")?; + let msg = WorkerMessage::Ticket(TicketMessage { + team_id: team_id.to_string(), + installation_id, + source: TicketSource::Alert, + ticket_id: unit.ticket.clone(), + title: unit.title.clone(), + body, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + issue_number: 0, + sender: "security".into(), + requester: Some(common::requester::Requester::coderhelm( + common::requester::SECURITY, + )), + base_branch: base, + ..Default::default() + }); + state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(serde_json::to_string(&msg).map_err(|e| e.to_string())?) + .delay_seconds(delay_secs.clamp(0, 900)) + .send() + .await + .map_err(|e| e.to_string())?; + Ok(()) +} + /// Queues one infrastructure fix run. async fn enqueue( state: &WorkerState, @@ -287,31 +336,16 @@ async fn enqueue( .send() .await .map_err(|e| e.to_string())?; - let msg = WorkerMessage::Ticket(TicketMessage { - team_id: team_id.to_string(), + send_ticket( + state, + team_id, installation_id, - source: TicketSource::Alert, - ticket_id: unit.ticket.clone(), - title: unit.title.clone(), - body: records::ticket_body(r), - repo_owner: owner.to_string(), - repo_name: name.to_string(), - issue_number: 0, - sender: "security".into(), - requester: Some(common::requester::Requester::coderhelm( - common::requester::SECURITY, - )), - base_branch: base, - ..Default::default() - }); - state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(serde_json::to_string(&msg).map_err(|e| e.to_string())?) - .send() - .await - .map_err(|e| e.to_string())?; + &unit, + records::ticket_body(r), + base, + 0, + ) + .await?; r.status = Status::Fixing; r.ticket = unit.ticket.clone(); r.updated_at = Utc::now().to_rfc3339(); @@ -359,15 +393,30 @@ async fn start_fixes( if only.is_some() && !asked { continue; } - if r.status != Status::Open - || r.finding.fix.kind != Some(FixKind::Pr) - || r.finding.fix.location.is_none() - { + if r.status != Status::Open || unit_for(r).is_none() { if asked { - why = Some("This finding has no PR to open (a runbook step, AWS-managed, or no file found).".into()); + why = Some(if r.finding.fix.decision.is_empty() { + "This finding has no PR to open (a runbook step, AWS-managed, or no file found).".into() + } else { + format!("This finding has no PR to open. {}", r.finding.fix.decision) + }); } 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. + if r.guard_blocks() && !asked { + continue; + } + // Production waits for its non-production copy. A person's own + // request for this finding goes ahead. + if !asked { + let today = Utc::now().format("%Y-%m-%d").to_string(); + if records::held(r, records, &today).is_some() { + continue; + } + } if !asked && (!cfg.acts() || !cadence_due(cfg.open_prs.get(r.tier().unwrap_or(Tier::P3)), daily)) { @@ -391,6 +440,9 @@ async fn start_fixes( match sec::admit_run(&slots(state, team_id), cfg, &day, busy).await { Admit::Start => { let r = &mut records[i]; + // A refusal about a change it no longer asks for, or one + // a person overrides, is forgotten: a full cycle again. + r.start_over(); match enqueue(state, team_id, installation_id, r).await { Ok(()) => started += 1, Err(e) => { @@ -579,7 +631,157 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { } } -/// A fix run for an infrastructure finding opened its PR. +/// 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 { + let changes: Vec = files + .iter() + .map(|(path, before, after)| common::infra_vuln::guard::Change { + path, + before, + after, + }) + .collect(); + common::infra_vuln::guard::refusals(&changes) +} + +/// What the guard needs to act on a pull request. +struct Guarded { + gh: crate::clients::github::GitHubClient, + installation_id: u64, + base: String, + reasons: Vec, +} + +/// Reads each infrastructure file the pull request changed, before and +/// after, and asks the replacement guard. `None` when the files could not +/// be read (the guard then has no say; the description still carries what +/// the plan must show). +async fn guard_pr( + state: &WorkerState, + team_id: &str, + unit: &FixUnit, + number: u64, +) -> Option { + let installation_id = super::review_reminder::team_installation_id(state, team_id).await?; + let gh = crate::clients::github::GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + installation_id, + &state.http, + ) + .ok()?; + let (owner, name) = unit.repo.split_once('/')?; + let base = gh.get_default_branch(owner, name).await.ok()?; + let changed = gh.list_pull_files(owner, name, number).await.ok()?; + let mut files = Vec::new(); + for (path, _) in changed { + if !common::infra_vuln::locate::maybe_iac_path(&path) { + continue; + } + let before = gh + .read_file_if_exists(owner, name, &path, &base) + .await + .ok()? + .unwrap_or_default(); + let after = gh + .read_file_if_exists(owner, name, &path, &unit.branch) + .await + .ok()? + .unwrap_or_default(); + files.push((path, before, after)); + } + let reasons = guard_refusals(&files); + Some(Guarded { + gh, + installation_id, + base, + reasons, + }) +} + +/// What a record shows after each outcome of the guard, and the line for +/// the finding's timeline. Pure. +pub(crate) fn after_guard( + r: &mut Record, + reasons: &[String], + number: u64, + url: &str, + now: &str, +) -> (records::GuardStep, String) { + let step = r.guard_step(reasons); + let pr = |state: &str| { + Some(records::PrRef { + number, + url: url.to_string(), + state: state.into(), + }) + }; + let event = match step { + records::GuardStep::Passed => { + r.status = Status::PrOpen; + r.pr = pr("open"); + format!("PR #{number} opened") + } + records::GuardStep::FixRound => { + // Still CoderHelm's to finish: the fix round is on its way. + r.status = Status::Fixing; + r.pr = pr("open"); + 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("; ") + ) + } + records::GuardStep::Draft => { + r.status = Status::Open; + r.pr = pr("draft"); + format!( + "PR #{number} is now a draft: after a fix round the change would still replace or destroy a resource that holds data ({}). The finding shows its runbook. {}", + reasons.join("; "), + records::GUARD_STOPPED + ) + } + }; + r.updated_at = now.to_string(); + (step, event) +} + +/// 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 { + return; + }; + let pr = match g.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"); + return; + } + }; + 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 { + warn!(number, error = %e, "infra findings: the pull request could not be made a draft"); + } + } + } + // 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 { + warn!(number, error = %e, "infra findings: the reason could not be written on the pull request"); + } +} + +/// A fix run for an infrastructure finding opened or updated its PR. The +/// replacement guard reads the change first. A change that would replace +/// or destroy a resource that holds data gets one fix round that is told +/// each offending line; if the change still trips the guard after it, the +/// pull request becomes a draft with the reason at its top, the finding +/// falls back to its runbook, and no further attempt starts by itself +/// until the finding's code or target changes. The pull request is never +/// closed and its branch is never deleted. pub async fn on_pr_opened( state: &WorkerState, team_id: &str, @@ -587,25 +789,41 @@ pub async fn on_pr_opened( number: u64, url: &str, ) { + let guarded = guard_pr(state, team_id, unit, number).await; + let reasons: Vec = guarded + .as_ref() + .map(|g| g.reasons.clone()) + .unwrap_or_default(); + let mut drafted = false; for id in &unit.finding_ids { let mut recs = load_records(state, team_id).await; - if let Some(r) = recs.iter_mut().find(|r| &r.finding.id == id) { - r.status = Status::PrOpen; - r.pr = Some(records::PrRef { - number, - url: url.to_string(), - state: "open".into(), - }); - r.updated_at = Utc::now().to_rfc3339(); - save(state, team_id, r).await; - super::security_fixes::add_event( - state, - team_id, - id, - &format!("PR #{number} opened"), - Some(url), - ) - .await; + let Some(r) = recs.iter_mut().find(|r| &r.finding.id == id) else { + continue; + }; + let (step, event) = after_guard(r, &reasons, number, url, &Utc::now().to_rfc3339()); + save(state, team_id, r).await; + super::security_fixes::add_event(state, team_id, id, &event, Some(url)).await; + match (step, &guarded) { + (records::GuardStep::FixRound, Some(g)) => { + if let Err(e) = send_ticket( + state, + team_id, + g.installation_id, + unit, + records::fix_round_body(r), + g.base.clone(), + FIX_ROUND_DELAY_SECS, + ) + .await + { + warn!(team_id, number, error = %e, "infra findings: the fix round could not be queued"); + } + } + (records::GuardStep::Draft, Some(g)) if !drafted => { + draft_with_reason(g, unit, number, &reasons).await; + drafted = true; + } + _ => {} } } } @@ -664,6 +882,148 @@ mod tests { let mut none = r.clone(); none.finding.fix.location = None; assert!(unit_for(&none).is_none(), "no file, no PR"); + // A location that is a guess is never a pull request. + let mut unsure = r.clone(); + if let Some(l) = unsure.finding.fix.location.as_mut() { + l.confidence = common::infra_vuln::inventory::Confidence::Low; + } + assert!( + unit_for(&unsure).is_none(), + "a low-confidence match opens no PR" + ); + // Nor is a runbook that happens to know where the code is. + let mut runbook = r.clone(); + runbook.finding.fix.kind = Some(FixKind::Runbook); + assert!(unit_for(&runbook).is_none()); + } + + fn pr_record() -> Record { + Record::new( + InfraFinding { + id: "abc".into(), + name: "orders".into(), + fix: Fix { + kind: Some(FixKind::Pr), + to: "16.6".into(), + location: Some(Location { + repo: "acme/infra".into(), + file: "db/main.tf".into(), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }, + "t", + ) + } + + const WHY: &str = "db/main.tf, line 2: `aws_db_instance.orders` changes `identifier`, which replaces the resource"; + + #[test] + fn a_tripped_guard_gets_one_fix_round_and_the_pull_request_stays_open() { + let mut r = pr_record(); + let (step, event) = after_guard(&mut r, &[WHY.to_string()], 7, "u", "now"); + assert_eq!(step, records::GuardStep::FixRound); + // Still CoderHelm's work, the pull request open, never closed. + assert_eq!(r.status, Status::Fixing); + assert_eq!(r.pr.as_ref().unwrap().state, "open"); + assert!(event.contains("One fix round corrects it"), "{event}"); + assert!(!event.contains("closed")); + // What the round is told. + let body = records::fix_round_body(&r); + assert!( + body.contains(WHY) && body.contains("Undo exactly those lines"), + "{body}" + ); + // The round's change passes: a normal open pull request again. + let (step, event) = after_guard(&mut r, &[], 7, "u", "now"); + assert_eq!(step, records::GuardStep::Passed); + assert_eq!(r.status, Status::PrOpen); + assert!(r.refused.is_empty()); + assert_eq!(event, "PR #7 opened"); + } + + #[test] + fn a_second_trip_makes_the_pull_request_a_draft_and_stops_automatic_attempts() { + let mut r = pr_record(); + after_guard(&mut r, &[WHY.to_string()], 7, "u", "now"); + let (step, event) = after_guard(&mut r, &[WHY.to_string()], 7, "u", "now"); + assert_eq!(step, records::GuardStep::Draft); + assert_eq!(r.pr.as_ref().unwrap().state, "draft"); + assert!( + event.contains("is now a draft") && event.contains("runbook"), + "{event}" + ); + assert!(!event.contains("closed")); + // Open again as a finding, shown as a runbook, and not picked up + // by itself while it asks for the same change. + assert_eq!(r.status, Status::Open); + assert_eq!(r.view()["fix"]["kind"], "runbook"); + assert!(unit_for(&r).is_some(), "still a code fix underneath"); + assert!(r.guard_blocks()); + // Its target changes: an attempt may start again, from the top. + r.finding.fix.to = "16.8".into(); + assert!(!r.guard_blocks()); + r.start_over(); + let (step, _) = after_guard(&mut r, &[WHY.to_string()], 8, "u", "now"); + assert_eq!(step, records::GuardStep::FixRound); + } + + /// The description's section is what keeps the draft a draft: the one + /// decision that marks pull requests ready reads it as a hold, and a + /// draft is never merged (`await_merge`). + #[test] + fn the_draft_reason_holds_the_pull_request_and_nothing_closes_it_or_deletes_its_branch() { + use common::infra_vuln::guard; + let body = guard::put_hold("\n\n## Summary\n", &[WHY.to_string()]); + let holds = crate::passes::ready::body_holds(&body); + assert_eq!(holds.len(), 1, "{holds:?}"); + assert!(crate::passes::ready::body_holds("## Summary\n").is_empty()); + let decided = crate::passes::ready::decide(&crate::passes::ready::Facts { + draft: true, + body, + ..Default::default() + }); + assert!( + matches!(decided, crate::passes::ready::Decision::Held { .. }), + "{decided:?}" + ); + // This file never closes a pull request, deletes a branch or + // marks one ready. + let src = include_str!("infra_findings.rs"); + let code = src.split("#[cfg(test)]").next().unwrap(); + for never in [ + "close_pull_request", + "delete_branch", + "delete_ref", + "mark_pr_ready", + "merge_pull_request", + ] { + assert!(!code.contains(never), "infra_findings calls {never}"); + } + // And it writes a description in exactly one place. + assert_eq!(code.matches("description::save(").count(), 1); + assert!(!code.contains(&[".update_pr", "_body("].concat())); + } + + #[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"; + let ok = vec![( + "db/main.tf".to_string(), + before.to_string(), + before.replace("16.4", "16.6"), + )]; + assert!(guard_refusals(&ok).is_empty()); + let bad = vec![( + "db/main.tf".to_string(), + before.to_string(), + before.replace("orders-prod", "orders"), + )]; + let why = guard_refusals(&bad); + assert_eq!(why.len(), 1); + assert!(why[0].contains("replaces the resource"), "{why:?}"); } #[test] diff --git a/services/worker/src/passes/infra_inventory.rs b/services/worker/src/passes/infra_inventory.rs index be9b08d2b..215123876 100644 --- a/services/worker/src/passes/infra_inventory.rs +++ b/services/worker/src/passes/infra_inventory.rs @@ -9,17 +9,23 @@ //! summary of the read (`RES_READ##`) with any call AWS //! refused, naming the permission. //! -//! Where each resource is defined comes from its tags (a repository tag, -//! its CloudFormation stack) or a search of the team's infrastructure -//! repositories for its AMI, group or name. Lambda functions come from the -//! team's Terraform only: the role never reads function settings, which -//! hold environment variables. +//! Where each resource is defined (`common::infra_vuln::locate`): its +//! CloudFormation stack and logical id (its tags, or CloudFormation asked +//! by physical id where tags are missing), matched to a template or a CDK +//! construct; Terraform and OpenTofu matched by resource type and +//! attributes through module calls and variable files; and its name +//! written in an infrastructure file as a last resort. Every enabled +//! repository is read, and files are recognised as infrastructure code by +//! their content. Lambda functions come from the team's Terraform only: +//! the role never reads function settings, which hold environment +//! variables. use std::collections::{BTreeMap, BTreeSet}; use aws_sdk_dynamodb::types::AttributeValue; use chrono::{Duration, Utc}; use common::infra_vuln::inventory::{self as inv, Resource}; +use common::infra_vuln::locate; use common::infra_vuln::raw::{ RawAccount, RawAsg, RawCacheUpdate, RawDatabase, RawDomain, RawEksCluster, RawImage, RawInstance, RawLoadBalancer, RawNodegroup, RawPending, RawService, @@ -33,9 +39,16 @@ use crate::WorkerState; /// Pages read per list call (each up to 100 to 1,000 items). const MAX_PAGES: usize = 10; -/// Repositories and files searched to place resources. -const MAX_REPOS: usize = 8; -const MAX_FILES: usize = 40; +/// Repositories searched to place resources (every enabled one, up to +/// this many), the names searched for in each, and what is read: files per +/// repository, files and bytes per read, and the largest file. +const MAX_REPOS: usize = 30; +const MAX_TERMS: usize = 60; +const MAX_FILES_PER_REPO: usize = 400; +const MAX_FILES: usize = 1_200; +const MAX_BYTES: usize = 12 * 1024 * 1024; +const MAX_FILE_BYTES: usize = 400 * 1024; +const MAX_MENTIONS: usize = 2_000; /// Prefix of a read's summary row. pub const READ_PREFIX: &str = "RES_READ#"; @@ -463,142 +476,305 @@ async fn read_ecs(s: &Session, raw: &mut RawAccount) { } } +fn fact(facts: &mut BTreeMap, key: &str, value: Option) { + if let Some(v) = value.filter(|v| !v.is_empty()) { + facts.insert(key.to_string(), v); + } +} + +/// Clusters, instances and pending maintenance, every page (each call +/// returns at most 100 records and a marker for the next). async fn read_rds(s: &Session, raw: &mut RawAccount) { let rds = client!(aws_sdk_rds, s); - match rds.describe_db_clusters().max_records(100).send().await { - Ok(o) => raw.db_clusters.extend(o.db_clusters().iter().map(|c| { - RawDatabase { - id: c.db_cluster_identifier().unwrap_or("").into(), - arn: c.db_cluster_arn().unwrap_or("").into(), - engine: c.engine().unwrap_or("").into(), - engine_version: c.engine_version().unwrap_or("").into(), - public: c.publicly_accessible().unwrap_or(false), - cluster: String::new(), - tags: tags_of( - c.tag_list() - .iter() - .map(|t| (t.key().unwrap_or(""), t.value().unwrap_or(""))), - ), + let mut writers: BTreeSet = BTreeSet::new(); + let mut marker: Option = None; + for _ in 0..MAX_PAGES { + match rds + .describe_db_clusters() + .max_records(100) + .set_marker(marker.take()) + .send() + .await + { + Ok(o) => { + for c in o.db_clusters() { + for m in c.db_cluster_members() { + if m.is_cluster_writer() == Some(true) { + writers.insert(m.db_instance_identifier().unwrap_or("").to_string()); + } + } + let mut facts = BTreeMap::new(); + fact( + &mut facts, + "subnet_group", + c.db_subnet_group().map(String::from), + ); + fact( + &mut facts, + "parameter_group", + c.db_cluster_parameter_group().map(String::from), + ); + fact(&mut facts, "multi_az", c.multi_az().map(|b| b.to_string())); + fact( + &mut facts, + "auto_minor", + c.auto_minor_version_upgrade().map(|b| b.to_string()), + ); + fact( + &mut facts, + "maintenance_window", + c.preferred_maintenance_window().map(String::from), + ); + fact( + &mut facts, + "backup_retention", + c.backup_retention_period().map(|n| n.to_string()), + ); + raw.db_clusters.push(RawDatabase { + id: c.db_cluster_identifier().unwrap_or("").into(), + arn: c.db_cluster_arn().unwrap_or("").into(), + engine: c.engine().unwrap_or("").into(), + engine_version: c.engine_version().unwrap_or("").into(), + public: c.publicly_accessible().unwrap_or(false), + cluster: String::new(), + tags: tags_of( + c.tag_list() + .iter() + .map(|t| (t.key().unwrap_or(""), t.value().unwrap_or(""))), + ), + writer: false, + facts, + }); + } + marker = o.marker().map(String::from); } - })), - Err(e) => note!(raw, "DescribeDBClusters", e), + Err(e) => { + note!(raw, "DescribeDBClusters", e); + break; + } + } + if marker.is_none() { + break; + } } - match rds.describe_db_instances().max_records(100).send().await { - Ok(o) => raw.db_instances.extend(o.db_instances().iter().map(|d| { - RawDatabase { - id: d.db_instance_identifier().unwrap_or("").into(), - arn: d.db_instance_arn().unwrap_or("").into(), - engine: d.engine().unwrap_or("").into(), - engine_version: d.engine_version().unwrap_or("").into(), - public: d.publicly_accessible().unwrap_or(false), - cluster: d.db_cluster_identifier().unwrap_or("").into(), - tags: tags_of( - d.tag_list() - .iter() - .map(|t| (t.key().unwrap_or(""), t.value().unwrap_or(""))), - ), + let mut marker: Option = None; + for _ in 0..MAX_PAGES { + match rds + .describe_db_instances() + .max_records(100) + .set_marker(marker.take()) + .send() + .await + { + Ok(o) => { + for d in o.db_instances() { + let id = d.db_instance_identifier().unwrap_or("").to_string(); + let mut facts = BTreeMap::new(); + fact( + &mut facts, + "subnet_group", + d.db_subnet_group() + .and_then(|g| g.db_subnet_group_name()) + .map(String::from), + ); + fact( + &mut facts, + "parameter_group", + d.db_parameter_groups() + .first() + .and_then(|g| g.db_parameter_group_name()) + .map(String::from), + ); + fact( + &mut facts, + "instance_class", + d.db_instance_class().map(String::from), + ); + fact(&mut facts, "multi_az", d.multi_az().map(|b| b.to_string())); + fact( + &mut facts, + "auto_minor", + d.auto_minor_version_upgrade().map(|b| b.to_string()), + ); + fact( + &mut facts, + "maintenance_window", + d.preferred_maintenance_window().map(String::from), + ); + fact( + &mut facts, + "backup_retention", + d.backup_retention_period().map(|n| n.to_string()), + ); + let replicas = d.read_replica_db_instance_identifiers().len(); + if replicas > 0 { + facts.insert("replicas".into(), replicas.to_string()); + } + fact( + &mut facts, + "replica_of", + d.read_replica_source_db_instance_identifier() + .map(String::from), + ); + raw.db_instances.push(RawDatabase { + writer: writers.contains(&id), + id, + arn: d.db_instance_arn().unwrap_or("").into(), + engine: d.engine().unwrap_or("").into(), + engine_version: d.engine_version().unwrap_or("").into(), + public: d.publicly_accessible().unwrap_or(false), + cluster: d.db_cluster_identifier().unwrap_or("").into(), + tags: tags_of( + d.tag_list() + .iter() + .map(|t| (t.key().unwrap_or(""), t.value().unwrap_or(""))), + ), + facts, + }); + } + marker = o.marker().map(String::from); + } + Err(e) => { + note!(raw, "DescribeDBInstances", e); + break; } - })), - Err(e) => note!(raw, "DescribeDBInstances", e), + } + if marker.is_none() { + break; + } } - match rds - .describe_pending_maintenance_actions() - .max_records(100) - .send() - .await - { - Ok(o) => { - for r in o.pending_maintenance_actions() { - for a in r.pending_maintenance_action_details() { - let d = |t: Option<&aws_smithy_types::DateTime>| { - t.and_then(|x| x.fmt(aws_smithy_types::date_time::Format::DateTime).ok()) + let mut marker: Option = None; + for _ in 0..MAX_PAGES { + match rds + .describe_pending_maintenance_actions() + .max_records(100) + .set_marker(marker.take()) + .send() + .await + { + Ok(o) => { + for r in o.pending_maintenance_actions() { + for a in r.pending_maintenance_action_details() { + let d = |t: Option<&aws_smithy_types::DateTime>| { + t.and_then(|x| { + x.fmt(aws_smithy_types::date_time::Format::DateTime).ok() + }) .unwrap_or_default() - }; - raw.pending.push(RawPending { - resource_arn: r.resource_identifier().unwrap_or("").into(), - action: a.action().unwrap_or("").into(), - description: a.description().unwrap_or("").into(), - auto_applied_after: d(a.auto_applied_after_date()), - forced_apply: d(a.forced_apply_date()), - current_apply: d(a.current_apply_date()), - }); + }; + raw.pending.push(RawPending { + resource_arn: r.resource_identifier().unwrap_or("").into(), + action: a.action().unwrap_or("").into(), + description: a.description().unwrap_or("").into(), + auto_applied_after: d(a.auto_applied_after_date()), + forced_apply: d(a.forced_apply_date()), + current_apply: d(a.current_apply_date()), + }); + } } + marker = o.marker().map(String::from); + } + Err(e) => { + note!(raw, "DescribePendingMaintenanceActions", e); + break; } } - Err(e) => note!(raw, "DescribePendingMaintenanceActions", e), + if marker.is_none() { + break; + } } } async fn read_elasticache(s: &Session, raw: &mut RawAccount) { let ec = client!(aws_sdk_elasticache, s); let mut severity: BTreeMap = BTreeMap::new(); - match ec - .describe_service_updates() - .service_update_status(aws_sdk_elasticache::types::ServiceUpdateStatus::Available) - .max_records(100) - .send() - .await - { - Ok(o) => { - for u in o.service_updates() { - severity.insert( - u.service_update_name().unwrap_or("").into(), - ( - u.service_update_severity() - .map(|x| x.as_str().to_string()) - .unwrap_or_default(), - u.service_update_type() - .map(|x| x.as_str().to_string()) - .unwrap_or_default(), - u.service_update_recommended_apply_by_date() - .and_then(|x| x.fmt(aws_smithy_types::date_time::Format::DateTime).ok()) - .unwrap_or_default(), - ), - ); + let mut marker: Option = None; + for _ in 0..MAX_PAGES { + match ec + .describe_service_updates() + .service_update_status(aws_sdk_elasticache::types::ServiceUpdateStatus::Available) + .max_records(100) + .set_marker(marker.take()) + .send() + .await + { + Ok(o) => { + for u in o.service_updates() { + severity.insert( + u.service_update_name().unwrap_or("").into(), + ( + u.service_update_severity() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + u.service_update_type() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + u.service_update_recommended_apply_by_date() + .and_then(|x| { + x.fmt(aws_smithy_types::date_time::Format::DateTime).ok() + }) + .unwrap_or_default(), + ), + ); + } + marker = o.marker().map(String::from); + } + Err(e) => { + note!(raw, "DescribeServiceUpdates", e); + return; } } - Err(e) => { - note!(raw, "DescribeServiceUpdates", e); - return; + if marker.is_none() { + break; } } if severity.is_empty() { return; } - match ec - .describe_update_actions() - .service_update_status(aws_sdk_elasticache::types::ServiceUpdateStatus::Available) - .max_records(100) - .send() - .await - { - Ok(o) => { - for a in o.update_actions() { - let name = a.service_update_name().unwrap_or("").to_string(); - let (sev, ty, by) = severity.get(&name).cloned().unwrap_or_default(); - raw.cache_updates.push(RawCacheUpdate { - group_id: a - .replication_group_id() - .or(a.cache_cluster_id()) - .unwrap_or("") - .into(), - status: a - .update_action_status() - .map(|x| x.as_str().to_string()) - .unwrap_or_default(), - severity: sev, - update_type: ty, - apply_by: a - .service_update_recommended_apply_by_date() - .and_then(|x| x.fmt(aws_smithy_types::date_time::Format::DateTime).ok()) - .unwrap_or(by), - engine: a.engine().unwrap_or("").into(), - engine_version: String::new(), - service_update: name, - }); + let mut marker: Option = None; + for _ in 0..MAX_PAGES { + match ec + .describe_update_actions() + .service_update_status(aws_sdk_elasticache::types::ServiceUpdateStatus::Available) + .max_records(100) + .set_marker(marker.take()) + .send() + .await + { + Ok(o) => { + for a in o.update_actions() { + let name = a.service_update_name().unwrap_or("").to_string(); + let (sev, ty, by) = severity.get(&name).cloned().unwrap_or_default(); + raw.cache_updates.push(RawCacheUpdate { + group_id: a + .replication_group_id() + .or(a.cache_cluster_id()) + .unwrap_or("") + .into(), + status: a + .update_action_status() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + severity: sev, + update_type: ty, + apply_by: a + .service_update_recommended_apply_by_date() + .and_then(|x| x.fmt(aws_smithy_types::date_time::Format::DateTime).ok()) + .unwrap_or(by), + engine: a.engine().unwrap_or("").into(), + engine_version: String::new(), + service_update: name, + }); + } + marker = o.marker().map(String::from); + } + Err(e) => { + note!(raw, "DescribeUpdateActions", e); + break; } } - Err(e) => note!(raw, "DescribeUpdateActions", e), + if marker.is_none() { + break; + } } } @@ -1069,17 +1245,99 @@ pub async fn infra_config( .unwrap_or_default() } -/// Places each resource in the team's code, and adds the Lambda functions -/// its Terraform defines. +/// CloudFormation is asked about at most this many resources per read. +const MAX_STACK_LOOKUPS: usize = 80; + +/// Asks CloudFormation which stack made each resource that carries no +/// stack tags (tags are not propagated to every resource type), and adds +/// the answer as the tags a stack would have set. A role that may not ask +/// is noted once, with the permission, and the read goes on without it. +async fn lookup_stacks(s: &Session, raw: &mut RawAccount, resources: &mut [Resource]) { + use common::infra_vuln::stacks::{self, Owner}; + let mut order: Vec = (0..resources.len()) + .filter(|i| locate::stack_ref(&resources[*i]).is_none()) + .filter(|i| stacks::physical_id(&resources[*i]).is_some()) + .collect(); + // What has an update pending first: those are the rows a fix needs. + order.sort_by_key(|i| resources[*i].pending.is_empty()); + let mut failed = 0; + for i in order.into_iter().take(MAX_STACK_LOOKUPS) { + let Some(id) = stacks::physical_id(&resources[i]) else { + continue; + }; + match stacks::owner_of(s, &id).await { + Owner::Stack { stack, logical_id } => { + let t = &mut resources[i].tags; + t.insert("aws:cloudformation:stack-name".into(), stack); + t.insert("aws:cloudformation:logical-id".into(), logical_id); + t.insert(locate::LOOKUP_TAG.into(), "true".into()); + } + Owner::None => {} + Owner::Denied(why) => { + raw.errors.push(("DescribeStackResources".into(), why)); + return; + } + Owner::Failed(why) => { + failed += 1; + if failed >= 3 { + raw.errors.push(("DescribeStackResources".into(), why)); + return; + } + } + } + } +} + +/// What placing read, kept on the read's summary so nothing is skipped +/// silently. +#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize)] +pub struct Placing { + pub repos: usize, + pub repos_not_searched: usize, + pub files_read: usize, + pub files_not_read: usize, + pub located: usize, + pub sure: usize, +} + +/// The order a repository's candidate files are read in, within the cap: +/// files a resource's name was found in, then Terraform and its variable +/// files (a module's caller and an environment's values may name nothing +/// the search looks for), then files found by a tool's marker, then other +/// files whose name says infrastructure. +pub fn read_order( + named: &BTreeSet, + marked: &BTreeSet, + tree: &[String], +) -> Vec { + let tf = |p: &str| p.ends_with(".tf") || p.ends_with(".tofu") || p.ends_with(".tfvars"); + let mut out: Vec = Vec::new(); + let mut push = |p: &String| { + if locate::maybe_iac_path(p) && !out.contains(p) { + out.push(p.clone()); + } + }; + named.iter().for_each(&mut push); + tree.iter().filter(|p| tf(p)).for_each(&mut push); + marked.iter().for_each(&mut push); + tree.iter() + .filter(|p| locate::iac_by_name(p)) + .for_each(&mut push); + out +} + +/// Places each resource in the team's code, across every connected +/// repository, and adds the Lambda functions its Terraform defines. async fn place( state: &WorkerState, team_id: &str, account: &str, region: &str, resources: &mut Vec, -) { +) -> Placing { + let mut report = Placing::default(); let Some(iid) = super::review_reminder::team_installation_id(state, team_id).await else { - return; + return report; }; let Ok(gh) = crate::clients::github::GitHubClient::new( &state.secrets.github_app_id, @@ -1087,61 +1345,102 @@ async fn place( iid, &state.http, ) else { - return; + return report; }; - let repos: Vec = super::infra_repo::team_repos(state, team_id) - .await + // Every enabled repository; those that speak of infrastructure first, + // so they are inside the cap when a team has very many. + let mut all = super::infra_repo::team_repos(state, team_id).await; + all.retain(|r| r.enabled); + all.sort_by_key(|r| !super::infra_repo::speaks_of_infrastructure(r)); + report.repos_not_searched = all.len().saturating_sub(MAX_REPOS); + let repos: Vec = all .into_iter() - .filter(|r| r.enabled) - .map(|r| r.full_name) .take(MAX_REPOS) + .map(|r| r.full_name) .collect(); - let mut files: Vec<(String, String, String)> = Vec::new(); - let mut fetched: BTreeSet<(String, String)> = BTreeSet::new(); - let mut wanted: Vec<(String, String)> = Vec::new(); - let mut terms: Vec = resources.iter().flat_map(inv::search_terms).collect(); - terms.push("aws_lambda_function".into()); - terms.sort(); - terms.dedup(); + report.repos = repos.len(); + let terms = locate::ranked_terms(resources, MAX_TERMS); + let mut files: Vec = Vec::new(); + let mut mentions: Vec = Vec::new(); + let mut bytes = 0usize; for repo in &repos { let Some((owner, name)) = repo.split_once('/') else { continue; }; - for term in terms.iter().take(30) { + let mut named: BTreeSet = BTreeSet::new(); + let mut marked: BTreeSet = BTreeSet::new(); + for term in &terms { if let Ok(hits) = gh.search_code(owner, name, "HEAD", term).await { - for h in hits - .into_iter() - .filter(|h| super::infra_repo::is_iac_path(&h.path)) - { - wanted.push((repo.clone(), h.path)); + for h in hits { + if mentions.len() < MAX_MENTIONS { + mentions.push(locate::Mention { + repo: repo.clone(), + path: h.path.clone(), + term: term.clone(), + }); + } + named.insert(h.path); } } } - } - for (repo, path) in wanted { - if files.len() >= MAX_FILES || !fetched.insert((repo.clone(), path.clone())) { - continue; + for marker in locate::MARKERS { + if let Ok(hits) = gh.search_code(owner, name, "HEAD", marker).await { + marked.extend(hits.into_iter().map(|h| h.path)); + } } - let Some((owner, name)) = repo.split_once('/') else { - continue; - }; - if let Ok(c) = gh.get_file_content(owner, name, &path).await { - files.push((repo, path, c)); + let tree: Vec = gh + .get_tree(owner, name, "HEAD") + .await + .map(|t| { + t.into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect() + }) + .unwrap_or_default(); + let order = read_order(&named, &marked, &tree); + let mut read = 0; + for path in &order { + if read >= MAX_FILES_PER_REPO || files.len() >= MAX_FILES || bytes >= MAX_BYTES { + report.files_not_read += 1; + continue; + } + let Ok(content) = gh.get_file_content(owner, name, path).await else { + continue; + }; + if content.len() > MAX_FILE_BYTES || locate::tool_of(path, &content).is_none() { + continue; + } + bytes += content.len(); + read += 1; + files.push(locate::SourceFile { + repo: repo.clone(), + path: path.clone(), + content, + }); } } + report.files_read = files.len(); + // Parsed once for every resource. + let code = locate::Code::new(&files, &mentions); for r in resources.iter_mut() { if r.defined_in.is_none() { - r.defined_in = inv::locate(r, &repos, &files); + r.defined_in = locate::locate_in(r, &repos, &code); + } + if let Some(l) = &r.defined_in { + report.located += 1; + report.sure += l.sure() as usize; } } let now = Utc::now().to_rfc3339(); - for (repo, path, content) in &files { - if path.ends_with(".tf") { + for f in &files { + if f.path.ends_with(".tf") { resources.extend(inv::lambdas_from_terraform( - repo, path, content, account, region, &now, + &f.repo, &f.path, &f.content, account, region, &now, )); } } + report } async fn save( @@ -1149,6 +1448,7 @@ async fn save( team_id: &str, raw: &RawAccount, resources: &[Resource], + placing: &Placing, ) -> usize { let ttl = (Utc::now() + Duration::days(inv::KEEP_DAYS)).timestamp(); let mut n = 0; @@ -1179,6 +1479,7 @@ async fn save( "resources": n, "errors": raw.errors.iter().map(|(c, w)| serde_json::json!({ "call": c, "why": w, "permission": common::infra_vuln::raw::CALLS.iter().find(|(x, _)| x == c).map(|(_, p)| *p) })).collect::>(), "latest_al2023": raw.latest_al2023, + "placing": placing, }); let _ = state .dynamo @@ -1242,10 +1543,11 @@ pub async fn read_account( .await .map_err(|e| e.message)?; let cfg = infra_config(state, team_id).await; - let raw = read_with(&session, &a.account, &cfg).await; + let mut raw = read_with(&session, &a.account, &cfg).await; let mut resources = raw.resources(); - place(state, team_id, &a.account, &a.region, &mut resources).await; - Ok(save(state, team_id, &raw, &resources).await) + lookup_stacks(&session, &mut raw, &mut resources).await; + let placing = place(state, team_id, &a.account, &a.region, &mut resources).await; + Ok(save(state, team_id, &raw, &resources, &placing).await) } /// The daily read, on the review-reminder tick: each account once a day. @@ -1284,3 +1586,66 @@ pub async fn sweep(state: &WorkerState) -> InventoryReport { ); report } + +#[cfg(test)] +mod tests { + use super::*; + + fn set(paths: &[&str]) -> BTreeSet { + paths.iter().map(|p| p.to_string()).collect() + } + + /// A module's caller and an environment's variable file may name + /// nothing the search looks for: every Terraform file is read, after + /// the files a name was found in and before files found by a marker. + #[test] + fn files_are_read_in_an_order_that_keeps_what_placing_needs() { + let tree: Vec = [ + "README.md", + "src/app/page.tsx", + "src/database.ts", + "modules/aurora/main.tf", + "envs/prod/main.tf", + "envs/prod.tfvars", + "deploy/api.yaml", + "serverless.yml", + "node_modules/aws-cdk-lib/index.js", + "package.json", + ] + .iter() + .map(|p| p.to_string()) + .collect(); + let named = set(&["deploy/api.yaml", "README.md", "scripts/deploy.sh"]); + let marked = set(&["src/database.ts", "node_modules/aws-cdk-lib/index.js"]); + let order = read_order(&named, &marked, &tree); + assert_eq!( + order, + vec![ + "deploy/api.yaml", + "modules/aurora/main.tf", + "envs/prod/main.tf", + "envs/prod.tfvars", + "src/database.ts", + "serverless.yml", + ] + ); + // Nothing vendored, no application page, no manifest, and a file + // is listed once. + assert!(order.iter().all(|p| !p.contains("node_modules"))); + } + + #[test] + fn the_caps_are_wide_enough_for_every_connected_repository() { + // The old caps were 8 repositories, 30 names and 40 files. + const { assert!(MAX_REPOS >= 30 && MAX_TERMS >= 60 && MAX_FILES >= 1_000) }; + const { assert!(MAX_FILES_PER_REPO < MAX_FILES) }; + let p = Placing { + repos: 3, + files_read: 12, + ..Default::default() + }; + let v = serde_json::to_value(&p).unwrap(); + assert_eq!(v["repos"], 3); + assert_eq!(v["files_not_read"], 0); + } +} diff --git a/services/worker/src/passes/infra_repo.rs b/services/worker/src/passes/infra_repo.rs index 1371f236e..3bbb926d9 100644 --- a/services/worker/src/passes/infra_repo.rs +++ b/services/worker/src/passes/infra_repo.rs @@ -37,6 +37,15 @@ pub struct CodeHit { pub repo: String, pub path: String, pub term: String, + /// The file was read and is infrastructure code by its content. + #[serde(default)] + pub iac: bool, +} + +impl CodeHit { + fn is_iac(&self) -> bool { + self.iac || is_iac_path(&self.path) + } } /// What the search found. @@ -58,15 +67,20 @@ pub enum Found { const MAX_REPOS: usize = 8; const MAX_TERMS: usize = 4; -/// Pure: whether a file is infrastructure code: Terraform, CloudFormation -/// or a CDK stack. +/// Files of one repository read to see whether they are infrastructure +/// code that their name does not give away. +const MAX_CONTENT_CHECKS: usize = 20; + +/// Pure: whether a file's name says it is infrastructure code: Terraform +/// and OpenTofu, CloudFormation and SAM templates, a Serverless Framework +/// service, a CDK or Pulumi program in a folder or file named for it. A +/// file at a neutral path is recognised by its content instead +/// ([`is_iac`]). pub fn is_iac_path(path: &str) -> bool { let p = path.to_ascii_lowercase(); let file = p.rsplit('/').next().unwrap_or(&p); - p.ends_with(".tf") + common::infra_vuln::locate::iac_by_name(path) || p.ends_with(".tf.json") - || p.ends_with(".tfvars") - || p.ends_with(".hcl") || ((p.ends_with(".yaml") || p.ends_with(".yml") || p.ends_with(".json")) && (p.contains("cloudformation") || p.contains("cfn") || file.contains("template"))) || ((p.ends_with(".ts") @@ -76,6 +90,13 @@ pub fn is_iac_path(path: &str) -> bool { && (file.contains("stack") || p.contains("/cdk/") || p.starts_with("cdk/"))) } +/// Pure: whether a file is infrastructure code, by what is in it: a CDK +/// construct file next to application code, a CloudFormation or SAM +/// template at any path, a `serverless.yml`, a Pulumi program. +pub fn is_iac(path: &str, content: &str) -> bool { + common::infra_vuln::locate::tool_of(path, content).is_some() +} + /// Pure: the names to search for, from the evidence: the task family, the /// service, the log group, the cluster; distinct, at least 4 characters. pub fn search_terms(ev: &LogEvidence) -> Vec { @@ -100,6 +121,11 @@ pub fn search_terms(ev: &LogEvidence) -> Vec { out } +/// Pure: the repository's role or description speaks of infrastructure. +pub fn speaks_of_infrastructure(r: &RepoInfo) -> bool { + infra_word(r) +} + fn infra_word(r: &RepoInfo) -> bool { let t = format!("{} {}", r.role, r.description).to_ascii_lowercase(); [ @@ -139,7 +165,7 @@ pub fn pick(primary: &str, repos: &[RepoInfo], hits: &[CodeHit], terms: &[String for (i, repo) in order.iter().enumerate() { let mut named: Vec<&str> = hits .iter() - .filter(|h| &h.repo == repo && is_iac_path(&h.path)) + .filter(|h| &h.repo == repo && h.is_iac()) .map(|h| h.term.as_str()) .collect(); named.sort(); @@ -163,14 +189,14 @@ pub fn pick(primary: &str, repos: &[RepoInfo], hits: &[CodeHit], terms: &[String Some((_, _, _, repo)) => { let mut files: Vec = hits .iter() - .filter(|h| h.repo == repo && is_iac_path(&h.path)) + .filter(|h| h.repo == repo && h.is_iac()) .map(|h| h.path.clone()) .collect(); files.sort(); files.dedup(); let mut found_terms: Vec = hits .iter() - .filter(|h| h.repo == repo && is_iac_path(&h.path)) + .filter(|h| h.repo == repo && h.is_iac()) .map(|h| h.term.clone()) .collect(); found_terms.sort(); @@ -342,13 +368,37 @@ pub async fn locate( let Some((owner, name)) = repo.split_once('/') else { continue; }; + // A file whose name does not say so may still be infrastructure + // code (CDK next to the application, a template at a neutral + // path): read it once to find out. + let mut by_content: std::collections::BTreeMap = + std::collections::BTreeMap::new(); for term in terms { if let Ok(found) = github.search_code(owner, name, "HEAD", term).await { - hits.extend(found.into_iter().map(|r| CodeHit { - repo: repo.clone(), - path: r.path, - term: term.clone(), - })); + for r in found { + let mut iac = false; + if !is_iac_path(&r.path) && common::infra_vuln::locate::maybe_iac_path(&r.path) + { + iac = match by_content.get(&r.path) { + Some(known) => *known, + None if by_content.len() < MAX_CONTENT_CHECKS => { + let is = github + .get_file_content(owner, name, &r.path) + .await + .is_ok_and(|c| is_iac(&r.path, &c)); + by_content.insert(r.path.clone(), is); + is + } + None => false, + }; + } + hits.push(CodeHit { + repo: repo.clone(), + path: r.path, + term: term.clone(), + iac, + }); + } } } } @@ -484,6 +534,7 @@ mod tests { repo: repo.into(), path: path.into(), term: term.into(), + iac: false, } } @@ -494,6 +545,42 @@ mod tests { assert!(is_iac_path("lib/web-stack.ts")); assert!(!is_iac_path("src/app/page.tsx")); assert!(!is_iac_path("docker-compose.yml")); + // By name: Serverless Framework, SAM, Pulumi, OpenTofu. + assert!(is_iac_path("services/api/serverless.yml")); + assert!(is_iac_path("samconfig.toml")); + assert!(is_iac_path("Pulumi.prod.yaml")); + assert!(is_iac_path("main.tofu")); + assert!(is_iac_path("infra/app.py")); + } + + #[test] + fn a_file_at_a_neutral_path_is_recognised_by_its_content() { + // CDK next to application code, in a file not named a stack. + assert!(!is_iac_path("src/database.ts")); + assert!(is_iac( + "src/database.ts", + "import * as rds from 'aws-cdk-lib/aws-rds';" + )); + // CloudFormation at a neutral path. + assert!(!is_iac_path("deploy/api.yaml")); + assert!(is_iac( + "deploy/api.yaml", + "AWSTemplateFormatVersion: '2010-09-09'\nResources:\n Db:\n Type: AWS::RDS::DBInstance\n" + )); + assert!(is_iac("index.ts", "import * as aws from '@pulumi/aws';")); + assert!(!is_iac( + "docker-compose.yml", + "services:\n web:\n image: nginx\n" + )); + assert!(!is_iac( + "src/app/page.tsx", + "export default function Page() {}" + )); + // A hit read and found to be infrastructure code counts. + let mut h = hit("acme/app", "src/database.ts", "orders"); + assert!(!h.is_iac()); + h.iac = true; + assert!(h.is_iac()); } #[test] diff --git a/services/worker/src/passes/link_checks.rs b/services/worker/src/passes/link_checks.rs index 26eef918d..30acd4aa8 100644 --- a/services/worker/src/passes/link_checks.rs +++ b/services/worker/src/passes/link_checks.rs @@ -1425,9 +1425,8 @@ pub async fn refresh_pr( super::completeness::Section::Links, String::new(), ); - if let Err(e) = github - .update_pr_body(owner, repo, pr_number, &without) - .await + if let Err(e) = + crate::passes::description::save(github, owner, repo, pr_number, &without).await { warn!(pr_number, error = %e, "Could not drop the link checks from the description"); } @@ -1453,9 +1452,8 @@ pub async fn refresh_pr( report.section(), ); if updated != body { - if let Err(e) = github - .update_pr_body(owner, repo, pr_number, &updated) - .await + if let Err(e) = + crate::passes::description::save(github, owner, repo, pr_number, &updated).await { warn!(pr_number, error = %e, "Could not save the link checks to the description"); return None; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 8aa8c7c57..5ce882505 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1205,6 +1205,7 @@ mod cross_repo; pub mod dep_fix; pub(crate) mod deploy_revert; pub mod deploy_stats; +pub mod description; pub mod dlq_cleanup; pub mod e2e; pub mod e2e_attribution; @@ -1212,6 +1213,7 @@ pub mod e2e_setup; pub mod email_events; pub mod feature; pub mod feedback; +pub mod file_claims; mod finish_planned; pub mod fix_location; pub(crate) mod flaky; @@ -6766,6 +6768,18 @@ async fn run_passes( "The proof check needs more time than this step has left" ); let mut gaps = proof::prove(&work, &mut evidence, usage, has_time).await; + // A sentence the run wrote into a file that says a check passes stays + // only on a recorded passing result. + let unproven_claims = file_claims::settle(state, msg, &github, work.branch, &evidence).await; + if !unproven_claims.is_empty() { + add_progress_note( + state, + &msg.team_id, + run_id, + &file_claims::note(&unproven_claims), + ) + .await; + } // Planned work the check found not done is never an Open item: it goes at // the top of the pull request, which stays a draft until it's done. if !proof::planned_work(&gaps).is_empty() { @@ -8120,6 +8134,16 @@ async fn run_repo_pipeline( has_time_for_remediation(start) }) .await; + let unproven_claims = file_claims::settle(state, msg, github, work.branch, &evidence).await; + if !unproven_claims.is_empty() { + add_progress_note( + state, + &msg.team_id, + run_id, + &file_claims::note(&unproven_claims), + ) + .await; + } // Planned work still not done after the fix rounds: this repository's // pull request stays a draft with it listed at the top. let unfinished = proof::unfinished_section(&gaps); diff --git a/services/worker/src/passes/outside_exec.rs b/services/worker/src/passes/outside_exec.rs index 51e9ad714..b9aed3713 100644 --- a/services/worker/src/passes/outside_exec.rs +++ b/services/worker/src/passes/outside_exec.rs @@ -862,7 +862,7 @@ pub async fn refresh_pr(github: &GitHubClient, owner: &str, repo: &str, pr: u64, ); let updated = outside_work::with_not_done_top(&super::completeness::assemble(&rest, &owned), c); if updated != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &updated).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr, &updated).await { warn!(pr, error = %e, "Could not update the PR's outside steps"); } } diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index cb536ed67..591f0fa92 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -646,9 +646,14 @@ Return ONLY the markdown body text."#, info!(pr_number = number, pr_url = %url, "Using existing PR"); // A re-run changed the code: the description is rewritten from this // diff, never left describing the earlier version. - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &full_body) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + number, + &full_body, + ) + .await { warn!(pr_number = number, error = %e, "Could not update the existing PR's description"); } @@ -1596,7 +1601,7 @@ pub async fn put_open_items( } let out = super::completeness::assemble(&rest, &owned); if out != body { - if let Err(e) = github.update_pr_body(owner, repo, number, &out).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, number, &out).await { warn!(pr_number = number, error = %e, "Could not list the open items on the PR"); } } @@ -1634,9 +1639,9 @@ pub async fn apply_checks( }; let out = with_checks(&body, plan, proof, &repo); if out != body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &out) - .await + if let Err(e) = + crate::passes::description::save(github, &msg.repo_owner, &msg.repo_name, number, &out) + .await { warn!(pr_number = number, error = %e, "Could not add the checks' results to the PR"); } @@ -1807,6 +1812,9 @@ pub async fn refresh_description( // writer's text and put back as they are. let release_section = super::release_plan::current_section(&rest); let rest = super::release_plan::put_section(&rest, ""); + // What the run did before and after the code is a record of checks + // that ran: the writer may move it, never reword or drop it. + let habits_section = super::habits_check::current_section(&rest); let shaped = super::completeness::assemble(&rest, &owned); let old = if requests.is_empty() { rest.trim().to_string() @@ -1917,6 +1925,11 @@ Return ONLY the markdown body text, then a line `{CHANGES_MARK}` and one bullet let written = split_changes(&written).0; // The Risk it states is at least what the diff now makes it. let written = super::pr_risk::enforce(&written, &risk_floor); + let written = if habits_section.is_empty() { + written + } else { + super::habits_check::shape_body(written, &habits_section) + }; if !keeps_ticket_line(&old, &written) { warn!( pr_number, @@ -1970,7 +1983,7 @@ Return ONLY the markdown body text, then a line `{CHANGES_MARK}` and one bullet if body == current { return None; } - if let Err(e) = github.update_pr_body(owner, repo, pr_number, &body).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr_number, &body).await { warn!(pr_number, error = %e, "Could not save the rewritten PR description"); return None; } @@ -2051,7 +2064,7 @@ async fn fill_placeholders_once( if fixed == body.trim() { return; } - match github.update_pr_body(owner, repo, pr_number, &fixed).await { + match crate::passes::description::save(github, owner, repo, pr_number, &fixed).await { Ok(()) => { let left = super::completeness::placeholder_holes(&fixed); if left.is_empty() { @@ -2094,7 +2107,7 @@ pub async fn link_siblings(github: &GitHubClient, prs: &[(String, String, u64)]) if new == body { continue; } - match github.update_pr_body(owner, name, *number, &new).await { + match crate::passes::description::save(github, owner, name, *number, &new).await { Ok(()) => info!( pr_number = number, "Named the run's sibling PRs and merge order" @@ -2125,7 +2138,7 @@ pub async fn settle_unverified_by_ci( let Some(body) = super::proof::settle_by_ci(pr["body"].as_str().unwrap_or("")) else { return; }; - match github.update_pr_body(owner, repo, pr_number, &body).await { + match crate::passes::description::save(github, owner, repo, pr_number, &body).await { Ok(()) => info!( pr_number, "CI passed: removed the checks it settled from the PR's Open items" diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index ed4a4dcf7..a55d40ba9 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -476,7 +476,10 @@ async fn perform( // request, never left as an unexplained verdict. let now = super::own_review::defer_findings(&body, &items, &why); if now != body { - if let Err(e) = github.update_pr_body(&c.owner, &c.repo, c.pr, &now).await { + if let Err(e) = + crate::passes::description::save(github, &c.owner, &c.repo, c.pr, &now) + .await + { warn!(run_id = %c.run_id, error = %e, "PR watch: could not list the deferred findings"); } } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index f4e72053b..06c7bda89 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -305,6 +305,14 @@ pub fn body_holds_on(body: &str, ci_green: bool) -> Vec { if let Some(r) = own_review_reason(body) { out.push(r); } + // An infrastructure fix the replacement guard gave up on: it would + // replace or destroy a resource that holds data. + if let Some(why) = common::infra_vuln::guard::hold(body) { + out.push(Reason::new( + why, + "Correct the lines named at the top of the description on this branch, then remove that section and mark the pull request ready; or apply the update with the runbook on the finding.", + )); + } // A stacked change asks a person to look first. if let Some(why) = super::stack::hold(body) { out.push(Reason::new( @@ -1147,9 +1155,7 @@ async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { // are deferred on the pull request with the reason and hold // nothing, so the draft waits only on what else holds it. let body = super::own_review::defer_findings(&f.body, &items, &why); - match ctx - .github - .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &body) + match crate::passes::description::save(ctx.github, ctx.owner, ctx.repo, ctx.pr, &body) .await { Ok(_) => { @@ -1407,10 +1413,8 @@ async fn write_body(ctx: &Ctx<'_>, body: &str, d: &Decision) { let Some(new) = body_for(body, d) else { return; }; - if let Err(e) = ctx - .github - .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &new) - .await + if let Err(e) = + crate::passes::description::save(ctx.github, ctx.owner, ctx.repo, ctx.pr, &new).await { warn!(pr = ctx.pr, error = %e, "Could not write the draft status to the description"); } @@ -1472,9 +1476,7 @@ async fn retry_or_give_up(ctx: &Ctx<'_>, run_id: &str, pr_url: &str, r: Refused) failed_section(&what), ); if new != body { - let _ = ctx - .github - .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &new) + let _ = crate::passes::description::save(ctx.github, ctx.owner, ctx.repo, ctx.pr, &new) .await; } } diff --git a/services/worker/src/passes/release_run.rs b/services/worker/src/passes/release_run.rs index 5dcf004a2..6fcb50835 100644 --- a/services/worker/src/passes/release_run.rs +++ b/services/worker/src/passes/release_run.rs @@ -564,7 +564,9 @@ pub async fn run(state: &WorkerState, msg: ReleaseStepsMessage) -> Result<(), Bo let body = p["body"].as_str().unwrap_or(""); let updated = release_plan::put_section(body, &release_plan::section(&after)); if updated != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &updated).await { + if let Err(e) = + crate::passes::description::save(&github, owner, repo, pr, &updated).await + { warn!(pr, error = %e, "release: could not update the PR's release section"); } } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 1def7ed08..551e0c4a6 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4088,7 +4088,17 @@ async fn run_fix_round( Ok(RoundEnd::Incomplete) } } - Ok(r) => { + Ok(mut r) => { + // The description is CoderHelm's to rebuild: an account that + // says it can't be edited, or leaves an edit of it to a person, + // loses that sentence and the rebuild runs below, whether or not + // the round pushed code. + let (account, handed_off) = + super::description::round_account(r.evidence.latest_notes()); + if handed_off { + warn!(run_id = %msg.run_id, "A fix round handed the description to a person; rebuilding it from the branch"); + r.evidence.notes = account; + } // What this round was asked and looked up reaches the next one. if round.kind == run_round::Kind::ReviewFix { record_own_round_note( @@ -4111,15 +4121,31 @@ async fn run_fix_round( // from the whole diff now, never left on the earlier // version. if files > 0 { - let _ = super::pr::refresh_description( + // A sentence the round wrote into a file that says + // a check passes stands only on a recorded result. + super::file_claims::settle( state, + &ctx.ticket_msg, &ctx.github, - (&msg.team_id, ctx.ticket_msg.installation_id), - pr.owner, - pr.repo, - pr.number, - &ctx.ticket_msg.team_instructions, - &[], + pr.branch, + &r.evidence, + ) + .await; + } + if files > 0 || handed_off { + let _ = super::description::head_moved( + &super::description::Moved { + state, + github: &ctx.github, + team_id: &msg.team_id, + installation_id: ctx.ticket_msg.installation_id, + owner: pr.owner, + repo: pr.repo, + number: pr.number, + ticket_id: &ctx.ticket_msg.ticket_id, + team_instructions: &ctx.ticket_msg.team_instructions, + requests: &[], + }, &ctx.provider, &mut ctx.usage, ) @@ -4129,6 +4155,25 @@ async fn run_fix_round( } super::round::Landed::Nothing => { super::round::clear(state, &msg.team_id, &msg.run_id).await; + if handed_off { + let _ = super::description::head_moved( + &super::description::Moved { + state, + github: &ctx.github, + team_id: &msg.team_id, + installation_id: ctx.ticket_msg.installation_id, + owner: pr.owner, + repo: pr.repo, + number: pr.number, + ticket_id: &ctx.ticket_msg.ticket_id, + team_instructions: &ctx.ticket_msg.team_instructions, + requests: &[], + }, + &ctx.provider, + &mut ctx.usage, + ) + .await; + } Ok(RoundEnd::Done { files: 0 }) } super::round::Landed::Refused(why) => { @@ -4718,10 +4763,14 @@ async fn after_planned_round( section.clone(), ); if updated != body { - if let Err(e) = ctx - .github - .update_pr_body(pr.owner, pr.repo, pr.number, &updated) - .await + if let Err(e) = crate::passes::description::save( + &ctx.github, + pr.owner, + pr.repo, + pr.number, + &updated, + ) + .await { warn!(run_id = msg.run_id, error = %e, "Could not update the PR's Not finished section"); } @@ -4906,10 +4955,9 @@ async fn recheck_security( } }; if let Some(updated) = super::proof::with_security_items(&body, &items) { - if let Err(e) = ctx - .github - .update_pr_body(pr.owner, pr.repo, pr.number, &updated) - .await + if let Err(e) = + crate::passes::description::save(&ctx.github, pr.owner, pr.repo, pr.number, &updated) + .await { warn!(run_id = msg.run_id, error = %e, "Could not update the PR's security items"); } @@ -6105,9 +6153,14 @@ async fn finish_on_own_findings( let body = p["body"].as_str().unwrap_or(""); let now = super::own_review::defer_findings(body, open, why); if now != body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, pr_number, &now) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + pr_number, + &now, + ) + .await { warn!(run_id, error = %e, "Could not list the deferred findings on the pull request"); } @@ -6206,9 +6259,8 @@ async fn hand_off_red_ci( match github.get_pull_request(pr.owner, pr.repo, pr.number).await { Ok(p) => { let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); - if let Err(e) = github - .update_pr_body(pr.owner, pr.repo, pr.number, &body) - .await + if let Err(e) = + crate::passes::description::save(github, pr.owner, pr.repo, pr.number, &body).await { warn!(run_id = msg.run_id, error = %e, "Could not write what fails on the pull request"); } @@ -6301,9 +6353,8 @@ pub(crate) async fn end_red_ci_rounds( match github.get_pull_request(pr.owner, pr.repo, number).await { Ok(p) => { let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); - if let Err(e) = github - .update_pr_body(pr.owner, pr.repo, number, &body) - .await + if let Err(e) = + crate::passes::description::save(github, pr.owner, pr.repo, number, &body).await { warn!(run_id, error = %e, "Could not write what fails on the pull request"); } @@ -6543,6 +6594,18 @@ async fn revert_dep_commit( apply_revert(state, msg, github, pr, files, ¬e).await?; super::dep_fix::save(state, ticket_msg, &msg.run_id, &run).await; super::dep_fix::settle(state, ticket_msg, &run).await; + // The head lost a set of bumps: the table and the headline say what it + // resolves now. + super::description::dependency_sections( + state, + github, + &msg.team_id, + pr.owner, + pr.repo, + pr.number, + &ticket_msg.ticket_id, + ) + .await; Some(note) } @@ -6669,9 +6732,7 @@ async fn apply_revert( } else { format!("{}\n\n## Deferred\n{line}", body.trim_end()) }; - let _ = github - .update_pr_body(pr.owner, pr.repo, pr.number, &now) - .await; + let _ = crate::passes::description::save(github, pr.owner, pr.repo, pr.number, &now).await; } Some(()) } diff --git a/services/worker/src/passes/review_fix/mod.rs b/services/worker/src/passes/review_fix/mod.rs index 1def9c499..f3ab956b4 100644 --- a/services/worker/src/passes/review_fix/mod.rs +++ b/services/worker/src/passes/review_fix/mod.rs @@ -1391,9 +1391,8 @@ pub async fn record_round( section, ); if updated != body { - if let Err(e) = github - .update_pr_body(owner, repo, pr_number, &updated) - .await + if let Err(e) = + crate::passes::description::save(github, owner, repo, pr_number, &updated).await { warn!(pr_number, error = %e, "review fix: could not record the round in the description"); } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 9ef7d5f13..ec274bdc7 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3579,9 +3579,14 @@ async fn run_once( section, ); if updated != pr_body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, msg.pr_number, &updated) - .await + if let Err(e) = crate::passes::description::save( + &github, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &updated, + ) + .await { warn!(pr = msg.pr_number, error = %e, "Could not update the own PR's open review findings"); } else { @@ -4568,9 +4573,14 @@ async fn end_self_review_rounds( let body = p["body"].as_str().unwrap_or(""); let now = super::own_review::defer_findings(body, open, why); if now != body { - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, msg.pr_number, &now) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &now, + ) + .await { warn!(pr = msg.pr_number, error = %e, "Could not list the deferred findings on the pull request"); } diff --git a/services/worker/src/passes/reviewer_guide.rs b/services/worker/src/passes/reviewer_guide.rs index a766f1613..25495dbe9 100644 --- a/services/worker/src/passes/reviewer_guide.rs +++ b/services/worker/src/passes/reviewer_guide.rs @@ -364,7 +364,8 @@ pub async fn refresh(github: &GitHubClient, owner: &str, repo: &str, pr_number: let floor = super::pr_risk::floor(&files, &HashMap::new()); let out = put(body, build(github, owner, repo, &files, &floor, head).await); if out != body { - if let Err(e) = github.update_pr_body(owner, repo, pr_number, &out).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr_number, &out).await + { warn!(pr_number, error = %e, "Reviewer guide: could not save the description"); } } diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index 9471a522f..cbbbd0830 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -2997,8 +2997,11 @@ async fn refresh_pr( ) .await; let links = body_links(cx.state, item.as_ref()); - let body = sec::pr_body_linked(unit, &pairs, &change, &check, &links); - if let Err(e) = cx.gh.update_pr_body(o, n, pr, &body).await { + // What the branch resolves now, with the fixes that joined or left. + let base = cx.gh.get_default_branch(o, n).await.unwrap_or_default(); + let head = head_facts(&cx.gh, unit, &base, &unit.branch).await; + let body = sec::pr_body_at_head(unit, &pairs, &change, &check, &links, &head); + if let Err(e) = crate::passes::description::save(&cx.gh, o, n, pr, &body).await { warn!(repo = %unit.repo, pr, error = %e, "security: could not write the bundle's description"); } if let Err(e) = cx.gh.update_pr_title(o, n, pr, &unit.title).await { @@ -4176,7 +4179,104 @@ pub async fn pr_body(state: &WorkerState, msg: &TicketMessage, change: &str) -> } } } - Some(sec::pr_body_linked(&unit, &pairs, change, &check, &links)) + // The table and the headline say what the branch's lockfile resolves, + // never what the run planned. + let head = match &gh { + Some(gh) => head_facts(gh, &unit, &msg.base_branch, &unit.branch).await, + None => common::dep_head::unknown(&unit, "GitHub could not be reached to read the branch"), + }; + Some(sec::pr_body_at_head( + &unit, &pairs, change, &check, &links, &head, + )) +} + +/// The lockfiles whose resolved copies CoderHelm reads. +fn is_read_lockfile(path: &str) -> bool { + let name = path.rsplit('/').next().unwrap_or(path); + !path.contains("node_modules/") + && (common::reachability::is_lockfile(path) + || matches!( + name, + "Cargo.lock" | "poetry.lock" | "uv.lock" | "Gemfile.lock" + )) +} + +/// What the head of a unit's branch resolves for each of its bumps: the +/// lockfiles its bumps go through, read on the base branch and on the head +/// and compared (`common::dep_head`). Whatever can't be read is said as not +/// known, with why. +pub(crate) async fn head_facts( + gh: &GitHubClient, + unit: &FixUnit, + base: &str, + head: &str, +) -> common::dep_head::HeadFacts { + use common::dep_head::{self, LockAt}; + let Some((o, n)) = unit.repo.split_once('/') else { + return dep_head::unknown(unit, "the repository is not known"); + }; + if head.is_empty() { + return dep_head::unknown(unit, "the pull request's branch is not known"); + } + let tree = match gh.get_tree(o, n, head).await { + Ok(t) => t, + Err(e) => { + warn!(repo = %unit.repo, error = %e, "security: could not list the head's files"); + return dep_head::unknown(unit, "the files on the head could not be listed"); + } + }; + let lockfiles: Vec = tree + .into_iter() + .map(|t| t.path) + .filter(|p| is_read_lockfile(p)) + .collect(); + let mut wanted: Vec = vec![]; + for b in &unit.bumps { + let lock = + common::dep_fix::lockfile_for(&b.manifest, &lockfiles).or_else(|| { + match lockfiles.as_slice() { + [one] => Some(one.clone()), + _ => None, + } + }); + if let Some(l) = lock { + if !wanted.contains(&l) { + wanted.push(l); + } + } + } + let mut locks = vec![]; + for path in wanted { + let mut at = LockAt { + path: path.clone(), + ..Default::default() + }; + for (side, git_ref) in [("the base branch", base), ("the head", head)] { + let copies = match gh.read_file_if_exists(o, n, &path, git_ref).await { + // Not there: nothing is installed through it on that side. + Ok(None) => Some(vec![]), + Ok(Some(text)) => { + let c = common::reachability::lock_copies(&path, &text); + if c.is_none() { + at.why = format!("`{path}` on {side} could not be read as a lockfile"); + } + c + } + Err(e) => { + at.why = format!("`{path}` could not be read on {side} ({e})"); + None + } + }; + if side == "the head" { + at.head = copies; + } else { + at.base = copies; + } + } + locks.push(at); + } + let sha = gh.get_ref(o, n, head).await.unwrap_or_default(); + dep_head::resolve(unit, &sha, &locks) } /// Where a security description points for what it leaves out: each @@ -4363,41 +4463,92 @@ async fn what_to_check( } /// A security pull request whose CI just ended (passed or failed): its -/// "What to check" and Proof say so, in place; the rest of the description -/// (the draft status at its top) stays. +/// description is rebuilt from its head. async fn refresh_ci_sections(cx: &Ctx<'_>, repo: &str, number: u64, ticket: &str) { - let Some(unit) = load_unit(cx.state, cx.team_id, ticket).await else { + rebuild_at_head(cx.state, &cx.gh, cx.team_id, repo, number, ticket).await; +} + +/// The sections of a security pull request's description CoderHelm +/// computes, written again from the head: the first sentences and the +/// table (what the lockfile on the head resolves, compared with the base +/// branch), "What to check" and Proof (where CI stands on this head). The +/// rest of the description (the draft status at its top, the run's words) +/// stays. Running it twice on one head writes nothing the second time. +pub(crate) async fn rebuild_at_head( + state: &WorkerState, + gh: &GitHubClient, + team_id: &str, + repo: &str, + number: u64, + ticket: &str, +) { + let Some(unit) = load_unit(state, team_id, ticket).await else { return; }; + if unit.ecosystem == common::infra_vuln::records::UNIT_ECOSYSTEM { + return; + } let Some((o, n)) = repo.split_once('/') else { return; }; - let Ok(pr) = cx.gh.get_pull_request(o, n, number).await else { + let Ok(pr) = gh.get_pull_request(o, n, number).await else { return; }; let body = pr["body"].as_str().unwrap_or(""); if !body.contains(sec::MARKER) { return; } - let item = ticket_item(cx.state, cx.team_id, ticket).await; + let item = ticket_item(state, team_id, ticket).await; let change = item.as_ref().map(|i| s(i, "change")).unwrap_or_default(); let notes = item.as_ref().map(|i| s(i, "notes")).unwrap_or_default(); - let members = unit_findings(cx.state, cx.team_id, &unit).await; + let members = unit_findings(state, team_id, &unit).await; let pairs: Vec<(&Finding, &FindingState)> = members.iter().map(|(f, st)| (f, st)).collect(); - let check = what_to_check(&cx.gh, &unit, ¬es, Some(number)).await; + let mut check = what_to_check(gh, &unit, ¬es, Some(number)).await; + check.dep_report = item + .as_ref() + .map(|i| s(i, "dep_report")) + .unwrap_or_default(); // The same links as when it opened: the rewritten sections are the // short ones a bundle's description carries. - let links = body_links(cx.state, item.as_ref()); - let fresh = sec::pr_body_linked(&unit, &pairs, &change, &check, &links); - let next = - common::upgrade_notes::replace_sections(body, &fresh, &["## What to check", "## Proof"]); + let links = body_links(state, item.as_ref()); + let head = head_facts( + gh, + &unit, + pr["base"]["ref"].as_str().unwrap_or(""), + pr["head"]["sha"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or(&unit.branch), + ) + .await; + let fresh = sec::pr_body_at_head(&unit, &pairs, &change, &check, &links, &head); + let next = rebuilt_body(body, &fresh); if next != body { - if let Err(e) = cx.gh.update_pr_body(o, n, number, &next).await { - warn!(%repo, number, error = %e, "security: could not write the CI result into the description"); + if let Err(e) = crate::passes::description::save(gh, o, n, number, &next).await { + warn!(%repo, number, error = %e, "security: could not rebuild the description from the head"); } } } +/// `body` with the sections computed from the head taken from `fresh`. +/// Every section CoderHelm owns elsewhere (the draft status, review fixes, +/// the settled items, CI notes, the reviewer guide, open items and the +/// rest of `completeness::Section`) is lifted out first and put back as it +/// was, so a rebuild can never overwrite one that sits under a rebuilt +/// heading. A body the rebuild does not change is returned as it is. +pub(crate) fn rebuilt_body(body: &str, fresh: &str) -> String { + let (owned, rest) = super::completeness::take_owned(body); + let next = common::upgrade_notes::replace_sections( + &rest, + fresh, + &["## Summary", "## What to check", "## Proof"], + ); + if next == rest { + return body.to_string(); + } + super::completeness::assemble(&next, &owned) +} + /// A security run opened its pull request: labels, the findings, the card. pub async fn on_pr_opened( state: &WorkerState, diff --git a/services/worker/src/passes/stack.rs b/services/worker/src/passes/stack.rs index 9b8e9799d..547d3a9e7 100644 --- a/services/worker/src/passes/stack.rs +++ b/services/worker/src/passes/stack.rs @@ -1063,7 +1063,7 @@ pub async fn note_pr(github: &GitHubClient, owner: &str, repo: &str, pr: u64, de let body = p["body"].as_str().unwrap_or(""); let updated = put_section(body, &dep.section()); if updated != body { - if let Err(e) = github.update_pr_body(owner, repo, pr, &updated).await { + if let Err(e) = crate::passes::description::save(github, owner, repo, pr, &updated).await { tracing::warn!(pr, error = %e, "Could not state the stacked pull request's dependency"); } } diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index b1dbd4cd4..bf1909a1c 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -430,9 +430,14 @@ pub async fn open_with( // The pull request already open says what is not finished too. if !unfinished.is_empty() { let now = with_unfinished(p["body"].as_str().unwrap_or(""), &unfinished); - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &now) - .await + if let Err(e) = crate::passes::description::save( + &github, + &msg.repo_owner, + &msg.repo_name, + number, + &now, + ) + .await { tracing::warn!(run_id, error = %e, "Could not say what is not finished on the open pull request"); } @@ -701,9 +706,14 @@ async fn ship( } else { format!("{}\n\n{deferred}", body.trim_end()) }; - if let Err(e) = github - .update_pr_body(&msg.repo_owner, &msg.repo_name, number, &now) - .await + if let Err(e) = crate::passes::description::save( + github, + &msg.repo_owner, + &msg.repo_name, + number, + &now, + ) + .await { tracing::warn!(run_id, error = %e, "Could not list what is deferred on the open pull request"); }