diff --git a/docs/incidents.md b/docs/incidents.md index f23ac4cc3..56df7a791 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -91,6 +91,7 @@ pipeline still calls it there. | bk. `bk_owns_the_outside_work` | A run with its pull request open ended waiting on people and its ticket comment handed over work CoderHelm could do: reading workflow runs, a lint, page checks (all failing on one 400 because a page check written as the confirm "query" was sent to the CMS's GROQ API), the production release (a tag after one approval), a review look, and a step number the ticket never showed; it opened on a raw Jira account id and counted nothing as handed over. | Each outside step's action comes from its own words; a failed attempt reaches a person only for a permission or credential in its own cause; a tool failure is diagnosed and reported once and its steps take another way; the release is one approval; a run waits on a person only with a gate-approved item and nothing it can still do; every comment, description, chat message and outside report passes the sink check; replies show names, never account ids; the team's history replays with no doable item reaching a person. | | bl. `bl_description_final_review` | A pull request description showed six checks as "still running when this was written" in its results and never changed them, asked a person for deploy credentials or to run the staging deploy in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id beside its name, and listed still-running and did-not-run checks on one line. The repository's template only guided the first draft. A run could also end as needing an outside change instead of delivering the code. | Every description passes a final review in the one save (`common::pr_review`): a running check reads Running and is never a result, and the stamp keeps the description rebuilt until the checks end; nothing the gate does not let through reaches a person, and a staging deploy the repository lets CoderHelm start (a dispatchable workflow, or a job a pull request label starts) is CoderHelm's step: the gate is told it can deploy, and the executor adds the label or dispatches, waits for the run and records its end; nothing is said twice; no filler; no raw id beside a name; running and did-not-run are said apart. The repository's template is the visible structure, filled with CoderHelm's content (`common::pr_template`). A plan with code is implemented and its pull request opened whatever outside work it needs, a person's feedback that part of the fix is outside the code keeps the code and its open pull request with the outside part attached, and the run ends delivered with only person-only items listed once under Needed from you. | | bm. `bm_teams_never_cross` | An audit of every event path found four keys that named a shared thing instead of the team: any team admin could point a Slack workspace at their own team and take another team's slash commands; the run page's GitHub check reads were cached by repository name, so a same-named repository was served another installation's cached checks; model-written replies were cached by Jira ticket key and comment id, which two Jira sites can share; and run events were keyed by run id with no team on the row. | Every inbound route resolves its team from something only that team holds (a signed installation, a per-team token or secret, a claim no other team can overwrite) and drops an event no team owns. A Slack workspace or Teams webhook is claimed by one team at a time (`common::plugins::flag::claim_chat`) and routes only while that team still names it. Every process-wide cache is keyed by the credential or team that read it, and a reply is reused only for the exact prompt it was written from. Every run event row names its team and reads keep only the asking team's rows (`common::run_events`). Source scans fail on a new inbound route, a new cache or a direct events table access that does not say how it stays in its team. | +| bn. `bn_infra_list_follows_aws` | Security, Infrastructure kept ten rows while AWS had moved on: an RDS instance deleted two days before still showed two pending actions, a Lambda function on a retired runtime came from a Terraform module nothing called, five rows already fixed kept their Runbook and Fix PR buttons, an older CVE row and the engine patch to the same version stood as two rows, and a serverless platform update and an operating system update on each instance AWS listed never appeared. The read kept every resource for three days and the match took them all as running. | Each read says which kinds it saw in full; what a full read no longer lists is dropped and its findings close as removed, with the time; a failed or partial read drops and closes nothing. The same move on one database is one item. Every pending action is an item, applied by CoderHelm after one approval when it has no code change, and a version change on a resource in code is a pull request whichever source raised it. Closed items offer nothing to do. Opening the page refreshes a read older than five minutes, at most once per team in that time. | ## Adding a case diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index c62e56075..f3d476856 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -9,6 +9,8 @@ Description: > named in SyncKnowledgeBases. With InfrastructureVulnerabilities "on" it also reads, read-only, which versions your EC2, EKS, RDS, ElastiCache and OpenSearch resources run, for matching against security advisories. + With ApplyMaintenance "on" it may also apply a pending RDS or Aurora + maintenance action that a person approved in CoderHelm. It only adds: to drop a permission an older release granted, update the CoderHelmLogReader stack itself with the current role template. Created from the dashboard's Update link; you can delete older @@ -85,6 +87,17 @@ Parameters: "on" lets CoderHelm read this account's AWS Health events through the Health API (read-only), which needs AWS Business Support or higher. + ApplyMaintenance: + Type: String + Default: "off" + AllowedValues: ["off", "on"] + Description: > + "on" lets CoderHelm apply a pending RDS or Aurora maintenance action + (an operating system update, an engine patch or upgrade, a serverless + platform update) that a person approved in CoderHelm, through AWS's + own ApplyPendingMaintenanceAction, only on this account's database + clusters and instances. Nothing is applied without that approval. + Conditions: ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] @@ -94,6 +107,7 @@ Conditions: ReadsInfrastructure: !Equals [!Ref InfrastructureVulnerabilities, "on"] ReadsInspector: !Equals [!Ref InspectorFindings, "on"] ReadsHealth: !Equals [!Ref HealthEvents, "on"] + AppliesMaintenance: !Equals [!Ref ApplyMaintenance, "on"] Resources: CoderHelmReadOnlyUpdate: @@ -331,6 +345,19 @@ Resources: - "inspector2:BatchGetAccountStatus" Resource: "*" - !Ref AWS::NoValue + # Applying a pending RDS or Aurora maintenance action, only when + # ApplyMaintenance is "on", and only after a person approved that + # action in CoderHelm. Only this account's clusters and instances. + - !If + - AppliesMaintenance + - Sid: ApplyApprovedMaintenance + Effect: Allow + Action: + - "rds:ApplyPendingMaintenanceAction" + Resource: + - !Sub "arn:aws:rds:*:${AWS::AccountId}:cluster:*" + - !Sub "arn:aws:rds:*:${AWS::AccountId}:db:*" + - !Ref AWS::NoValue # AWS Health events, only when HealthEvents is "on" (the Health API needs # Business Support or higher). Read-only. - !If diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 925224189..d3f96932b 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -5,7 +5,9 @@ Description: > Only when you name them in SyncKnowledgeBases, it may also copy your chosen Coderhelm knowledge bases into those Bedrock knowledge bases. With InfrastructureVulnerabilities "on" it also reads, read-only, which versions - your EC2, EKS, RDS, ElastiCache and OpenSearch resources run. + your EC2, EKS, RDS, ElastiCache and OpenSearch resources run. With + ApplyMaintenance "on" it may also apply a pending RDS or Aurora + maintenance action that a person approved in CoderHelm. This role uses an External ID to prevent confused deputy attacks. Parameters: @@ -95,6 +97,17 @@ Parameters: "on" lets CoderHelm read this account's AWS Health events through the Health API (read-only), which needs AWS Business Support or higher. + ApplyMaintenance: + Type: String + Default: "off" + AllowedValues: ["off", "on"] + Description: > + "on" lets CoderHelm apply a pending RDS or Aurora maintenance action + (an operating system update, an engine patch or upgrade, a serverless + platform update) that a person approved in CoderHelm, through AWS's + own ApplyPendingMaintenanceAction, only on this account's database + clusters and instances. Nothing is applied without that approval. + Conditions: ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] @@ -104,6 +117,7 @@ Conditions: ReadsInfrastructure: !Equals [!Ref InfrastructureVulnerabilities, "on"] ReadsInspector: !Equals [!Ref InspectorFindings, "on"] ReadsHealth: !Equals [!Ref HealthEvents, "on"] + AppliesMaintenance: !Equals [!Ref ApplyMaintenance, "on"] Resources: CoderHelmLogReaderRole: @@ -405,6 +419,23 @@ Resources: - "inspector2:BatchGetAccountStatus" Resource: "*" - !Ref AWS::NoValue + # Applying a pending RDS or Aurora maintenance action, only when + # ApplyMaintenance is "on", and only after a person approved that + # action in CoderHelm. Only this account's clusters and instances. + - !If + - AppliesMaintenance + - PolicyName: ApplyApprovedMaintenance + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: ApplyApprovedMaintenance + Effect: Allow + Action: + - "rds:ApplyPendingMaintenanceAction" + Resource: + - !Sub "arn:aws:rds:*:${AWS::AccountId}:cluster:*" + - !Sub "arn:aws:rds:*:${AWS::AccountId}:db:*" + - !Ref AWS::NoValue - !If - ReadsHealth - PolicyName: HealthEventsReadOnly diff --git a/infra/lib/own-account-read.ts b/infra/lib/own-account-read.ts index 939350a36..82c06367e 100644 --- a/infra/lib/own-account-read.ts +++ b/infra/lib/own-account-read.ts @@ -64,6 +64,8 @@ const OWN_CONDITIONS: Record = { ReadsImportBuckets: false, SyncsKnowledgeBases: false, SyncsEveryKnowledgeBase: false, + // The install's own role only reads: it never applies database maintenance. + AppliesMaintenance: false, }; /** diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 2cc8682f3..da53ab6c9 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -197,7 +197,9 @@ test("self-host: the gateway and worker read the install's own account with this }; // Inspector and Health are switches (off by default) like infrastructure // vulnerabilities (on by default): their statements are there, each behind its condition. - const abilities = ["imports", "sync"].reduce(without, all); + // Applying approved database maintenance is a write a team grants its own + // CoderHelmLogReader role; the install's own role only reads. + const abilities = ["imports", "sync", "maintenance"].reduce(without, all); const needed = [...new Set([...abilities.matchAll(/"([a-z0-9-]+:[A-Za-z]+)"/g)].map((m) => m[1]))]; assert.ok(needed.length > 20, `${needed.length} actions`); for (const [stack, fn] of [ diff --git a/services/common/src/infra_vuln/actions.rs b/services/common/src/infra_vuln/actions.rs index 18b50c2bd..6a1b7eeb1 100644 --- a/services/common/src/infra_vuln/actions.rs +++ b/services/common/src/infra_vuln/actions.rs @@ -149,6 +149,15 @@ pub fn target_in(description: &str) -> String { .unwrap_or_default() } +/// The platform version a serverless update names (`Upgrade to platform +/// version 4`), as `platform version 4`; empty when it names none. +pub fn platform_in(description: &str) -> String { + re(r"(?i)platform version (\d+(?:\.\d+)*)") + .captures(description) + .map(|c| format!("platform version {}", &c[1])) + .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) { @@ -434,6 +443,8 @@ pub fn reconcile(engine: &str, running: &str, lines: &[Line]) -> Vec { let meaning = meaning_of(&l.action, scope, engine); let target = if matches!(meaning, Meaning::EngineUpgrade | Meaning::EnginePatch) { target_in(&l.description) + } else if meaning == Meaning::ServerlessPlatform { + platform_in(&l.description) } else { String::new() }; diff --git a/services/common/src/infra_vuln/inventory.rs b/services/common/src/infra_vuln/inventory.rs index de6b3da54..a678c250a 100644 --- a/services/common/src/infra_vuln/inventory.rs +++ b/services/common/src/infra_vuln/inventory.rs @@ -51,6 +51,141 @@ pub enum Kind { ContainerImage, } +/// Every kind, in declaration order. +pub const ALL_KINDS: &[Kind] = &[ + Kind::Ec2Instance, + Kind::AutoScalingGroup, + Kind::EksNodegroup, + Kind::EksCluster, + Kind::EcsFargateService, + Kind::LambdaFunction, + Kind::RdsInstance, + Kind::RdsCluster, + Kind::ElasticacheGroup, + Kind::OpensearchDomain, + Kind::ContainerImage, +]; + +/// What one account and region's latest read saw in full, from its summary +/// row: only these kinds may close a finding or drop a resource. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct KindsRead { + pub account: String, + pub region: String, + pub read_at: String, + /// Kinds every call answered for, every page read. + pub complete: Vec, +} + +/// Every account and region's latest full reads. +#[derive(Debug, Clone, Default)] +pub struct Coverage { + pub reads: Vec, +} + +impl Coverage { + /// The latest read of this account and region saw every resource of + /// this kind. + pub fn complete(&self, account: &str, region: &str, kind: Kind) -> bool { + self.reads + .iter() + .any(|r| r.account == account && r.region == region && r.complete.contains(&kind)) + } + + /// When the account and region was last read, empty when never. + pub fn read_at(&self, account: &str, region: &str) -> &str { + self.reads + .iter() + .find(|r| r.account == account && r.region == region) + .map(|r| r.read_at.as_str()) + .unwrap_or("") + } +} + +/// The resources a new read replaces: stored rows of this account and +/// region that the read did not return, of a kind the read saw in full. +/// Rows of a kind the read did not see in full are kept (a failed or +/// partial read removes nothing). Returns their sort keys. +pub fn gone(stored: &[Resource], fresh: &[Resource], complete: &[Kind]) -> Vec { + let seen: std::collections::BTreeSet = fresh.iter().map(Resource::sk).collect(); + let mut out: Vec = stored + .iter() + .filter(|r| complete.contains(&r.kind)) + .map(Resource::sk) + .filter(|sk| !seen.contains(sk)) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// Terraform module folders nothing calls: the `.tf` files read hold no +/// provider, backend or `terraform` block there and no `module` block +/// anywhere names the folder as its `source`. What is declared in them is +/// never applied, so it is not something that runs. A folder is kept when +/// unsure (a remote source that ends in its name, a root with no +/// provider block of its own). +pub fn uncalled_modules(files: &[(&str, &str, &str)]) -> std::collections::BTreeSet { + use std::collections::{BTreeMap, BTreeSet}; + let dir_of = |p: &str| { + p.rsplit_once('/') + .map(|(d, _)| d.to_string()) + .unwrap_or_default() + }; + let source = re(r#"(?m)^\s*source\s*=\s*"([^"]+)""#); + let root = re(r#"(?m)^\s*(provider\s+"|terraform\s*\{|backend\s+")"#); + // (repo, dir) of each .tf file, and whether one of its files is a root. + let mut dirs: BTreeMap<(String, String), bool> = BTreeMap::new(); + let mut called: BTreeSet<(String, String)> = BTreeSet::new(); + let mut remote_tails: BTreeSet = BTreeSet::new(); + for (repo, path, content) in files { + if !path.ends_with(".tf") { + continue; + } + let d = dir_of(path); + let is_root = root.is_match(content); + let e = dirs.entry((repo.to_string(), d.clone())).or_insert(false); + *e |= is_root; + for c in source.captures_iter(content) { + let src = c[1].to_string(); + if src.starts_with("./") || src.starts_with("../") { + let mut parts: Vec<&str> = if d.is_empty() { + Vec::new() + } else { + d.split('/').collect() + }; + for seg in src.split('/') { + match seg { + "." | "" => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + called.insert((repo.to_string(), parts.join("/"))); + } else if let Some(tail) = src + .split("//") + .last() + .and_then(|t| t.split('?').next()) + .and_then(|t| t.trim_end_matches('/').rsplit('/').next()) + { + remote_tails.insert(tail.to_string()); + } + } + } + dirs.into_iter() + .filter(|((repo, d), is_root)| { + !is_root + && d.split('/').any(|s| s == "modules") + && !called.contains(&(repo.clone(), d.clone())) + && !remote_tails.contains(d.rsplit('/').next().unwrap_or("")) + }) + .map(|((repo, d), _)| format!("{repo}:{d}")) + .collect() +} + impl Kind { pub fn label(self) -> &'static str { match self { diff --git a/services/common/src/infra_vuln/matching.rs b/services/common/src/infra_vuln/matching.rs index f06e93d02..f5f9aee56 100644 --- a/services/common/src/infra_vuln/matching.rs +++ b/services/common/src/infra_vuln/matching.rs @@ -34,10 +34,33 @@ use crate::security_fixes::Tier; #[serde(rename_all = "snake_case")] pub enum FixKind { Pr, + /// CoderHelm applies AWS's pending action itself, after one person's + /// approval ([`ApplyPlan`]). + Apply, Runbook, Aws, } +/// The IAM action CoderHelm needs to apply a pending RDS or Aurora action. +pub const APPLY_PERMISSION: &str = "rds:ApplyPendingMaintenanceAction"; + +/// How CoderHelm applies a pending action in AWS once a person approves: +/// `apply-pending-maintenance-action` on each ARN, in order. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ApplyPlan { + /// AWS's name for the action (`os-upgrade`, `system-update`, + /// `db-upgrade`, `serverless-platform-version-update`). + pub action: String, + /// Every ARN, in the order to apply it. + pub arns: Vec, + /// The IAM action the team's role needs. + pub permission: String, + /// `next-maintenance` unless the person picks `immediate`. + pub default_opt_in: String, + /// What applying it does to the database, in a line. + pub effect: String, +} + /// One advisory or bulletin behind a finding. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Source { @@ -79,9 +102,13 @@ pub struct Fix { /// 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. + /// The whole runbook, when a person applies the update in AWS (and + /// behind an apply, for when the role may not). #[serde(default, skip_serializing_if = "Option::is_none")] pub runbook: Option, + /// What CoderHelm applies after one approval. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub apply: Option, /// What a pull request must say and check, for the tool that defines /// the resource. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -922,10 +949,18 @@ fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) &v, feeds.today, )); - format!( + let mut d = 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) - ) + ); + if let Some(e) = l.edit.as_ref().filter(|e| !e.shared.is_empty()) { + d.push_str(&format!( + " The value is shared ({}): the pull request raises it for {} only, through that environment's own input, so no other environment changes by surprise.", + e.shared, + if l.environment.is_empty() { "this resource" } else { l.environment.as_str() } + )); + } + d } _ => { 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(); @@ -934,10 +969,35 @@ fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) } }; + // A step in AWS with no code change: CoderHelm applies it itself after + // one approval, through AWS's own pending-maintenance call. An engine + // upgrade whose code CoderHelm is unsure of stays a runbook (applying + // it in AWS would leave that code pinned behind the live version). + let rds = matches!(r.kind, Kind::RdsCluster | Kind::RdsInstance); + let unsure_code = m.in_code() && located.is_some() && sure.is_none(); + let mut decision = decision; + let mut apply = None; + if rds && kind == FixKind::Runbook && m != Meaning::Unknown && !unsure_code { + kind = FixKind::Apply; + let why = decision + .strip_prefix("A runbook: ") + .map(str::to_string) + .unwrap_or(decision.clone()); + decision = format!( + "CoderHelm applies this in AWS after one approval (apply-pending-maintenance-action, in the next maintenance window unless you pick now), non-production first, and checks the result on the next read. {why}" + ); + apply = Some(apply_plan(m, &p)); + } + // 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) { + // An apply keeps the commands too: they are the runbook a person follows + // when the role may not apply it. + let (cli, console) = match rb + .as_ref() + .filter(|_| matches!(kind, FixKind::Runbook | FixKind::Apply)) + { Some(rb) => ( rb.steps .iter() @@ -956,6 +1016,21 @@ fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) } else { format!("{} to {}", m.label(), p.target) }; + // The cluster-level action that stands for the same update on each + // instance says so in its title. + let members = r + .facts + .get("members") + .map(|m| m.split(',').filter(|x| !x.is_empty()).count()) + .unwrap_or(0); + let what = if p.merged.iter().any(|x| x.starts_with("also listed")) && members > 0 { + format!( + "{what} (the cluster and its {members} instance{})", + if members == 1 { "" } else { "s" } + ) + } else { + what + }; let summary = match (kind, &sure) { (FixKind::Pr, Some(l)) => { let e = l.edit.as_ref(); @@ -967,6 +1042,10 @@ fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) e.map(|e| e.file.as_str()).unwrap_or(l.file.as_str()) ) } + (FixKind::Apply, _) => format!( + "CoderHelm applies the {what} in AWS after your approval (`{}`)", + p.kind + ), _ => format!("Apply the {what} in AWS (`{}`)", p.kind), }; let mut order = Vec::new(); @@ -989,6 +1068,7 @@ fn update(r: &Resource, p: &Pending, feeds: &Feeds, out: &mut Vec) decision, meaning: Some(m), runbook: rb, + apply, notes, code_note, order, @@ -1055,7 +1135,61 @@ fn health(r: &Resource, p: &Pending, out: &mut Vec) { )); } +fn apply_plan(m: Meaning, p: &Pending) -> ApplyPlan { + let effect = match m { + Meaning::OsUpdate => "Each instance restarts while its operating system is patched; on a cluster, readers go first and the writer last (a short failover).".to_string(), + Meaning::EnginePatch => format!("The engine is patched in place to {}: each instance restarts briefly.", p.target), + Meaning::EngineUpgrade => format!("The engine moves to {}: each instance restarts, and a major version takes longer.", if p.target.is_empty() { "the version AWS lists" } else { p.target.as_str() }), + Meaning::ServerlessPlatform => "The serverless instances move to the new platform version: connections pause briefly while each one moves.".to_string(), + Meaning::HardwareMaintenance => "AWS moves the instance to new hardware: it restarts.".to_string(), + Meaning::CertificateRotation => "The server certificate is rotated: clients that pin the old certificate authority must trust the new one first.".to_string(), + _ => String::new(), + }; + ApplyPlan { + action: p.kind.clone(), + arns: p.arns.clone(), + permission: APPLY_PERMISSION.into(), + default_opt_in: "next-maintenance".into(), + effect, + } +} + +/// A CVE that both an engine patch and an engine upgrade on the same +/// database fix stands on the upgrade when the upgrade is a pull request: +/// the code change fixes it for good (a patch applied in AWS alone leaves +/// the code pinned behind). The patch keeps its row, without the CVE, and +/// says where it went. +fn cves_to_the_pull_request(found: &mut [InfraFinding]) { + let prs: Vec<(String, Vec, String)> = found + .iter() + .filter(|f| { + f.fix.meaning == Some(Meaning::EngineUpgrade) && f.fix.kind == Some(FixKind::Pr) + }) + .map(|f| (f.group.clone(), f.cves.clone(), f.fix.to.clone())) + .collect(); + for f in found + .iter_mut() + .filter(|f| f.fix.meaning == Some(Meaning::EnginePatch)) + { + let Some((_, cves, to)) = prs.iter().find(|(g, cves, _)| { + *g == f.group && !f.cves.is_empty() && f.cves.iter().all(|c| cves.contains(c)) + }) else { + continue; + }; + f.fix.advisory_note = format!( + "{} {} also fixed by the engine upgrade to {to}, whose pull request carries {}: that change fixes it in the code too.", + f.cves.join(", "), + if f.cves.len() == 1 { "is" } else { "are" }, + if cves.len() == 1 { "it" } else { "them" } + ); + f.cves.clear(); + f.sources.retain(|s| s.kind != "bulletin"); + f.kev = false; + } +} + fn match_managed(r: &Resource, feeds: &Feeds, out: &mut Vec) { + let start = out.len(); for p in &r.pending { match meaning(r, p) { Meaning::Health => health(r, p, out), @@ -1063,7 +1197,10 @@ fn match_managed(r: &Resource, feeds: &Feeds, out: &mut Vec) { | Meaning::EnginePatch | Meaning::EngineUpgrade | Meaning::ServiceUpdate - | Meaning::ServiceSoftware => update(r, p, feeds, out), + | Meaning::ServiceSoftware + | Meaning::ServerlessPlatform + | Meaning::HardwareMaintenance + | Meaning::CertificateRotation => 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 @@ -1077,12 +1214,10 @@ fn match_managed(r: &Resource, feeds: &Feeds, out: &mut Vec) { { 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. _ => {} } } + cves_to_the_pull_request(&mut out[start..]); } /// The same resource in more than one environment: the non-production @@ -1416,15 +1551,17 @@ mod tests { } #[test] - fn the_2026_160_example_gives_two_prs_one_runbook_and_aws_rows_for_fargate_and_lambda() { + fn the_2026_160_example_gives_two_prs_one_approved_apply_and_aws_rows_for_fargate_and_lambda() { let f = example(); let prs: Vec<&InfraFinding> = f .iter() .filter(|x| x.fix.kind == Some(FixKind::Pr)) .collect(); + // The operating system update has no code change: CoderHelm applies + // it after an approval, with the runbook behind it. let runbooks: Vec<&InfraFinding> = f .iter() - .filter(|x| x.fix.kind == Some(FixKind::Runbook)) + .filter(|x| x.fix.kind == Some(FixKind::Apply)) .collect(); let aws: Vec<&InfraFinding> = f .iter() @@ -1496,8 +1633,8 @@ mod tests { "{}", 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. + // The cluster is in the team's Terraform, and it is still applied in + // AWS, because an OS update cannot be expressed in code. assert!( db.fix.decision.contains("cannot be expressed in code"), "{}", @@ -1510,6 +1647,8 @@ mod tests { ); let rb = db.fix.runbook.as_ref().expect("a full runbook"); assert!(!rb.prechecks.is_empty() && !rb.backup.is_empty() && !rb.rollback.is_empty()); + let plan = db.fix.apply.as_ref().expect("what CoderHelm applies"); + assert_eq!(plan.permission, APPLY_PERMISSION); // AWS-managed rows, never counted as open. let fargate = aws @@ -1913,11 +2052,12 @@ mod tests { )); assert!(x.fix.code_note.contains("raise its pinned version")); - // Not in any repository: a runbook. + // Not in any repository: applied in AWS after an approval, saying + // where code may need raising. let mut nowhere = r.clone(); nowhere.defined_in = None; let x = &one(nowhere, &[])[0]; - assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert_eq!(x.fix.kind, Some(FixKind::Apply)); assert!(x .fix .decision @@ -1932,7 +2072,7 @@ mod tests { inventory::Confidence::High, )); let x = &one(prefix, &[])[0]; - assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert_eq!(x.fix.kind, Some(FixKind::Apply)); assert!( x.fix.decision.contains("already allows version 8.0.40"), "{}", @@ -1952,7 +2092,7 @@ mod tests { } unpinned.defined_in = Some(l); let x = &one(unpinned, &[])[0]; - assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert_eq!(x.fix.kind, Some(FixKind::Apply)); assert!( x.fix.decision.contains("does not pin a version"), "{}", @@ -1968,12 +2108,12 @@ mod tests { ); vague.defined_in = r.defined_in.clone(); let x = &one(vague, &[])[0]; - assert_eq!(x.fix.kind, Some(FixKind::Runbook)); + assert_eq!(x.fix.kind, Some(FixKind::Apply)); 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() { + fn what_cannot_be_expressed_in_code_is_applied_in_aws_even_when_the_resource_is_in_code() { for (engine, version, action, description, meaning) in [ ( "postgres", @@ -2008,7 +2148,8 @@ mod tests { 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_eq!(x.fix.kind, Some(FixKind::Apply), "{action} on {engine}"); + assert!(x.fix.apply.is_some(), "{action} on {engine}"); assert!( x.fix.decision.contains("cannot be expressed in code"), "{}", @@ -2024,9 +2165,9 @@ mod tests { 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. + // Hardware maintenance is an item of its own, applied after an + // approval. 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", @@ -2036,8 +2177,14 @@ mod tests { ("system-update", "something", "2026-12-01"), ], ); - let f = one(r, &[]); - assert_eq!(f.len(), 1); + let mut f = one(r, &[]); + assert_eq!(f.len(), 2); + let hw = f + .iter() + .find(|x| x.fix.meaning == Some(Meaning::HardwareMaintenance)) + .expect("hardware maintenance"); + assert_eq!(hw.fix.kind, Some(FixKind::Apply)); + f.retain(|x| x.fix.meaning == Some(Meaning::Unknown)); assert_eq!(f[0].fix.meaning, Some(Meaning::Unknown)); assert!( f[0].title.contains("AWS action `system-update` pending"), diff --git a/services/common/src/infra_vuln/raw.rs b/services/common/src/infra_vuln/raw.rs index 61093e87b..d1d3064cd 100644 --- a/services/common/src/infra_vuln/raw.rs +++ b/services/common/src/infra_vuln/raw.rs @@ -700,6 +700,83 @@ impl RawAccount { } } +/// The calls whose full answer a read of each kind of resource needs. A +/// call that failed, or stopped at a page cap (it is noted as failed too), +/// leaves that kind unread: what the read did not see is not gone. +pub fn calls_for(kind: Kind) -> &'static [&'static str] { + const AMI: &[&str] = &[ + "DescribeInstances", + "DescribeImages", + "DescribeAutoScalingGroups", + "DescribeTargetGroups", + "DescribeLoadBalancers", + "GetParameters", + "ListInventoryEntries", + ]; + match kind { + Kind::Ec2Instance | Kind::AutoScalingGroup => AMI, + Kind::EksCluster => &["ListClusters (EKS)", "DescribeCluster"], + Kind::EksNodegroup => &[ + "ListClusters (EKS)", + "DescribeCluster", + "ListNodegroups", + "DescribeNodegroup", + "GetParameters", + ], + Kind::EcsFargateService => &[ + "ListClusters (ECS)", + "ListServices", + "DescribeServices", + "DescribeTargetGroups", + "DescribeLoadBalancers", + ], + Kind::RdsCluster | Kind::RdsInstance => &[ + "DescribeDBClusters", + "DescribeDBInstances", + "DescribePendingMaintenanceActions", + ], + Kind::ElasticacheGroup => &["DescribeServiceUpdates", "DescribeUpdateActions"], + Kind::OpensearchDomain => &["ListDomainNames", "DescribeDomains"], + Kind::ContainerImage => &[ + "ListClusters (ECS)", + "ListServices", + "DescribeServices", + "DescribeImageScanFindings", + ], + // Read from the team's code, never from AWS: the read of the code + // decides ([`crate::infra_vuln::inventory::KindsRead`]). + Kind::LambdaFunction => &["(code)"], + } +} + +/// Calls whose failure leaves every kind unread: what they add (Inspector +/// findings, Health events) can be on any resource. +pub const OPTIONAL_SOURCES: &[&str] = &[ + "ListFindings (Inspector)", + "DescribeEvents (Health)", + "DescribeAffectedEntities (Health)", + "GetQueueUrl (Health events)", + "ReceiveMessage (Health events)", +]; + +impl RawAccount { + /// The kinds of resource this read saw in full: every call they need + /// answered, every page read. Lambda functions are never among them + /// (they come from the code). + pub fn complete_kinds(&self) -> Vec { + let failed = |c: &str| self.errors.iter().any(|(x, _)| x == c); + if OPTIONAL_SOURCES.iter().any(|c| failed(c)) { + return Vec::new(); + } + inv::ALL_KINDS + .iter() + .copied() + .filter(|k| *k != Kind::LambdaFunction) + .filter(|k| !calls_for(*k).iter().any(|c| failed(c))) + .collect() + } +} + /// The calls a read makes and the permission each needs, so a refusal can /// name it. pub const CALLS: &[(&str, &str)] = &[ diff --git a/services/common/src/infra_vuln/records.rs b/services/common/src/infra_vuln/records.rs index 3610b5fb2..83c4de6fa 100644 --- a/services/common/src/infra_vuln/records.rs +++ b/services/common/src/infra_vuln/records.rs @@ -17,6 +17,10 @@ use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; +use std::collections::BTreeSet; + +use super::actions::Meaning; +use super::inventory::Coverage; use super::matching::{FixKind, InfraFinding}; use crate::security_fixes::Tier; @@ -68,12 +72,53 @@ pub enum Status { Fixed, AwsManaged, Dismissed, + /// The resource is gone: a full read of its account and region no + /// longer lists it ([`Record::removed_at`] says when). + Removed, + /// The same problem as another finding, which now carries both + /// reasons ([`Record::merged_into`]). Never shown. + Merged, } impl Status { pub fn is_open(self) -> bool { matches!(self, Status::Open | Status::Fixing | Status::PrOpen) } + + /// Closed by a read of the account: fixed, or its resource removed. + pub fn is_closed(self) -> bool { + matches!(self, Status::Fixed | Status::Removed) + } +} + +/// When CoderHelm applies a pending action itself (`apply`): a person's +/// approval, what was asked of AWS, and what came back. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ApplyState { + /// `next-maintenance` (the default) or `immediate`. + pub opt_in: String, + pub approved_by: String, + pub approved_at: String, + /// When AWS accepted the request for every ARN. + #[serde(skip_serializing_if = "String::is_empty")] + pub applied_at: String, + /// The ARNs AWS accepted it for, in order. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub applied: Vec, + /// Why it has not been sent yet (the non-production copy first), or + /// what AWS answered when it refused. + #[serde(skip_serializing_if = "String::is_empty")] + pub note: String, + /// The IAM action the team's role lacks, when AWS refused for that. + #[serde(skip_serializing_if = "String::is_empty")] + pub missing_permission: String, +} + +impl ApplyState { + pub fn sent(&self) -> bool { + !self.applied_at.is_empty() + } } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -135,6 +180,15 @@ pub struct Record { /// What the page says after a person ended its fix run. #[serde(default, skip_serializing_if = "Option::is_none")] pub release_note: Option, + /// When a full read of the account no longer listed the resource. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub removed_at: Option, + /// The finding that now carries this one's reasons. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub merged_into: Option, + /// A person approved CoderHelm applying the pending action in AWS. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub apply: Option, /// A line for the timeline when something changed (not stored). #[serde(skip)] pub event: Option, @@ -167,6 +221,9 @@ impl Record { hold_until: None, claimed_at: None, release_note: None, + removed_at: None, + merged_into: None, + apply: None, } } @@ -184,6 +241,11 @@ 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)); + o.insert("removed_at".into(), json!(self.removed_at)); + o.insert("apply".into(), json!(self.apply)); + // A closed finding offers nothing to do: no pull request to + // open, no runbook to follow, nothing to approve. + o.insert("actionable".into(), json!(self.status.is_open())); // The fix's kind as the contract names it. o["fix"]["kind"] = json!(self.finding.fix.kind); if !self.refused.is_empty() { @@ -360,7 +422,9 @@ impl Claim for Record { Status::Fixing => Standing::Fixing, Status::PrOpen => Standing::InPr, Status::Fixed => Standing::Fixed, - Status::AwsManaged | Status::Dismissed => Standing::Other, + Status::AwsManaged | Status::Dismissed | Status::Removed | Status::Merged => { + Standing::Other + } } } /// An open pull request and a draft the guard held are read every @@ -547,10 +611,83 @@ pub fn fix_round_body(r: &Record) -> String { format!("{}{}", ticket_body(r), super::guard::fix_round(&r.refused)) } +/// What the read behind a match saw. +#[derive(Debug, Clone, Copy)] +pub enum Seen<'a> { + /// Everything, in full (tests, and callers that pass one whole read). + All, + /// Each account and region's latest read: what it saw in full, and the + /// resources stored after it. + Read { + coverage: &'a Coverage, + present: &'a BTreeSet, + }, +} + +/// The version an engine move ends at: the fix's target, or, for a record +/// written before targets were kept, the version its title or AWS's +/// description names. +fn move_target(f: &InfraFinding) -> String { + if !f.fix.to.is_empty() { + return f.fix.to.clone(); + } + let t = super::actions::target_in(&f.title); + if !t.is_empty() { + return t; + } + super::actions::target_in(&f.fix.reason) +} + +fn engine_move(f: &InfraFinding) -> bool { + matches!( + f.kind, + Some(super::inventory::Kind::RdsCluster | super::inventory::Kind::RdsInstance) + ) && match f.fix.meaning { + Some(m) => matches!(m, Meaning::EnginePatch | Meaning::EngineUpgrade), + // Written before meanings were kept: an AWS action whose title + // names the version it moves to. + None => f.fix.kind != Some(FixKind::Aws), + } +} + +/// Two findings are one problem: the same database moving to the same +/// version (a CVE's upgrade target and the engine patch that reaches it). +pub fn same_problem(a: &InfraFinding, b: &InfraFinding) -> bool { + a.id != b.id + && a.account == b.account + && a.region == b.region + && a.group == b.group + && engine_move(a) + && engine_move(b) + && { + let t = move_target(a); + !t.is_empty() && t == move_target(b) + } +} + /// 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. +/// changed (new, updated, fixed, removed or merged). Dismissed ones stay +/// dismissed while they still match. See [`reconcile_with`]. pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime) -> Vec { + reconcile_with(stored, fresh, Seen::All, now) +} + +/// A new read's findings against the stored ones. +/// +/// - A finding the read produces is new, or updated; a closed one found +/// again opens again. +/// - A stored finding that is the same problem as another (same database, +/// same target version) is merged into it: one item, both reasons. +/// - A stored finding the read no longer produces closes only when the +/// latest read of its account and region saw its kind in full: as +/// **removed** when none of its resources is listed any more, else as +/// **fixed**. A failed or partial read closes nothing. +pub fn reconcile_with( + stored: &[Record], + fresh: Vec, + seen: Seen, + now: DateTime, +) -> Vec { let now_s = now.to_rfc3339(); let mut out = Vec::new(); for f in &fresh { @@ -558,7 +695,7 @@ pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime None => out.push(Record::new(f.clone(), &now_s)), Some(r) => { let mut r2 = r.clone(); - let reopened = r.status == Status::Fixed; + let reopened = matches!(r.status, Status::Fixed | Status::Removed | Status::Merged); r2.finding = f.clone(); if reopened { r2.status = if f.is_open() { @@ -567,6 +704,9 @@ pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime Status::AwsManaged }; r2.fixed_at = None; + r2.removed_at = None; + r2.merged_into = None; + r2.apply = None; r2.pr = None; r2.ticket.clear(); r2.clear_guard(); @@ -579,21 +719,77 @@ pub fn reconcile(stored: &[Record], fresh: Vec, now: DateTime } } } - for r in stored + // What a duplicate merges into: a finding of this read, or a stored + // one written with today's shape. + let canonical: Vec<&InfraFinding> = fresh .iter() - .filter(|r| r.status != Status::Fixed && r.status != Status::Dismissed) - { - if fresh.iter().any(|f| f.id == r.finding.id) { + .chain( + stored + .iter() + .filter(|r| !matches!(r.status, Status::Merged) && r.finding.fix.meaning.is_some()) + .filter(|r| !fresh.iter().any(|f| f.id == r.finding.id)) + .map(|r| &r.finding), + ) + .collect(); + for r in stored.iter().filter(|r| { + !matches!(r.status, Status::Dismissed | Status::Merged) + && !fresh.iter().any(|f| f.id == r.finding.id) + }) { + let mut r2 = r.clone(); + r2.updated_at = now_s.clone(); + // Today's shape wins over a record written before it; between two + // of today's, the one this read produced. + let into = canonical.iter().find(|c| { + same_problem(&r.finding, c) + && (r.finding.fix.meaning.is_none() || fresh.iter().any(|f| f.id == c.id)) + }); + if let Some(c) = into { + r2.status = Status::Merged; + r2.merged_into = Some(c.id.clone()); + r2.event = Some(format!( + "Merged into \"{}\": the same move to {} on the same database", + c.title, + move_target(c) + )); + out.push(r2); continue; } - let mut r2 = r.clone(); - r2.status = Status::Fixed; + if r.status.is_closed() { + continue; + } + let closes_as = match seen { + Seen::All => Some(Status::Fixed), + Seen::Read { coverage, present } => match r.finding.kind { + Some(k) if coverage.complete(&r.finding.account, &r.finding.region, k) => { + if r.finding.resources.iter().any(|id| present.contains(id)) { + Some(Status::Fixed) + } else { + Some(Status::Removed) + } + } + _ => None, + }, + }; + let Some(closes_as) = closes_as else { + continue; + }; + r2.status = closes_as; r2.fixed_at = Some(now_s.clone()); - r2.updated_at = now_s.clone(); - r2.event = Some(if r.status == Status::AwsManaged { - "No longer applies (the resource or the bulletin changed)".into() - } else { - "Fixed: the latest read of the account shows the fix running".into() + r2.event = Some(match (closes_as, r.status) { + (Status::Removed, _) => { + r2.removed_at = Some(now_s.clone()); + format!( + "Resource removed: the latest full read of the account ({}) no longer lists {}", + r.finding.region, r.finding.name + ) + } + (_, Status::AwsManaged) => { + "No longer applies (the resource or the bulletin changed)".into() + } + _ if r.apply.as_ref().is_some_and(ApplyState::sent) => { + "Fixed: CoderHelm applied it in AWS and the latest read of the account no longer lists it".into() + } + _ => "Fixed: the latest read of the account shows the fix running".into(), }); if let Some(p) = &mut r2.pr { if p.state == "open" { @@ -620,6 +816,16 @@ pub fn counts(records: &[Record], now: DateTime) -> Value { .is_some_and(|t| t > since) }) .count(); + let removed_30d = records + .iter() + .filter(|r| r.status == Status::Removed) + .filter(|r| { + r.removed_at + .as_deref() + .and_then(|t| DateTime::parse_from_rfc3339(t).ok()) + .is_some_and(|t| t > since) + }) + .count(); json!({ "open": open.len(), "p0": n(Tier::P0), "p1": n(Tier::P1), "p2": n(Tier::P2), "p3": n(Tier::P3), @@ -627,6 +833,8 @@ pub fn counts(records: &[Record], now: DateTime) -> Value { "runbooks": open.iter().filter(|r| r.finding.fix.kind == Some(FixKind::Runbook)).count(), "aws_managed": records.iter().filter(|r| r.status == Status::AwsManaged).count(), "fixed_30d": fixed_30d, + "removed_30d": removed_30d, + "applies": open.iter().filter(|r| r.finding.fix.kind == Some(FixKind::Apply)).count(), }) } @@ -640,7 +848,7 @@ pub fn insights(records: &[Record], now: DateTime) -> Value { }; let actionable: Vec<&Record> = records .iter() - .filter(|r| r.finding.fix.kind != Some(FixKind::Aws)) + .filter(|r| r.finding.fix.kind != Some(FixKind::Aws) && r.status != Status::Merged) .collect(); let mut days: Vec = actionable .iter() diff --git a/services/common/src/live/iam_resource_types.json b/services/common/src/live/iam_resource_types.json index 78aa1e3e4..253340c49 100644 --- a/services/common/src/live/iam_resource_types.json +++ b/services/common/src/live/iam_resource_types.json @@ -200,6 +200,10 @@ "cluster", "db" ], + "rds:ApplyPendingMaintenanceAction": [ + "cluster", + "db" + ], "elasticache:DescribeServiceUpdates": [ "" ], diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index 13a4b0048..18ddea906 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -222,12 +222,24 @@ pub const ABILITIES: &[Ability] = &[ ], chosen: true, }, + Ability { + key: "maintenance", + name: "Applying approved database maintenance", + why: "Applies a pending RDS or Aurora maintenance action (an operating system update, an engine patch or upgrade, a serverless platform update) after a person approves it on the infrastructure findings page: in the next maintenance window, or now when they pick that. Only the account's own clusters and instances, only when the stack's ApplyMaintenance parameter is on, and never without that approval.", + actions: &["rds:ApplyPendingMaintenanceAction"], + chosen: true, + }, ]; /// Optional abilities a team switches on per account: the live check /// asks about them too, but a missing one never makes the role "need an /// update" unless the team switched it on (`AwsAccount::infra_on`). -pub const OPTIONAL: &[&str] = &["infra", "inspector", "health"]; +pub const OPTIONAL: &[&str] = &["infra", "inspector", "health", "maintenance"]; + +/// The one action that changes a database, in [`ability`] `maintenance`: +/// granted only when a team switches ApplyMaintenance on, and used only for +/// a pending action a person approved. +pub const MAINTENANCE_WRITES: &[&str] = &["rds:ApplyPendingMaintenanceAction"]; /// The only actions that change anything, all in [`ability`] `sync` and /// granted only on the knowledge bases a team names in SyncKnowledgeBases. @@ -252,6 +264,8 @@ pub struct Chosen<'a> { /// its API. pub inspector: bool, pub health: bool, + /// The team lets CoderHelm apply approved database maintenance. + pub maintenance: bool, } impl<'a> Chosen<'a> { @@ -263,6 +277,7 @@ impl<'a> Chosen<'a> { infrastructure: false, inspector: false, health: false, + maintenance: false, } } @@ -275,6 +290,14 @@ impl<'a> Chosen<'a> { } } + /// The same, also applying approved database maintenance. + pub fn with_maintenance(self, on: bool) -> Chosen<'a> { + Chosen { + maintenance: on, + ..self + } + } + /// The same, also reading infrastructure versions (`infra`). pub fn with_infrastructure(self, on: bool) -> Chosen<'a> { Chosen { @@ -298,6 +321,7 @@ impl<'a> Chosen<'a> { && !self.infrastructure && !self.inspector && !self.health + && !self.maintenance } } @@ -525,6 +549,9 @@ pub fn update_url(update_template_url: &str, region: &str, chosen: &Chosen) -> S if chosen.health { u.push_str("¶m_HealthEvents=on"); } + if chosen.maintenance { + u.push_str("¶m_ApplyMaintenance=on"); + } u } @@ -563,6 +590,9 @@ pub fn update_stack_name_for(chosen: &Chosen) -> String { if chosen.health { seed.push_str("|health"); } + if chosen.maintenance { + seed.push_str("|maintenance"); + } format!( "{}-kb{}", update_stack_name(), @@ -619,7 +649,8 @@ mod tests { let ok_reads = ["logs:StartQuery", "logs:StopQuery", "airflow:InvokeRestApi"]; for a in all_actions() { let verb = a.split(':').nth(1).unwrap(); - if ok_reads.contains(&a) || SYNC_WRITES.contains(&a) { + if ok_reads.contains(&a) || SYNC_WRITES.contains(&a) || MAINTENANCE_WRITES.contains(&a) + { continue; } assert!( @@ -654,6 +685,20 @@ mod tests { "{w} only in the sync statement" ); } + // Database maintenance: only in its own statement, only behind + // ApplyMaintenance, only on the account's own databases. + for w in MAINTENANCE_WRITES { + assert_eq!(t.matches(&format!("\"{w}\"")).count(), 1, "{w}"); + } + let m = t + .split("- AppliesMaintenance") + .nth(1) + .expect("the maintenance statement"); + let m = m.split("- !Ref AWS::NoValue").next().unwrap(); + assert!(m.contains("rds:ApplyPendingMaintenanceAction")); + assert!(m.contains(":cluster:*") && m.contains(":db:*")); + assert!(!m.contains("Resource: \"*\"")); + assert!(t.contains("AppliesMaintenance: !Equals [!Ref ApplyMaintenance, \"on\"]")); // Imports: read objects only in the buckets named, decrypt only // through S3. assert!(t.contains("- Sid: ReadImportBuckets")); @@ -816,8 +861,9 @@ 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 (20), Inspector (3) and Health (3). - assert_eq!(checked.len() + 42, all_actions().len()); + // reads (20), Inspector (3), Health (3) and applying approved + // maintenance (1). + assert_eq!(checked.len() + 43, 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/main.rs b/services/gateway/src/main.rs index 031a55666..5dc6874d4 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -620,6 +620,10 @@ fn build_app(state: Arc) -> Router { "/security/infrastructure/findings/:id/fix", post(routes::infra_security::fix), ) + .route( + "/security/infrastructure/findings/:id/apply", + post(routes::infra_security::apply), + ) .route( "/alert-routes", get(routes::alerts::list_routes) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 52ffa6dbf..59507cb6b 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -718,7 +718,7 @@ pub const CAPABILITIES: &[Capability] = &[ }, Capability { key: "security", - label: "Change security fix settings, dismiss or reopen findings, open fix PRs, check repositories now and preview what would open", + label: "Change security fix settings, dismiss or reopen findings, open fix PRs, approve infrastructure updates CoderHelm applies in AWS, check repositories now and preview what would open", short_label: "Manage security fixes", min_role: "admin", @@ -727,6 +727,7 @@ pub const CAPABILITIES: &[Capability] = &[ "infra_security::check", "infra_security::put_config", "infra_security::fix", + "infra_security::apply", "security::dismiss", "security::reopen", "security::scan", diff --git a/services/gateway/src/routes/infra_security.rs b/services/gateway/src/routes/infra_security.rs index 75a16aee3..981eef9dc 100644 --- a/services/gateway/src/routes/infra_security.rs +++ b/services/gateway/src/routes/infra_security.rs @@ -10,12 +10,18 @@ //! and the permissions it was refused, and the accounts where the option //! is on but the role lacks the reads. Any team member. //! - `GET /api/security/infrastructure` — the findings, one per fix, the -//! counts and each account's state. Any team member. +//! counts and each account's state. Any team member. When the latest read +//! is older than [`REFRESH_AFTER_SECS`], it also starts a refresh of the +//! team's accounts in the background (at most one per team in that +//! time), and says so (`refreshing`) with when it last read (`read_at`). //! - `GET /api/security/infrastructure/insights` — Analytics' counts. //! - `POST /api/security/infrastructure/check` — read every switched-on //! account again now. Admin. //! - `POST /api/security/infrastructure/findings/{id}/fix` — open the fix //! PR now, within the day's limits. Admin. +//! - `POST /api/security/infrastructure/findings/{id}/apply` — approve a +//! pending action CoderHelm applies in AWS (`{"when": "next-maintenance"}` +//! or `"immediate"`). Admin. //! - `GET`/`PUT /api/security/infrastructure/config` — the opt-in switches //! (Amazon Inspector, AWS Health), with what each costs or needs. Saving //! is Admin. @@ -46,6 +52,11 @@ type Item = HashMap; const MAX_ROWS: usize = 2_000; /// The summary row of an account's last read (the worker writes it). const READ_PREFIX: &str = "RES_READ#"; +/// A read older than this starts a refresh when someone opens the page. +pub const REFRESH_AFTER_SECS: i64 = 5 * 60; +/// One refresh per team in this time, however often the page opens. +const REFRESH_CLAIM_SECS: u64 = 5 * 60; +const REFRESH_CLAIM_SK: &str = "INFRA_REFRESH"; /// GET /api/security/infrastructure/sources pub async fn sources( @@ -245,8 +256,40 @@ pub async fn health_template( ) } -fn account_states(accounts: &[aws_account::AwsAccount], reads: &[Value]) -> Vec { - account_states_with(accounts, reads, &records::InfraConfig::default()) +/// Each account's state ([`account_states_with`]), also saying whether its role may apply +/// approved maintenance, and its update link asking for that when an +/// approved action there was refused for the permission. +pub fn account_states_for( + accounts: &[aws_account::AwsAccount], + reads: &[Value], + found: &[Record], +) -> Vec { + let cfg = records::InfraConfig::default(); + accounts + .iter() + .zip(account_states_with(accounts, reads, &cfg)) + .map(|(a, mut v)| { + let may = a + .permissions + .as_ref() + .and_then(|p| p.optional_ability("maintenance")); + let refused = found.iter().any(|r| { + r.finding.account == a.account + && r.status.is_open() + && r.apply + .as_ref() + .is_some_and(|x| !x.missing_permission.is_empty()) + }); + v["apply_maintenance"] = json!(may); + if refused && may != Some(true) { + v["update_url"] = json!(super::connectors::update_stack_url( + &a.region, + &a.chosen().with_maintenance(true) + )); + } + v + }) + .collect() } /// Each account's state; the update link also asks for Inspector's and @@ -291,10 +334,13 @@ pub fn findings_view( reads: &[Value], now: chrono::DateTime, ) -> Value { + // A merged duplicate is never shown (its finding carries both + // reasons); a fixed or removed one for 30 days, under its own filter. let mut shown: Vec<&Record> = found .iter() + .filter(|r| r.status != records::Status::Merged) .filter(|r| { - r.status != records::Status::Fixed + !r.status.is_closed() || r.fixed_at .as_deref() .is_some_and(|t| t > (now - chrono::Duration::days(30)).to_rfc3339().as_str()) @@ -303,7 +349,7 @@ pub fn findings_view( shown.sort_by(|a, b| { let k = |r: &Record| { ( - r.status == records::Status::Fixed, + r.status.is_closed(), r.finding.fix.kind == Some(common::infra_vuln::matching::FixKind::Aws), r.tier().is_none(), r.tier(), @@ -313,6 +359,9 @@ pub fn findings_view( k(a).cmp(&k(b)) }); let read_at = reads.iter().filter_map(|r| r["read_at"].as_str()).max(); + // The oldest of the accounts' latest reads: what "checked N min ago" + // is honest about. + let oldest_read_at = reads.iter().filter_map(|r| r["read_at"].as_str()).min(); json!({ "enabled": cfg.enabled, "dry_run": cfg.dry_run, @@ -320,9 +369,72 @@ pub fn findings_view( "accounts": accounts, "findings": shown.iter().map(|r| r.view()).collect::>(), "read_at": read_at, + "oldest_read_at": oldest_read_at, + "refresh_after_secs": REFRESH_AFTER_SECS, }) } +/// The latest read is old enough that opening the page refreshes it: some +/// account with the option on has never been read, or its last read is +/// older than [`REFRESH_AFTER_SECS`]. Pure. +pub fn stale( + accounts: &[aws_account::AwsAccount], + reads: &[Value], + now: chrono::DateTime, +) -> bool { + accounts.iter().filter(|a| a.infra_on()).any(|a| { + let at = reads + .iter() + .filter(|r| r["account"] == a.account.as_str()) + .filter_map(|r| r["read_at"].as_str()) + .filter_map(|t| chrono::DateTime::parse_from_rfc3339(t).ok()) + .max(); + at.is_none_or(|t| (now - t.with_timezone(&chrono::Utc)).num_seconds() > REFRESH_AFTER_SECS) + }) +} + +/// Starts a background refresh when the reads are stale: one per team per +/// [`REFRESH_CLAIM_SECS`]. Returns whether one is under way. +async fn refresh_if_stale( + state: &AppState, + claims: &Claims, + accounts: &[aws_account::AwsAccount], + reads: &[Value], +) -> bool { + if !stale(accounts, reads, chrono::Utc::now()) { + return false; + } + match common::claim::claim( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + REFRESH_CLAIM_SK, + REFRESH_CLAIM_SECS, + ) + .await + { + common::claim::Claim::Won => { + if queue(state, claims, "infrastructure_refresh", "") + .await + .is_err() + { + common::claim::release( + &state.dynamo, + &state.config.settings_table_name, + &claims.team_id, + REFRESH_CLAIM_SK, + ) + .await; + return false; + } + true + } + // Another open of the page started it a moment ago. + common::claim::Claim::Held => true, + common::claim::Claim::Failed(_) => false, + } +} + pub(crate) async fn load_records( state: &AppState, team_id: &str, @@ -364,13 +476,16 @@ pub async fn findings( let cfg = super::security::load_config(&state, &claims.team_id) .await? .unwrap_or_default(); - Ok(Json(findings_view( + let refreshing = refresh_if_stale(&state, &claims, &accounts, &r).await; + let mut v = findings_view( &found, - account_states(&accounts, &r), + account_states_for(&accounts, &r, &found), &cfg, &r, chrono::Utc::now(), - ))) + ); + v["refreshing"] = json!(refreshing); + Ok(Json(v)) } /// GET /api/security/infrastructure/insights @@ -432,6 +547,9 @@ pub async fn fix( (Some(common::infra_vuln::matching::FixKind::Pr), _, _) => { Some("A fix is already open or done.") } + (Some(common::infra_vuln::matching::FixKind::Apply), _, _) => { + Some("This update is applied in AWS, not in code: approve it and CoderHelm applies it.") + } _ => Some("This fix happens in AWS or is AWS-managed: there is no PR to open."), }; if let Some(reason) = skip { @@ -442,6 +560,66 @@ pub async fn fix( Ok(Json(json!({ "status": "queued", "reason": null }))) } +#[derive(Debug, serde::Deserialize, Default)] +pub struct ApplyBody { + /// `next-maintenance` (the default) or `immediate`. + #[serde(default)] + pub when: String, +} + +/// Why a finding cannot be approved for CoderHelm to apply, or `None`. +/// Pure. +pub fn apply_refusal(r: &Record) -> Option<&'static str> { + use common::infra_vuln::matching::FixKind; + if !r.status.is_open() { + return Some("This finding is closed: nothing to apply."); + } + if r.finding.fix.kind != Some(FixKind::Apply) || r.finding.fix.apply.is_none() { + return Some("This finding has no action CoderHelm applies in AWS."); + } + if r.apply.as_ref().is_some_and(|a| a.sent()) { + return Some("AWS already accepted it: it closes when the next read no longer lists it."); + } + None +} + +/// POST /api/security/infrastructure/findings/{id}/apply +pub async fn apply( + State(state): State>, + Extension(claims): Extension, + Path(id): Path, + body: Option>, +) -> Result, StatusCode> { + claims.require_role(3)?; + if id.len() > 64 || !id.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(StatusCode::BAD_REQUEST); + } + let when = body.map(|b| b.0.when).unwrap_or_default(); + let when = match when.as_str() { + "" | "next-maintenance" => "next-maintenance", + "immediate" => "immediate", + _ => return Err(StatusCode::BAD_REQUEST), + }; + let found = load_records(&state, &claims.team_id).await?; + let Some(r) = found.iter().find(|r| r.finding.id == id) else { + return Err(StatusCode::NOT_FOUND); + }; + if let Some(reason) = apply_refusal(r) { + return Ok(Json(json!({ "status": "skipped", "reason": reason }))); + } + let msg = WorkerMessage::SecurityEvent(SecurityEventMessage { + team_id: claims.team_id.clone(), + kind: "infrastructure_apply".into(), + repo: id.clone(), + action: when.into(), + requested_by: claims.email.clone(), + ..Default::default() + }); + super::github_webhook::send_to_queue(&state, &state.config.ticket_queue_url, &msg).await?; + tracing::info!(team = %claims.team_id, finding = %id, by = %claims.email, when, "Infrastructure update approved"); + Ok(Json(json!({ "status": "queued", "when": when }))) +} + /// Pure: what a person's Retry of an infrastructure fix run does. When /// the run's pull request is gone (closed unmerged, or the run ended /// without one) and the finding still has a pull request to open, the diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 7e3e16690..399cc4ade 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -767,9 +767,7 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe } models::WorkerMessage::SecurityEvent(msg) => { info!(team_id = %msg.team_id, kind = %msg.kind, repo = %msg.repo, "Security event"); - if msg.kind == passes::infra_findings::CHECK_KIND - || msg.kind == passes::infra_findings::FIX_KIND - { + if passes::infra_findings::handles(&msg.kind) { passes::infra_findings::on_event(&state, &msg).await; } else { passes::security_fixes::on_event(&state, &msg).await; diff --git a/services/worker/src/passes/incidents/an_six_database_findings.rs b/services/worker/src/passes/incidents/an_six_database_findings.rs index e3d50aa38..e59740f88 100644 --- a/services/worker/src/passes/incidents/an_six_database_findings.rs +++ b/services/worker/src/passes/incidents/an_six_database_findings.rs @@ -20,8 +20,9 @@ //! 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. +//! that cannot be expressed in code is applied in AWS after an approval +//! (`bn`) and says so, with a complete runbook behind it. A change that +//! would replace a database is refused. use std::collections::BTreeMap; @@ -513,10 +514,11 @@ fn a_generated_identifier_is_found_by_its_prefix_and_settings() { #[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. + // In a CloudFormation template, found by its stack tags, and still + // applied in AWS (after an approval, with the runbook behind it): 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)); + assert_eq!(billing.fix.kind, Some(FixKind::Apply)); let l = billing.fix.location.as_ref().unwrap(); assert_eq!( (l.how.as_str(), l.file.as_str(), l.address.as_str()), @@ -534,10 +536,10 @@ fn what_code_cannot_do_or_does_not_hold_is_a_complete_runbook_that_says_why() { 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. + // Not in any connected repository: applied in AWS after an approval, + // with a complete runbook behind it and the real identifiers. let reports = find(&s, "reports-prod", Meaning::EngineUpgrade); - assert_eq!(reports.fix.kind, Some(FixKind::Runbook)); + assert_eq!(reports.fix.kind, Some(FixKind::Apply)); assert!(reports .fix .decision diff --git a/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs b/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs new file mode 100644 index 000000000..015be41da --- /dev/null +++ b/services/worker/src/passes/incidents/bn_infra_list_follows_aws.rs @@ -0,0 +1,709 @@ +//! bn. Security, Infrastructure kept ten rows for one account while AWS had +//! moved on. An RDS instance deleted two days before still showed an +//! operating system update and an engine upgrade pending. A Lambda function +//! on a retired runtime was listed from a Terraform module nothing called, +//! so it never ran anywhere. Both Aurora clusters already ran the new engine +//! version, so five rows were fixed, yet they kept their Runbook and Fix PR +//! buttons beside "Fixed", and an older CVE row and the engine patch to the +//! same version stood as two rows. Meanwhile AWS listed a serverless +//! platform update on both clusters and an operating system update on each +//! of their three instances, and the page showed neither. The operating +//! system updates it did show were handed over as runbooks, and a person +//! asking "this should refresh, right?" had no way to know when the list +//! was last read. The read kept every resource it had seen for three days, +//! and the match took all of them as running: nothing told a resource that +//! is gone apart from one a read failed to list. +//! +//! Guarantee: each read says which kinds of resource it saw in full. A +//! resource a full read no longer lists is dropped at once and its findings +//! close as removed, with the time; a finding whose fix is running closes +//! as fixed. A failed or partial read drops nothing and closes nothing. Two +//! findings for the same move on the same database are one. Every pending +//! action AWS lists is an item; one with no code change is applied by +//! CoderHelm after one approval (the role's missing permission named when +//! it lacks it), never only handed over; a version change on a resource +//! defined in code is a pull request, whichever source raised it. Closed +//! items offer nothing to do. Opening the page refreshes a read older than +//! five minutes, at most once per team in that time. + +use std::collections::{BTreeMap, BTreeSet}; + +use common::infra_vuln::actions::Meaning; +use common::infra_vuln::feeds::{Bulletin, Runtime, ServiceStatus, Who}; +use common::infra_vuln::inventory::{ + self as inv, Confidence, Coverage, Edit, Kind, KindsRead, Location, Resource, +}; +use common::infra_vuln::matching::{self, Feeds, FixKind, InfraFinding}; +use common::infra_vuln::raw::{RawAccount, RawDatabase, RawPending}; +use common::infra_vuln::records::{self, ApplyState, Record, Seen, Status}; + +use crate::passes::infra_findings; + +const ACCOUNT: &str = "111122223333"; +const REGION: &str = "us-east-1"; +const CVE: &str = "CVE-2026-98432"; +const INFRA: &str = "acme/platform-infra"; +const GONE: &str = "legacy-db-0002"; +const STAGING: &str = "staging-orders-db"; +const PROD: &str = "prod-orders-db"; +const BEFORE: &str = "2026-11-13T00:20:00Z"; +const NOW: &str = "2026-11-15T00:20:00Z"; + +fn arn(kind: &str, name: &str) -> String { + format!("arn:aws:rds:{REGION}:{ACCOUNT}:{kind}:{name}") +} + +fn db(kind: &str, name: &str, engine: &str, version: &str, of: &str, writer: bool) -> RawDatabase { + RawDatabase { + id: name.into(), + arn: arn(kind, name), + engine: engine.into(), + engine_version: version.into(), + cluster: of.into(), + writer, + ..Default::default() + } +} + +fn pending(on: &str, action: &str, description: &str) -> RawPending { + RawPending { + resource_arn: on.into(), + action: action.into(), + description: description.into(), + ..Default::default() + } +} + +fn members(version: &str) -> Vec { + vec![ + db( + "db", + "prod-orders-db-1", + "aurora-postgresql", + version, + PROD, + true, + ), + db( + "db", + "prod-orders-db-2", + "aurora-postgresql", + version, + PROD, + false, + ), + db( + "db", + "staging-orders-db-1", + "aurora-postgresql", + version, + STAGING, + true, + ), + ] +} + +/// Two days ago: the old instance, both clusters on 16.11 with an upgrade +/// to 16.13, the engine patch to 16.11.6 and an operating system update. +fn before() -> RawAccount { + let mut pend = vec![ + pending( + &arn("db", GONE), + "system-update", + "New Operating System patch is available", + ), + pending( + &arn("db", GONE), + "db-upgrade", + "Upgrade to the next minor version", + ), + ]; + for c in [STAGING, PROD] { + pend.push(pending( + &arn("cluster", c), + "db-upgrade", + "Upgrade to Aurora PostgreSQL 16.13", + )); + pend.push(pending( + &arn("cluster", c), + "system-update", + "Upgrade to Aurora PostgreSQL 16.11.6", + )); + pend.push(pending( + &arn("cluster", c), + "os-upgrade", + "New Operating System patch is available", + )); + } + let mut instances = members("16.11"); + instances.push(db("db", GONE, "mysql", "8.0.45", "", false)); + RawAccount { + account: ACCOUNT.into(), + region: REGION.into(), + read_at: BEFORE.into(), + db_clusters: vec![ + db("cluster", STAGING, "aurora-postgresql", "16.11", "", false), + db("cluster", PROD, "aurora-postgresql", "16.11", "", false), + ], + db_instances: instances, + pending: pend, + ..Default::default() + } +} + +/// Now, as AWS answers: the instance is gone, both clusters run 16.13, and +/// AWS lists an operating system update and a serverless platform update +/// on each cluster and an operating system update on each instance. +fn now_read() -> RawAccount { + let mut pend = Vec::new(); + for c in [STAGING, PROD] { + pend.push(pending( + &arn("cluster", c), + "os-upgrade", + "New Operating System patch is available", + )); + pend.push(pending( + &arn("cluster", c), + "serverless-platform-version-update", + "Upgrade to platform version 4", + )); + } + for i in [ + "prod-orders-db-1", + "prod-orders-db-2", + "staging-orders-db-1", + ] { + pend.push(pending( + &arn("db", i), + "system-update", + "New Operating System patch is available", + )); + } + RawAccount { + account: ACCOUNT.into(), + region: REGION.into(), + read_at: NOW.into(), + db_clusters: vec![ + db("cluster", STAGING, "aurora-postgresql", "16.13", "", false), + db("cluster", PROD, "aurora-postgresql", "16.13", "", false), + ], + db_instances: members("16.13"), + pending: pend, + ..Default::default() + } +} + +/// The Terraform: the clusters through a module each environment calls, +/// and a redirect module with a Lambda function that nothing calls. +const MODULE: &str = "variable \"engine_version\" {}\nresource \"aws_rds_cluster\" \"this\" {\n engine_version = var.engine_version\n}\n"; +const ENV: &str = "terraform {\n backend \"s3\" {}\n}\nmodule \"orders\" {\n source = \"../../modules/aurora\"\n engine_version = \"16.11\"\n}\n"; +const REDIRECT: &str = "resource \"aws_lambda_function\" \"redirect_function\" {\n function_name = \"redirect-function\"\n handler = \"index.handler\"\n runtime = \"python3.9\"\n}\n"; + +fn code() -> Vec<(&'static str, &'static str, &'static str)> { + vec![ + (INFRA, "modules/aurora/main.tf", MODULE), + (INFRA, "envs/prod/main.tf", ENV), + (INFRA, "envs/staging/main.tf", ENV), + (INFRA, "modules/redirect/main.tf", REDIRECT), + ] +} + +fn lambda() -> Resource { + inv::lambdas_from_terraform( + INFRA, + "modules/redirect/main.tf", + REDIRECT, + ACCOUNT, + REGION, + BEFORE, + ) + .pop() + .expect("the function the module declares") +} + +/// Each cluster found for sure in the code, through its environment's +/// module call. +fn placed(mut rs: Vec) -> Vec { + for r in rs.iter_mut().filter(|r| r.kind == Kind::RdsCluster) { + let env = if r.name.starts_with("prod") { + "prod" + } else { + "staging" + }; + r.defined_in = Some(Location { + repo: INFRA.into(), + file: "modules/aurora/main.tf".into(), + address: "module.orders.aws_rds_cluster.this".into(), + how: "terraform_module".into(), + tool: "terraform".into(), + confidence: Confidence::High, + environment: if env == "prod" { + "production".into() + } else { + "staging".into() + }, + edit: Some(Edit { + file: format!("envs/{env}/main.tf"), + line: 6, + attribute: "engine_version".into(), + value: "16.11".into(), + via: "module_input".into(), + shared: String::new(), + }), + ..Default::default() + }); + } + rs +} + +fn bulletin() -> Bulletin { + Bulletin { + id: "2026-160-AWS".into(), + title: "Issue with Aurora PostgreSQL".into(), + url: "https://aws.amazon.com/security/security-bulletins/2026-160-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 Aurora PostgreSQL 16.11.6 or later.".into(), + ..Default::default() + }], + ..Default::default() + } +} + +fn runtimes() -> Vec { + vec![ + Runtime { + id: "python3.9".into(), + deprecated: true, + ..Default::default() + }, + Runtime { + id: "python3.13".into(), + ..Default::default() + }, + ] +} + +fn find(resources: &[Resource], today: &str) -> Vec { + let b = bulletin(); + let rt = runtimes(); + let (kev, latest) = (BTreeMap::new(), BTreeMap::new()); + matching::findings( + resources, + &Feeds { + advisories: &[], + bulletins: std::slice::from_ref(&b), + runtimes: &rt, + latest: &[], + kev: &kev, + latest_al2023: &latest, + today, + }, + ) +} + +fn at(s: &str) -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339(s) + .unwrap() + .with_timezone(&chrono::Utc) +} + +/// A row written before findings kept what an action means: the CVE's +/// upgrade target, with no target field of its own. +fn legacy_cve_row(cluster: &str) -> Record { + let mut r = Record::new( + InfraFinding { + id: format!("legacy{}", cluster.len()), + account: ACCOUNT.into(), + region: REGION.into(), + group: arn("cluster", cluster), + kind: Some(Kind::RdsCluster), + name: cluster.into(), + resources: vec![arn("cluster", cluster)], + title: format!("Aurora cluster {cluster}: Upgrade to Aurora PostgreSQL 16.11.6"), + cves: vec![CVE.into()], + fix: matching::Fix { + kind: Some(FixKind::Runbook), + summary: "Apply system update in AWS".into(), + from: "16.11".into(), + ..Default::default() + }, + ..Default::default() + }, + BEFORE, + ); + r.status = Status::Fixed; + r.fixed_at = Some(BEFORE.into()); + r +} + +/// The stored rows the page showed: two days ago's read, its findings, +/// and the two rows written before meanings were kept. +fn stored() -> (Vec, Vec) { + let mut res = placed(before().resources()); + res.push(lambda()); + let mut recs = records::reconcile(&[], find(&res, "2026-11-13"), at(BEFORE)); + recs.push(legacy_cve_row(STAGING)); + recs.push(legacy_cve_row(PROD)); + (res, recs) +} + +fn apply_changes(stored: &[Record], changed: Vec) -> Vec { + let mut out = stored.to_vec(); + for c in changed { + match out.iter_mut().find(|x| x.finding.id == c.finding.id) { + Some(x) => *x = c, + None => out.push(c), + } + } + out +} + +fn open_titles(recs: &[Record]) -> Vec { + let mut t: Vec = recs + .iter() + .filter(|r| r.status.is_open()) + .map(|r| r.finding.title.clone()) + .collect(); + t.sort(); + t +} + +/// What the old read did: every row it had seen stayed, and the match took +/// them all as running. +#[test] +fn before_the_gone_instance_and_the_uncalled_function_stay_open() { + let (mut res, recs) = stored(); + // The new read saved its resources over the old ones and dropped none. + let fresh = placed(now_read().resources()); + res.retain(|r| !fresh.iter().any(|f| f.sk() == r.sk())); + res.extend(fresh); + let after = apply_changes( + &recs, + records::reconcile(&recs, find(&res, "2026-11-15"), at(NOW)), + ); + let open = open_titles(&after); + assert!( + open.iter() + .any(|t| t.contains(GONE) && t.contains("operating system")), + "{open:#?}" + ); + assert!( + open.iter() + .any(|t| t.contains(GONE) && t.contains("engine version upgrade")), + "{open:#?}" + ); + assert!( + open.iter() + .any(|t| t.contains("redirect-function") && t.contains("python3.9")), + "{open:#?}" + ); +} + +/// What a read sees in full drops what it no longer lists, and the match +/// closes those findings as removed; fixed ones stay fixed; the same move +/// on the same cluster is one item; every pending action AWS lists is on +/// the page, applied by CoderHelm after one approval. +#[test] +fn after_a_full_read_the_list_is_what_aws_says_now() { + let (stored_res, recs) = stored(); + let raw = now_read(); + let fresh = placed(raw.resources()); + // The code read in full: the redirect module is called by nothing. + let uncalled = inv::uncalled_modules(&code()); + assert!( + uncalled.contains(&format!("{INFRA}:modules/redirect")), + "{uncalled:?}" + ); + assert!( + !uncalled.contains(&format!("{INFRA}:modules/aurora")), + "{uncalled:?}" + ); + let placing = crate::passes::infra_inventory::Placing { + repos: 1, + files_read: 4, + ..Default::default() + }; + let complete = crate::passes::infra_inventory::complete_kinds(&raw, Some(&placing)); + assert!(complete.contains(&Kind::RdsInstance) && complete.contains(&Kind::LambdaFunction)); + let gone = inv::gone(&stored_res, &fresh, &complete); + assert_eq!(gone.len(), 2, "{gone:?}"); + assert!(gone.iter().any(|sk| sk.ends_with(&format!(":db:{GONE}")))); + assert!(gone + .iter() + .any(|sk| sk.contains("aws_lambda_function.redirect_function"))); + + let present: BTreeSet = fresh.iter().map(|r| r.id.clone()).collect(); + let coverage = Coverage { + reads: vec![KindsRead { + account: ACCOUNT.into(), + region: REGION.into(), + read_at: NOW.into(), + complete, + }], + }; + let changed = records::reconcile_with( + &recs, + find(&fresh, "2026-11-15"), + Seen::Read { + coverage: &coverage, + present: &present, + }, + at(NOW), + ); + let after = apply_changes(&recs, changed); + let by = |pred: &dyn Fn(&Record) -> bool| -> Vec<&Record> { + after.iter().filter(|r| pred(r)).collect() + }; + + // Rows 1, 4 and 5: removed, with when. + let removed = by(&|r| r.status == Status::Removed); + assert_eq!( + removed.len(), + 3, + "{:#?}", + removed.iter().map(|r| &r.finding.title).collect::>() + ); + for r in &removed { + assert_eq!(r.removed_at.as_deref(), Some(at(NOW).to_rfc3339().as_str())); + assert!(r.view()["actionable"] == false); + } + // Rows 6 and 7 (the CVE's 16.11.6 target) are the engine patch rows. + let merged = by(&|r| r.status == Status::Merged); + assert_eq!(merged.len(), 2); + for m in &merged { + let into = after + .iter() + .find(|r| Some(&r.finding.id) == m.merged_into.as_ref()) + .expect("merged into a finding on the page"); + assert_eq!(into.finding.fix.meaning, Some(Meaning::EnginePatch)); + assert_eq!(into.finding.group, m.finding.group); + } + // Rows 8 to 10: fixed, and a fixed row offers nothing to do. + let fixed = by(&|r| r.status == Status::Fixed); + assert_eq!(fixed.len(), 4, "the upgrade and the patch on each cluster"); + for r in &fixed { + assert_eq!(r.view()["actionable"], false, "{}", r.finding.title); + } + // What AWS lists now, each an item: the operating system update on each + // cluster stands for its instances too, and the serverless platform + // update appears. + let open = by(&|r| r.status.is_open()); + let titles: Vec<&str> = open.iter().map(|r| r.finding.title.as_str()).collect(); + assert_eq!(open.len(), 4, "{titles:#?}"); + let os = open + .iter() + .find(|r| r.finding.name == PROD && r.finding.fix.meaning == Some(Meaning::OsUpdate)) + .expect("the operating system update"); + assert!( + os.finding.title.contains("the cluster and its 2 instances"), + "{}", + os.finding.title + ); + let platform = open + .iter() + .find(|r| { + r.finding.name == STAGING && r.finding.fix.meaning == Some(Meaning::ServerlessPlatform) + }) + .expect("the serverless platform update"); + assert!( + platform.finding.title.contains("platform version 4"), + "{}", + platform.finding.title + ); + // None is handed over as a runbook: CoderHelm applies each after one + // approval, production after staging. + for r in &open { + let f = &r.finding.fix; + assert_eq!(f.kind, Some(FixKind::Apply), "{}", r.finding.title); + let plan = f.apply.as_ref().unwrap(); + assert_eq!(plan.permission, "rds:ApplyPendingMaintenanceAction"); + assert_eq!(plan.default_opt_in, "next-maintenance"); + assert!(f.runbook.is_some(), "the runbook stays behind it"); + assert_eq!(r.view()["actionable"], true); + } + assert!( + !os.finding.fix.after.is_empty(), + "production waits for staging" + ); +} + +/// A failed or partial read drops nothing and closes nothing. +#[test] +fn a_partial_read_never_closes_or_drops() { + let (stored_res, recs) = stored(); + let mut raw = now_read(); + raw.errors.push(( + "DescribePendingMaintenanceActions".into(), + "Throttling: Rate exceeded".into(), + )); + // The database rows: neither seen in full. + let complete = crate::passes::infra_inventory::complete_kinds(&raw, None); + assert!(!complete.contains(&Kind::RdsInstance) && !complete.contains(&Kind::RdsCluster)); + assert!( + !complete.contains(&Kind::LambdaFunction), + "a refresh never reads the code" + ); + let fresh = placed(raw.resources()); + assert!(inv::gone(&stored_res, &fresh, &complete).is_empty()); + let coverage = Coverage { + reads: vec![KindsRead { + account: ACCOUNT.into(), + region: REGION.into(), + read_at: NOW.into(), + complete, + }], + }; + let present: BTreeSet = stored_res.iter().map(|r| r.id.clone()).collect(); + // The throttled read listed no pending action at all. + let mut quiet = fresh.clone(); + for r in quiet.iter_mut() { + r.pending.clear(); + } + let changed = records::reconcile_with( + &recs, + find(&quiet, "2026-11-15"), + Seen::Read { + coverage: &coverage, + present: &present, + }, + at(NOW), + ); + assert!( + changed.iter().all(|r| !r.status.is_closed() + || recs + .iter() + .any(|x| x.finding.id == r.finding.id && x.status.is_closed())), + "{:#?}", + changed + .iter() + .map(|r| (&r.finding.title, r.status)) + .collect::>() + ); + // An Inspector or Health read that failed leaves every kind unread. + let mut raw = now_read(); + raw.errors + .push(("ListFindings (Inspector)".into(), "AccessDenied: no".into())); + assert!(raw.complete_kinds().is_empty()); + // A read stopped at its page cap is partial too. + let mut raw = now_read(); + raw.errors.push(( + "DescribeDBInstances".into(), + "more than 10 pages: the rest was not read".into(), + )); + assert!(!raw.complete_kinds().contains(&Kind::RdsCluster)); +} + +/// The CVE stands on the engine upgrade's pull request in the code that +/// defines the cluster; the patch and the operating system update are +/// applied by CoderHelm after an approval, not handed over as runbooks. +#[test] +fn the_cve_is_a_pull_request_and_os_upgrade_is_an_approved_apply() { + let res = placed(before().resources()); + let found = find(&res, "2026-11-13"); + let on = |name: &str, m: Meaning| { + found + .iter() + .find(|f| f.name == name && f.fix.meaning == Some(m)) + .unwrap_or_else(|| panic!("no {m:?} on {name}")) + }; + let up = on(PROD, Meaning::EngineUpgrade); + assert_eq!(up.fix.kind, Some(FixKind::Pr)); + assert_eq!(up.cves, vec![CVE]); + let l = up.fix.location.as_ref().unwrap(); + assert_eq!( + (l.repo.as_str(), l.edit.as_ref().unwrap().file.as_str()), + (INFRA, "envs/prod/main.tf") + ); + assert!( + up.fix.notes.is_some(), + "the rollout notes go into the pull request" + ); + let patch = on(PROD, Meaning::EnginePatch); + assert!(patch.cves.is_empty(), "the CVE is the pull request's"); + assert!( + patch.fix.advisory_note.contains("engine upgrade to 16.13"), + "{}", + patch.fix.advisory_note + ); + assert_eq!(patch.fix.kind, Some(FixKind::Apply)); + let os = on(PROD, Meaning::OsUpdate); + assert_eq!(os.fix.kind, Some(FixKind::Apply)); + assert_ne!(os.fix.kind, Some(FixKind::Runbook)); + let plan = os.fix.apply.as_ref().unwrap(); + assert_eq!(plan.action, "os-upgrade"); + assert_eq!(plan.arns, vec![arn("cluster", PROD)]); + // Where the cluster is defined is shown on every item, PR or not. + assert!(os.fix.location.is_some() && patch.fix.location.is_some()); +} + +/// Production's approved apply waits for staging's to be fixed and read +/// back; a refusal for the permission names it. +#[test] +fn production_waits_for_staging_and_a_refusal_names_the_permission() { + let (_, recs) = stored(); + let mut recs: Vec = recs.into_iter().filter(|r| r.status.is_open()).collect(); + let approve = |r: &mut Record| { + r.apply = Some(ApplyState { + opt_in: "next-maintenance".into(), + approved_by: "admin@example.com".into(), + approved_at: NOW.into(), + ..Default::default() + }) + }; + let prod = recs + .iter() + .position(|r| r.finding.name == PROD && r.finding.fix.meaning == Some(Meaning::OsUpdate)) + .unwrap(); + approve(&mut recs[prod]); + let why = infra_findings::not_due(&recs[prod], &recs, "2026-11-15"); + assert!( + why.as_deref().is_some_and(|w| w.contains(STAGING)), + "{why:?}" + ); + // Staging's copy is fixed: production goes. + for r in recs.iter_mut().filter(|r| r.finding.name == STAGING) { + r.status = Status::Fixed; + } + assert_eq!( + infra_findings::not_due(&recs[prod], &recs, "2026-11-15"), + None + ); + let (perm, note) = infra_findings::refusal( + "AccessDenied", + "User is not authorized to perform: rds:ApplyPendingMaintenanceAction", + ); + assert_eq!(perm, "rds:ApplyPendingMaintenanceAction"); + assert!(note.contains("ApplyMaintenance"), "{note}"); + let (perm, _) = infra_findings::refusal( + "InvalidParameterCombination", + "No pending maintenance action", + ); + assert!(perm.is_empty()); +} + +/// Opening the page refreshes a read older than five minutes: the gateway +/// asks only when stale, and the refresh reads AWS without the code. +#[test] +fn the_page_refreshes_a_stale_read_and_the_refresh_reads_aws_only() { + let gw = include_str!("../../../../gateway/src/routes/infra_security.rs"); + assert!(gw.contains("pub const REFRESH_AFTER_SECS: i64 = 5 * 60;")); + assert!(gw.contains("refresh_if_stale(&state, &claims, &accounts, &r)")); + assert!(gw.contains("\"infrastructure_refresh\"")); + let worker = include_str!("../infra_findings.rs"); + assert!(worker.contains("pub const REFRESH_KIND: &str = \"infrastructure_refresh\";")); + let inv_src = include_str!("../infra_inventory.rs"); + let aws_only = inv_src.split("Depth::Aws => {").nth(1).unwrap(); + let aws_only = aws_only.split("};").next().unwrap(); + assert!( + !aws_only.contains("place("), + "a refresh makes no GitHub calls" + ); + assert!(aws_only.contains("carry_over(")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index c6610c268..45c0cf660 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -53,6 +53,7 @@ mod bj_release_through_a_busy_hour; mod bk_owns_the_outside_work; mod bl_description_final_review; mod bm_teams_never_cross; +mod bn_infra_list_follows_aws; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/infra_findings.rs b/services/worker/src/passes/infra_findings.rs index 2e0d27c32..0c762f6a7 100644 --- a/services/worker/src/passes/infra_findings.rs +++ b/services/worker/src/passes/infra_findings.rs @@ -18,11 +18,11 @@ //! - New P0 and P1 findings post one card each, inside the day's card //! limit shared with dependency findings (`SECCARDS#`). -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use aws_sdk_dynamodb::types::AttributeValue; use chrono::Utc; -use common::infra_vuln::inventory::{Resource, RESOURCE_PREFIX}; +use common::infra_vuln::inventory::{Coverage, KindsRead, Resource, RESOURCE_PREFIX}; use common::infra_vuln::matching::{self, Feeds, FixKind}; use common::infra_vuln::records::{self, Record, Status}; use common::infra_vuln::store; @@ -40,6 +40,18 @@ type Item = HashMap; pub const CHECK_KIND: &str = "infrastructure_check"; /// `SecurityEventMessage.kind` for "open the fix PR now" (`repo` = the id). pub const FIX_KIND: &str = "infrastructure_fix"; +/// `SecurityEventMessage.kind` for the refresh when someone opens the page +/// and the last read is old: AWS only, then the match. +pub const REFRESH_KIND: &str = "infrastructure_refresh"; +/// `SecurityEventMessage.kind` for a person's approval of a pending action +/// CoderHelm applies in AWS (`repo` = the finding id, `action` = when: +/// `next-maintenance` or `immediate`, `requested_by` = who). +pub const APPLY_KIND: &str = "infrastructure_apply"; + +/// Whether a security event is this pass's. +pub fn handles(kind: &str) -> bool { + [CHECK_KIND, FIX_KIND, REFRESH_KIND, APPLY_KIND].contains(&kind) +} fn s(i: &Item, k: &str) -> String { i.get(k) @@ -113,11 +125,16 @@ async fn save(state: &WorkerState, team_id: &str, r: &Record) { } } -/// The team's resources and, per account, AWS's latest AL2023 AMIs there. +/// The team's resources, per account AWS's latest AL2023 AMIs there, and +/// what each account and region's latest read saw in full. async fn inventory( state: &WorkerState, team_id: &str, -) -> (Vec, BTreeMap>) { +) -> ( + Vec, + BTreeMap>, + Coverage, +) { let table = &state.config.aws_insights_table_name; let res: Vec = query(state, table, team_id, RESOURCE_PREFIX) .await @@ -125,15 +142,21 @@ async fn inventory( .filter_map(|i| serde_json::from_str(&s(i, "json")).ok()) .collect(); let mut latest = BTreeMap::new(); + let mut coverage = Coverage::default(); for i in query(state, table, team_id, super::infra_inventory::READ_PREFIX).await { if let Ok(v) = serde_json::from_str::(&s(&i, "json")) { let acct = v["account"].as_str().unwrap_or("").to_string(); let m: BTreeMap = serde_json::from_value(v["latest_al2023"].clone()).unwrap_or_default(); latest.insert(acct, m); + // A summary written before reads said what they saw in full + // has no `complete`: it closes nothing. + if let Ok(k) = serde_json::from_value::(v) { + coverage.reads.push(k); + } } } - (res, latest) + (res, latest, coverage) } async fn kev(state: &WorkerState) -> BTreeMap { @@ -154,7 +177,8 @@ async fn kev(state: &WorkerState) -> BTreeMap { /// Matches the team's inventory now and saves what changed. Returns the /// stored records after the match. pub async fn match_team(state: &WorkerState, team_id: &str) -> Vec { - let (resources, latest) = inventory(state, team_id).await; + let (resources, latest, coverage) = inventory(state, team_id).await; + let present: BTreeSet = resources.iter().map(|r| r.id.clone()).collect(); let mut stored = load_records(state, team_id).await; if resources.is_empty() && stored.is_empty() { return stored; @@ -184,7 +208,11 @@ pub async fn match_team(state: &WorkerState, team_id: &str) -> Vec { }; fresh.extend(matching::findings(res, &feeds)); } - let changed = records::reconcile(&stored, fresh, Utc::now()); + let seen = records::Seen::Read { + coverage: &coverage, + present: &present, + }; + let changed = records::reconcile_with(&stored, fresh, seen, Utc::now()); for r in &changed { save(state, team_id, r).await; if let Some(e) = &r.event { @@ -195,6 +223,8 @@ pub async fn match_team(state: &WorkerState, team_id: &str) -> Vec { None => stored.push(r.clone()), } } + // Approved actions whose turn came (the non-production copy is fixed). + apply_due(state, team_id, &mut stored).await; stored } @@ -597,7 +627,13 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { let cfg = super::security_fixes::load_config(state, team) .await .unwrap_or_default(); - if msg.kind == CHECK_KIND { + if msg.kind == CHECK_KIND || msg.kind == REFRESH_KIND { + use super::infra_inventory::Depth; + let depth = if msg.kind == CHECK_KIND { + Depth::Full + } else { + Depth::Aws + }; for a in common::live::aws_account::list( &state.dynamo, &state.config.aws_insights_table_name, @@ -607,13 +643,15 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { .unwrap_or_default() { if a.infra_on() { - if let Err(e) = super::infra_inventory::read_account(state, team, &a).await { + if let Err(e) = super::infra_inventory::read_account(state, team, &a, depth).await { warn!(team_id = %team, account = %a.account, error = %e, "infra check: the role couldn't be taken on"); } } } let recs = match_team(state, team).await; cards(state, team, &cfg, &recs).await; + } else if msg.kind == APPLY_KIND { + approve(state, team, &msg.repo, &msg.action, &msg.requested_by).await; } else if msg.kind == FIX_KIND { let mut recs = load_records(state, team).await; let iid = if msg.installation_id > 0 { @@ -652,6 +690,239 @@ pub async fn on_event(state: &WorkerState, msg: &SecurityEventMessage) { } } +// ── Apply: a pending action CoderHelm applies after one approval ──────── + +/// AWS's two answers for when to apply. +pub const OPT_INS: &[&str] = &["next-maintenance", "immediate"]; + +/// Why an approved action is not sent to AWS now, or `None` when it is +/// due. Pure. +pub(crate) fn not_due(r: &Record, all: &[Record], today: &str) -> Option { + let a = r.apply.as_ref()?; + if a.sent() || !r.status.is_open() || r.finding.fix.kind != Some(FixKind::Apply) { + return Some(String::new()); + } + if r.finding.fix.apply.is_none() { + return Some("Nothing to apply on this finding.".into()); + } + // Production waits for its non-production copy to be fixed and read + // back healthy; AWS's own date close by does not wait. + records::held(r, all, today) +} + +/// A person approved: recorded on the finding, then sent if it is due. +async fn approve(state: &WorkerState, team_id: &str, id: &str, opt_in: &str, by: &str) { + let mut recs = load_records(state, team_id).await; + let Some(i) = recs.iter().position(|r| r.finding.id == id) else { + return; + }; + let r = &mut recs[i]; + if !r.status.is_open() || r.finding.fix.kind != Some(FixKind::Apply) { + super::security_fixes::add_event( + state, + team_id, + id, + "Approval not used: this finding has nothing to apply in AWS now", + None, + ) + .await; + return; + } + let opt_in = if OPT_INS.contains(&opt_in) { + opt_in + } else { + "next-maintenance" + }; + r.apply = Some(records::ApplyState { + opt_in: opt_in.into(), + approved_by: by.into(), + approved_at: Utc::now().to_rfc3339(), + ..Default::default() + }); + r.updated_at = Utc::now().to_rfc3339(); + save(state, team_id, r).await; + super::security_fixes::add_event( + state, + team_id, + id, + &format!( + "Approved by {}: CoderHelm applies it in AWS {}", + if by.is_empty() { "an admin" } else { by }, + if opt_in == "immediate" { + "now" + } else { + "in the next maintenance window" + } + ), + None, + ) + .await; + apply_due(state, team_id, &mut recs).await; +} + +/// Sends every approved action that is due, and notes why the others wait. +async fn apply_due(state: &WorkerState, team_id: &str, recs: &mut [Record]) { + let today = Utc::now().format("%Y-%m-%d").to_string(); + for i in 0..recs.len() { + if recs[i].apply.is_none() { + continue; + } + match not_due(&recs[i], recs, &today) { + Some(why) if why.is_empty() => {} + Some(why) => { + let r = &mut recs[i]; + if let Some(a) = r.apply.as_mut().filter(|a| a.note != why) { + a.note = why; + save(state, team_id, r).await; + } + } + None => { + let r = &mut recs[i]; + send_apply(state, team_id, r).await; + } + } + } +} + +/// What a refusal from AWS means for the page: the permission the role +/// lacks, when that is why. Pure. +pub(crate) fn refusal(code: &str, message: &str) -> (String, String) { + let denied = matches!( + code, + "AccessDenied" | "AccessDeniedException" | "UnauthorizedOperation" | "AuthorizationError" + ) || message.contains("not authorized"); + if denied { + ( + matching::APPLY_PERMISSION.to_string(), + format!( + "AWS refused: the CoderHelm role in this account may not call {}. Turn ApplyMaintenance on in the role's update stack (the account's Update link), or follow the runbook.", + matching::APPLY_PERMISSION + ), + ) + } else { + (String::new(), format!("AWS refused ({code}): {message}")) + } +} + +async fn send_apply(state: &WorkerState, team_id: &str, r: &mut Record) { + let Some(plan) = r.finding.fix.apply.clone() else { + return; + }; + let opt_in = r + .apply + .as_ref() + .map(|a| a.opt_in.clone()) + .unwrap_or_else(|| "next-maintenance".into()); + let account = common::live::aws_account::list( + &state.dynamo, + &state.config.aws_insights_table_name, + team_id, + ) + .await + .unwrap_or_default() + .into_iter() + .find(|a| a.account == r.finding.account); + let Some(account) = account else { + if let Some(a) = r.apply.as_mut() { + a.note = "The AWS account is no longer connected.".into(); + } + save(state, team_id, r).await; + return; + }; + let mut target = account.target(); + if !r.finding.region.is_empty() { + target.region = r.finding.region.clone(); + } + let session = match common::live::aws::assume(&state.sts, &target, "infra-apply").await { + Ok(s) => s, + Err(e) => { + if let Some(a) = r.apply.as_mut() { + a.note = format!("The role could not be taken on: {}", e.message); + } + save(state, team_id, r).await; + return; + } + }; + let mut accepted: Vec = r + .apply + .as_ref() + .map(|a| a.applied.clone()) + .unwrap_or_default(); + let todo: Vec = plan + .arns + .iter() + .filter(|a| !accepted.contains(a)) + .cloned() + .collect(); + for arn in &todo { + match super::infra_inventory::apply_pending(&session, arn, &plan.action, &opt_in).await { + Ok(()) => accepted.push(arn.clone()), + Err((code, message)) => { + let (missing, note) = refusal(&code, &message); + if let Some(a) = r.apply.as_mut() { + a.applied = accepted.clone(); + a.missing_permission = missing; + a.note = note.clone(); + } + r.updated_at = Utc::now().to_rfc3339(); + save(state, team_id, r).await; + super::security_fixes::add_event( + state, + team_id, + &r.finding.id, + &format!("Not applied: {note}"), + None, + ) + .await; + warn!(team_id, code = %code, "infra apply: AWS refused"); + return; + } + } + } + let when = if opt_in == "immediate" { + "now" + } else { + "in the next maintenance window" + }; + if let Some(a) = r.apply.as_mut() { + a.applied = accepted; + a.applied_at = Utc::now().to_rfc3339(); + a.missing_permission.clear(); + a.note = format!( + "AWS accepted `{}` {when}. CoderHelm reads the account again and closes this when the action is no longer pending.", + plan.action + ); + } + r.updated_at = Utc::now().to_rfc3339(); + save(state, team_id, r).await; + super::security_fixes::add_event( + state, + team_id, + &r.finding.id, + &format!("Applied in AWS ({}) {when}", plan.action), + None, + ) + .await; + // Applied now: read it back in a quarter of an hour. + if opt_in == "immediate" && !state.config.ticket_queue_url.is_empty() { + let msg = WorkerMessage::SecurityEvent(SecurityEventMessage { + team_id: team_id.to_string(), + kind: REFRESH_KIND.into(), + ..Default::default() + }); + if let Ok(body) = serde_json::to_string(&msg) { + let _ = state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .delay_seconds(900) + .send() + .await; + } + } +} + // ── Release: fixing and pr_open follow GitHub and the run ─────────────── use super::security_fixes::release::{self as rel, ReleaseIo, Scope}; diff --git a/services/worker/src/passes/infra_inventory.rs b/services/worker/src/passes/infra_inventory.rs index 215123876..b99d85027 100644 --- a/services/worker/src/passes/infra_inventory.rs +++ b/services/worker/src/passes/infra_inventory.rs @@ -79,6 +79,15 @@ pub struct InventoryReport { pub resources: usize, } +/// A list call that stopped at its page cap: what it did not read is not +/// gone, so the read of that kind is partial (`RawAccount::complete_kinds`). +fn capped(raw: &mut RawAccount, call: &str) { + raw.errors.push(( + call.to_string(), + format!("more than {MAX_PAGES} pages: the rest was not read"), + )); +} + fn tags_of<'a>(it: impl IntoIterator) -> Vec<(String, String)> { it.into_iter() .map(|(k, v)| (k.to_string(), v.to_string())) @@ -147,6 +156,9 @@ async fn read_ec2(s: &Session, raw: &mut RawAccount) { } } } + if token.is_some() { + capped(raw, "DescribeInstances"); + } let ids: BTreeSet = raw .instances .iter() @@ -220,6 +232,9 @@ async fn read_asgs(s: &Session, raw: &mut RawAccount) { } } } + if token.is_some() { + capped(raw, "DescribeAutoScalingGroups"); + } } async fn read_lbs(s: &Session, raw: &mut RawAccount) { @@ -377,22 +392,42 @@ async fn read_eks(s: &Session, raw: &mut RawAccount) { /// start times; the task definition's environment is never read). async fn read_ecs(s: &Session, raw: &mut RawAccount) { let ecs = client!(aws_sdk_ecs, s); - let Ok(clusters) = ecs.list_clusters().max_results(100).send().await else { - return; + // Every failure and every cap is noted: services this read did not see + // are not gone. + let clusters = match ecs.list_clusters().max_results(100).send().await { + Ok(c) => c, + Err(e) => { + note!(raw, "ListClusters (ECS)", e); + return; + } }; + if clusters.next_token().is_some() || clusters.cluster_arns().len() > 20 { + capped(raw, "ListClusters (ECS)"); + } for c in clusters.cluster_arns().iter().take(20) { - let Ok(svcs) = ecs.list_services().cluster(c).max_results(100).send().await else { - continue; + let svcs = match ecs.list_services().cluster(c).max_results(100).send().await { + Ok(v) => v, + Err(e) => { + note!(raw, "ListServices", e); + continue; + } }; + if svcs.next_token().is_some() || svcs.service_arns().len() > 50 { + capped(raw, "ListServices"); + } for chunk in svcs.service_arns().chunks(10).take(5) { - let Ok(d) = ecs + let d = match ecs .describe_services() .cluster(c) .set_services(Some(chunk.to_vec())) .send() .await - else { - continue; + { + Ok(d) => d, + Err(e) => { + note!(raw, "DescribeServices", e); + continue; + } }; for sv in d.services() { let launch = sv @@ -557,6 +592,9 @@ async fn read_rds(s: &Session, raw: &mut RawAccount) { break; } } + if marker.is_some() { + capped(raw, "DescribeDBClusters"); + } let mut marker: Option = None; for _ in 0..MAX_PAGES { match rds @@ -643,6 +681,9 @@ async fn read_rds(s: &Session, raw: &mut RawAccount) { break; } } + if marker.is_some() { + capped(raw, "DescribeDBInstances"); + } let mut marker: Option = None; for _ in 0..MAX_PAGES { match rds @@ -682,6 +723,9 @@ async fn read_rds(s: &Session, raw: &mut RawAccount) { break; } } + if marker.is_some() { + capped(raw, "DescribePendingMaintenanceActions"); + } } async fn read_elasticache(s: &Session, raw: &mut RawAccount) { @@ -907,6 +951,12 @@ async fn read_scans(s: &Session, raw: &mut RawAccount) { let mut seen = BTreeSet::new(); let images: Vec<(String, String)> = raw.services.iter().flat_map(|s| s.images.clone()).collect(); + if images.len() > 30 { + raw.errors.push(( + "DescribeImageScanFindings".into(), + "more than 30 images: the rest was not read".into(), + )); + } for (image, digest) in images.into_iter().take(30) { // Only images in this account's ECR: `.dkr.ecr..amazonaws.com/:`. let Some((host, rest)) = image.split_once('/') else { @@ -1296,8 +1346,24 @@ pub struct Placing { pub repos_not_searched: usize, pub files_read: usize, pub files_not_read: usize, + /// Trees and files GitHub did not return. + pub failed: usize, pub located: usize, pub sure: usize, + /// Lambda functions left out: declared in a Terraform module folder + /// nothing calls, so never applied. + pub uncalled: usize, +} + +impl Placing { + /// Every connected repository was searched and every candidate file + /// read: the Lambda functions the code declares are all of them. + pub fn complete(&self) -> bool { + self.repos > 0 + && self.repos_not_searched == 0 + && self.files_not_read == 0 + && self.failed == 0 + } } /// The order a repository's candidate files are read in, within the cap: @@ -1388,16 +1454,17 @@ async fn place( marked.extend(hits.into_iter().map(|h| h.path)); } } - 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 tree: Vec = match gh.get_tree(owner, name, "HEAD").await { + Ok(t) => t + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect(), + Err(_) => { + report.failed += 1; + Vec::new() + } + }; let order = read_order(&named, &marked, &tree); let mut read = 0; for path in &order { @@ -1406,6 +1473,7 @@ async fn place( continue; } let Ok(content) = gh.get_file_content(owner, name, path).await else { + report.failed += 1; continue; }; if content.len() > MAX_FILE_BYTES || locate::tool_of(path, &content).is_none() { @@ -1433,22 +1501,87 @@ async fn place( } } let now = Utc::now().to_rfc3339(); + // A module folder nothing calls is never applied: what it declares does + // not run. Only said when every Terraform file was read (an unread file + // could be its caller). + let uncalled = if report.files_not_read == 0 && report.failed == 0 { + inv::uncalled_modules( + &files + .iter() + .map(|f| (f.repo.as_str(), f.path.as_str(), f.content.as_str())) + .collect::>(), + ) + } else { + BTreeSet::new() + }; for f in &files { if f.path.ends_with(".tf") { - resources.extend(inv::lambdas_from_terraform( - &f.repo, &f.path, &f.content, account, region, &now, - )); + let dir = f.path.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + let found = + inv::lambdas_from_terraform(&f.repo, &f.path, &f.content, account, region, &now); + if uncalled.contains(&format!("{}:{dir}", f.repo)) { + report.uncalled += found.len(); + continue; + } + resources.extend(found); } } report } +/// The resource rows stored for one account and region. +async fn stored_rows( + state: &WorkerState, + team_id: &str, + account: &str, + region: &str, +) -> Result, String> { + let prefix = format!("{}{account}#{region}#", inv::RESOURCE_PREFIX); + let mut out = Vec::new(); + let mut start: Option> = None; + for _ in 0..50 { + let r = state + .dynamo + .query() + .table_name(&state.config.aws_insights_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", attr_s(team_id)) + .expression_attribute_values(":p", attr_s(&prefix)) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| e.to_string())?; + out.extend(r.items().iter().filter_map(|i| { + i.get("json") + .and_then(|v| v.as_s().ok()) + .and_then(|j| serde_json::from_str::(j).ok()) + })); + match r.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => return Ok(out), + } + } + Err("too many rows".into()) +} + +/// What a read saw in full: the kinds every AWS call answered for, and the +/// Lambda functions when the code was read in full this time. +pub fn complete_kinds(raw: &RawAccount, placing: Option<&Placing>) -> Vec { + let mut k = raw.complete_kinds(); + if placing.is_some_and(Placing::complete) && !k.is_empty() { + k.push(inv::Kind::LambdaFunction); + } + k +} + async fn save( state: &WorkerState, team_id: &str, raw: &RawAccount, resources: &[Resource], placing: &Placing, + complete: &[inv::Kind], + stored: Option<&[Resource]>, ) -> usize { let ttl = (Utc::now() + Duration::days(inv::KEEP_DAYS)).timestamp(); let mut n = 0; @@ -1472,11 +1605,35 @@ async fn save( Err(e) => warn!(team_id, error = %e, "infra inventory: a resource could not be saved"), } } + // What the read no longer lists, of a kind it saw in full, is gone + // from the account: its rows go now, not when their TTL runs out. A + // kind the read did not see in full keeps every row. + let mut removed = 0; + if let Some(stored) = stored { + for sk in inv::gone(stored, resources, complete) { + match state + .dynamo + .delete_item() + .table_name(&state.config.aws_insights_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&sk)) + .send() + .await + { + Ok(_) => removed += 1, + Err(e) => { + warn!(team_id, error = %e, "infra inventory: a removed resource could not be dropped") + } + } + } + } let summary = serde_json::json!({ "account": raw.account, "region": raw.region, "read_at": raw.read_at, "resources": n, + "removed": removed, + "complete": complete, "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, @@ -1533,11 +1690,52 @@ async fn accounts(state: &WorkerState) -> Vec<(String, AwsAccount)> { out } -/// One read now, for one account (a person's "check now", or the sweep). +/// Asks AWS to apply one pending RDS or Aurora action on one ARN +/// (`ApplyPendingMaintenanceAction`), `immediate` or `next-maintenance`. +/// The error is `(code, message)`. +pub async fn apply_pending( + s: &Session, + arn: &str, + action: &str, + opt_in: &str, +) -> Result<(), (String, String)> { + let rds = client!(aws_sdk_rds, s); + rds.apply_pending_maintenance_action() + .resource_identifier(arn) + .apply_action(action) + .opt_in_type(opt_in) + .send() + .await + .map(|_| ()) + .map_err(|e| match e.as_service_error() { + Some(se) => { + use aws_sdk_dynamodb::error::ProvideErrorMetadata; + ( + se.code().unwrap_or("error").to_string(), + common::truncate_str(se.message().unwrap_or(""), 240).to_string(), + ) + } + None => ("unreachable".into(), "AWS didn't answer".into()), + }) +} + +/// How much of the account a read covers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Depth { + /// AWS and the team's code (the daily read, a person's "check now"). + Full, + /// AWS only, each resource keeping where its code was found last time + /// (the refresh when someone opens the page): no GitHub calls, and + /// the Lambda functions read from the code are left as they are. + Aws, +} + +/// One read now, for one account. pub async fn read_account( state: &WorkerState, team_id: &str, a: &AwsAccount, + depth: Depth, ) -> Result { let session = common::live::aws::assume(&state.sts, &a.target(), "infra-inventory") .await @@ -1545,9 +1743,52 @@ pub async fn read_account( let cfg = infra_config(state, team_id).await; let mut raw = read_with(&session, &a.account, &cfg).await; let mut resources = raw.resources(); - 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) + // What is stored now: what this read replaces. Unreadable, nothing is + // dropped (the read still saves what it saw). + let stored = stored_rows(state, team_id, &a.account, &raw.region) + .await + .ok(); + let (placing, complete) = match depth { + Depth::Full => { + lookup_stacks(&session, &mut raw, &mut resources).await; + let placing = place(state, team_id, &a.account, &a.region, &mut resources).await; + let complete = complete_kinds(&raw, Some(&placing)); + (placing, complete) + } + Depth::Aws => { + if let Some(old) = &stored { + carry_over(&mut resources, old); + } + (Placing::default(), complete_kinds(&raw, None)) + } + }; + Ok(save( + state, + team_id, + &raw, + &resources, + &placing, + &complete, + stored.as_deref(), + ) + .await) +} + +/// A refresh keeps where each resource's code was found by the last full +/// read, and the stack it came from. +pub fn carry_over(fresh: &mut [Resource], stored: &[Resource]) { + for r in fresh.iter_mut() { + if let Some(old) = stored.iter().find(|o| o.sk() == r.sk()) { + if r.defined_in.is_none() { + r.defined_in = old.defined_in.clone(); + } + for (k, v) in &old.tags { + if k.starts_with("aws:cloudformation:") || k == locate::LOOKUP_TAG { + r.tags.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + } + } } /// The daily read, on the review-reminder tick: each account once a day. @@ -1569,7 +1810,7 @@ pub async fn sweep(state: &WorkerState) -> InventoryReport { if !matches!(won, common::claim::Claim::Won) { continue; } - match read_account(state, &team, &a).await { + match read_account(state, &team, &a, Depth::Full).await { Ok(n) => { report.accounts += 1; report.resources += n;