diff --git a/docs/incidents/bo_alarm_reads_its_evidence.md b/docs/incidents/bo_alarm_reads_its_evidence.md new file mode 100644 index 000000000..7fbc9a456 --- /dev/null +++ b/docs/incidents/bo_alarm_reads_its_evidence.md @@ -0,0 +1,5 @@ +# bo. `bo_alarm_reads_its_evidence` + +**What happened:** An alert route sends a WAF signature-drift alarm (a Count rule seeing crawler A get past a Block rule after it changed its JA4 or user agent) to the team's terraform repository, where the fix is a pull request that updates the block rule's match. The run ended `needs_input` with a long question asking a person to grant the team's read-only role WAF and Athena access, "Default if unanswered in 4 hours: Grant access". `wafv2:ListWebACLs` and `GetSampledRequests` were denied: the role's setup script never added any WAF read. The web ACL logs to an `aws-waf-logs-*` bucket with an Athena table, and nothing read it. + +**The guarantee:** The role's setup script adds `coderhelm-read-waf`: WAF reads, and read-only Athena queries over the Glue tables on `aws-waf-logs-*` buckets, in the WAF log workgroups, with results written only under the workgroup's own results prefix. With those reads the run gathers the rule's matches before it plans (sampled requests, and the logs in S3 by JA4, JA3, user agent, accept language, path and cookie presence, over the last three hours) and goes on to its pull request. Without them the refusal is the install's one setup item, **AWS role reads**, with the one-line CloudShell update; the run names it in one line and goes on. The stop judge turns an ask or a hold for the role's reads into a proceed, the hand-back list doesn't carry it, and an access question never shows a default that can't happen. diff --git a/docs/self-host/check-your-install.md b/docs/self-host/check-your-install.md index c5254303b..c19f781bc 100644 --- a/docs/self-host/check-your-install.md +++ b/docs/self-host/check-your-install.md @@ -155,6 +155,9 @@ The last result is kept in `.coderhelm/doctor.json`. ### Integrations +- **AWS role reads** (`aws_role_reads`, in the dashboard only)\ + *If it warns:* A team's connected AWS role was refused a read an alert route needed, such as AWS WAF's sampled requests for a WAF alarm. Alarm runs read what the role allows and go on without the rest; no run asks a person for it.\ + *Fix:* The one line to paste into AWS CloudShell in that account. It adds the read-only `coderhelm-read-waf` policy to the role and changes nothing else. The item clears the next time an alarm run reads with it. ## The guided install @@ -210,7 +213,7 @@ Install admins (`admins` in the config) who are team admins can call these while } ``` -`status` is `pass`, `warn`, `fail` or `skip` (an optional integration that isn't set up). `fix` has `text` and any of `command` (to copy), `url` (outside CoderHelm) and `href` (a dashboard page). `ready` is true when nothing fails. Keys: `url`, `domain`, `github_keys`, `github_app`, `github_permissions`, `github_workflow_starts`, `github_installations`, `github_webhook`, `github_sign_in`, `email_sender`, `email_identity`, `email_sandbox`, `email_cognito`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`. A self-hosted install has no Google sign-in, so there is no `google_sign_in` check. On an install that uses CoderHelm's GitHub App (hybrid), `github_app` and `github_installations` say whether the app is linked instead, and never block an update. `github_sign_in` passes when the install's own GitHub App has its OAuth client id and secret stored, or when the install has neither and is registered with CoderHelm (GitHub sign-in then goes through CoderHelm's app, [Sign in with GitHub through CoderHelm](./hybrid.md#sign-in-with-github-through-coderhelm)). It warns when only one of the two is stored, when the install's own app has neither, and when an install on CoderHelm's GitHub App isn't registered yet: the sign-in page doesn't offer Continue with GitHub until then. It never blocks an update. +`status` is `pass`, `warn`, `fail` or `skip` (an optional integration that isn't set up). `fix` has `text` and any of `command` (to copy), `url` (outside CoderHelm) and `href` (a dashboard page). `ready` is true when nothing fails. Keys: `url`, `domain`, `github_keys`, `github_app`, `github_permissions`, `github_workflow_starts`, `github_installations`, `github_webhook`, `github_sign_in`, `email_sender`, `email_identity`, `email_sandbox`, `email_cognito`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`, `aws_role_reads`. `aws_role_reads` warns, and never blocks an update, while a team's connected AWS role lacks a read an alert route used; its `fix.command` is the one-line CloudShell update. A self-hosted install has no Google sign-in, so there is no `google_sign_in` check. On an install that uses CoderHelm's GitHub App (hybrid), `github_app` and `github_installations` say whether the app is linked instead, and never block an update. `github_sign_in` passes when the install's own GitHub App has its OAuth client id and secret stored, or when the install has neither and is registered with CoderHelm (GitHub sign-in then goes through CoderHelm's app, [Sign in with GitHub through CoderHelm](./hybrid.md#sign-in-with-github-through-coderhelm)). It warns when only one of the two is stored, when the install's own app has neither, and when an install on CoderHelm's GitHub App isn't registered yet: the sign-in page doesn't offer Continue with GitHub until then. It never blocks an update. ### `GET /api/system/domain`, `PUT /api/system/domain`, `DELETE /api/system/domain` diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index 1ad5a0c36..4fab1c7c3 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -24,6 +24,16 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar 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. - **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. +- **The data-source role, and AWS WAF alarms**\ + AWS data sources (databases, warehouses) use the read-only role `CoderhelmReadOnly`, made by the setup script a team pastes into AWS CloudShell from **Settings, Data sources, AWS**. The script also gives it `coderhelm-read-waf`, so a run an alert rule starts for an AWS WAF alarm can read what the alarm's rule matched: + - `wafv2:Get*` and `wafv2:List*`: web ACLs, sampled requests, where a web ACL logs; + - `s3:GetObject`, `s3:ListBucket` and `s3:GetBucketLocation` on `aws-waf-logs-*` buckets only; + - when the account has an Athena workgroup with `waf` in its name (with a results location) and a Glue table on an `aws-waf-logs-*` bucket, in the region the script runs in: `glue:Get*` on those databases and tables, `athena:StartQueryExecution`, `athena:Get*` and `athena:StopQueryExecution` in those workgroups, and `s3:PutObject` only under each workgroup's own results prefix; + - every change to WAF, Athena, Glue or a bucket, Glue's connections, and any object written outside the results prefix are denied. + + A web ACL that logs to S3 is read with one Athena query: the alarm's rule only, the last three hours (bounded by the table's projected date partition, or by the workgroup's scan limit; with neither the bucket isn't queried), counted by JA4, JA3, user agent, accept language, path and whether a cookie was sent. No client address, cookie or other header value is selected. +- **When a role lacks a read an alert route needs**\ + It is one setup item for the whole install, **AWS role reads** (`aws_role_reads` in Settings, then **Setup**), with one line to paste into AWS CloudShell in the role's account. The line adds `coderhelm-read-waf` to the existing role and changes nothing else. Until then, alarm runs read what the role allows, name the item in one line and go on to the pull request they can justify: no run asks a person for access, and none waits on it. - **Alert routes (SNS)**\ **Settings, Alerts** shows the subscription endpoint, `https://coderhelm.example.com/webhooks/alerts/sns`. Save and turn on the route before you subscribe the topic: CoderHelm only confirms subscriptions for topics with a route that's on. If you subscribed first, press **Request confirmation** on the subscription in SNS. Every message's signature is checked before anything else. - **Alarms that keep firing**\ diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 2c950ffe6..a0454f6eb 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -37,7 +37,7 @@ order: 11 - Each function has its own role with only the tables, queues, keys and actions it uses. - The build sandbox runs a repository's own build scripts, which are untrusted: its CodeBuild role can only read and write one bucket of short-lived source tarballs and write its logs. No GitHub token, no tables, no KMS. -- Roles in teams' AWS accounts are assumed only by name (`CoderHelmLogReader`, `CoderhelmReadOnly*`) and with an external id. When the data is in the install's own account, see the exception in [The permissions boundary](#the-permissions-boundary). +- Roles in teams' AWS accounts are assumed only by name (`CoderHelmLogReader`, `CoderhelmReadOnly*`) and with an external id. `CoderhelmReadOnly`'s one write is `s3:PutObject` for Athena query results, held by an explicit deny to the WAF log workgroup's own results prefix (see [Integrations](./integrations.md#connected-aws-accounts)). When the data is in the install's own account, see the exception in [The permissions boundary](#the-permissions-boundary). - An install made with Launch Stack holds no broad standing rights in your account: see [What an install can do in your account](#what-an-install-can-do-in-your-account). ## What an install can do in your account diff --git a/services/Cargo.lock b/services/Cargo.lock index cdac12a37..a9235388f 100644 --- a/services/Cargo.lock +++ b/services/Cargo.lock @@ -227,6 +227,29 @@ dependencies = [ "uuid", ] +[[package]] +name = "aws-sdk-athena" +version = "1.131.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77552fe3d20252b306e00f1fd5a833259336693579b99731a127ea270fc90768" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "fastrand", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-autoscaling" version = "1.143.0" @@ -653,6 +676,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-glue" +version = "1.187.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e708873404aca92a3a254a2e0590b3787b3ea337b35c2f27b3bb2350bd40264" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-health" version = "1.127.0" @@ -1808,6 +1856,7 @@ version = "0.1.0" dependencies = [ "async-trait", "aws-config", + "aws-sdk-athena", "aws-sdk-bedrockagent", "aws-sdk-bedrockagentruntime", "aws-sdk-bedrockruntime", @@ -1818,6 +1867,7 @@ dependencies = [ "aws-sdk-ec2", "aws-sdk-ecr", "aws-sdk-ecs", + "aws-sdk-glue", "aws-sdk-iam", "aws-sdk-kms", "aws-sdk-lambda", diff --git a/services/common/Cargo.toml b/services/common/Cargo.toml index 5cfea0aa9..c398340fc 100644 --- a/services/common/Cargo.toml +++ b/services/common/Cargo.toml @@ -54,6 +54,9 @@ aws-sdk-cloudwatchlogs = { version = "1", default-features = false, features = [ aws-sdk-cloudwatch = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] } # alarm_evidence: what an AWS WAF alarm's rule matched (sampled requests, read-only) aws-sdk-wafv2 = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] } +# alarm_evidence: a web ACL's logs held in S3, read through its Athena table (read-only query) +aws-sdk-athena = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] } +aws-sdk-glue = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] } # log_repo: which repo a log group's code lives in (read-only lookups) aws-sdk-ecs = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] } aws-sdk-lambda = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] } diff --git a/services/common/src/alarm_evidence.rs b/services/common/src/alarm_evidence.rs index e5b1cc204..2cdacac71 100644 --- a/services/common/src/alarm_evidence.rs +++ b/services/common/src/alarm_evidence.rs @@ -10,13 +10,21 @@ //! signature) is fixed by updating the block rule's match to what these say. //! //! Reads only: `wafv2:ListWebACLs`, `wafv2:GetSampledRequests`, -//! `wafv2:GetLoggingConfiguration` and a Logs Insights query on the web -//! ACL's log group (a web ACL logging to S3 is named, not read: CoderHelm's -//! roles read no bucket objects). Request values +//! `wafv2:GetLoggingConfiguration`, and the web ACL's logs: a Logs Insights +//! query on its log group, or, when it logs to an `aws-waf-logs-*` bucket, +//! one bounded Athena query over the Glue table on that bucket ([`athena_query`]: +//! the last three hours, the alarm's rule only), in a WAF log workgroup +//! the role may query (`live::aws::waf_policy_template`). Request values //! that can carry secrets or people's data (client addresses, cookies, -//! authorization and every other header value but the user agent, query -//! strings) are never kept. What remains came from outside parties and is -//! handed to the run as data, fenced. +//! authorization and every other header value but the user agent and +//! accept language, query strings) are never kept; from the logs in S3, +//! only JA4, JA3, user agent, accept language, path, whether a cookie was +//! sent, and counts. What remains came from outside parties and is handed +//! to the run as data, fenced. +//! +//! A read the role is refused is the install's setup item +//! (`aws_role_reads`), named once in [`Gathered::refused`] and in one line +//! of the evidence, never a question on the run. use std::collections::BTreeMap; use std::time::Duration; @@ -40,6 +48,12 @@ const TOP: usize = 5; const MAX_VALUE: usize = 200; /// How long the Logs Insights query is waited for. const QUERY_WAIT: Duration = Duration::from_secs(20); +/// How long the Athena query is waited for before it is stopped. +const ATHENA_WAIT: Duration = Duration::from_secs(45); +/// Most rows the Athena query returns. +const ATHENA_ROWS: i32 = 20; +/// Most Glue databases and Athena workgroups looked through. +const MAX_LISTED: usize = 50; /// The web ACL and rule an AWS WAF alarm watches, from its dimensions. #[derive(Debug, Clone, PartialEq, Eq)] @@ -284,6 +298,193 @@ pub fn bucket_of(destination: &str) -> Option { b.starts_with("aws-waf-logs-").then(|| b.to_string()) } +/// Pure: a Glue database, table or column name that is safe to quote in a +/// query. +fn is_sql_name(v: &str) -> bool { + !v.is_empty() + && v.len() <= 255 + && v.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// Pure: whether a Glue table's location is in `bucket`. +pub fn table_in_bucket(location: &str, bucket: &str) -> bool { + location + .strip_prefix("s3://") + .and_then(|l| l.strip_prefix(bucket)) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) +} + +/// The Glue table over a web ACL's log bucket: what a query needs of it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LogTable { + pub database: String, + pub table: String, + /// Column names, lower case. + pub columns: Vec, + /// Partition keys with a projected date format (`projection..format`), + /// so the query reads only the last three hours' partitions. + pub date_partitions: Vec<(String, String)>, +} + +impl LogTable { + fn has(&self, column: &str) -> bool { + self.columns.iter().any(|c| c == column) + } +} + +/// Pure: a projected partition's Java date format (`yyyy/MM/dd/HH`) as a +/// chrono format, when it is made only of year, month, day, hour and +/// minute fields and separators, so its values sort as text in time order. +pub fn date_format(java: &str) -> Option { + let mut out = String::new(); + let mut rest = java; + let mut fields = 0; + while !rest.is_empty() { + let token = ["yyyy", "MM", "dd", "HH", "mm"] + .iter() + .find(|t| rest.starts_with(**t)); + if let Some(t) = token { + out.push_str(match *t { + "yyyy" => "%Y", + "MM" => "%m", + "dd" => "%d", + "HH" => "%H", + _ => "%M", + }); + rest = &rest[t.len()..]; + fields += 1; + continue; + } + let c = rest.chars().next()?; + if !"/-_ :".contains(c) { + return None; + } + out.push(c); + rest = &rest[c.len_utf8()..]; + } + (fields > 0 && java.starts_with("yyyy")).then_some(out) +} + +/// Pure: the date-projected partition keys of a table, from its keys and +/// its parameters. +pub fn date_partitions( + keys: &[String], + parameters: &std::collections::HashMap, +) -> Vec<(String, String)> { + keys.iter() + .filter(|k| is_sql_name(k)) + .filter(|k| { + parameters + .get(&format!("projection.{k}.type")) + .is_some_and(|t| t.eq_ignore_ascii_case("date")) + }) + .filter_map(|k| { + let f = parameters.get(&format!("projection.{k}.format"))?; + date_format(f).map(|f| (k.to_lowercase(), f)) + }) + .collect() +} + +/// Pure: the one Athena query over a web ACL's logs: the rule's matches in +/// the last three hours, counted by JA4, JA3, user agent, accept language, +/// path and whether a cookie was sent. Nothing else of a request is +/// selected (no client address, no cookie or other header value, no query +/// string). `None` when a name can't be quoted safely or the table isn't a +/// WAF log table. +pub fn athena_query(t: &LogTable, rule: &str, start: i64, end: i64) -> Option { + if !is_waf_name(rule) || !is_sql_name(&t.database) || !is_sql_name(&t.table) { + return None; + } + if !(t.has("timestamp") && t.has("httprequest") && t.has("terminatingruleid")) { + return None; + } + let col = |c: &str, name: &str| { + if t.has(c) { + format!("{c} AS {name}") + } else { + format!("CAST(NULL AS varchar) AS {name}") + } + }; + let header = |h: &str| { + format!( + "element_at(transform(filter(httprequest.headers, x -> lower(x.name) = '{h}'), x -> x.value), 1)" + ) + }; + let fmt = |secs: i64, f: &str| { + DateTime::::from_timestamp(secs, 0) + .map(|d| d.format(f).to_string()) + .unwrap_or_default() + }; + let mut filter = format!("\"timestamp\" BETWEEN {} AND {}", start * 1000, end * 1000); + for (k, f) in &t.date_partitions { + filter.push_str(&format!( + " AND \"{k}\" BETWEEN '{}' AND '{}'", + fmt(start, f), + fmt(end, f) + )); + } + let matched = if t.has("nonterminatingmatchingrules") { + format!( + "(terminatingruleid = '{rule}' OR cardinality(filter(nonterminatingmatchingrules, r -> r.ruleid = '{rule}')) > 0)" + ) + } else { + format!("terminatingruleid = '{rule}'") + }; + Some(format!( + "SELECT {ja4}, {ja3}, {ua} AS ua, {lang} AS accept_language, \ + split_part(httprequest.uri, '?', 1) AS path, \ + cardinality(filter(httprequest.headers, x -> lower(x.name) = 'cookie')) > 0 AS has_cookie, \ + count(*) AS requests \ + FROM \"{db}\".\"{table}\" \ + WHERE {filter} AND {matched} \ + GROUP BY 1, 2, 3, 4, 5, 6 ORDER BY requests DESC LIMIT {ATHENA_ROWS}", + ja4 = col("ja4fingerprint", "ja4"), + ja3 = col("ja3fingerprint", "ja3"), + ua = header("user-agent"), + lang = header("accept-language"), + db = t.database, + table = t.table, + )) +} + +/// Pure: the Athena query's result rows (its first row is the header) as +/// evidence lines, each value clipped. +pub fn athena_lines(rows: &[Vec>]) -> Vec { + let mut out: Vec = Vec::new(); + let Some((head, body)) = rows.split_first() else { + return out; + }; + let at = |name: &str| head.iter().position(|h| h.as_deref() == Some(name)); + let get = |row: &[Option], name: &str| { + at(name) + .and_then(|i| row.get(i).cloned().flatten()) + .map(|v| clip(&v)) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "-".into()) + }; + for row in body { + let cookie = match get(row, "has_cookie").as_str() { + "true" => "a cookie", + "false" => "no cookie", + _ => "cookie unknown", + }; + out.push(format!( + " - {} requests: JA4 {} · JA3 {} · {} · Accept-Language {} · {} · {cookie}", + get(row, "requests"), + get(row, "ja4"), + get(row, "ja3"), + get(row, "ua"), + get(row, "accept_language"), + get(row, "path"), + )); + } + if out.is_empty() { + out.push(" - none in the last three hours".into()); + } + out +} + /// Pure: the evidence as the ticket's section: fenced, and labelled as data. pub fn render(alarm: &WafAlarm, lines: &[String]) -> String { format!( @@ -335,26 +536,64 @@ fn waf_client(s: &Session) -> aws_sdk_wafv2::Client { ) } -/// Read the evidence for a WAF alarm. Every lookup that fails says why in -/// the result, so a missing permission is named, not silent. -pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> String { - use aws_sdk_wafv2::error::ProvideErrorMetadata; - let (scope, region) = alarm.scope_and_region(); - let waf = waf_client(&session_in(session, ®ion)); - let mut lines: Vec = Vec::new(); - let failed = |what: &str, action: &str, code: Option<&str>, msg: Option<&str>| { +/// What [`gather`] read: the ticket's section, and the IAM actions the +/// team's role was refused (the install's setup item, `aws_role_reads`). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Gathered { + pub text: String, + pub refused: Vec, +} + +/// The evidence lines and the refusals met while reading them. +#[derive(Default)] +struct Notes { + lines: Vec, + refused: Vec, +} + +impl Notes { + /// 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) { - format!( - "Couldn't {what}: CoderHelm's AWS role doesn't allow {action} yet (the role update \ - on the AWS card adds it)." - ) + 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 { - format!( + self.lines.push(format!( "Couldn't {what}: {}", clip(msg.or(code).unwrap_or("no answer")) - ) + )); } - }; + } + + fn done(self, alarm: &WafAlarm) -> Gathered { + evidence(alarm, self.lines, self.refused) + } +} + +/// 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 { + if !refused.is_empty() { + lines.push(crate::aws_role_reads::run_line(&refused)); + } + Gathered { + text: render(alarm, &lines), + refused, + } +} + +/// Read the evidence for a WAF alarm. Every lookup that fails says why in +/// the result, so a missing permission is named, not silent. +pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> Gathered { + use aws_sdk_wafv2::error::ProvideErrorMetadata; + let (scope, region) = alarm.scope_and_region(); + let waf = waf_client(&session_in(session, ®ion)); + let mut n = Notes::default(); // The web ACL's ARN, by its name. let mut arn: Option = None; @@ -384,21 +623,22 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> } } Err(e) => { - lines.push(failed( + n.failed( "find the web ACL", "wafv2:ListWebACLs", e.code(), e.message(), - )); + ); break; } } } let Some(arn) = arn else { - if lines.is_empty() { - lines.push(format!("No web ACL named {} in {region}.", alarm.web_acl)); + if n.lines.is_empty() { + n.lines + .push(format!("No web ACL named {} in {region}.", alarm.web_acl)); } - return render(alarm, &lines); + return n.done(alarm); }; // The requests the rule matched. @@ -450,17 +690,20 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> ) }) .collect(); - lines.push(format!("Sampled requests the rule {} matched:", alarm.rule)); - lines.extend(summarize(&samples)); + n.lines + .push(format!("Sampled requests the rule {} matched:", alarm.rule)); + n.lines.extend(summarize(&samples)); } - Err(e) => lines.push(failed( + Err(e) => n.failed( "read the sampled requests", "wafv2:GetSampledRequests", e.code(), e.message(), - )), + ), }, - Err(e) => lines.push(format!("Couldn't read the sampled requests: {e}")), + Err(e) => n + .lines + .push(format!("Couldn't read the sampled requests: {e}")), } // TLS fingerprints come only from the web ACL's logs. @@ -475,19 +718,19 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> .map(|c| c.log_destination_configs().to_vec()) .unwrap_or_default(), Err(e) if e.code() == Some("WAFNonexistentItemException") => { - lines.push( + n.lines.push( "The web ACL has no logging, so no TLS fingerprints (JA3, JA4) are recorded." .into(), ); vec![] } Err(e) => { - lines.push(failed( + n.failed( "read where the web ACL logs", "wafv2:GetLoggingConfiguration", e.code(), e.message(), - )); + ); vec![] } }; @@ -495,21 +738,380 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> let bucket = destinations.iter().find_map(|d| bucket_of(d)); match (group, bucket, insights_query(&alarm.rule)) { (Some((region, name)), _, Some(query)) => { - lines.extend(fingerprints(session, ®ion, &name, &query, start, end).await); + n.lines + .extend(fingerprints(session, ®ion, &name, &query, start, end).await); } - (None, Some(bucket), _) => lines.push(format!( - "The web ACL logs to the S3 bucket {bucket}, which CoderHelm doesn't read: TLS \ - fingerprints (JA3, JA4) are in those log records (an Athena table on the bucket, \ - for one); the sampled requests above have the user agent and header order." - )), - (None, None, _) if !destinations.is_empty() => lines.push( + (None, Some(bucket), _) => { + let mut regions = vec![session.region.clone()]; + if region != session.region { + regions.push(region.clone()); + } + athena_fingerprints(session, ®ions, alarm, &bucket, start, end, &mut n).await; + } + (None, None, _) if !destinations.is_empty() => n.lines.push( "The web ACL logs through Firehose, which CoderHelm doesn't read: TLS fingerprints \ (JA3, JA4) need its log records." .into(), ), _ => {} } - render(alarm, &lines) + n.done(alarm) +} + +fn glue_client(s: &Session) -> aws_sdk_glue::Client { + use aws_sdk_glue::config::{BehaviorVersion, Credentials, Region}; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + aws_sdk_glue::Client::from_conf( + aws_sdk_glue::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(s.region.clone())) + .credentials_provider(creds) + .build(), + ) +} + +fn athena_client(s: &Session) -> aws_sdk_athena::Client { + use aws_sdk_athena::config::{BehaviorVersion, Credentials, Region}; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + aws_sdk_athena::Client::from_conf( + aws_sdk_athena::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(s.region.clone())) + .credentials_provider(creds) + .build(), + ) +} + +/// The Glue table over `bucket` in `region`: every database the role may +/// list, and the tables of those it may read (the WAF log databases; the +/// others refuse, which is expected). A refused listing is noted in `n`. +async fn find_log_table( + glue: &aws_sdk_glue::Client, + bucket: &str, + n: &mut Notes, +) -> Option { + use aws_sdk_glue::error::ProvideErrorMetadata; + let mut databases: Vec = Vec::new(); + let mut token: Option = None; + loop { + match glue + .get_databases() + .set_next_token(token.take()) + .max_results(100) + .send() + .await + { + Ok(o) => { + databases.extend(o.database_list().iter().map(|d| d.name().to_string())); + token = o.next_token().filter(|t| !t.is_empty()).map(str::to_string); + if token.is_none() || databases.len() >= MAX_LISTED { + break; + } + } + Err(e) => { + n.failed( + "list the Glue databases to find the web ACL's log table", + "glue:GetDatabases", + e.code(), + e.message(), + ); + return None; + } + } + } + for db in databases.iter().take(MAX_LISTED) { + let mut token: Option = None; + for _ in 0..5 { + let Ok(o) = glue + .get_tables() + .database_name(db) + .set_next_token(token.take()) + .send() + .await + else { + break; + }; + for t in o.table_list() { + let Some(sd) = t.storage_descriptor() else { + continue; + }; + if !sd.location().is_some_and(|l| table_in_bucket(l, bucket)) { + continue; + } + let keys: Vec = t + .partition_keys() + .iter() + .map(|k| k.name().to_lowercase()) + .collect(); + let params: std::collections::HashMap = t + .parameters() + .map(|p| p.iter().map(|(k, v)| (k.clone(), v.clone())).collect()) + .unwrap_or_default(); + return Some(LogTable { + database: db.clone(), + table: t.name().to_string(), + columns: sd + .columns() + .iter() + .map(|c| c.name().to_lowercase()) + .chain(keys.iter().cloned()) + .collect(), + date_partitions: date_partitions(&keys, ¶ms), + }); + } + token = o.next_token().filter(|t| !t.is_empty()).map(str::to_string); + if token.is_none() { + break; + } + } + } + None +} + +/// A workgroup the role may query: one of the account's, WAF log ones +/// first (`live::aws::waf_policy_template` allows only those), enabled, +/// with a results location; and whether it caps the bytes a query scans. +async fn find_workgroup(athena: &aws_sdk_athena::Client, n: &mut Notes) -> Option<(String, bool)> { + use aws_sdk_athena::error::ProvideErrorMetadata; + use aws_sdk_athena::types::WorkGroupState; + let mut names: Vec = Vec::new(); + let mut token: Option = None; + loop { + match athena + .list_work_groups() + .set_next_token(token.take()) + .max_results(50) + .send() + .await + { + Ok(o) => { + names.extend( + o.work_groups() + .iter() + .filter_map(|w| w.name()) + .map(str::to_string), + ); + token = o.next_token().filter(|t| !t.is_empty()).map(str::to_string); + if token.is_none() || names.len() >= MAX_LISTED { + break; + } + } + Err(e) => { + n.failed( + "list the Athena workgroups", + "athena:ListWorkGroups", + e.code(), + e.message(), + ); + return None; + } + } + } + names.sort_by_key(|w| !w.to_lowercase().contains("waf")); + for name in names.iter().take(MAX_LISTED) { + let Ok(o) = athena.get_work_group().work_group(name).send().await else { + continue; + }; + let Some(wg) = o.work_group() else { continue }; + if wg.state() == Some(&WorkGroupState::Disabled) { + continue; + } + let cfg = wg.configuration(); + let has_results = cfg + .and_then(|c| c.result_configuration()) + .and_then(|r| r.output_location()) + .is_some_and(|l| l.starts_with("s3://")); + if !has_results { + continue; + } + let capped = cfg + .and_then(|c| c.bytes_scanned_cutoff_per_query()) + .is_some_and(|b| b > 0); + return Some((name.clone(), capped)); + } + None +} + +/// The rule's matches in the web ACL's logs held in S3, through Athena: +/// the Glue table over the bucket, a workgroup the role may query, one +/// bounded query (stopped if it runs long), its rows. +async fn athena_fingerprints( + session: &Session, + regions: &[String], + alarm: &WafAlarm, + bucket: &str, + start: i64, + end: i64, + n: &mut Notes, +) { + use aws_sdk_athena::error::ProvideErrorMetadata; + use aws_sdk_athena::types::{QueryExecutionContext, QueryExecutionState}; + let mut found: Option<(Session, LogTable)> = None; + for r in regions { + let s = session_in(session, r); + if let Some(t) = find_log_table(&glue_client(&s), bucket, n).await { + found = Some((s, t)); + break; + } + if !n.refused.is_empty() { + break; + } + } + let Some((s, table)) = found else { + if n.refused.is_empty() { + n.lines.push(format!( + "The web ACL logs to the S3 bucket {bucket}, and no Glue table CoderHelm's role \ + may read is on it, so its log records (with the TLS fingerprints JA3 and JA4) \ + weren't queried; the sampled requests above have the user agent and header order." + )); + } + return; + }; + let athena = athena_client(&s); + let Some((workgroup, capped)) = find_workgroup(&athena, n).await else { + if n.refused.is_empty() { + n.lines.push(format!( + "The web ACL's logs are in the Athena table {}.{}, and no Athena workgroup \ + CoderHelm's role may query has a results location, so they weren't queried.", + table.database, table.table + )); + } + return; + }; + if table.date_partitions.is_empty() && !capped { + n.lines.push(format!( + "The web ACL's logs are in the Athena table {}.{}, which has no projected date \ + partition to bound a query to the last three hours, and the workgroup {workgroup} \ + sets no scan limit, so they weren't queried (it would read the whole bucket).", + table.database, table.table + )); + return; + } + let Some(query) = athena_query(&table, &alarm.rule, start, end) else { + n.lines.push(format!( + "The table {}.{} on the bucket {bucket} isn't one of WAF's log tables (it lacks \ + timestamp, httprequest or terminatingruleid), so it wasn't queried.", + table.database, table.table + )); + return; + }; + let id = match athena + .start_query_execution() + .query_string(&query) + .work_group(&workgroup) + .query_execution_context( + QueryExecutionContext::builder() + .database(&table.database) + .build(), + ) + .send() + .await + { + Ok(o) => o.query_execution_id().unwrap_or_default().to_string(), + Err(e) => { + n.failed( + "query the web ACL's logs in S3", + "athena:StartQueryExecution", + e.code(), + e.message(), + ); + return; + } + }; + let started = std::time::Instant::now(); + loop { + tokio::time::sleep(Duration::from_millis(1_500)).await; + let state = athena + .get_query_execution() + .query_execution_id(&id) + .send() + .await + .ok() + .and_then(|o| { + o.query_execution().and_then(|q| q.status()).and_then(|st| { + st.state() + .cloned() + .map(|s| (s, st.state_change_reason().map(str::to_string))) + }) + }); + match state { + Some((QueryExecutionState::Succeeded, _)) => break, + Some((QueryExecutionState::Failed | QueryExecutionState::Cancelled, why)) => { + n.lines.push(format!( + "The query of the web ACL's logs ({}.{}) didn't finish: {}", + table.database, + table.table, + clip(why.as_deref().unwrap_or("no reason given")) + )); + return; + } + _ if started.elapsed() > ATHENA_WAIT => { + // Only this run's own query is ever stopped. + let _ = athena + .stop_query_execution() + .query_execution_id(&id) + .send() + .await; + n.lines.push(format!( + "The query of the web ACL's logs ({}.{}) took longer than {} seconds and was \ + stopped.", + table.database, + table.table, + ATHENA_WAIT.as_secs() + )); + return; + } + _ => {} + } + } + match athena + .get_query_results() + .query_execution_id(&id) + .max_results(ATHENA_ROWS + 1) + .send() + .await + { + Ok(o) => { + let rows: Vec>> = o + .result_set() + .map(|r| { + r.rows() + .iter() + .map(|row| { + row.data() + .iter() + .map(|d| d.var_char_value().map(str::to_string)) + .collect() + }) + .collect() + }) + .unwrap_or_default(); + n.lines.push(format!( + "Matching requests in the web ACL's logs in S3 (Athena table {}.{}), by TLS \ + fingerprint, user agent, accept language, path and cookie presence:", + table.database, table.table + )); + n.lines.extend(athena_lines(&rows)); + } + Err(e) => n.failed( + "read the query's results", + "athena:GetQueryResults", + e.code(), + e.message(), + ), + } } /// The rule's matches in the web ACL's log group, by TLS fingerprint and @@ -675,6 +1277,156 @@ mod tests { assert_eq!(bucket_of("arn:aws:s3:::another-bucket"), None); } + /// The Glue table over a web ACL's log bucket, as WAF's documented + /// table defines it, with a projected hourly partition. + pub(crate) fn waf_log_table() -> LogTable { + let keys = vec!["log_time".to_string()]; + let params: std::collections::HashMap = [ + ("projection.enabled", "true"), + ("projection.log_time.type", "date"), + ("projection.log_time.format", "yyyy/MM/dd/HH"), + ] + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + LogTable { + database: "acme_waf_logs".into(), + table: "waf_logs".into(), + columns: [ + "timestamp", + "terminatingruleid", + "action", + "httprequest", + "ja3fingerprint", + "ja4fingerprint", + "nonterminatingmatchingrules", + "log_time", + ] + .iter() + .map(|c| c.to_string()) + .collect(), + date_partitions: date_partitions(&keys, ¶ms), + } + } + + #[test] + fn the_athena_query_is_bounded_to_the_rule_and_keeps_no_private_values() { + let t = waf_log_table(); + assert_eq!( + t.date_partitions, + vec![("log_time".into(), "%Y/%m/%d/%H".into())] + ); + // 2026-11-17 12:00 UTC, three hours back. + let end = 1_794_916_800; + let q = athena_query(&t, "ExampleCrawlerCount", end - WINDOW_SECS, end).unwrap(); + assert!(q.contains("FROM \"acme_waf_logs\".\"waf_logs\""), "{q}"); + assert!( + q.contains("\"timestamp\" BETWEEN 1794906000000 AND 1794916800000"), + "{q}" + ); + assert!( + q.contains("\"log_time\" BETWEEN '2026/11/17/09' AND '2026/11/17/12'"), + "{q}" + ); + assert!(q.contains("terminatingruleid = 'ExampleCrawlerCount'")); + assert!(q.contains("r.ruleid = 'ExampleCrawlerCount'")); + assert!(q.contains("LIMIT 20")); + for kept in [ + "ja4fingerprint AS ja4", + "ja3fingerprint AS ja3", + "'user-agent'", + "'accept-language'", + "AS path", + "AS has_cookie", + "count(*) AS requests", + ] { + assert!(q.contains(kept), "{kept}"); + } + // No client address, no cookie or other header value, no query string. + for never in [ + "clientip", + "x.value) = 'cookie'", + "args", + "httprequest.headers AS", + "SELECT *", + ] { + assert!(!q.contains(never), "{never}: {q}"); + } + // A cookie header is only counted, never read. + assert!(q.contains( + "cardinality(filter(httprequest.headers, x -> lower(x.name) = 'cookie')) > 0" + )); + // Names that can't be quoted safely, or a table that isn't WAF's. + assert_eq!(athena_query(&t, "a' OR 1=1 --", 0, 1), None); + let mut bad = waf_log_table(); + bad.table = "waf\"; DROP".into(); + assert_eq!(athena_query(&bad, "ExampleCrawlerCount", 0, 1), None); + let mut other = waf_log_table(); + other.columns.retain(|c| c != "httprequest"); + assert_eq!(athena_query(&other, "ExampleCrawlerCount", 0, 1), None); + // An older table without fingerprint columns still reads. + let mut old = waf_log_table(); + old.columns.retain(|c| !c.ends_with("fingerprint")); + let q = athena_query(&old, "ExampleCrawlerCount", 0, 1).unwrap(); + assert!(q.contains("CAST(NULL AS varchar) AS ja4")); + } + + #[test] + fn projected_date_formats_sort_as_text_or_are_left_out() { + assert_eq!(date_format("yyyy/MM/dd/HH").as_deref(), Some("%Y/%m/%d/%H")); + assert_eq!(date_format("yyyy-MM-dd").as_deref(), Some("%Y-%m-%d")); + assert_eq!(date_format("dd/MM/yyyy"), None); + assert_eq!(date_format("yyyy/MM/dd'T'HH"), None); + assert!(table_in_bucket( + "s3://aws-waf-logs-acme/AWSLogs/", + "aws-waf-logs-acme" + )); + assert!(table_in_bucket( + "s3://aws-waf-logs-acme", + "aws-waf-logs-acme" + )); + assert!(!table_in_bucket( + "s3://aws-waf-logs-acme-old/x", + "aws-waf-logs-acme" + )); + } + + #[test] + fn athena_rows_become_lines_with_only_what_is_kept() { + let row = |v: &[&str]| v.iter().map(|x| Some(x.to_string())).collect::>(); + let rows = vec![ + row(&[ + "ja4", + "ja3", + "ua", + "accept_language", + "path", + "has_cookie", + "requests", + ]), + row(&[ + "t13d1516h2_8daaf6152771_e5627efa2ab1", + "773906b0efdefa24a7f2b8eb6985bf37", + "CrawlerA/3.1", + "en-US", + "/listings/42", + "false", + "812", + ]), + ]; + let lines = athena_lines(&rows); + assert_eq!(lines.len(), 1); + assert!(lines[0].contains("812 requests")); + assert!(lines[0].contains("JA4 t13d1516h2_8daaf6152771_e5627efa2ab1")); + assert!(lines[0].contains("CrawlerA/3.1")); + assert!(lines[0].contains("no cookie")); + assert_eq!( + athena_lines(&rows[..1]), + vec![" - none in the last three hours"] + ); + assert!(athena_lines(&[]).is_empty()); + } + #[test] fn the_evidence_is_added_once() { let ev = render(&waf_alarm(BODY).unwrap(), &["x".into()]); diff --git a/services/common/src/aws_role_reads.rs b/services/common/src/aws_role_reads.rs new file mode 100644 index 000000000..bd70dd981 --- /dev/null +++ b/services/common/src/aws_role_reads.rs @@ -0,0 +1,311 @@ +//! A read an alert route needs that the team's connected AWS role lacks: +//! one install-level setup item, never a question on a run. +//! +//! A run an alert rule started for an AWS WAF alarm ended `needs_input` +//! with a long question asking a person to grant the team's read-only role +//! WAF and Athena access, with "Grant access" as the default if nobody +//! answered. The role's setup script had never added any WAF read, so every +//! such run would have asked the same thing. A permission the role lacks is +//! the install's, like a GitHub App permission +//! (`github_grants::install_item`): it is recorded here once per connected +//! account when a read is refused ([`record`]), the install's setup checks +//! show it as one item with the one-line CloudShell update +//! (`live::aws::waf_update_line`), and the first read that works again +//! clears it ([`clear`]). A run names the item in one line ([`run_line`]) +//! and goes on with what it could read. +//! +//! [`is_install_grant`] is how the stop judge and the hand-back list know a +//! question or a blocker is this item, so neither can turn it into a wait +//! on a person. + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; + +use crate::github_grants::INSTALL_LEVEL; + +/// The setup item's name, as the install's setup checks show it. +pub const ITEM_LABEL: &str = "AWS role reads"; +/// The setup check's key. +pub const CHECK_KEY: &str = "aws_role_reads"; +/// One record per connected account, in the settings table under the team. +const SK_PREFIX: &str = "AWS_ROLE_GAP#"; +/// Most actions kept on one record. +const MAX_ACTIONS: usize = 20; + +/// Reads a team's connected AWS role was refused, in one account. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Gap { + pub account: String, + /// The connected role, for the update line (its name). + pub role_arn: String, + /// The IAM actions AWS refused, once each. + pub actions: Vec, + /// What needed them, in a few words (`an AWS WAF alarm's evidence`). + pub needed_for: String, + pub seen_at: String, +} + +/// Pure: the one line a run says about the missing reads: what was +/// refused, and that it is the install's setup item, never this run's +/// question. +pub fn run_line(actions: &[String]) -> String { + format!( + "CoderHelm's AWS role was refused {}: that is the install's setup item \"{ITEM_LABEL}\" \ + (one line in AWS CloudShell), asked once for the whole install {INSTALL_LEVEL}. This run \ + asks nobody for it and goes on with what it could read.", + if actions.is_empty() { + "a read".to_string() + } else { + actions.join(", ") + } + ) +} + +/// Pure: the record for reads `account`'s role was refused, or none when +/// nothing was refused. +pub fn gap( + account: &str, + role_arn: &str, + refused: &[String], + needed_for: &str, + now: &str, +) -> Option { + (!refused.is_empty() && is_account(account)).then(|| Gap { + account: account.to_string(), + role_arn: role_arn.to_string(), + actions: refused.to_vec(), + needed_for: needed_for.to_string(), + seen_at: now.to_string(), + }) +} + +/// AWS services whose `service:Action` names mean an AWS permission. +const AWS_SERVICES: &[&str] = &[ + "wafv2", + "waf", + "athena", + "glue", + "s3", + "logs", + "cloudwatch", + "iam", + "kms", + "ecs", + "rds", + "rds-data", + "redshift", + "redshift-data", + "secretsmanager", + "lambda", + "ec2", + "ssm", + "sts", +]; + +/// Words that name an AWS service the role reads. +const AWS_WORDS: &[&str] = &[ + "wafv2", + "waf", + "athena", + "glue", + "cloudwatch", + "aws-waf-logs", + "s3", + "iam", +]; + +/// Words that name the team's connected AWS role. +const ROLE_WORDS: &[&str] = &[ + "read-only role", + "readonly role", + "read only role", + "coderhelmreadonly", + "coderhelmlogreader", + "aws role", + "iam role", + "coderhelm's role", + "team's role", + "role's policy", + "role policy", +]; + +/// Words that ask for access. +const ASK_WORDS: &[&str] = &[ + "grant", + "permission", + "access", + "allow", + "denied", + "lacks", + "missing", + "add ", +]; + +/// Pure: whether the text has an AWS IAM action (`wafv2:GetSampledRequests`). +fn has_aws_action(t: &str) -> bool { + t.split(|c: char| c.is_whitespace() || "`'\"(),;".contains(c)) + .filter_map(|w| w.split_once(':')) + .any(|(svc, act)| { + AWS_SERVICES.contains(&svc) + && act + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '*') + }) +} + +/// Pure: whether a question, a blocker or a step asks a person for a read +/// the team's connected AWS role lacks (or names this item). That is the +/// install's setup item, never a run's question or wait. +pub fn is_install_grant(text: &str) -> bool { + let t = text.to_lowercase(); + if t.contains(&ITEM_LABEL.to_lowercase()) && t.contains(&INSTALL_LEVEL.to_lowercase()) { + return true; + } + let words: Vec<&str> = t + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) + .filter(|w| !w.is_empty()) + .collect(); + let aws = has_aws_action(&t) || words.iter().any(|w| AWS_WORDS.contains(w)); + let role = ROLE_WORDS.iter().any(|w| t.contains(w)); + let asks = ASK_WORDS.iter().any(|w| t.contains(w)); + aws && role && asks +} + +fn attr(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn is_account(a: &str) -> bool { + a.len() == 12 && a.chars().all(|c| c.is_ascii_digit()) +} + +/// Records the reads `gap.account`'s role was refused (best effort). One +/// record per account: a later refusal adds its actions to it. +pub async fn record(dynamo: &DynamoClient, table: &str, team_id: &str, gap: &Gap) { + if !is_account(&gap.account) || gap.actions.is_empty() { + return; + } + let mut actions: Vec = list(dynamo, table, team_id) + .await + .into_iter() + .find(|g| g.account == gap.account) + .map(|g| g.actions) + .unwrap_or_default(); + for a in &gap.actions { + if !actions.contains(a) { + actions.push(a.clone()); + } + } + actions.truncate(MAX_ACTIONS); + let res = dynamo + .put_item() + .table_name(table) + .item("pk", attr(team_id)) + .item("sk", attr(&format!("{SK_PREFIX}{}", gap.account))) + .item("account", attr(&gap.account)) + .item("role_arn", attr(&gap.role_arn)) + .item( + "actions", + AttributeValue::L(actions.iter().map(|a| attr(a)).collect()), + ) + .item("needed_for", attr(&gap.needed_for)) + .item("seen_at", attr(&gap.seen_at)) + .send() + .await; + if let Err(e) = res { + tracing::warn!(team_id, error = %e, "Could not record the AWS role's missing reads"); + } +} + +/// Clears `account`'s record once its role reads again (best effort). +pub async fn clear(dynamo: &DynamoClient, table: &str, team_id: &str, account: &str) { + if !is_account(account) { + return; + } + let _ = dynamo + .delete_item() + .table_name(table) + .key("pk", attr(team_id)) + .key("sk", attr(&format!("{SK_PREFIX}{account}"))) + .send() + .await; +} + +/// Every account whose role lacks a read, for the setup check. +pub async fn list(dynamo: &DynamoClient, table: &str, team_id: &str) -> Vec { + let out = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :p AND begins_with(sk, :s)") + .expression_attribute_values(":p", attr(team_id)) + .expression_attribute_values(":s", attr(SK_PREFIX)) + .send() + .await; + let Ok(out) = out else { + return Vec::new(); + }; + let s = |i: &std::collections::HashMap, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + out.items() + .iter() + .map(|i| Gap { + account: s(i, "account"), + role_arn: s(i, "role_arn"), + actions: i + .get("actions") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|x| x.as_s().ok().cloned()).collect()) + .unwrap_or_default(), + needed_for: s(i, "needed_for"), + seen_at: s(i, "seen_at"), + }) + .filter(|g| is_account(&g.account)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The question the alarm run asked, in its own words. + const ASKED: &str = "Can someone grant the team's read-only role WAF and Athena access? \ + wafv2:ListWebACLs and wafv2:GetSampledRequests were denied for CoderHelm's role."; + + #[test] + fn asking_for_the_roles_aws_reads_is_the_install_item() { + assert!(is_install_grant(ASKED)); + assert!(is_install_grant( + "Add athena:StartQueryExecution to the CoderhelmReadOnly role" + )); + assert!(is_install_grant(&run_line(&["wafv2:ListWebACLs".into()]))); + // Not AWS, not the role, or not asking for access. + for other in [ + "Grant the GitHub app Actions: write", + "Which page should the export button go on?", + "The WAF rule should block crawler A by JA4", + "Grant access to the staging database password", + "The read-only role reads WAF logs", + ] { + assert!(!is_install_grant(other), "{other}"); + } + } + + #[test] + fn the_run_line_names_the_item_once_for_the_install() { + let l = run_line(&[ + "wafv2:ListWebACLs".into(), + "wafv2:GetSampledRequests".into(), + ]); + assert!(l.contains("\"AWS role reads\"")); + assert!(l.contains(INSTALL_LEVEL)); + assert!(l.contains("wafv2:ListWebACLs, wafv2:GetSampledRequests")); + assert!(l.contains("asks nobody")); + // A recorded refusal on an install-level item is never a person's grant. + assert!(!crate::person_gate::grant_backed(&l)); + } +} diff --git a/services/common/src/handback.rs b/services/common/src/handback.rs index cc54edf65..a14e9adc6 100644 --- a/services/common/src/handback.rs +++ b/services/common/src/handback.rs @@ -128,6 +128,10 @@ impl HandBack { /// From what the stop judge found only a person has. pub fn of_person_only(p: crate::stop_judge::PersonOnly, question: &str) -> Option { use crate::stop_judge::PersonOnly as P; + // A read the team's AWS role lacks is the install's setup item. + if crate::aws_role_reads::is_install_grant(question) { + return None; + } let why = match p { P::ProductChoice => HumanOnly::ProductDecision, P::Access => { @@ -160,8 +164,13 @@ impl HandBack { /// Reads a reason on the list from words a run, a check or the judge wrote. /// `None` when they name none, which is the case for every stall, red -/// check, tool error, time limit or budget. +/// check, tool error, time limit or budget, and for a read the team's +/// connected AWS role lacks: that is the install's setup item +/// (`aws_role_reads`), asked once for the whole install, never a run's wait. pub fn human_only_in(text: &str) -> Option { + if crate::aws_role_reads::is_install_grant(text) { + return None; + } let t = text.to_lowercase(); let any = |marks: &[&str]| marks.iter().any(|m| t.contains(m)); if any(&[ @@ -255,4 +264,16 @@ mod tests { Some(HumanOnly::Credential) ); } + + #[test] + fn a_read_the_aws_role_lacks_is_the_install_item_never_a_wait() { + let asked = "Grant access: the team's read-only role was denied wafv2:ListWebACLs and \ + wafv2:GetSampledRequests, and no source can read the WAF logs in Athena"; + assert_eq!(human_only_in(asked), None); + // Other access stays on the list. + assert_eq!( + human_only_in("Grant access to the repository: the app isn't installed"), + Some(HumanOnly::MissingAccess) + ); + } } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 31813a1bf..8a5cd0019 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -72,6 +72,8 @@ pub mod agent_policy; pub mod alarm_evidence; pub mod alert_episodes; pub mod alert_notify; +/// A read the team's AWS role lacks: one install-level setup item. +pub mod aws_role_reads; pub mod coder_shell; /// Chat notifications (Teams and Slack): one message model, a renderer per /// channel, sealed webhook URLs. diff --git a/services/common/src/live/aws.rs b/services/common/src/live/aws.rs index 66d7b223a..ba7d16ebc 100644 --- a/services/common/src/live/aws.rs +++ b/services/common/src/live/aws.rs @@ -398,6 +398,222 @@ pub fn warehouse_policy_template(account: &str) -> serde_json::Value { }) } +/// The role's inline policy for AWS WAF and its logs. +pub const WAF_POLICY_NAME: &str = "coderhelm-read-waf"; + +/// Placeholders the setup script fills with what it finds in the account: +/// the Athena workgroups for WAF logs (`WAF_WORKGROUPS`, their ARNs), the +/// Glue databases and tables over `aws-waf-logs-*` buckets (`WAF_GLUE`), +/// and where each of those workgroups writes its query results +/// (`WAF_RESULT_OBJECTS`, `WAF_RESULT_BUCKETS`, `WAF_RESULT_PREFIXES`). +/// Each sits alone in a JSON array, as a string, so a list of quoted ARNs +/// replaces it. +pub const WAF_PLACEHOLDERS: &[&str] = &[ + "WAF_WORKGROUPS", + "WAF_GLUE", + "WAF_RESULT_OBJECTS", + "WAF_RESULT_BUCKETS", + "WAF_RESULT_PREFIXES", +]; + +/// What the WAF policy never allows, whatever else on the role does: every +/// change to WAF, Athena, Glue or a bucket, and Glue's connections (they +/// carry passwords). +const WAF_NEVER: &[&str] = &[ + "wafv2:Create*", + "wafv2:Update*", + "wafv2:Delete*", + "wafv2:Put*", + "wafv2:Associate*", + "wafv2:Disassociate*", + "wafv2:Tag*", + "wafv2:Untag*", + "athena:Create*", + "athena:Update*", + "athena:Delete*", + "athena:Put*", + "athena:Import*", + "athena:Tag*", + "athena:Untag*", + "glue:Create*", + "glue:Update*", + "glue:Delete*", + "glue:Put*", + "glue:Batch*", + "glue:GetConnection", + "glue:GetConnections", + "s3:Delete*", + "s3:PutBucket*", + "s3:PutObjectAcl", + "s3:PutObjectTagging", +]; + +/// Reads AWS WAF (web ACLs, sampled requests, where a web ACL logs) and, +/// with `athena`, the web ACL's logs held in S3 through their Athena table: +/// read-only queries in the WAF log workgroups the script found, over the +/// Glue tables on `aws-waf-logs-*` buckets, with results written only +/// under those workgroups' own results prefix. Everything that changes +/// WAF, Athena, Glue or a bucket is denied, and so is any object written +/// anywhere but the results prefix. Without `athena` (no WAF log +/// workgroup or table in the account) it reads WAF and the log buckets' +/// objects only, and writes nothing. +pub fn waf_policy_template(account: &str, athena: bool) -> serde_json::Value { + let mut statements = vec![ + json!({ + "Sid": "ReadWaf", + "Effect": "Allow", + "Action": ["wafv2:Get*", "wafv2:List*"], + "Resource": "*" + }), + json!({ + "Sid": "ReadWafLogObjects", + "Effect": "Allow", + "Action": ["s3:GetObject"], + "Resource": "arn:aws:s3:::aws-waf-logs-*/*" + }), + json!({ + "Sid": "ListWafLogBuckets", + "Effect": "Allow", + "Action": ["s3:ListBucket", "s3:GetBucketLocation"], + "Resource": "arn:aws:s3:::aws-waf-logs-*" + }), + ]; + if athena { + statements.extend([ + json!({ + "Sid": "FindWafLogWorkgroups", + "Effect": "Allow", + "Action": ["athena:ListWorkGroups"], + "Resource": "*" + }), + json!({ + "Sid": "FindWafLogDatabases", + "Effect": "Allow", + "Action": ["glue:GetDatabases"], + "Resource": [ + format!("arn:aws:glue:*:{account}:catalog"), + format!("arn:aws:glue:*:{account}:database/*") + ] + }), + json!({ + "Sid": "ReadWafLogTables", + "Effect": "Allow", + "Action": ["glue:Get*"], + "Resource": [format!("arn:aws:glue:*:{account}:catalog"), "WAF_GLUE".to_string()] + }), + json!({ + "Sid": "QueryWafLogs", + "Effect": "Allow", + "Action": ["athena:StartQueryExecution", "athena:Get*", "athena:StopQueryExecution"], + "Resource": ["WAF_WORKGROUPS"] + }), + json!({ + "Sid": "WriteQueryResultsOnly", + "Effect": "Allow", + "Action": ["s3:PutObject", "s3:GetObject"], + "Resource": ["WAF_RESULT_OBJECTS"] + }), + json!({ + "Sid": "FindQueryResults", + "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket"], + "Resource": ["WAF_RESULT_BUCKETS"], + "Condition": { "StringLike": { "s3:prefix": ["WAF_RESULT_PREFIXES"] } } + }), + json!({ + "Sid": "NoWritesButQueryResults", + "Effect": "Deny", + "Action": "s3:PutObject", + "NotResource": ["WAF_RESULT_OBJECTS"] + }), + ]); + } else { + statements.push(json!({ + "Sid": "NoWrites", + "Effect": "Deny", + "Action": "s3:PutObject", + "Resource": "*" + })); + } + statements.push(json!({ + "Sid": "NeverChange", + "Effect": "Deny", + "Action": WAF_NEVER, + "Resource": "*" + })); + json!({ "Version": "2012-10-17", "Statement": statements }) +} + +/// The part of the setup script that finds the account's WAF log +/// workgroups and tables and puts [`WAF_POLICY_NAME`] on `$ROLE`. Needs +/// `ROLE`, `REGION` and `ACCOUNT`; asks nothing, and changes nothing but +/// that one policy, so running it again is safe. +fn waf_policy_step() -> String { + let athena = waf_policy_template("ACCOUNT_ID", true).to_string(); + let plain = waf_policy_template("ACCOUNT_ID", false).to_string(); + format!( + r##"WAF_WG=""; WAF_OBJ=""; WAF_BKT=""; WAF_PFX=""; WAF_GLUE="" +for W in $(aws athena list-work-groups --region "$REGION" --query 'WorkGroups[].Name' --output text 2>/dev/null | tr '\t' '\n' | grep -i waf || true); do + OUT=$(aws athena get-work-group --region "$REGION" --work-group "$W" --query 'WorkGroup.Configuration.ResultConfiguration.OutputLocation' --output text 2>/dev/null || true) + case "$OUT" in s3://*) ;; *) continue;; esac + B="${{OUT#s3://}}"; B="${{B%%/*}}"; P="${{OUT#s3://$B}}"; P="${{P#/}}" + WAF_WG="$WAF_WG${{WAF_WG:+,}}\"arn:aws:athena:$REGION:$ACCOUNT:workgroup/$W\"" + WAF_OBJ="$WAF_OBJ${{WAF_OBJ:+,}}\"arn:aws:s3:::$B/$P*\"" + WAF_BKT="$WAF_BKT${{WAF_BKT:+,}}\"arn:aws:s3:::$B\"" + WAF_PFX="$WAF_PFX${{WAF_PFX:+,}}\"$P*\"" +done +for D in $(aws glue get-databases --region "$REGION" --query 'DatabaseList[].Name' --output text 2>/dev/null | tr '\t' '\n'); do + T=$(aws glue get-tables --region "$REGION" --database-name "$D" --query "TableList[?StorageDescriptor.Location && starts_with(StorageDescriptor.Location, 's3://aws-waf-logs-')].Name" --output text 2>/dev/null || true) + if [ -n "$T" ] && [ "$T" != "None" ]; then + WAF_GLUE="$WAF_GLUE${{WAF_GLUE:+,}}\"arn:aws:glue:$REGION:$ACCOUNT:database/$D\",\"arn:aws:glue:$REGION:$ACCOUNT:table/$D/*\"" + fi +done +if [ -n "$WAF_WG" ] && [ -n "$WAF_GLUE" ]; then + WAF_DOC=$(echo '{athena}' | sed -e "s#\"WAF_WORKGROUPS\"#$WAF_WG#g" -e "s#\"WAF_GLUE\"#$WAF_GLUE#g" -e "s#\"WAF_RESULT_OBJECTS\"#$WAF_OBJ#g" -e "s#\"WAF_RESULT_BUCKETS\"#$WAF_BKT#g" -e "s#\"WAF_RESULT_PREFIXES\"#$WAF_PFX#g" -e "s#ACCOUNT_ID#$ACCOUNT#g") + WAF_SAID="AWS WAF, and its logs in S3 through Athena (results only under the workgroup's results prefix)" +else + WAF_DOC=$(echo '{plain}' | sed -e "s#ACCOUNT_ID#$ACCOUNT#g") + WAF_SAID="AWS WAF and its log buckets (no Athena workgroup with waf in its name, or no Glue table on an aws-waf-logs- bucket, in $REGION)" +fi +aws iam put-role-policy --role-name "$ROLE" --policy-name {WAF_POLICY_NAME} --policy-document "$WAF_DOC" +echo "WAF reads ready: $WAF_SAID." +"## + ) +} + +/// Pure: a role name the update line may name. +fn is_role_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 64 + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || "+=,.@_-".contains(c)) +} + +/// The update that adds only [`WAF_POLICY_NAME`] to an existing role +/// (`role`, its name), for a team whose role was made before it: no +/// questions, nothing pasted back, and safe to run again. +pub fn waf_update_script(role: &str) -> Option { + is_role_name(role).then(|| { + format!( + "coderhelm_waf_update() (\nset -euo pipefail\nROLE={role}\nREGION=\"${{AWS_REGION:-us-east-1}}\"\nACCOUNT=$(aws sts get-caller-identity --query Account --output text)\necho \"Adding read-only AWS WAF access to $ROLE in account $ACCOUNT ($REGION)...\"\n{}\n)\ncoderhelm_waf_update\n", + waf_policy_step() + ) + }) +} + +/// [`waf_update_script`] as the one line a person pastes into AWS +/// CloudShell in the role's account (and the region of its Athena +/// workgroup). +pub fn waf_update_line(role_arn: &str) -> Option { + let role = role_arn.rsplit('/').next().unwrap_or(role_arn); + let script = waf_update_script(role)?; + Some(format!( + "echo {} | base64 -d | bash", + STANDARD.encode(script) + )) +} + /// The script a team pastes into AWS CloudShell. It creates (or updates) the /// role, lets them pick a database to share, creates a database user that can /// only read, and prints the line to paste back. It defines a function and @@ -409,6 +625,7 @@ pub fn setup_script(our_account: &str, external_id: &str) -> String { let logs = logs_policy().to_string(); let db = database_policy_template("ACCOUNT_ID").to_string(); let wh = warehouse_policy_template("ACCOUNT_ID").to_string(); + let waf = waf_policy_step(); format!( r#"coderhelm_setup() ( set -euo pipefail @@ -422,8 +639,8 @@ else aws iam create-role --role-name "$ROLE" --description "Coderhelm: read-only access to logs and one database" --max-session-duration 3600 --assume-role-policy-document '{trust}' >/dev/null fi aws iam put-role-policy --role-name "$ROLE" --policy-name coderhelm-read-logs --policy-document '{logs}' -ROLE_ARN=$(aws iam get-role --role-name "$ROLE" --query Role.Arn --output text) -echo "Role ready: $ROLE_ARN (it can read logs; it can't change anything)." +{waf}ROLE_ARN=$(aws iam get-role --role-name "$ROLE" --query Role.Arn --output text) +echo "Role ready: $ROLE_ARN (it can read logs and AWS WAF; it can't change anything)." DB_PART="" CLUSTERS=$(aws rds describe-db-clusters --region "$REGION" --query "DBClusters[?Engine=='aurora-postgresql' && HttpEndpointEnabled].DBClusterIdentifier" --output text | tr '\t' '\n' | sed '/^$/d') if [ -n "$CLUSTERS" ]; then @@ -749,6 +966,7 @@ pub fn rdsdata_client(s: &Session) -> aws_sdk_rdsdata::Client { #[cfg(test)] mod tests { use super::*; + use serde_json::Value; const ROLE: &str = "arn:aws:iam::123456789012:role/CoderhelmReadOnly"; @@ -978,6 +1196,157 @@ mod tests { assert!(new_external_id().starts_with("coderhelm-")); } + #[test] + fn the_waf_policy_reads_waf_and_queries_only_its_logs() { + let never = serde_json::to_value(WAF_NEVER).unwrap(); + assert_eq!( + waf_policy_template("111122223333", true), + json!({ + "Version": "2012-10-17", + "Statement": [ + { "Sid": "ReadWaf", "Effect": "Allow", + "Action": ["wafv2:Get*", "wafv2:List*"], "Resource": "*" }, + { "Sid": "ReadWafLogObjects", "Effect": "Allow", + "Action": ["s3:GetObject"], "Resource": "arn:aws:s3:::aws-waf-logs-*/*" }, + { "Sid": "ListWafLogBuckets", "Effect": "Allow", + "Action": ["s3:ListBucket", "s3:GetBucketLocation"], + "Resource": "arn:aws:s3:::aws-waf-logs-*" }, + { "Sid": "FindWafLogWorkgroups", "Effect": "Allow", + "Action": ["athena:ListWorkGroups"], "Resource": "*" }, + { "Sid": "FindWafLogDatabases", "Effect": "Allow", + "Action": ["glue:GetDatabases"], + "Resource": ["arn:aws:glue:*:111122223333:catalog", + "arn:aws:glue:*:111122223333:database/*"] }, + { "Sid": "ReadWafLogTables", "Effect": "Allow", "Action": ["glue:Get*"], + "Resource": ["arn:aws:glue:*:111122223333:catalog", "WAF_GLUE"] }, + { "Sid": "QueryWafLogs", "Effect": "Allow", + "Action": ["athena:StartQueryExecution", "athena:Get*", + "athena:StopQueryExecution"], + "Resource": ["WAF_WORKGROUPS"] }, + { "Sid": "WriteQueryResultsOnly", "Effect": "Allow", + "Action": ["s3:PutObject", "s3:GetObject"], + "Resource": ["WAF_RESULT_OBJECTS"] }, + { "Sid": "FindQueryResults", "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket"], + "Resource": ["WAF_RESULT_BUCKETS"], + "Condition": { "StringLike": { "s3:prefix": ["WAF_RESULT_PREFIXES"] } } }, + { "Sid": "NoWritesButQueryResults", "Effect": "Deny", + "Action": "s3:PutObject", "NotResource": ["WAF_RESULT_OBJECTS"] }, + { "Sid": "NeverChange", "Effect": "Deny", "Action": never, "Resource": "*" } + ] + }) + ); + assert_eq!( + waf_policy_template("111122223333", false), + json!({ + "Version": "2012-10-17", + "Statement": [ + { "Sid": "ReadWaf", "Effect": "Allow", + "Action": ["wafv2:Get*", "wafv2:List*"], "Resource": "*" }, + { "Sid": "ReadWafLogObjects", "Effect": "Allow", + "Action": ["s3:GetObject"], "Resource": "arn:aws:s3:::aws-waf-logs-*/*" }, + { "Sid": "ListWafLogBuckets", "Effect": "Allow", + "Action": ["s3:ListBucket", "s3:GetBucketLocation"], + "Resource": "arn:aws:s3:::aws-waf-logs-*" }, + { "Sid": "NoWrites", "Effect": "Deny", "Action": "s3:PutObject", + "Resource": "*" }, + { "Sid": "NeverChange", "Effect": "Deny", "Action": never, "Resource": "*" } + ] + }) + ); + // Every allow is a read but the one write, which is held to the + // workgroup's results prefix by its own deny. + for athena in [true, false] { + let p = waf_policy_template("1", athena); + for st in p["Statement"].as_array().unwrap() { + let actions: Vec<&str> = match &st["Action"] { + Value::String(a) => vec![a.as_str()], + v => v + .as_array() + .unwrap() + .iter() + .map(|a| a.as_str().unwrap()) + .collect(), + }; + if st["Effect"] == "Allow" { + for a in &actions { + let verb = a.split(':').nth(1).unwrap(); + let read = ["Get", "List"].iter().any(|r| verb.starts_with(r)) + || matches!( + *a, + "athena:StartQueryExecution" | "athena:StopQueryExecution" + ); + assert!(read || *a == "s3:PutObject", "{a} is not a read"); + if *a == "s3:PutObject" { + assert_eq!(st["Resource"], json!(["WAF_RESULT_OBJECTS"])); + } + } + assert_ne!(st["Action"], json!("*")); + } + } + // Every placeholder is alone in its array, so the script's list replaces it. + let text = p.to_string(); + for ph in WAF_PLACEHOLDERS { + if athena { + assert!(text.contains(&format!("\"{ph}\"")), "{ph}"); + } else { + assert!(!text.contains(ph), "{ph}"); + } + } + } + // Glue's connections carry passwords: never readable. + assert!(WAF_NEVER.contains(&"glue:GetConnection")); + } + + #[test] + fn the_setup_script_adds_the_waf_policy_and_the_update_line_only_that() { + let s = setup_script("654654210434", "coderhelm-abc"); + assert!(s.contains(&format!("--policy-name {WAF_POLICY_NAME}"))); + assert!(s.contains("grep -i waf")); + assert!(s.contains("starts_with(StorageDescriptor.Location, 's3://aws-waf-logs-')")); + let line = waf_update_line("arn:aws:iam::111122223333:role/CoderhelmReadOnly").unwrap(); + assert!(line.starts_with("echo ") && line.ends_with(" | base64 -d | bash")); + assert!(!line.contains('\n')); + let b64 = line + .trim_start_matches("echo ") + .trim_end_matches(" | base64 -d | bash"); + let script = String::from_utf8(STANDARD.decode(b64).unwrap()).unwrap(); + assert!(script.contains("ROLE=CoderhelmReadOnly\n")); + assert!(script.contains(&format!("--policy-name {WAF_POLICY_NAME}"))); + // Nothing else: no trust change, no other policy, nothing pasted back. + assert_eq!(script.matches("put-role-policy").count(), 1); + for no in [ + "update-assume-role-policy", + "create-role", + "coderhelm:$CODE", + "read -r", + ] { + assert!(!script.contains(no), "{no}"); + } + assert!(waf_update_line("arn:aws:iam::111122223333:role/x;rm -rf").is_none()); + for sh in [script, s] { + use std::io::Write; + let mut child = std::process::Command::new("bash") + .arg("-n") + .stdin(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("bash is installed"); + child + .stdin + .take() + .unwrap() + .write_all(sh.as_bytes()) + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + } + } + #[test] fn the_script_is_valid_bash() { use std::io::Write; diff --git a/services/common/src/log_findings.rs b/services/common/src/log_findings.rs index 750614598..b0303ed42 100644 --- a/services/common/src/log_findings.rs +++ b/services/common/src/log_findings.rs @@ -3060,6 +3060,29 @@ pub async fn fetch_samples( } } +/// The role a team connected for `account` (from its AWS connection), for +/// naming it in a setup item. Empty when there is none. +pub async fn connection_role( + dynamo: &DynamoClient, + insights_table: &str, + team_id: &str, + account: &str, +) -> String { + if account.is_empty() || !account.chars().all(|c| c.is_ascii_digit()) { + return String::new(); + } + dynamo + .get_item() + .table_name(insights_table) + .key("pk", attr(team_id)) + .key("sk", attr(&format!("AWS_CONN#{account}"))) + .send() + .await + .ok() + .and_then(|o| o.item().map(|i| s(i, "role_arn"))) + .unwrap_or_default() +} + /// Take on the team's log reader role for the finding's account. pub async fn session_for( dynamo: &DynamoClient, diff --git a/services/common/src/stop_judge.rs b/services/common/src/stop_judge.rs index c0875a423..1269b6d60 100644 --- a/services/common/src/stop_judge.rs +++ b/services/common/src/stop_judge.rs @@ -392,6 +392,29 @@ pub struct Question { pub deadline_hours: u32, } +impl Question { + /// Whether the run may take the default by itself once the deadline + /// passes: never for access, which only a person can grant. + pub fn has_default(&self) -> bool { + self.person_only != PersonOnly::Access + } + + /// What happens without an answer, in one sentence. + pub fn unanswered(&self) -> String { + if self.has_default() { + format!( + "If there is no answer within {} hours, I go ahead with the recommended option ({}).", + self.deadline_hours, + self.default.trim() + ) + } else { + "Access is only granted by a person, so this has no default: the rest of the work \ + goes on without it." + .to_string() + } + } +} + /// A named blocker, on checked evidence. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Hold { @@ -526,10 +549,8 @@ impl Judged { }; s.push_str(&format!("{}. {}{}\n", i + 1, o.trim(), mark)); } - s.push_str(&format!( - "\nIf there is no answer within {} hours, I go ahead with the recommended option.", - q.deadline_hours - )); + s.push('\n'); + s.push_str(&q.unanswered()); Some(s) } @@ -539,10 +560,7 @@ impl Judged { Some(crate::run_questions::Question { id: "q1".into(), question: q.question.clone(), - why: format!( - "Default if unanswered in {} hours: {}", - q.deadline_hours, q.default - ), + why: q.unanswered(), suggestions: q.options.clone(), checked: q.tried.clone(), ..Default::default() @@ -793,6 +811,15 @@ pub fn validate(p: &Picture, v: &Value) -> Result { return Err("an ask must list what was tried in `tried`".into()); } let options = list("options"); + if person_only == PersonOnly::Access + && crate::aws_role_reads::is_install_grant(&format!( + "{question} {} {}", + tried.join(" "), + options.join(" ") + )) + { + return Err(install_level_rule()); + } if !(2..=4).contains(&options.len()) { return Err(format!( "an ask needs 2 to 4 `options`, not {}", @@ -827,6 +854,9 @@ pub fn validate(p: &Picture, v: &Value) -> Result { if blocker.is_empty() { return Err("a hold must name its blocker in `blocker`".into()); } + if crate::aws_role_reads::is_install_grant(&blocker) { + return Err(install_level_rule()); + } let evidence = list("evidence"); if evidence.is_empty() { return Err("a hold must cite evidence ids from the picture in `evidence`".into()); @@ -928,19 +958,65 @@ fn settled_by_rule(p: &Picture) -> Option<(Verdict, String)> { None } +/// What the re-ask says when an answer asks a person for, or holds on, a +/// read the team's AWS role lacks. +fn install_level_rule() -> String { + format!( + "a read CoderHelm's connected AWS role lacks is the install's setup item \"{}\", asked \ + once for the whole install, never a question or a hold on a run: proceed on the evidence \ + the run has and name the setup item in `assumption`", + crate::aws_role_reads::ITEM_LABEL + ) +} + +/// An ask for access, or a hold, that is a read the team's connected AWS +/// role lacks: a proceed instead. A missing install permission is one +/// install-level item (`aws_role_reads`), never a run's question or wait. +fn install_level(v: &Verdict) -> Option { + let words = match v { + Verdict::Ask(q) if q.person_only == PersonOnly::Access => { + format!( + "{} {} {}", + q.question, + q.tried.join(" "), + q.options.join(" ") + ) + } + Verdict::Hold(h) => h.blocker.clone(), + _ => return None, + }; + crate::aws_role_reads::is_install_grant(&words).then(|| Verdict::Proceed { + assumption: format!( + "the reads CoderHelm's AWS role lacks are the install's setup item \"{}\", asked once \ + for the whole install {}; this run doesn't ask for them and goes on with what it \ + could read", + crate::aws_role_reads::ITEM_LABEL, + crate::github_grants::INSTALL_LEVEL + ), + }) +} + /// The decision. One model call; a rule-breaking answer is asked again once /// with what was wrong; then the deterministic fallback. pub async fn judge(model: &M, picture: Picture) -> Judged { let picture = picture.with_ids(); let kind = picture.kind(); let step = picture.step.clone(); - let make = |verdict, source, replies| Judged { - kind, - step: step.clone(), - verdict, - source, - replies, - _sealed: (), + // Every answer, the model's, a rule's or the fallback's, passes the + // install-level rule last. + let make = |verdict: Verdict, source: Source, replies| { + let (verdict, source) = match install_level(&verdict) { + Some(v) => (v, Source::Rule("install-level item".into())), + None => (verdict, source), + }; + Judged { + kind, + step: step.clone(), + verdict, + source, + replies, + _sealed: (), + } }; if let Some((verdict, rule)) = settled_by_rule(&picture) { return make(verdict, Source::Rule(rule), Vec::new()); @@ -1213,6 +1289,70 @@ mod tests { assert_eq!(rq.suggestions, vec!["Monthly", "Yearly"]); } + /// The alarm run's question, as the model asked it. + fn waf_access_ask(hours: u32) -> Value { + json!({"verdict":"ask","assumption":"","person_only":"access", + "question":"Grant the team's read-only role WAF and Athena access so the run can read \ + the crawler's new JA4 and user agent?", + "tried":["wafv2:ListWebACLs and GetSampledRequests were denied for CoderHelm's role", + "no connected source reads the aws-waf-logs bucket"], + "options":["Grant access","Paste the JA4 and user agent here"], + "default":"Grant access","deadline_hours":hours,"blocker":"","evidence":[], + "category":"","location":""}) + } + + #[test] + fn a_read_the_aws_role_lacks_is_never_asked_or_held_on() { + // Asked twice: the rule is said once, then the fallback proceeds. + let m = Recorded::new(vec![Ok(waf_access_ask(4)), Ok(waf_access_ask(4))]); + let j = run(judge(&m, picture(Kind::Ask))); + assert!(j.proceeds(), "{:?}", j.verdict()); + assert!(j.question().is_none()); + assert!(j.run_question().is_none()); + // Re-asked with the rule, the model proceeds on its own words. + let m = Recorded::new(vec![ + Ok(waf_access_ask(4)), + Ok(proceed( + "the role's WAF reads are the install's setup item; plan from the alarm", + )), + ]); + let j = run(judge(&m, picture(Kind::Ask))); + assert_eq!(j.source(), &Source::ModelReasked); + assert!(j.proceeds()); + // Irreversible work's fallback hold on the same words: still a proceed. + let mut p = picture(Kind::Stop); + p.reversible = false; + p.reason = "grant the read-only role wafv2:GetSampledRequests access".into(); + let j = run(judge(&Recorded::new(vec![]), p)); + assert!(j.proceeds(), "{:?}", j.verdict()); + assert_eq!(j.source(), &Source::Rule("install-level item".into())); + assert!(j.assumption().unwrap().contains("\"AWS role reads\"")); + assert!(crate::handback::HandBack::of_judged(&j).is_none()); + } + + #[test] + fn access_has_no_default_a_choice_keeps_its_own() { + let p = picture(Kind::Ask).with_ids(); + let other_access = json!({"verdict":"ask","assumption":"","person_only":"access", + "question":"Add the staging API key to the sandbox secrets?","tried":["read the ticket"], + "options":["Add it","Skip the staging check"],"default":"Add it","deadline_hours":4, + "blocker":"","evidence":[],"category":"","location":""}); + let Ok(Verdict::Ask(q)) = validate(&p, &other_access) else { + panic!("a credential is still asked"); + }; + assert!(!q.has_default()); + assert!(!q.unanswered().contains("Add it")); + assert!(q.unanswered().contains("no default")); + let m = Recorded::new(vec![Ok(other_access)]); + let j = run(judge(&m, picture(Kind::Ask))); + assert!(!j + .run_question() + .unwrap() + .why + .contains("Default if unanswered")); + assert!(!j.question_markdown().unwrap().contains("I go ahead")); + } + #[test] fn the_prompt_carries_the_whole_picture() { let mut p = picture(Kind::Stop); diff --git a/services/gateway/src/routes/data_sources.rs b/services/gateway/src/routes/data_sources.rs index 25560b71d..efe66fea9 100644 --- a/services/gateway/src/routes/data_sources.rs +++ b/services/gateway/src/routes/data_sources.rs @@ -1588,6 +1588,9 @@ pub async fn aws_setup( "script": live_aws::setup_script(&our_account, &ext), "existing": existing_connections(&state, &claims.team_id).await, "role_prefix": live_aws::ROLE_PREFIX, + // For a role made before the WAF reads: the one line that adds + // only those (the install's "AWS role reads" setup item). + "waf_update": live_aws::waf_update_line(live_aws::ROLE_PREFIX), }))) } diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index 382f8831b..d541b630e 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -1005,6 +1005,66 @@ pub fn aws_connections( } } +/// Reads an alert route needs that a team's connected AWS role was +/// refused (`common::aws_role_reads`): one item for the whole install, +/// with the one line that adds them in AWS CloudShell. Never a failure, +/// and never a question on a run: alarm runs go on with what they could +/// read until it is done. Passes when every connected role read what it +/// was asked to. +pub fn aws_role_reads(gaps: &[common::aws_role_reads::Gap]) -> Check { + use common::aws_role_reads::{CHECK_KEY, ITEM_LABEL}; + let Some(first) = gaps.first() else { + return Check::pass( + CHECK_KEY, + X, + ITEM_LABEL, + "Every connected AWS role has the reads its alert routes used.", + ); + }; + let accounts: Vec<&str> = gaps.iter().map(|g| g.account.as_str()).collect(); + let mut actions: Vec<&str> = Vec::new(); + for a in gaps.iter().flat_map(|g| g.actions.iter()) { + if !actions.contains(&a.as_str()) { + actions.push(a); + } + } + let role = if first.role_arn.is_empty() { + format!( + "arn:aws:iam::{}:role/{}", + first.account, + common::live::aws::ROLE_PREFIX + ) + } else { + first.role_arn.clone() + }; + let mut fix = Fix::text(format!( + "Paste this one line into AWS CloudShell in account {} (in the region of its WAF log \ + Athena workgroup). It adds the read-only {} policy to the role: AWS WAF reads, and \ + queries of the WAF logs through Athena with results only under the workgroup's own \ + results prefix.", + accounts.join(", "), + common::live::aws::WAF_POLICY_NAME + )) + .url("https://docs.coderhelm.com/self-host/integrations#connected-aws-accounts"); + if let Some(line) = common::live::aws::waf_update_line(&role) { + fix = fix.command(line); + } + Check::not_ok( + Status::Warn, + CHECK_KEY, + X, + ITEM_LABEL, + format!( + "CoderHelm's AWS role in account {} was refused {} ({}).", + accounts.join(", "), + actions.join(", "), + first.needed_for + ), + "Alarm runs read what the role allows and go on without the rest; no run asks for this.", + fix, + ) +} + // ── Your own domain ─────────────────────────────────────────────────────── // // The updater requests the certificate and moves the domain along @@ -1983,11 +2043,12 @@ async fn aws_connections_check(state: &AppState) -> Check { async fn integration_checks(state: &AppState, team_id: &str) -> Vec { use common::notify::{store, ChannelKind}; let jira_key = [("pk", team_id), ("sk", "JIRA#config")]; - let (notify, jira_secret, jira_config, aws) = tokio::join!( + let (notify, jira_secret, jira_config, aws, gaps) = tokio::join!( super::alerts::team_notify_settings(state, team_id), super::api::load_jira_secret(state, team_id), get_item(state, &state.config.jira_config_table_name, &jira_key), aws_connections_check(state), + common::aws_role_reads::list(&state.dynamo, &state.config.settings_table_name, team_id), ); let forge = jira_config.as_ref().is_some_and(|i| { i.get("add_comment_url") @@ -2009,6 +2070,7 @@ async fn integration_checks(state: &AppState, team_id: &str) -> Vec { ), jira(forge || jira_secret.is_some()), aws, + aws_role_reads(&gaps), ] } @@ -2831,6 +2893,47 @@ mod tests { assert!(blockers.iter().all(|b| b.key != "github_sign_in")); } + #[test] + fn a_read_the_aws_role_lacks_is_one_install_item_with_the_update_line() { + use super::{aws_role_reads, Status}; + use common::aws_role_reads::Gap; + let ok = aws_role_reads(&[]); + assert_eq!(ok.status, Status::Pass); + let gap = Gap { + account: "111122223333".into(), + role_arn: "arn:aws:iam::111122223333:role/CoderhelmReadOnly".into(), + actions: vec![ + "wafv2:ListWebACLs".into(), + "wafv2:GetSampledRequests".into(), + ], + needed_for: "an AWS WAF alarm's evidence".into(), + seen_at: "2026-11-17T10:00:00Z".into(), + }; + let c = aws_role_reads(&[ + gap.clone(), + Gap { + account: "444455556666".into(), + ..gap + }, + ]); + // A warning for the install, never a failure that blocks an update. + assert_eq!(c.status, Status::Warn); + assert_eq!(c.key, "aws_role_reads"); + assert!( + c.detail.contains("111122223333, 444455556666"), + "{}", + c.detail + ); + assert!(c + .detail + .contains("wafv2:ListWebACLs, wafv2:GetSampledRequests")); + assert!(c.why.contains("no run asks")); + let fix = c.fix.unwrap(); + let line = fix.command.unwrap(); + assert!(line.ends_with(" | base64 -d | bash") && !line.contains('\n')); + assert!(fix.text.contains("coderhelm-read-waf")); + } + #[test] fn aws_connections_need_the_install_account_and_this_release_templates() { use super::{aws_connections, Fetched, Status}; diff --git a/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs b/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs new file mode 100644 index 000000000..cf9a7b5a7 --- /dev/null +++ b/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs @@ -0,0 +1,242 @@ +//! bo. An alert route sends a CloudWatch signature-drift alarm to a team's +//! terraform repository: a WAF Count rule seeing a crawler that got +//! past a Block rule by changing its JA4 or user agent, fixed by a pull +//! request that updates the block rule's match. The run ended `needs_input` +//! with a long question asking a person to grant the team's read-only role +//! WAF and Athena access, "Default if unanswered in 4 hours: Grant access". +//! `wafv2:ListWebACLs` and `GetSampledRequests` were denied: the role's +//! setup script had never added any WAF read. The web ACL logs to an +//! `aws-waf-logs-*` bucket with an Athena table, and nothing read it. +//! +//! Guarantee: the role's setup script adds `coderhelm-read-waf` (WAF reads, +//! Athena queries over the WAF log tables with results only under the +//! workgroup's results prefix). With those reads the run gathers the rule's +//! matches (sampled requests, and the logs in S3 by JA4, JA3, user agent, +//! accept language, path and cookie presence) before it plans, and goes on +//! to its pull request. Without them, the refusal is the install's one +//! setup item ("AWS role reads", with the one-line CloudShell update), +//! never a question or a wait on the run: the stop judge turns such an ask +//! or hold into a proceed, the hand-back list doesn't carry it, and an +//! access question never shows a default that can't happen. + +use common::alarm_evidence::{self as ae, LogTable}; +use common::aws_role_reads; +use common::stop_judge::{self as sj, JudgeModel, Kind, Picture}; +use serde_json::{json, Value}; +use std::sync::Mutex; + +const OLD_DEFAULT: &str = "Default if unanswered in 4 hours: Grant access"; + +/// The ticket the alert route wrote for the alarm. +const TICKET: &str = "- Alarm: acme-crawler-a-signature-drift\n\ + - State: ALARM (was OK)\n\ + - Description: CrawlerASignatureCount counts crawler A requests BlockCrawlerASignature didn't block.\n\ + - Metric: AWS/WAFV2 / CountedRequests\n\ + - Dimensions: WebACL=acme-web-acl, Rule=CrawlerASignatureCount\n"; + +/// The question the run asked, in its words. +const ASKED: &str = "Can someone grant the team's read-only role WAF and Athena access? \ + wafv2:ListWebACLs and GetSampledRequests were denied for CoderHelm's role, origin telemetry \ + sees every user agent as CloudFront, and no connected source can read the WAF logs in the \ + aws-waf-logs bucket."; + +/// Plays back the model's answers in order. +struct Recorded(Mutex>); + +impl JudgeModel for Recorded { + async fn answer(&self, _: &str, _: &str, _: &Value) -> Result { + self.0.lock().unwrap().pop().ok_or_else(|| "no more".into()) + } +} + +fn the_ask() -> Value { + json!({"verdict":"ask","assumption":"","person_only":"access","question":ASKED, + "tried":["wafv2:ListWebACLs was denied","GetSampledRequests was denied", + "origin logs see every user agent as CloudFront"], + "options":["Grant access","Paste the crawler's new JA4 and user agent"], + "default":"Grant access","deadline_hours":4,"blocker":"","evidence":[], + "category":"","location":""}) +} + +fn run(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap() + .block_on(f) +} + +/// The Glue table over the web ACL's log bucket, as the team's terraform +/// defines it (WAF's documented columns, an hourly projected partition). +fn log_table() -> LogTable { + let params: std::collections::HashMap = [ + ("projection.enabled", "true"), + ("projection.log_time.type", "date"), + ("projection.log_time.format", "yyyy/MM/dd/HH"), + ] + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + LogTable { + database: "acme_waf".into(), + table: "waf_logs".into(), + columns: [ + "timestamp", + "terminatingruleid", + "httprequest", + "ja3fingerprint", + "ja4fingerprint", + "nonterminatingmatchingrules", + "log_time", + ] + .iter() + .map(|c| c.to_string()) + .collect(), + date_partitions: ae::date_partitions(&["log_time".to_string()], ¶ms), + } +} + +#[test] +fn with_waf_reads_the_run_gathers_the_evidence_and_moves_to_a_pr() { + let alarm = ae::waf_alarm(TICKET).expect("a WAF alarm"); + assert_eq!(alarm.rule, "CrawlerASignatureCount"); + // The logging configuration names the bucket; its Glue table is found. + let bucket = ae::bucket_of("arn:aws:s3:::aws-waf-logs-acme").unwrap(); + assert!(ae::table_in_bucket( + "s3://aws-waf-logs-acme/AWSLogs/", + &bucket + )); + let end = 1_794_916_800; + let q = ae::athena_query(&log_table(), &alarm.rule, end - 3 * 3600, end).unwrap(); + assert!(q.contains("\"log_time\" BETWEEN '2026/11/17/09' AND '2026/11/17/12'")); + assert!(q.contains("r.ruleid = 'CrawlerASignatureCount'")); + assert!(!q.contains("clientip")); + // What the reads returned. + let samples = vec![ae::sample( + 40, + &[ + ("User-Agent".into(), "CrawlerA/3.1".into()), + ("Accept-Language".into(), "en-US".into()), + ("Cookie".into(), "session=private-value".into()), + ], + "GET", + "/listings/42?page=2", + "US", + &[], + )]; + let rows: Vec>> = [ + vec![ + "ja4", + "ja3", + "ua", + "accept_language", + "path", + "has_cookie", + "requests", + ], + vec![ + "t13d1516h2_8daaf6152771_e5627efa2ab1", + "773906b0efdefa24a7f2b8eb6985bf37", + "CrawlerA/3.1", + "en-US", + "/listings/42", + "false", + "812", + ], + ] + .iter() + .map(|r| r.iter().map(|v| Some(v.to_string())).collect()) + .collect(); + let mut lines = ae::summarize(&samples); + lines.extend(ae::athena_lines(&rows)); + let got = ae::evidence(&alarm, lines, vec![]); + assert!(got.refused.is_empty()); + assert!(aws_role_reads::gap("111122223333", "", &got.refused, "x", "t").is_none()); + let ticket = ae::with_evidence(TICKET, &got.text); + assert!(ticket.contains(ae::HEADING)); + assert!(ticket.contains("JA4 t13d1516h2_8daaf6152771_e5627efa2ab1")); + assert!(ticket.contains("CrawlerA/3.1")); + assert!(!ticket.contains("private-value") && !ticket.contains("page=2")); + assert!(!ticket.contains(aws_role_reads::ITEM_LABEL)); + // The planner reads it: the evidence joins the ticket before planning. + let src = include_str!("../mod.rs"); + let read = src.find("alarm_evidence_for_run(state, msg)").unwrap(); + let plan = src[read..].find("plan::run(").unwrap(); + assert!(plan > 0); + // Nothing for a person: the judge proceeds and the run builds its PR. + let m = Recorded(Mutex::new(vec![json!({"verdict":"proceed", + "assumption":"update BlockCrawlerASignature to match the JA4 and user agent the logs show", + "question":"","person_only":"","tried":[],"options":[],"default":"","deadline_hours":0, + "blocker":"","evidence":[],"category":"","location":""})])); + let j = run(sj::judge( + &m, + Picture::new(Kind::Ask, "plan", "the planner asks"), + )); + assert!(j.proceeds()); +} + +#[test] +fn without_waf_reads_no_question_and_one_install_item() { + let alarm = ae::waf_alarm(TICKET).unwrap(); + let refused = vec![ + "wafv2:ListWebACLs".to_string(), + "wafv2:GetSampledRequests".to_string(), + ]; + let got = ae::evidence( + &alarm, + vec![ + "Couldn't find the web ACL: CoderHelm's AWS role doesn't allow wafv2:ListWebACLs yet." + .into(), + ], + refused.clone(), + ); + // One short line in the run names the install's setup item. + assert!(got.text.contains("\"AWS role reads\"")); + assert!(got.text.contains("asks nobody")); + // The install-level item exists, with the one-line update for the role. + let role = "arn:aws:iam::111122223333:role/CoderhelmReadOnly"; + let gap = aws_role_reads::gap( + "111122223333", + role, + &got.refused, + "an AWS WAF alarm's evidence", + "t", + ) + .expect("the install item"); + assert_eq!(gap.actions, refused); + let line = common::live::aws::waf_update_line(&gap.role_arn).unwrap(); + assert!(line.ends_with("| base64 -d | bash")); + let checks = include_str!("../../../../gateway/src/routes/setup_checks.rs"); + assert!(checks.contains("aws_role_reads(&gaps)")); + assert!(checks.contains("common::aws_role_reads::list(")); + // The run's question becomes a proceed, asked twice or not. + let m = Recorded(Mutex::new(vec![the_ask(), the_ask()])); + let mut p = Picture::new(Kind::Ask, "plan", "the planner asks before it can plan"); + p.ticket_body = got.text.clone(); + let j = run(sj::judge(&m, p)); + assert!(j.proceeds(), "{:?}", j.verdict()); + assert!(j.run_question().is_none()); + assert!(common::handback::HandBack::of_judged(&j).is_none()); + assert!(crate::passes::supervisor::hand_back_for(&j, ASKED).is_none()); + assert_eq!(common::handback::human_only_in(ASKED), None); + // Every place a question is turned into a wait takes the judge's verdict. + let src = include_str!("../stop_judge.rs"); + assert!(src.contains("judged.question().filter(|q| q.has_default())")); +} + +#[test] +fn an_access_question_never_shows_a_default_that_cant_happen() { + // Access that isn't the AWS role's (a credential) is still asked, with + // no default to take. + let ask = json!({"verdict":"ask","assumption":"","person_only":"access", + "question":"Add the staging API key to the sandbox secrets?","tried":["read the ticket"], + "options":["Grant access","Skip the staging check"],"default":"Grant access", + "deadline_hours":4,"blocker":"","evidence":[],"category":"","location":""}); + let m = Recorded(Mutex::new(vec![ask])); + let j = run(sj::judge(&m, Picture::new(Kind::Ask, "plan", "asks"))); + let q = j.run_question().expect("still asked"); + assert!(!q.why.contains(OLD_DEFAULT)); + assert!(!q.why.contains("Default if unanswered")); + assert!(q.why.contains("no default")); + assert!(!j.question_markdown().unwrap().contains("I go ahead")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 7c319da6d..c161d242c 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1965,7 +1965,34 @@ async fn alarm_evidence_for_run(state: &WorkerState, msg: &TicketMessage) -> Opt ) .await; Some(match session { - Ok(Some(s)) => ae::gather(&s, &alarm, chrono::Utc::now()).await, + Ok(Some(s)) => { + let got = ae::gather(&s, &alarm, chrono::Utc::now()).await; + // A refused read is the install's setup item, recorded once for + // the account; a read that works again clears it. + let table = &state.config.settings_table_name; + if got.refused.is_empty() { + common::aws_role_reads::clear(&state.dynamo, table, &msg.team_id, &account).await; + } else { + let role_arn = common::log_findings::connection_role( + &state.dynamo, + &state.config.aws_insights_table_name, + &msg.team_id, + &account, + ) + .await; + if let Some(gap) = common::aws_role_reads::gap( + &account, + &role_arn, + &got.refused, + "an AWS WAF alarm's evidence", + &chrono::Utc::now().to_rfc3339(), + ) { + common::aws_role_reads::record(&state.dynamo, table, &msg.team_id, &gap).await; + } + info!(team_id = %msg.team_id, account = %account, refused = ?got.refused, "AWS role lacks reads an alert route needs: install setup item"); + } + got.text + } Ok(None) => ae::render( &alarm, &[format!( @@ -2772,13 +2799,17 @@ async fn run_passes( // fingerprints from the web ACL's logs) before planning; it joins the // ticket as data --- if let Some(ev) = alarm_evidence_for_run(state, msg).await { - add_progress_note( - state, - &msg.team_id, - run_id, - "Read the requests the alarm's WAF rule matched (sampled requests and the web ACL's logs).", - ) - .await; + let note = if ev.contains(common::aws_role_reads::ITEM_LABEL) { + format!( + "Read what the alarm's WAF rule matched that the AWS role allows; the rest is the \ + install's setup item \"{}\", not a question on this run.", + common::aws_role_reads::ITEM_LABEL + ) + } else { + "Read the requests the alarm's WAF rule matched (sampled requests and the web ACL's logs)." + .to_string() + }; + add_progress_note(state, &msg.team_id, run_id, ¬e).await; msg.body = common::alarm_evidence::with_evidence(&msg.body, &ev); } if let Some(ev) = log_ev.as_ref() { diff --git a/services/worker/src/passes/stop_judge.rs b/services/worker/src/passes/stop_judge.rs index 87b9cdb1f..8605e776f 100644 --- a/services/worker/src/passes/stop_judge.rs +++ b/services/worker/src/passes/stop_judge.rs @@ -370,7 +370,8 @@ pub fn assumed_answers( /// stuck-run sweep can take the default once the deadline passes on /// reversible work (`lambda/stuck-run-cleanup`). pub async fn keep_ask_deadline(state: &WorkerState, team_id: &str, run_id: &str, judged: &Judged) { - let Some(q) = judged.question() else { + // Access has no default to take: nothing for the sweep to answer. + let Some(q) = judged.question().filter(|q| q.has_default()) else { return; }; let due = chrono::Utc::now() + chrono::Duration::hours(i64::from(q.deadline_hours));