From b317756fad5284c1315aee13c9bb458862dc46fb Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 11:06:51 -0500 Subject: [PATCH 1/2] Infrastructure: pull requests where the code is found, complete runbooks where it is not; advisories only where they apply A pending action is named for what it means on its ARN, and one database's actions are one ordered set of rows. An advisory is attached only when it ties to the action (service, engine, version range, kind of action, date); an action AWS publishes with no CVE list gets none. RDS and ElastiCache reads follow every page. The code that defines a resource is found across every connected repository and layout: CloudFormation, CDK, SAM and Serverless Framework by stack name and logical id (tags, or DescribeStackResources by physical id), Terraform and OpenTofu by resource type and attributes through module calls and variable files. Each location says how it was found and how sure it is; a low-confidence one never becomes a pull request. An update with a code equivalent is a pull request on the line that sets the value, with the rollout notes for its tool; one that cannot be expressed in code stays a runbook and says so. A runbook is complete. A change that would replace or destroy a data resource is refused. The facts come from a guidance store with a source and a review date on every entry. Adds cloudformation:DescribeStackResources to the optional Infrastructure vulnerabilities read permissions. --- docs/incidents.md | 1 + infra/cfn/coderhelm-log-reader-update.yaml | 4 + infra/cfn/coderhelm-log-reader.yaml | 4 + services/common/src/infra_vuln/actions.rs | 1061 ++++++++++++ services/common/src/infra_vuln/feeds.rs | 37 +- services/common/src/infra_vuln/guard.rs | 696 ++++++++ services/common/src/infra_vuln/guidance.rs | 459 ++++++ .../src/infra_vuln/guidance/aurora.json | 59 + .../src/infra_vuln/guidance/compute.json | 35 + .../src/infra_vuln/guidance/elasticache.json | 29 + .../src/infra_vuln/guidance/opensearch.json | 29 + .../common/src/infra_vuln/guidance/rds.json | 46 + services/common/src/infra_vuln/hcl.rs | 528 ++++++ services/common/src/infra_vuln/inventory.rs | 215 ++- services/common/src/infra_vuln/locate.rs | 1426 ++++++++++++++++ services/common/src/infra_vuln/matching.rs | 1120 +++++++++++-- services/common/src/infra_vuln/mod.rs | 26 +- services/common/src/infra_vuln/raw.rs | 60 +- services/common/src/infra_vuln/records.rs | 301 +++- services/common/src/infra_vuln/runbook.rs | 673 ++++++++ services/common/src/infra_vuln/stacks.rs | 143 ++ services/common/src/infra_vuln/terraform.rs | 1427 +++++++++++++++++ .../common/src/live/iam_resource_types.json | 3 + services/common/src/log_reader.rs | 7 +- services/gateway/src/routes/infra_security.rs | 72 + .../incidents/an_six_database_findings.rs | 575 +++++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/infra_findings.rs | 171 +- services/worker/src/passes/infra_inventory.rs | 679 ++++++-- services/worker/src/passes/infra_repo.rs | 113 +- 30 files changed, 9585 insertions(+), 415 deletions(-) create mode 100644 services/common/src/infra_vuln/actions.rs create mode 100644 services/common/src/infra_vuln/guard.rs create mode 100644 services/common/src/infra_vuln/guidance.rs create mode 100644 services/common/src/infra_vuln/guidance/aurora.json create mode 100644 services/common/src/infra_vuln/guidance/compute.json create mode 100644 services/common/src/infra_vuln/guidance/elasticache.json create mode 100644 services/common/src/infra_vuln/guidance/opensearch.json create mode 100644 services/common/src/infra_vuln/guidance/rds.json create mode 100644 services/common/src/infra_vuln/hcl.rs create mode 100644 services/common/src/infra_vuln/locate.rs create mode 100644 services/common/src/infra_vuln/runbook.rs create mode 100644 services/common/src/infra_vuln/stacks.rs create mode 100644 services/common/src/infra_vuln/terraform.rs create mode 100644 services/worker/src/passes/incidents/an_six_database_findings.rs diff --git a/docs/incidents.md b/docs/incidents.md index f57786b7d..f7ff32dd5 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -69,6 +69,7 @@ pipeline still calls it there. | 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. | +| 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. | ## Adding a case 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/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..6c2dc0765 --- /dev/null +++ b/services/common/src/infra_vuln/guard.rs @@ -0,0 +1,696 @@ +//! 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). +//! +//! 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}` is removed or renamed with no `moved` block. Terraform would destroy the resource it manages.", + c.path + )); + } + continue; + }; + 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).", + c.path + )); + } + } + 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.", + c.path + )); + } + } + 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.", + c.path + )); + } + } + } + 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.", + c.path + )); + } + 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.", + c.path + )); + } + if !truthy(b.attr("skip_final_snapshot")) && truthy(a.attr("skip_final_snapshot")) { + out.push(format!( + "{}: `{address}` turns `skip_final_snapshot` on.", + c.path + )); + } + 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`.", + c.path + )); + } + } +} + +/// 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 +} + +/// The refusal as a card or a closed pull request says it. +pub fn explain(reasons: &[String]) -> String { + let mut out = String::from( + "CoderHelm refused this change: 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. The update is still open; apply it with the runbook on the finding, or change the code by hand with a plan reviewed first."); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tf(before: &str, after: &str) -> Vec { + refusals(&[Change { + path: "db/main.tf", + before, + after, + }]) + } + + const DB: &str = r#" +resource "aws_db_instance" "orders" { + identifier = "orders-prod" + engine = "postgres" + engine_version = "16.4" + deletion_protection = true + lifecycle { + prevent_destroy = true + } +} +"#; + + #[test] + fn raising_the_engine_version_in_place_passes() { + assert_eq!(tf(DB, &DB.replace("16.4", "16.6")), Vec::::new()); + // A new file replaces nothing. + assert!(refusals(&[Change { + path: "new.tf", + before: "", + after: DB + }]) + .is_empty()); + } + + #[test] + fn a_change_that_replaces_or_destroys_the_database_is_refused_with_the_reason() { + let r = tf(DB, &DB.replace("orders-prod", "orders-production")); + assert_eq!(r.len(), 1, "{r:?}"); + assert!( + r[0].contains("changes `identifier`, which replaces the resource"), + "{r:?}" + ); + let r = tf(DB, &DB.replace("\"orders\"", "\"orders_db\"")); + assert!( + r[0].contains("removed or renamed with no `moved` block"), + "{r:?}" + ); + // A rename with a moved block keeps the resource. + let moved = format!( + "{}\nmoved {{\n from = aws_db_instance.orders\n to = aws_db_instance.orders_db\n}}\n", + DB.replace("\"orders\"", "\"orders_db\"") + ); + assert!(tf(DB, &moved).is_empty(), "{:?}", tf(DB, &moved)); + let r = tf(DB, &DB.replace("16.4", "15.8")); + assert!( + r[0].contains("lowers `engine_version` from 16.4 to 15.8"), + "{r:?}" + ); + let r = tf( + DB, + &DB.replace("deletion_protection = true", "deletion_protection = false"), + ); + assert!(r[0].contains("turns `deletion_protection` off"), "{r:?}"); + let r = tf( + DB, + &DB.replace("prevent_destroy = true", "prevent_destroy = false"), + ); + assert!(r[0].contains("removes `prevent_destroy`"), "{r:?}"); + let r = tf(DB, ""); + assert!(r[0].contains("Terraform would destroy"), "{r:?}"); + assert!(explain(&r).contains("Nothing was merged or applied")); + // A variable file that lowers a version. + let r = refusals(&[Change { + path: "envs/prod.tfvars", + before: "db_engine_version = \"16.6\"\n", + after: "db_engine_version = \"16.4\"\n", + }]); + assert!(r[0].contains("goes down"), "{r:?}"); + } + + #[test] + fn an_aurora_version_is_raised_on_the_cluster_never_on_a_member() { + let both = r#" +resource "aws_rds_cluster" "ledger" { + cluster_identifier = "ledger" + engine_version = "16.4" +} +resource "aws_rds_cluster_instance" "ledger" { + cluster_identifier = aws_rds_cluster.ledger.id + engine_version = "16.4" +} +"#; + let member_only = both.replacen( + " engine_version = \"16.4\"\n}\n", + " engine_version = \"16.6\"\n}\n", + 2, + ); + // replacen(2) changed both: that passes. + assert!( + tf(both, &member_only).is_empty(), + "{:?}", + tf(both, &member_only) + ); + let at = both.rfind("16.4").unwrap(); + let just_member = format!("{}16.6{}", &both[..at], &both[at + 4..]); + let r = tf(both, &just_member); + assert!(r[0].contains("on a cluster instance"), "{r:?}"); + // The cluster's identifier is a replacing attribute. + let r = tf( + both, + &both.replace( + "\"ledger\"\n engine_version", + "\"ledger2\"\n engine_version", + ), + ); + assert!( + r.iter().any(|x| x.contains("`cluster_identifier`")), + "{r:?}" + ); + } + + const DOMAIN: &str = r#"AWSTemplateFormatVersion: "2010-09-09" +Resources: + Search: + Type: AWS::OpenSearchService::Domain + Properties: + DomainName: search-prod + EngineVersion: OpenSearch_2.11 +"#; + + fn cfn(before: &str, after: &str) -> Vec { + refusals(&[Change { + path: "search.yaml", + before, + after, + }]) + } + + #[test] + fn an_opensearch_version_change_needs_the_upgrade_policy() { + let bumped = DOMAIN.replace("2.11", "2.19"); + let r = cfn(DOMAIN, &bumped); + assert_eq!(r.len(), 1, "{r:?}"); + assert!(r[0].contains("replaces the whole domain"), "{r:?}"); + // With the policy in the same change, the guidance says it is in place. + let safe = bumped.replace( + " Type: AWS::OpenSearchService::Domain\n", + " Type: AWS::OpenSearchService::Domain\n UpdatePolicy:\n EnableVersionUpgrade: true\n", + ); + assert!(cfn(DOMAIN, &safe).is_empty(), "{:?}", cfn(DOMAIN, &safe)); + let r = cfn(DOMAIN, &DOMAIN.replace("search-prod", "search")); + assert!( + r[0].contains("`DomainName`, a replacement property"), + "{r:?}" + ); + let r = cfn(DOMAIN, &DOMAIN.replace(" Search:", " SearchV2:")); + assert!(r[0].contains("removed, renamed or changes type"), "{r:?}"); + } + + #[test] + fn a_database_template_keeps_its_identifier_policy_and_version_direction() { + let t = "Resources:\n Db:\n Type: AWS::RDS::DBInstance\n DeletionPolicy: Snapshot\n Properties:\n DBInstanceIdentifier: orders\n EngineVersion: \"16.4\"\n DeletionProtection: true\n"; + assert!(cfn(t, &t.replace("16.4", "16.6")).is_empty()); + assert!(cfn(t, &t.replace("16.4", "15.8"))[0].contains("lowers `EngineVersion`")); + assert!(cfn( + t, + &t.replace( + "DBInstanceIdentifier: orders", + "DBInstanceIdentifier: orders2" + ) + )[0] + .contains("replacement property")); + assert!(cfn( + t, + &t.replace("DeletionPolicy: Snapshot", "DeletionPolicy: Delete") + )[0] + .contains("no longer keeps its data")); + assert!(cfn( + t, + &t.replace("DeletionProtection: true", "DeletionProtection: false") + )[0] + .contains("turns `DeletionProtection` off")); + } + + #[test] + fn a_cdk_construct_id_is_never_changed() { + let a = "import * as rds from 'aws-cdk-lib/aws-rds';\nnew rds.DatabaseCluster(this, 'Ledger', { engine: rds.DatabaseClusterEngine.auroraPostgres({ version: rds.AuroraPostgresEngineVersion.VER_16_4 }) });\n"; + let cdk = |after: &str| { + refusals(&[Change { + path: "src/data.ts", + before: a, + after, + }]) + }; + assert!(cdk(&a.replace("VER_16_4", "VER_16_6")).is_empty()); + let r = cdk(&a.replace("'Ledger'", "'LedgerV2'")); + assert!( + r[0].contains("CloudFormation replaces the resource"), + "{r:?}" + ); + let os = "import * as opensearch from 'aws-cdk-lib/aws-opensearchservice';\nnew opensearch.Domain(this, 'Search', { version: opensearch.EngineVersion.OPENSEARCH_2_11 });\n"; + let r = refusals(&[Change { + path: "src/search.ts", + before: os, + after: &os.replace("2_11", "2_19"), + }]); + assert!( + r[0].contains("without `enableVersionUpgrade: true`"), + "{r:?}" + ); + let safe = os.replace("2_11 }", "2_19, enableVersionUpgrade: true }"); + assert!(refusals(&[Change { + path: "src/search.ts", + before: os, + after: &safe + }]) + .is_empty()); + } + + #[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..bf4eae290 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,316 @@ 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) + } + } + }; + + let rb = (kind == FixKind::Runbook).then(|| runbook::build(r, &p, feeds.today)); + let (cli, console) = match &rb { + 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 +1055,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 +1202,9 @@ fn with_inspector(r: &Resource, own: Vec, feeds: &Feeds) -> Vec { for s in hit_sources.sources.drain(..) { @@ -891,7 +1275,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 +1314,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 +1470,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 +1607,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 +1701,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 +1736,447 @@ 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 + ); + assert!(x.fix.runbook.is_none()); + 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..1ca41df42 100644 --- a/services/common/src/infra_vuln/records.rs +++ b/services/common/src/infra_vuln/records.rs @@ -91,6 +91,11 @@ 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`]). While it is set no new fix run starts by + /// itself: the finding is applied by its runbook or by hand. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub refused: Vec, /// A line for the timeline when something changed (not stored). #[serde(skip)] pub event: Option, @@ -116,6 +121,7 @@ impl Record { first_seen_at: now.into(), updated_at: now.into(), fixed_at: None, + refused: Vec::new(), } } @@ -133,6 +139,9 @@ impl Record { o.insert("first_seen_at".into(), json!(self.first_seen_at)); o.insert("updated_at".into(), json!(self.updated_at)); o.insert("fixed_at".into(), json!(self.fixed_at)); + if !self.refused.is_empty() { + o.insert("refused".into(), json!(self.refused)); + } // The fix's kind as the contract names it. o["fix"]["kind"] = json!(self.finding.fix.kind); if self.status == Status::PrOpen @@ -167,6 +176,7 @@ pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime r2.fixed_at = None; r2.pr = None; r2.ticket.clear(); + r2.refused.clear(); r2.event = Some("Found again in the latest read".into()); } if r2 != *r { @@ -262,42 +272,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 +433,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 +466,24 @@ 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"); } out } @@ -497,6 +635,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 +648,128 @@ 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); + } + + #[test] + fn a_refused_change_is_kept_on_the_record_and_shown() { + let mut r = Record::new(upgrade("a", "ledger-prod-aurora", "production", ""), "t"); + assert!(r.view().get("refused").is_none()); + r.refused = vec!["db/main.tf: `aws_db_instance.orders` changes `identifier`".into()]; + assert_eq!(r.view()["refused"][0], r.refused[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()); + } } 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/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/gateway/src/routes/infra_security.rs b/services/gateway/src/routes/infra_security.rs index c11741dba..d42c62c0f 100644 --- a/services/gateway/src/routes/infra_security.rs +++ b/services/gateway/src/routes/infra_security.rs @@ -541,6 +541,78 @@ 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!(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/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/mod.rs b/services/worker/src/passes/incidents/mod.rs index 2f967f03f..dcf2f222e 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -27,6 +27,7 @@ mod ah_dep_run_choice_and_proof; mod ai_open_items_settled; mod aj_coder_habits; mod al_learning_loop; +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..d2b33d82d 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!( @@ -359,15 +364,28 @@ 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 the last change: no new run by itself. + if !r.refused.is_empty() && !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)) { @@ -579,7 +597,66 @@ 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) +} + +/// 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<(crate::clients::github::GitHubClient, Vec)> { + let iid = 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, + iid, + &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 refusals = guard_refusals(&files); + Some((gh, refusals)) +} + +/// A fix run for an infrastructure finding opened its PR. The replacement +/// guard reads the change first: a change that would replace or destroy a +/// resource that holds data is refused, its pull request is closed with +/// the reason, and the finding goes back to its runbook. pub async fn on_pr_opened( state: &WorkerState, team_id: &str, @@ -587,22 +664,54 @@ pub async fn on_pr_opened( number: u64, url: &str, ) { + let refused = match guard_pr(state, team_id, unit, number).await { + Some((gh, reasons)) if !reasons.is_empty() => { + if let Some((owner, name)) = unit.repo.split_once('/') { + let explain = common::infra_vuln::guard::explain(&reasons); + if let Err(e) = gh.update_pr_body(owner, name, number, &explain).await { + warn!(team_id, number, error = %e, "infra findings: the refusal could not be written on the pull request"); + } + if let Err(e) = gh.close_pull_request(owner, name, number).await { + warn!(team_id, number, error = %e, "infra findings: the refused pull request could not be closed"); + } + } + reasons + } + _ => Vec::new(), + }; 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(), - }); + if refused.is_empty() { + r.status = Status::PrOpen; + r.pr = Some(records::PrRef { + number, + url: url.to_string(), + state: "open".into(), + }); + } else { + r.status = Status::Open; + r.pr = Some(records::PrRef { + number, + url: url.to_string(), + state: "closed".into(), + }); + r.refused = refused.clone(); + } 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"), + &if refused.is_empty() { + format!("PR #{number} opened") + } else { + format!( + "PR #{number} refused and closed: the change would replace or destroy a resource that holds data ({})", + refused.join("; ") + ) + }, Some(url), ) .await; @@ -664,6 +773,38 @@ 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()); + } + + #[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] From 71b36b8efec4778cf08564b0e513519b086d06ce Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 12:52:48 -0500 Subject: [PATCH 2/2] Infrastructure: a change the replacement guard refuses gets one fix round, then a draft with the reason and the runbook The pull request is never closed and its branch is never deleted. On the first trip one fix round is told each offending file and line and must produce the in-place change; the guard reads the result again. If it still trips, the pull request becomes a draft with the reason and the lines at the top of its description, which holds it from being marked ready or merged, and the finding falls back to its runbook. No further attempt starts by itself until the finding's code or target changes. --- docs/incidents.md | 2 +- services/common/src/infra_vuln/guard.rs | 143 ++++++- services/common/src/infra_vuln/matching.rs | 15 +- services/common/src/infra_vuln/records.rs | 253 +++++++++++- services/gateway/src/routes/infra_security.rs | 1 + services/worker/src/clients/github.rs | 17 + services/worker/src/passes/infra_findings.rs | 384 ++++++++++++++---- services/worker/src/passes/ready.rs | 8 + 8 files changed, 713 insertions(+), 110 deletions(-) diff --git a/docs/incidents.md b/docs/incidents.md index f7ff32dd5..4e56077aa 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -66,10 +66,10 @@ 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. | +| 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. | -| 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. | ## Adding a case diff --git a/services/common/src/infra_vuln/guard.rs b/services/common/src/infra_vuln/guard.rs index 6c2dc0765..e674b1ebe 100644 --- a/services/common/src/infra_vuln/guard.rs +++ b/services/common/src/infra_vuln/guard.rs @@ -18,6 +18,12 @@ //! - 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. @@ -171,19 +177,28 @@ fn terraform(c: &Change, out: &mut Vec) { let Some(a) = resources(&after).into_iter().find(|a| a.labels == b.labels) else { if !moved.contains(&address) { out.push(format!( - "{}: `{address}` is removed or renamed with no `moved` block. Terraform would destroy the resource it manages.", - c.path + "{}: `{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).", - c.path + at(n) )); } } @@ -191,7 +206,7 @@ fn terraform(c: &Change, out: &mut Vec) { 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.", - c.path + at(n) )); } } @@ -203,7 +218,7 @@ fn terraform(c: &Change, out: &mut Vec) { 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.", - c.path + at(n) )); } } @@ -212,20 +227,20 @@ fn terraform(c: &Change, out: &mut Vec) { { 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.", - c.path + 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.", - c.path + 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.", - c.path + at("skip_final_snapshot") )); } let guarded = |x: &Block| { @@ -235,7 +250,7 @@ fn terraform(c: &Change, out: &mut Vec) { if guarded(b) && !guarded(a) { out.push(format!( "{}: `{address}` removes `prevent_destroy`.", - c.path + at("lifecycle") )); } } @@ -453,18 +468,68 @@ pub fn refusals(changes: &[Change]) -> Vec { out } -/// The refusal as a card or a closed pull request says it. -pub fn explain(reasons: &[String]) -> String { +/// 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( - "CoderHelm refused this change: it would replace or destroy a resource that holds data, or take away what protects it.\n\n", + "\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("\nNothing was merged or applied. The update is still open; apply it with the runbook on the finding, or change the code by hand with a plan reviewed first."); + 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")); diff --git a/services/common/src/infra_vuln/matching.rs b/services/common/src/infra_vuln/matching.rs index bf4eae290..f06e93d02 100644 --- a/services/common/src/infra_vuln/matching.rs +++ b/services/common/src/infra_vuln/matching.rs @@ -934,8 +934,10 @@ fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) } }; - let rb = (kind == FixKind::Runbook).then(|| runbook::build(r, &p, feeds.today)); - let (cli, console) = match &rb { + // 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() @@ -1857,7 +1859,14 @@ mod tests { "{}", x.fix.decision ); - assert!(x.fix.runbook.is_none()); + // 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")); diff --git a/services/common/src/infra_vuln/records.rs b/services/common/src/infra_vuln/records.rs index 1ca41df42..2369f74ab 100644 --- a/services/common/src/infra_vuln/records.rs +++ b/services/common/src/infra_vuln/records.rs @@ -92,10 +92,21 @@ pub struct Record { #[serde(default)] pub fixed_at: Option, /// Why the replacement guard refused the change a fix run made - /// ([`super::guard`]). While it is set no new fix run starts by - /// itself: the finding is applied by its runbook or by hand. + /// ([`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, @@ -122,6 +133,9 @@ impl Record { updated_at: now.into(), fixed_at: None, refused: Vec::new(), + guard_attempts: 0, + drafted: false, + guard_sig: String::new(), } } @@ -139,11 +153,24 @@ impl Record { o.insert("first_seen_at".into(), json!(self.first_seen_at)); o.insert("updated_at".into(), json!(self.updated_at)); 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)); + } } - // The fix's kind as the contract names it. - o["fix"]["kind"] = json!(self.finding.fix.kind); if self.status == Status::PrOpen && self.pr.as_ref().is_some_and(|p| p.state == "merged") { @@ -154,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. @@ -176,7 +284,7 @@ pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime r2.fixed_at = None; r2.pr = None; r2.ticket.clear(); - r2.refused.clear(); + r2.clear_guard(); r2.event = Some("Found again in the latest read".into()); } if r2 != *r { @@ -485,6 +593,11 @@ pub fn pr_body(r: &Record, change: &str) -> String { } 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 } @@ -761,15 +874,137 @@ mod tests { 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_refused_change_is_kept_on_the_record_and_shown() { + 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()); - r.refused = vec!["db/main.tf: `aws_db_instance.orders` changes `identifier`".into()]; - assert_eq!(r.view()["refused"][0], r.refused[0]); + } + + #[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()); + assert!(again[0].refused.is_empty() && !again[0].drafted); } } diff --git a/services/gateway/src/routes/infra_security.rs b/services/gateway/src/routes/infra_security.rs index d42c62c0f..1751c5be2 100644 --- a/services/gateway/src/routes/infra_security.rs +++ b/services/gateway/src/routes/infra_security.rs @@ -603,6 +603,7 @@ mod tests { ); 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() 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/infra_findings.rs b/services/worker/src/passes/infra_findings.rs index d2b33d82d..b4eeebf8a 100644 --- a/services/worker/src/passes/infra_findings.rs +++ b/services/worker/src/passes/infra_findings.rs @@ -251,6 +251,50 @@ pub(crate) 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, @@ -292,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(); @@ -374,8 +403,10 @@ async fn start_fixes( } continue; } - // The guard refused the last change: no new run by itself. - if !r.refused.is_empty() && !asked { + // 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 @@ -409,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) => { @@ -611,6 +645,14 @@ pub fn guard_refusals(files: &[(String, String, String)]) -> Vec { 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 @@ -620,12 +662,12 @@ async fn guard_pr( team_id: &str, unit: &FixUnit, number: u64, -) -> Option<(crate::clients::github::GitHubClient, Vec)> { - let iid = super::review_reminder::team_installation_id(state, team_id).await?; +) -> 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, - iid, + installation_id, &state.http, ) .ok()?; @@ -649,14 +691,97 @@ async fn guard_pr( .unwrap_or_default(); files.push((path, before, after)); } - let refusals = guard_refusals(&files); - Some((gh, refusals)) + 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) = g.gh.update_pr_body(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 its PR. The replacement -/// guard reads the change first: a change that would replace or destroy a -/// resource that holds data is refused, its pull request is closed with -/// the reason, and the finding goes back to its runbook. +/// 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, @@ -664,57 +789,41 @@ pub async fn on_pr_opened( number: u64, url: &str, ) { - let refused = match guard_pr(state, team_id, unit, number).await { - Some((gh, reasons)) if !reasons.is_empty() => { - if let Some((owner, name)) = unit.repo.split_once('/') { - let explain = common::infra_vuln::guard::explain(&reasons); - if let Err(e) = gh.update_pr_body(owner, name, number, &explain).await { - warn!(team_id, number, error = %e, "infra findings: the refusal could not be written on the pull request"); - } - if let Err(e) = gh.close_pull_request(owner, name, number).await { - warn!(team_id, number, error = %e, "infra findings: the refused pull request could not be closed"); - } - } - reasons - } - _ => Vec::new(), - }; + 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) { - if refused.is_empty() { - r.status = Status::PrOpen; - r.pr = Some(records::PrRef { - number, - url: url.to_string(), - state: "open".into(), - }); - } else { - r.status = Status::Open; - r.pr = Some(records::PrRef { - number, - url: url.to_string(), - state: "closed".into(), - }); - r.refused = refused.clone(); + 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"); + } } - r.updated_at = Utc::now().to_rfc3339(); - save(state, team_id, r).await; - super::security_fixes::add_event( - state, - team_id, - id, - &if refused.is_empty() { - format!("PR #{number} opened") - } else { - format!( - "PR #{number} refused and closed: the change would replace or destroy a resource that holds data ({})", - refused.join("; ") - ) - }, - Some(url), - ) - .await; + (records::GuardStep::Draft, Some(g)) if !drafted => { + draft_with_reason(g, unit, number, &reasons).await; + drafted = true; + } + _ => {} } } } @@ -788,6 +897,115 @@ mod tests { 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(".update_pr_body(").count(), 1); + } + #[test] fn the_guard_reads_a_pull_requests_files_before_and_after() { let before = "resource \"aws_db_instance\" \"orders\" {\n identifier = \"orders-prod\"\n engine_version = \"16.4\"\n}\n"; diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index f4e72053b..3caf59fda 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(