From bb1f6519822defef4bec33d6f3a0a327365957a5 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 17:24:38 -0500 Subject: [PATCH] Every team AWS read is made as the team's role On a self-hosted install in the team's own AWS account, live::aws::assume swapped CoderHelmLogReader for the install's own Lambda role, which never gets the WAF reads. A run's WAF tools were refused as the worker's role, the refusal blamed the team's role and the run waited; the wait's re-check took on the reader itself, was allowed and restarted the run, which was refused again: a loop. - assume always takes on the team's role and returns a TeamSession, the only session WAF, alarm evidence, WAF log objects, metrics, log reads and the permission check accept. - log_findings::session_for (the re-check) is the account's connection taken on with assume: the same target and call as the run's tools. - A refusal of a principal that isn't the team's role names it and is CoderHelm's own failure, never the team's setup item. - A run a re-check restarted never waits again for what the re-check read (role_wait::ending_after): an error log, one line on the run, and it goes on with what it has. - Incident rk_team_reads_as_the_team_role. --- .../rk_team_reads_as_the_team_role.md | 11 ++ docs/self-host/integrations.md | 2 +- services/common/src/alarm_evidence.rs | 87 +++++++-- services/common/src/knowledge/remote.rs | 1 + .../common/src/knowledge/sources/connect.rs | 1 + services/common/src/live/aws.rs | 161 +++++++++------- services/common/src/live/db.rs | 2 +- services/common/src/live/metrics.rs | 39 +++- services/common/src/live/permissions.rs | 29 +-- services/common/src/log_findings.rs | 45 ++--- services/common/src/log_repo/live.rs | 2 +- services/common/src/role_move.rs | 4 +- services/common/src/role_wait.rs | 96 ++++++++++ services/common/src/waf_logs.rs | 4 +- services/gateway/src/routes/connectors.rs | 10 +- services/gateway/src/routes/data_sources.rs | 2 +- services/gateway/src/routes/integrations.rs | 10 +- .../cx_role_reads_wait_then_finish.rs | 2 +- .../rk_team_reads_as_the_team_role.rs | 180 ++++++++++++++++++ services/worker/src/passes/log_look.rs | 2 +- services/worker/src/passes/mod.rs | 18 +- services/worker/src/passes/role_wait.rs | 2 + 22 files changed, 546 insertions(+), 164 deletions(-) create mode 100644 docs/incidents/rk_team_reads_as_the_team_role.md create mode 100644 services/worker/src/passes/incidents/rk_team_reads_as_the_team_role.rs diff --git a/docs/incidents/rk_team_reads_as_the_team_role.md b/docs/incidents/rk_team_reads_as_the_team_role.md new file mode 100644 index 000000000..7e0a6c898 --- /dev/null +++ b/docs/incidents/rk_team_reads_as_the_team_role.md @@ -0,0 +1,11 @@ +# rk. `rk_team_reads_as_the_team_role` + +**What happened:** On a self-hosted install that runs in the same AWS account as the team's resources, an AWS WAF alarm run called its WAF tools (`waf_sampled_requests`, `waf_log_objects`). AWS logged those calls (`wafv2:ListWebACLs` and the rest) as the worker's own Lambda service role, and refused them. `live::aws::assume` swapped the account's `CoderHelmLogReader` for the install's own role whenever the reader was in the install's account, and the install's own role never gets the WAF reads. The refusal was reported as "CoderHelm's AWS role doesn't allow wafv2:ListWebACLs yet" and recorded as the team role's setup item, so the run waited for it. The wait's re-check took on the reader role itself (`log_findings::session_for`), was allowed, and started the run again. The new run read with the worker's role again, was refused again and waited again: a loop. + +**The guarantee:** +- Every read of a team's AWS data is made as the team's role. `live::aws::assume` always takes on the connected role with the team's private ID, the install's own account included. It returns a `TeamSession`, which only `assume` and `assume_exact` can make. The WAF tools, alarm evidence, WAF log objects, CloudWatch metrics, log reads and the permission check accept only a `TeamSession`, so the install's own credentials can't reach them. +- `log_findings::session_for`, which the re-check of a waiting run uses, is the account's connection taken on with `assume`. That is the same target and the same call the run's tools use, so the re-check and the run can't disagree. +- A refusal names the principal AWS refused when it isn't the team's role. It counts as CoderHelm's own failure (an error log), never as the team's setup item. +- A run that a re-check started again never waits again for a read the re-check had read (`role_wait::ending_after`). It records CoderHelm's own failure (an error log and one line on the run) and goes on with what it has. + +**Test:** `services/worker/src/passes/incidents/rk_team_reads_as_the_team_role.rs` diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index efdc8685d..c89a926b8 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -21,7 +21,7 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar - **Making the role by hand**\ The AWS page lists every action the role needs, grouped by what CoderHelm reads with it, and your install's account id. Create the role named `CoderHelmLogReader`, let your install's account assume it only with the team's External ID, and allow those actions. - **Reading the install's own account**\ - Connect it the same way: the `CoderHelmLogReader` role there, with the team's External ID, proves the team may read it. After that, the install reads its own account with its gateway's and worker's own roles, which the install's stack gives this release's read-only permissions (`infra/lib/own-account-read.ts`, the same list as the update template). Each version update brings any new permission, so the install's own account never shows **Update in AWS**; if a permission is still missing, the page says it comes with the next version update. + Connect it the same way: the `CoderHelmLogReader` role there, with the team's External ID. Every read of the account (logs, metrics, WAF, settings and the rest) is made as that role, exactly as in any other account, so AWS records every read under the team's role and the permission check looks at the same role. When a release adds a read, the account shows **Update in AWS** like any other. Knowledge bases in the install's account are the one exception: the install's own role searches them (see [bedrock.md](bedrock.md)). - **When a release needs new permissions**\ Each AWS connection shows **Permissions up to date** or **Update needed: N new read-only permissions**. The check runs live: it asks IAM's policy simulator about the role (`iam:SimulatePrincipalPolicy` on that one role), or, for roles made before that, tries the cheapest read of each kind. **Update in AWS** opens a stack (`CoderHelmLogReaderUpdate-`) that adds exactly this release's permissions to the existing role. Sign in to the role's account, review it and press **Create stack**. When you come back, the page checks again by itself. If something went wrong, it names the reason and the fix: the stack failed, it isn't in the role's account, a permissions boundary or an organization policy (SCP) blocks the permissions. Once a day the install checks every account, and each team's Slack or Teams channel hears once per release that needs an update. Until then, features that need a missing permission say so where they are used, skip that step and keep working with the rest. - **One template for every read**\ diff --git a/services/common/src/alarm_evidence.rs b/services/common/src/alarm_evidence.rs index 3d98b3e60..19341c85c 100644 --- a/services/common/src/alarm_evidence.rs +++ b/services/common/src/alarm_evidence.rs @@ -35,7 +35,7 @@ use std::time::Duration; use chrono::{DateTime, Utc}; -use crate::live::aws::Session; +use crate::live::aws::{Session, TeamSession}; /// The heading the evidence goes under in the ticket (and how a later step /// of the same run knows it is there). @@ -582,6 +582,8 @@ pub struct Gathered { /// The evidence lines and the refusals met while reading them. #[derive(Default)] struct Notes { + /// The team's role the reads are made with (`TeamSession::role_arn`). + role: String, lines: Vec, refused: Vec, results: String, @@ -590,22 +592,21 @@ struct Notes { } impl Notes { + fn on(session: &TeamSession) -> Notes { + Notes { + role: session.role_arn().to_string(), + ..Default::default() + } + } + /// A lookup that failed: a refusal names the action and counts toward /// the install's setup item; anything else says AWS's own words. fn failed(&mut self, what: &str, action: &str, code: Option<&str>, msg: Option<&str>) { - if refused(code) { - if !self.refused.iter().any(|a| a == action) { - self.refused.push(action.to_string()); - } - self.lines.push(format!( - "Couldn't {what}: CoderHelm's AWS role doesn't allow {action} yet." - )); - } else { - self.lines.push(format!( - "Couldn't {what}: {}", - clip(msg.or(code).unwrap_or("no answer")) - )); + let (line, team_gap) = failure_line(what, action, code, msg, &self.role); + if team_gap && !self.refused.iter().any(|a| a == action) { + self.refused.push(action.to_string()); } + self.lines.push(line); } fn done(self, alarm: &WafAlarm) -> Gathered { @@ -618,6 +619,48 @@ impl Notes { } } +/// Pure: the line for a lookup that failed, and whether it is the team's +/// setup item (the team's role `role_arn` was refused `action`). AWS +/// refusing any other principal is CoderHelm's own failure: the line names +/// the principal, and it is never counted against the team's role. +pub fn failure_line( + what: &str, + action: &str, + code: Option<&str>, + msg: Option<&str>, + role_arn: &str, +) -> (String, bool) { + if !refused(code) { + return ( + format!( + "Couldn't {what}: {}", + clip(msg.or(code).unwrap_or("no answer")) + ), + false, + ); + } + match crate::live::aws::refused_other_principal(msg.unwrap_or(""), role_arn) { + Some(principal) => { + tracing::error!( + action, + principal = %principal, + "CoderHelm's own failure: a team read was made with a role that isn't the team's" + ); + ( + format!( + "Couldn't {what}: AWS refused {action} to {principal}, which isn't the \ + team's role, so this is CoderHelm's own failure, not the team's role." + ), + false, + ) + } + None => ( + format!("Couldn't {what}: CoderHelm's AWS role doesn't allow {action} yet."), + true, + ), + } +} + /// Pure: the ticket's section from what was read, with the one line that /// names the install's setup item when the role was refused a read. pub fn evidence(alarm: &WafAlarm, mut lines: Vec, refused: Vec) -> Gathered { @@ -818,7 +861,7 @@ async fn log_destinations(waf: &aws_sdk_wafv2::Client, arn: &str, n: &mut Notes) /// The rule's matches in the web ACL's log objects, read straight from its /// bucket (no Athena); `true` when records naming the rule came back. async fn read_log_objects( - session: &Session, + session: &TeamSession, arn: &str, destination: &str, alarm: &WafAlarm, @@ -842,10 +885,14 @@ async fn read_log_objects( /// The sampled requests the alarm's rule matched in the last three hours /// (for an agent's lookup): the lines, and the IAM actions the role was /// refused (the install's setup item). -pub async fn sampled_requests(session: &Session, alarm: &WafAlarm, now: DateTime) -> Gathered { +pub async fn sampled_requests( + session: &TeamSession, + alarm: &WafAlarm, + now: DateTime, +) -> Gathered { let (_, region) = alarm.scope_and_region(); let waf = waf_client(&session_in(session, ®ion)); - let mut n = Notes::default(); + let mut n = Notes::on(session); if let Some(arn) = find_web_acl(&waf, alarm, &mut n).await { let end = now.timestamp(); read_samples(&waf, &arn, alarm, end - WINDOW_SECS + 60, end, &mut n).await; @@ -857,7 +904,7 @@ pub async fn sampled_requests(session: &Session, alarm: &WafAlarm, now: DateTime /// agent's lookup), read straight from its `aws-waf-logs-*` bucket: the /// bucket named, else where the web ACL logs. pub async fn log_objects( - session: &Session, + session: &TeamSession, alarm: &WafAlarm, bucket: Option<&str>, start: i64, @@ -865,7 +912,7 @@ pub async fn log_objects( ) -> Gathered { let (_, region) = alarm.scope_and_region(); let waf = waf_client(&session_in(session, ®ion)); - let mut n = Notes::default(); + let mut n = Notes::on(session); let Some(arn) = find_web_acl(&waf, alarm, &mut n).await else { return n.done(alarm); }; @@ -891,10 +938,10 @@ pub async fn log_objects( /// the result, so a missing permission is named, not silent. The logs held /// in S3 are read straight from the bucket first; Athena only when that /// found nothing. -pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> Gathered { +pub async fn gather(session: &TeamSession, alarm: &WafAlarm, now: DateTime) -> Gathered { let (_, region) = alarm.scope_and_region(); let waf = waf_client(&session_in(session, ®ion)); - let mut n = Notes::default(); + let mut n = Notes::on(session); let Some(arn) = find_web_acl(&waf, alarm, &mut n).await else { return n.done(alarm); }; diff --git a/services/common/src/knowledge/remote.rs b/services/common/src/knowledge/remote.rs index da293d74b..2dde17da5 100644 --- a/services/common/src/knowledge/remote.rs +++ b/services/common/src/knowledge/remote.rs @@ -296,6 +296,7 @@ pub async fn session( }; aws::assume(sts, &target, actor) .await + .map(aws::TeamSession::into_session) .map_err(|e| Refusal::new("access", e.message, e.fix)) } } diff --git a/services/common/src/knowledge/sources/connect.rs b/services/common/src/knowledge/sources/connect.rs index b6eaad953..87a4e8588 100644 --- a/services/common/src/knowledge/sources/connect.rs +++ b/services/common/src/knowledge/sources/connect.rs @@ -112,6 +112,7 @@ impl Env { // every bucket the role may read. crate::live::aws::assume_exact(&a.sts, &target, &a.actor) .await + .map(crate::live::aws::TeamSession::into_session) .map_err(|e| ConnectorError::Reconnect(format!("{} {}", e.message, e.fix))) } } diff --git a/services/common/src/live/aws.rs b/services/common/src/live/aws.rs index 3585f0503..36c43bc78 100644 --- a/services/common/src/live/aws.rs +++ b/services/common/src/live/aws.rs @@ -513,26 +513,6 @@ pub fn in_install_account(role_arn: &str, own: Option<&str>) -> bool { }) } -/// What to read through instead of `target`, when `target` is the log -/// reader a person created in the install's own account: the install's own -/// role, whose permissions arrive with each version update. `None` for any -/// other role or account (the data-source role, another account, the -/// hosted deployment). Connecting still proves the person's role with the -/// team's private ID; this only changes how a connected account is read. -pub fn install_target(target: &AwsTarget, own: Option<&str>) -> Option { - let own = own?; - let name = target.role_arn.rsplit('/').next().unwrap_or(""); - // A database or a warehouse is read through the role stack's own - // groups (DatabaseClusters, Warehouses), never the install's role. - let data = !target.cluster_arn.is_empty() || !target.cluster_id.is_empty(); - (name == LOG_READER_ROLE && !data && in_install_account(&target.role_arn, Some(own))).then( - || AwsTarget { - role_arn: own.to_string(), - ..target.clone() - }, - ) -} - /// A session on the function's own role (its environment's credentials), /// in `region`. `None` outside Lambda. pub fn own_session(region: &str) -> Option { @@ -545,21 +525,87 @@ pub fn own_session(region: &str) -> Option { }) } +/// A session on the team's own role (the one connected for the account, +/// taken on with the team's private ID). It is the only session a read of a +/// team's AWS data accepts: it is made only by [`assume`] and +/// [`assume_exact`], so the install's own role ([`own_session`]) or the +/// function's ambient credentials can never read a team's data in its name. +/// A run and the re-check of a waiting run (`role_wait`) both take it with +/// [`assume`], so they ask AWS as the same principal. +#[derive(Clone, Debug)] +pub struct TeamSession { + session: Session, + role_arn: String, +} + +impl TeamSession { + /// The team's role this session is on. + pub fn role_arn(&self) -> &str { + &self.role_arn + } + + /// The same team role in another region. + pub fn in_region(&self, region: &str) -> TeamSession { + TeamSession { + session: Session { + region: region.to_string(), + ..self.session.clone() + }, + role_arn: self.role_arn.clone(), + } + } + + /// The keys, for a client a team read builds. + pub fn into_session(self) -> Session { + self.session + } +} + +impl std::ops::Deref for TeamSession { + type Target = Session; + fn deref(&self) -> &Session { + &self.session + } +} + +/// Pure: the role or user AWS refused, from an AccessDenied message +/// ("User: arn:aws:sts::111122223333:assumed-role/NAME/session is not +/// authorized to perform: ..."): `NAME`. `None` when the message names none. +pub fn refused_principal(message: &str) -> Option { + let arn = message.split_whitespace().find(|w| { + w.starts_with("arn:aws") + && (w.contains(":assumed-role/") || w.contains(":user/") || w.contains(":role/")) + })?; + let arn = arn.trim_end_matches([',', '.', ';']); + let rest = arn + .split_once(":assumed-role/") + .or_else(|| arn.split_once(":role/")) + .or_else(|| arn.split_once(":user/"))? + .1; + let name = rest.split('/').next().unwrap_or(""); + (!name.is_empty()).then(|| name.to_string()) +} + +/// Pure: AWS refused a principal that isn't the team's role `role_arn` +/// (CoderHelm read with the wrong role): the refused principal's name. A +/// refusal of the team's own role, or one that names nobody, is `None`. +pub fn refused_other_principal(message: &str, role_arn: &str) -> Option { + let name = refused_principal(message)?; + let team = role_arn.rsplit('/').next().unwrap_or(""); + (name != team).then_some(name) +} + /// Takes on a team's role. `actor` names the session in the team's AWS -/// records (`reviewer`, `planner`, a person's email). In a self-hosted -/// install's own account the log reader is read with the install's own role -/// ([`install_target`]). +/// records (`reviewer`, `planner`, a person's email). Always the team's +/// own role, also in a self-hosted install's own account: a read of a +/// team's data is made, and refused, as the team's role, and the role's +/// one-click update stack is what adds a read. pub async fn assume( sts: &aws_sdk_sts::Client, target: &AwsTarget, actor: &str, -) -> Result { +) -> Result { check_target(target)?; - if install_target(target, install_read_role().as_deref()).is_some() { - if let Some(s) = own_session(&target.region) { - return Ok(s); - } - } assume_exact(sts, target, actor).await } @@ -568,7 +614,7 @@ pub async fn assume_exact( sts: &aws_sdk_sts::Client, target: &AwsTarget, actor: &str, -) -> Result { +) -> Result { let external_id = target.external_id.as_str(); if external_id.is_empty() { return Err(StepError::new( @@ -603,11 +649,14 @@ pub async fn assume_exact( let c = out .credentials() .ok_or_else(|| StepError::new("sign_in", "AWS returned no session.", "Try again."))?; - Ok(Session { - access_key_id: c.access_key_id().to_string(), - secret_access_key: c.secret_access_key().to_string(), - session_token: c.session_token().to_string(), - region: target.region.clone(), + Ok(TeamSession { + session: Session { + access_key_id: c.access_key_id().to_string(), + secret_access_key: c.secret_access_key().to_string(), + session_token: c.session_token().to_string(), + region: target.region.clone(), + }, + role_arn: target.role_arn.clone(), }) } @@ -697,26 +746,16 @@ mod tests { } #[test] - fn the_install_account_reads_with_the_install_role() { - let t = install_target(&reader("111122223333"), Some(OWN)).expect("swapped"); - assert_eq!(t.role_arn, OWN); - // The team's private ID and region carry over. - assert_eq!(t.external_id, "team-id"); - assert_eq!(t.region, "us-east-1"); - } - - #[test] - fn other_accounts_roles_and_installs_keep_their_role() { - // Another account keeps the person's log reader and its update flow. - assert!(install_target(&reader("444455556666"), Some(OWN)).is_none()); - // The data-source role is never swapped. - let data = AwsTarget { - role_arn: "arn:aws:iam::111122223333:role/CoderhelmReadOnly".into(), - ..reader("111122223333") - }; - assert!(install_target(&data, Some(OWN)).is_none()); - // No install role (the hosted deployment, or an install not updated yet). - assert!(install_target(&reader("111122223333"), None).is_none()); + fn a_refusal_names_the_principal_aws_refused() { + let worker = "User: arn:aws:sts::111122223333:assumed-role/coderhelm-prod-ServiceRole-ABC123/coderhelm-prod-worker is not authorized to perform: wafv2:ListWebACLs on resource: arn:aws:wafv2:us-east-1:111122223333:regional/webacl/*"; + let team = reader("111122223333").role_arn; + assert_eq!( + refused_other_principal(worker, &team).as_deref(), + Some("coderhelm-prod-ServiceRole-ABC123") + ); + let as_team = "User: arn:aws:sts::111122223333:assumed-role/CoderHelmLogReader/coderhelm-x is not authorized to perform: wafv2:ListWebACLs"; + assert_eq!(refused_other_principal(as_team, &team), None); + assert_eq!(refused_other_principal("Access denied", &team), None); assert!(!in_install_account( "arn:aws:iam::111122223333:role/x", None @@ -725,6 +764,7 @@ mod tests { "arn:aws:iam::111122223333:role/x", Some("not-an-arn") )); + assert!(in_install_account(&team, Some(OWN))); } #[test] @@ -945,17 +985,6 @@ mod tests { ); } - #[test] - fn a_database_on_the_log_reader_is_read_with_that_role_in_the_install_account() { - let mut t = db_target(); - t.role_arn = format!("arn:aws:iam::111122223333:role/{LOG_READER_ROLE}"); - assert!(install_target(&t, Some(OWN)).is_none()); - let mut w = t.clone(); - w.cluster_arn.clear(); - w.cluster_id = "analytics".into(); - assert!(install_target(&w, Some(OWN)).is_none()); - } - /// Writes the setup script to the file named by SETUP_SCRIPT_OUT, for /// running it by hand. Needs SETUP_ACCOUNT and SETUP_EXTERNAL_ID. #[test] diff --git a/services/common/src/live/db.rs b/services/common/src/live/db.rs index b53ee7367..f73ede9a6 100644 --- a/services/common/src/live/db.rs +++ b/services/common/src/live/db.rs @@ -774,7 +774,7 @@ mod tests { assert!(!aws::opens_without_private_id(&sts, &t).await); let session = aws::assume(&sts, &t, "integration-test").await.unwrap(); - let report = connect_checks(Ok(session.clone()), &t).await; + let report = connect_checks(Ok(session.clone().into_session()), &t).await; for c in &report.checks { println!("check {} ok={} {}", c.id, c.ok, c.detail); } diff --git a/services/common/src/live/metrics.rs b/services/common/src/live/metrics.rs index 7eea9c9fe..c2e447ec3 100644 --- a/services/common/src/live/metrics.rs +++ b/services/common/src/live/metrics.rs @@ -16,7 +16,7 @@ use std::time::Duration; use serde_json::Value; -use super::aws::Session; +use super::aws::{Session, TeamSession}; use super::http::window; use super::StepError; @@ -413,7 +413,7 @@ pub fn format_list(list: &[MetricInfo]) -> String { /// The real reads, on a session of the team's role. pub struct Aws<'a> { - pub session: &'a Session, + pub session: &'a TeamSession, } fn client(s: &Session, region: Option<&str>) -> aws_sdk_cloudwatch::Client { @@ -434,9 +434,15 @@ fn client(s: &Session, region: Option<&str>) -> aws_sdk_cloudwatch::Client { ) } -/// AWS's answer to a refused or failed call. A refusal is the role's: the -/// install's setup item for `action`, named in one line. -fn aws_error(e: &aws_sdk_cloudwatch::error::SdkError, action: &str) -> StepError +/// AWS's answer to a refused or failed call. A refusal of the team's role +/// (`role_arn`) is the install's setup item for `action`, named in one +/// line; a refusal of any other principal is CoderHelm's own failure, named +/// with the principal AWS refused. +fn aws_error( + e: &aws_sdk_cloudwatch::error::SdkError, + action: &str, + role_arn: &str, +) -> StepError where E: aws_sdk_cloudwatch::error::ProvideErrorMetadata + std::error::Error + 'static, R: std::fmt::Debug, @@ -445,6 +451,21 @@ where let code = e.code().unwrap_or("").to_string(); let msg = e.message().unwrap_or("").to_string(); if is_denied(&code) { + if let Some(principal) = super::aws::refused_other_principal(&msg, role_arn) { + tracing::error!( + action, + principal = %principal, + "CoderHelm's own failure: a team read was made with a role that isn't the team's" + ); + return StepError::new( + "read", + format!( + "AWS refused {action} to {principal}, which isn't the team's role, so this \ + is CoderHelm's own failure, not the team's role." + ), + "", + ); + } return StepError::role_refused(&[action]); } StepError::new( @@ -477,7 +498,7 @@ impl MetricsApi for Aws<'_> { let out = req .send() .await - .map_err(|e| aws_error(&e, "cloudwatch:ListMetrics"))?; + .map_err(|e| aws_error(&e, "cloudwatch:ListMetrics", self.session.role_arn()))?; Ok(out .metrics() .iter() @@ -530,7 +551,7 @@ impl MetricsApi for Aws<'_> { let out = req .send() .await - .map_err(|e| aws_error(&e, "cloudwatch:GetMetricData"))?; + .map_err(|e| aws_error(&e, "cloudwatch:GetMetricData", self.session.role_arn()))?; let mut series = Vec::new(); for mq in &q.queries { let r = out @@ -558,12 +579,12 @@ impl MetricsApi for Aws<'_> { /// Whether the role can read metrics: one ListMetrics. `Ok(false)` when AWS /// says the role isn't allowed. -pub async fn probe(session: &Session) -> Result { +pub async fn probe(session: &TeamSession) -> Result { let c = client(session, None); match c.list_metrics().namespace("AWS/Lambda").send().await { Ok(_) => Ok(true), Err(e) => { - let err = aws_error(&e, "cloudwatch:ListMetrics"); + let err = aws_error(&e, "cloudwatch:ListMetrics", session.role_arn()); if !err.role_refused.is_empty() { Ok(false) } else { diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index fe74472cc..615f5b1d0 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -17,9 +17,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use super::aws::{ - assume_exact, install_read_role, install_target, own_session, AwsTarget, Session, -}; +use super::aws::{assume, AwsTarget, Session, TeamSession}; use crate::log_reader::{self, ABILITIES}; /// What the simulator said about one action. @@ -554,7 +552,7 @@ async fn simulate(s: &Session, target: &AwsTarget) -> Result, boo } /// The cheapest real read per ability: `Some(false)` when refused. -async fn probes(s: &Session) -> Vec<(&'static str, Option)> { +async fn probes(s: &TeamSession) -> Vec<(&'static str, Option)> { let ok = |r: Result<(), bool>| match r { Ok(()) => Some(true), Err(true) => Some(false), @@ -636,33 +634,22 @@ pub async fn check( actor: &str, now: &str, ) -> PermissionCheck { - let own = install_read_role(); - let install_account = super::aws::in_install_account(&target.role_arn, own.as_deref()); - if let Some(t) = install_target(target, own.as_deref()) { - if let Some(session) = own_session(&t.region) { - // The install's own role, checked as the role it is. - let mut c = check_with(session, &t, now).await; - c.install_account = true; - c.install_role = true; - return c; - } - } + // The role every read of the account is made with ([`assume`]), also in + // a self-hosted install's own account: the check and the reads can't + // disagree about which role lacks what. let mut c = PermissionCheck::new(target, now); - let session = match assume_exact(sts, target, actor).await { + let session = match assume(sts, target, actor).await { Ok(s) => s, Err(e) => { c.error = e.message; - c.install_account = install_account; return c; } }; - let mut c = check_with(session, target, now).await; - c.install_account = install_account; - c + check_with(session, target, now).await } /// [`check`] with a session on `target`'s role. -async fn check_with(session: Session, target: &AwsTarget, now: &str) -> PermissionCheck { +async fn check_with(session: TeamSession, target: &AwsTarget, now: &str) -> PermissionCheck { let mut c = PermissionCheck::new(target, now); c.works = true; match simulate(&session, target).await { diff --git a/services/common/src/log_findings.rs b/services/common/src/log_findings.rs index b0303ed42..4593fad80 100644 --- a/services/common/src/log_findings.rs +++ b/services/common/src/log_findings.rs @@ -3083,14 +3083,18 @@ pub async fn connection_role( .unwrap_or_default() } -/// Take on the team's log reader role for the finding's account. +/// Take on the team's log reader role for the finding's account: the +/// account's connection ([`crate::live::aws_account::AwsAccount::target`]) +/// taken on with [`crate::live::aws::assume`], the one way a run's tools and +/// a waiting run's re-check read the account, so both ask AWS as the same +/// role. pub async fn session_for( dynamo: &DynamoClient, sts: &aws_sdk_sts::Client, insights_table: &str, team_id: &str, account: &str, -) -> Result, String> { +) -> Result, String> { if account.is_empty() || !account.chars().all(|c| c.is_ascii_digit()) { return Ok(None); } @@ -3102,32 +3106,23 @@ pub async fn session_for( .send() .await .map_err(|e| e.to_string())?; - let Some(item) = item.item() else { + let Some(target) = item.item().and_then(reader_target) else { return Ok(None); }; - let (role, external) = (s(item, "role_arn"), s(item, "external_id")); - if role.is_empty() || external.is_empty() { - return Ok(None); - } - let region = Some(s(item, "region")) - .filter(|r| !r.is_empty()) - .unwrap_or_else(|| "us-east-1".into()); - let out = sts - .assume_role() - .role_arn(role) - .role_session_name("coderhelm-log-findings") - .external_id(external) - .duration_seconds(900) - .send() + crate::live::aws::assume(sts, &target, "log-findings") .await - .map_err(|e| aws_sdk_sts::error::DisplayErrorContext(e).to_string())?; - let c = out.credentials().ok_or("AWS returned no session")?; - Ok(Some(crate::live::aws::Session { - access_key_id: c.access_key_id().to_string(), - secret_access_key: c.secret_access_key().to_string(), - session_token: c.session_token().to_string(), - region, - })) + .map(Some) + .map_err(|e| e.message) +} + +/// Pure: the role a stored connection reads with, the same target the +/// run's tools take on (`AwsAccount::target`). `None` without a role or the +/// team's private ID. +pub fn reader_target( + item: &std::collections::HashMap, +) -> Option { + let a = crate::live::aws_account::AwsAccount::from_item(item)?; + (!a.external_id.is_empty()).then(|| a.target()) } /// Pure: the log group's page in the CloudWatch console. diff --git a/services/common/src/log_repo/live.rs b/services/common/src/log_repo/live.rs index f2778c67d..143e84461 100644 --- a/services/common/src/log_repo/live.rs +++ b/services/common/src/log_repo/live.rs @@ -48,7 +48,7 @@ pub trait Judge: Send + Sync { /// The real environment. pub struct Live<'a> { /// A session on the team's log reader role for the target's account. - pub session: Option, + pub session: Option, /// The team's code, through its GitHub App installation. pub host: Option<&'a dyn RepoHost>, pub dynamo: &'a DynamoClient, diff --git a/services/common/src/role_move.rs b/services/common/src/role_move.rs index 84b6bb3bf..f1c622078 100644 --- a/services/common/src/role_move.rs +++ b/services/common/src/role_move.rs @@ -88,7 +88,9 @@ pub async fn try_move( source: &Source, candidate: &AwsTarget, ) -> Result { - let session = crate::live::aws::assume_exact(sts, candidate, "role-move").await; + let session = crate::live::aws::assume_exact(sts, candidate, "role-move") + .await + .map(crate::live::aws::TeamSession::into_session); if !candidate.cluster_id.is_empty() { let s = session.map_err(|e| e.message)?; let r = crate::live::redshift::connect_checks(&s, candidate).await; diff --git a/services/common/src/role_wait.rs b/services/common/src/role_wait.rs index c11b1693a..773b9a08e 100644 --- a/services/common/src/role_wait.rs +++ b/services/common/src/role_wait.rs @@ -49,6 +49,11 @@ pub enum Ending { AwaitRole(Vec), /// Nothing for a person and nothing to wait for: plan again. PlanAgain, + /// The run was started again because a re-check read these actions as + /// the team's role, and the run was refused them anyway: CoderHelm's own + /// failure (the run and the re-check disagreed). It never waits again; + /// it goes on with what it has. + OwnFailure(Vec), } /// Pure: how the run ends. `person_items` are the items left for a person @@ -64,6 +69,49 @@ pub fn ending(person_items: &[String], refused: Vec) -> Ending { } } +/// Pure: [`ending`] for a run [`went_on`] started after a re-check read +/// `went_on`'s actions: refused one of them again, it ends +/// [`Ending::OwnFailure`] instead of waiting, so a run restarts at most once +/// for the same refused read. +pub fn ending_after( + person_items: &[String], + refused: Vec, + went_on: Option<&Waiting>, +) -> Ending { + match ending(person_items, refused) { + Ending::AwaitRole(gaps) => { + let again: Vec = went_on + .map(|w| { + let mut a: Vec = Vec::new(); + for g in &gaps { + for x in &g.actions { + if w.actions.contains(x) && !a.contains(x) { + a.push(x.clone()); + } + } + } + a + }) + .unwrap_or_default(); + if again.is_empty() { + Ending::AwaitRole(gaps) + } else { + Ending::OwnFailure(again) + } + } + e => e, + } +} + +/// Pure: the one line a run that ended [`Ending::OwnFailure`] says. +pub fn own_failure_line(actions: &[String]) -> String { + format!( + "CoderHelm's own failure: the re-check read {} as the team's role, and this run was \ + refused it anyway. It goes on with what it has instead of waiting again.", + actions.join(", ") + ) +} + /// Pure: the install's recorded gaps this run met: refused at or after /// `run_started` (RFC 3339). A gap is written again each time a read is /// refused, so one older than the run was not this run's. @@ -217,6 +265,54 @@ pub async fn list(dynamo: &DynamoClient, table: &str, team_id: &str) -> Vec Option { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", attr(team_id)) + .key("sk", attr(&format!("{WENT_ON_PREFIX}{run_id}"))) + .send() + .await + .ok()?; + let json = out.item()?.get("waiting")?.as_s().ok()?.clone(); + serde_json::from_str(&json).ok() +} + /// The wait is over (the run went on, or ended another way). pub async fn remove(dynamo: &DynamoClient, table: &str, team_id: &str, run_id: &str) { let _ = dynamo diff --git a/services/common/src/waf_logs.rs b/services/common/src/waf_logs.rs index 1830ff609..d3ba0dd20 100644 --- a/services/common/src/waf_logs.rs +++ b/services/common/src/waf_logs.rs @@ -22,7 +22,7 @@ use std::io::{BufRead, BufReader, Read as _}; use chrono::{DateTime, TimeZone, Utc}; use serde_json::Value; -use crate::live::aws::Session; +use crate::live::aws::{Session, TeamSession}; /// Most objects read in one lookup (four hours of five-minute files). pub const MAX_OBJECTS: usize = 48; @@ -438,7 +438,7 @@ fn s3_client(s: &Session, region: &str) -> aws_sdk_s3::Client { /// Reads the rule's matches from the log objects in `[start, end]` (at /// most [`MAX_WINDOW_SECS`], newest first, within the bounds above). pub async fn read( - session: &Session, + session: &TeamSession, loc: &LogLocation, rule: &str, start: i64, diff --git a/services/gateway/src/routes/connectors.rs b/services/gateway/src/routes/connectors.rs index 805bba435..e629f3ff6 100644 --- a/services/gateway/src/routes/connectors.rs +++ b/services/gateway/src/routes/connectors.rs @@ -931,13 +931,9 @@ pub async fn aws_check( Ok(Json(json!({ "check": check, "missing": missing, - // The install's own account gets these with its version updates. - "update_url": if missing.is_empty() - || common::live::aws::in_install_account( - &t.role_arn, - common::live::aws::install_read_role().as_deref(), - ) - { + // The team's role reads every account, the install's own too: its + // update stack is what adds a read. + "update_url": if missing.is_empty() { None } else { update_stack_url(&t.region, &common::log_reader::Chosen::default()) diff --git a/services/gateway/src/routes/data_sources.rs b/services/gateway/src/routes/data_sources.rs index 81646f5bf..10956bd3e 100644 --- a/services/gateway/src/routes/data_sources.rs +++ b/services/gateway/src/routes/data_sources.rs @@ -1662,7 +1662,7 @@ async fn role_checks( detail: "Coderhelm can use the role, and only with your private ID.".into(), fix: None, }], - Ok(s), + Ok(s.into_session()), ), Err(e) => ( vec![Check { diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index e5f519ead..f83b6ead0 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -314,14 +314,12 @@ pub fn aws_missing(a: &AwsAccount) -> Vec<&'static str> { out } -/// The account is the self-hosted install's own. Its read-only permissions -/// arrive with the install's version updates, so no update stack is offered. +/// The account's last check ran on the install's own role (a check from +/// before every read went through the team's role). Reads of the account, +/// the install's own included, are made with the team's role, so its update +/// stack is offered everywhere once the account is checked again. pub fn install_account(a: &AwsAccount) -> bool { a.permissions.as_ref().is_some_and(|p| p.install_account) - || common::live::aws::in_install_account( - &a.role_arn, - common::live::aws::install_read_role().as_deref(), - ) } /// The one-click update stack's link, when the role lacks something and a diff --git a/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs b/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs index fc37dc185..2126480ce 100644 --- a/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs +++ b/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs @@ -176,7 +176,7 @@ fn without_the_roles_waf_reads_the_run_waits_and_raises_the_item() { // The pipeline decides this way, and the re-checks are armed and sent. let m = include_str!("../mod.rs"); let body = &m[m.find("async fn finish_without_code(").unwrap()..]; - assert!(body.contains("common::role_wait::ending(&left.human")); + assert!(body.contains("common::role_wait::ending_after(&left.human")); assert!(body.contains("common::run_status::AWAITING_SETUP")); assert!(body.contains("role_wait::arm(")); assert!(m.contains("NoCodeEnd::PlanAgain(why)")); diff --git a/services/worker/src/passes/incidents/rk_team_reads_as_the_team_role.rs b/services/worker/src/passes/incidents/rk_team_reads_as_the_team_role.rs new file mode 100644 index 000000000..ceeb56637 --- /dev/null +++ b/services/worker/src/passes/incidents/rk_team_reads_as_the_team_role.rs @@ -0,0 +1,180 @@ +//! rk. A self-hosted install runs in the same AWS account as the team's +//! resources. An AWS WAF alarm run's WAF tools were refused +//! `wafv2:ListWebACLs`: `live::aws::assume` read with the worker's own +//! Lambda role instead of the team's `CoderHelmLogReader`. The refusal +//! blamed the team's role and the run waited. The wait's re-check took on +//! the reader, was allowed and started the run again, which was refused +//! again and waited again: a loop. +//! +//! Guarantee: every team read is made as the team's role (`TeamSession`, +//! made only by `assume`); the re-check takes the same target with the same +//! call; a refusal of another principal names it and is CoderHelm's own +//! failure; a restarted run never waits again for what the re-check read. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::alarm_evidence as ae; +use common::aws_role_reads::Gap; +use common::live::aws::{self, AwsTarget}; +use common::live::aws_account::AwsAccount; +use common::role_wait::{self, Ending, Waiting}; +use std::collections::HashMap; + +const ACCOUNT: &str = "111122223333"; +const READER: &str = "arn:aws:iam::111122223333:role/CoderHelmLogReader"; +const WORKER: &str = "arn:aws:iam::111122223333:role/coderhelm-prod-ServiceRole-EXAMPLE"; + +/// The worker's refusal as AWS words it (CloudTrail named the same role). +fn worker_refused() -> String { + format!( + "User: arn:aws:sts::{ACCOUNT}:assumed-role/coderhelm-prod-ServiceRole-EXAMPLE/\ + coderhelm-prod-worker is not authorized to perform: wafv2:ListWebACLs on resource: \ + arn:aws:wafv2:us-east-1:{ACCOUNT}:regional/webacl/*" + ) +} + +fn reader() -> AwsTarget { + AwsTarget { + role_arn: READER.into(), + external_id: "team-private-id".into(), + region: "us-east-1".into(), + ..Default::default() + } +} + +/// An STS that answers nothing (a closed local port): taking on a role +/// fails, so any session that comes back was never the team's role. +fn dead_sts() -> aws_sdk_sts::Client { + use aws_sdk_sts::config::{BehaviorVersion, Credentials, Region}; + aws_sdk_sts::Client::from_conf( + aws_sdk_sts::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new("us-east-1")) + .endpoint_url("http://127.0.0.1:9") + .retry_config(aws_sdk_sts::config::retry::RetryConfig::disabled()) + .credentials_provider(Credentials::new("caller", "caller", None, None, "test")) + .build(), + ) +} + +#[tokio::test] +async fn a_same_account_reader_is_never_swapped_for_the_workers_own_role() { + // The Lambda's environment: its own role, with the install's read role + // set (infra/lib/own-account-read.ts), in the reader's account. + std::env::set_var(aws::OWN_ROLE_ENV, WORKER); + std::env::set_var("AWS_ACCESS_KEY_ID", "WORKER-KEY"); + std::env::set_var("AWS_SECRET_ACCESS_KEY", "worker-secret"); + let got = aws::assume(&dead_sts(), &reader(), "run").await; + std::env::remove_var(aws::OWN_ROLE_ENV); + std::env::remove_var("AWS_ACCESS_KEY_ID"); + std::env::remove_var("AWS_SECRET_ACCESS_KEY"); + // Before: the worker's keys came back without asking STS, and every + // WAF read was made, and refused, as the worker's role. + match got { + Ok(s) => { + assert_ne!(s.access_key_id, "WORKER-KEY", "read as the worker's role"); + assert_eq!(s.role_arn(), READER); + } + Err(e) => assert_eq!(e.step, "sign_in", "{e:?}"), + } +} + +#[test] +fn the_recheck_and_the_run_take_on_the_same_role() { + let item: HashMap = [ + ("account_id", ACCOUNT), + ("role_arn", READER), + ("external_id", "team-private-id"), + ("region", "us-east-1"), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect(); + let run = AwsAccount::from_item(&item).expect("account").target(); + let recheck = common::log_findings::reader_target(&item).expect("target"); + assert_eq!(run, recheck); + assert_eq!(recheck.role_arn, READER); +} + +#[test] +fn a_refusal_of_another_role_names_it_and_is_never_the_teams_item() { + let msg = worker_refused(); + let (line, team_gap) = ae::failure_line( + "find the web ACL", + "wafv2:ListWebACLs", + Some("AccessDeniedException"), + Some(&msg), + READER, + ); + assert!(!team_gap, "the worker's refusal blamed the team's role"); + assert!( + line.contains("coderhelm-prod-ServiceRole-EXAMPLE"), + "{line}" + ); + assert!(line.contains("CoderHelm's own failure"), "{line}"); + assert!( + !line.contains("CoderHelm's AWS role doesn't allow"), + "{line}" + ); + // The team's own role refused: that is the team's setup item. + let as_team = msg.replace("coderhelm-prod-ServiceRole-EXAMPLE", "CoderHelmLogReader"); + let (line, team_gap) = ae::failure_line( + "find the web ACL", + "wafv2:ListWebACLs", + Some("AccessDeniedException"), + Some(&as_team), + READER, + ); + assert!(team_gap); + assert!( + line.contains("doesn't allow wafv2:ListWebACLs yet"), + "{line}" + ); + assert_eq!( + aws::refused_other_principal(&msg, READER).as_deref(), + Some("coderhelm-prod-ServiceRole-EXAMPLE") + ); + assert_eq!(aws::refused_other_principal(&msg, WORKER), None); +} + +#[test] +fn a_restarted_run_refused_what_the_recheck_read_never_waits_again() { + let gap = Gap { + account: ACCOUNT.into(), + role_arn: READER.into(), + actions: vec!["wafv2:ListWebACLs".into()], + needed_for: "an AWS WAF rule's requests".into(), + seen_at: "2026-11-18T10:00:00Z".into(), + ..Default::default() + }; + // The first run waits for the role. + assert!(matches!( + role_wait::ending_after(&[], vec![gap.clone()], None), + Ending::AwaitRole(_) + )); + // The re-check read it and started the run again; refused again, it is + // CoderHelm's own failure, never a second wait. + let read = Waiting::of("run-1", std::slice::from_ref(&gap), "2026-11-18T10:05:00Z"); + match role_wait::ending_after(&[], vec![gap.clone()], Some(&read)) { + Ending::OwnFailure(a) => { + assert_eq!(a, vec!["wafv2:ListWebACLs".to_string()]); + let line = role_wait::own_failure_line(&a); + assert!(line.starts_with("CoderHelm's own failure"), "{line}"); + assert!(!line.contains('\n')); + } + e => panic!("waited again: {e:?}"), + } + // A different read the re-check never looked at still waits. + let other = Gap { + actions: vec!["s3:GetObject".into()], + ..gap + }; + assert!(matches!( + role_wait::ending_after(&[], vec![other], Some(&read)), + Ending::AwaitRole(_) + )); + // A person's item still goes to the person. + assert_eq!( + role_wait::ending_after(&["a decision".into()], vec![], Some(&read)), + Ending::Person + ); +} diff --git a/services/worker/src/passes/log_look.rs b/services/worker/src/passes/log_look.rs index bd17b5b45..2871f77cf 100644 --- a/services/worker/src/passes/log_look.rs +++ b/services/worker/src/passes/log_look.rs @@ -44,7 +44,7 @@ fn refusal(e: &impl ProvideErrorMetadata, action: &str) -> Option { pub struct LiveLook<'a> { /// A session on the team's log reader role in the finding's account. - pub session: Option, + pub session: Option, pub host: Option<&'a dyn RepoHost>, /// The team's enabled repos (`owner/name`). pub repos: Vec, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 34bcbba77..717a6142a 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -9157,8 +9157,24 @@ async fn finish_without_code( ) .await; let refused = common::role_wait::refused_this_run(&gaps, &run_started_at(msg, start)); - match common::role_wait::ending(&left.human, refused) { + let went_on = common::role_wait::went_on( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + run_id, + ) + .await; + match common::role_wait::ending_after(&left.human, refused, went_on.as_ref()) { common::role_wait::Ending::Person => {} + common::role_wait::Ending::OwnFailure(actions) => { + let line = common::role_wait::own_failure_line(&actions); + error!(run_id, actions = ?actions, "{line}"); + add_progress_note(state, &msg.team_id, run_id, &line).await; + return NoCodeEnd::PlanAgain(format!( + "the plan stopped on reads the re-check had read as the team's role ({})", + actions.join(", ") + )); + } common::role_wait::Ending::AwaitRole(gaps) => { waiting = Some(common::role_wait::Waiting::of( run_id, diff --git a/services/worker/src/passes/role_wait.rs b/services/worker/src/passes/role_wait.rs index 4c742a125..3563a02b6 100644 --- a/services/worker/src/passes/role_wait.rs +++ b/services/worker/src/passes/role_wait.rs @@ -248,6 +248,8 @@ async fn go_on(state: &WorkerState, team_id: &str, run_id: &str, item: &Item, w: } let table = &state.config.settings_table_name; role_wait::remove(&state.dynamo, table, team_id, run_id).await; + // The new run never waits for these reads again (`ending_after`). + role_wait::record_went_on(&state.dynamo, table, team_id, &new_run, w).await; for a in &w.accounts { common::aws_role_reads::clear(&state.dynamo, table, team_id, a).await; }