diff --git a/docs/incidents/cx_role_reads_wait_then_finish.md b/docs/incidents/cx_role_reads_wait_then_finish.md new file mode 100644 index 000000000..7b6f68f4f --- /dev/null +++ b/docs/incidents/cx_role_reads_wait_then_finish.md @@ -0,0 +1,5 @@ +# cx. `cx_role_reads_wait_then_finish` + +**What happened:** An alert route sent an AWS WAF signature-drift alarm (a Count rule counting a crawler's requests that got past a Block rule) to the team's terraform repository. The account's role stack predated the WAF reads the role template has, so the alarm's evidence (sampled requests, the web ACL's logs) was refused. The planner then asked CloudWatch for the alarm's own metric, `AWS/WAFV2`, and CoderHelm refused it itself ("isn't a namespace Coderhelm reads") although the role allows `cloudwatch:GetMetricData` on every namespace. It read the counts through New Relic instead, five lookups, yet the decision was labelled "Not checked against the data (no lookups were made)" because only data-source lookups were counted. The run ended `needs_outside_change` with "Needed from you: Nothing" and asked a person to run an Athena query: the only missing read was the install's setup item, so nothing was left for any person, and nothing would ever take the run up again once the role could read. + +**The guarantee:** Any CloudWatch namespace may be read: the team's role is the boundary, the common namespaces (`AWS/WAFV2` with WebACL, Rule, Region and its request counts among them) are hints in the tool description, a CloudFront web ACL's WAF metrics are read in us-east-1, and a refusal from AWS comes back as the install's setup item "AWS role reads", never as a refusal of ours. A WAF rule's matches are read without Athena: `waf_sampled_requests` (WAF's sampled requests) and `waf_log_objects` (the log objects straight from the `aws-waf-logs-*` bucket, bounded, grouped in the process by JA4, user agent, accept language, path and cookie presence), and the alarm's own evidence reads the log objects before it tries Athena. Every lookup the planner makes counts, so "no lookups were made" appears only when none were. A run whose plan changes no code ends `needs_outside_change` only when a person has an item; with none, a run the role was refused reads waits (`awaiting_setup`), raises the one install item, re-checks the role every 15 minutes and then daily (and at once when another run reads again), and starts again from its ticket once the role reads, to read the data and open its pull request. Any other run with nothing for a person plans again. diff --git a/services/Cargo.lock b/services/Cargo.lock index a9235388f..d78dc6a2e 100644 --- a/services/Cargo.lock +++ b/services/Cargo.lock @@ -1886,6 +1886,7 @@ dependencies = [ "base64 0.22.1", "chrono", "ed25519-dalek", + "flate2", "futures", "graphql-parser", "hex", diff --git a/services/common/Cargo.toml b/services/common/Cargo.toml index c398340fc..0dd5fff6f 100644 --- a/services/common/Cargo.toml +++ b/services/common/Cargo.toml @@ -84,6 +84,8 @@ serde_yaml = "0.9" # e2e: JUnit XML test reports quick-xml = "0.37" aws-sdk-s3 = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio", "sigv4a", "http-1x"] } +# waf_logs: a web ACL's log objects (gzip JSON lines) read straight from its bucket +flate2 = "1" lopdf = { version = "0.46", default-features = false } yaml-rust2 = "0.10" diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 5979cdf2c..3a5704afb 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -201,6 +201,8 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("aws_identity", Risk::Read), ("aws_bucket_settings", Risk::Read), ("aws_kms_key", Risk::Read), + ("waf_sampled_requests", Risk::Read), + ("waf_log_objects", Risk::Read), ("newrelic_accounts", Risk::Read), ("newrelic_nrql", Risk::Read), ("newrelic_entities", Risk::Read), @@ -366,6 +368,8 @@ const DATA_SOURCE_TOOLS: &[(&str, &str)] = &[ ("aws_identity", "aws"), ("aws_bucket_settings", "aws"), ("aws_kms_key", "aws"), + ("waf_sampled_requests", "aws"), + ("waf_log_objects", "aws"), ("newrelic_", "newrelic"), ("confluence_", "confluence"), ("metrics_", "cloudwatch"), diff --git a/services/common/src/alarm_evidence.rs b/services/common/src/alarm_evidence.rs index ebd2d5e9e..3d98b3e60 100644 --- a/services/common/src/alarm_evidence.rs +++ b/services/common/src/alarm_evidence.rs @@ -12,10 +12,13 @@ //! Reads only: `wafv2:ListWebACLs`, `wafv2:GetSampledRequests`, //! `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 (the role template's WAF log group, -//! `infra/cfn/coderhelm-log-reader.yaml`, `WafLogs`). Request values +//! its log objects read straight from the bucket (`crate::waf_logs`: +//! `s3:ListBucket` and `s3:GetObject`, bounded, grouped in the process, no +//! Athena), and only when they hold nothing, 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 (the +//! role template's WAF log group, `infra/cfn/coderhelm-log-reader.yaml`, +//! `WafLogs`). Request values //! that can carry secrets or people's data (client addresses, cookies, //! authorization and every other header value but the user agent and //! accept language, query strings) are never kept; from the logs in S3, @@ -67,6 +70,27 @@ pub struct WafAlarm { } impl WafAlarm { + /// A web ACL and rule an agent named, when the names are WAF names. + /// `region` is the web ACL's region; none for a CloudFront web ACL. + pub fn new(web_acl: &str, rule: &str, region: Option<&str>) -> Option { + let region = region + .map(str::trim) + .filter(|r| !r.is_empty() && !r.eq_ignore_ascii_case("global")); + if let Some(r) = region { + let ok = r.len() <= 30 + && r.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + if !ok { + return None; + } + } + (is_waf_name(web_acl.trim()) && is_waf_name(rule.trim())).then(|| WafAlarm { + web_acl: web_acl.trim().to_string(), + rule: rule.trim().to_string(), + region: region.map(str::to_string), + }) + } + /// WAF's scope for the web ACL, and the region its API is called in. fn scope_and_region(&self) -> (aws_sdk_wafv2::types::Scope, String) { match &self.region { @@ -542,6 +566,8 @@ fn waf_client(s: &Session) -> aws_sdk_wafv2::Client { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Gathered { pub text: String, + /// The same evidence as lines, unfenced (an agent's lookup result). + pub lines: Vec, pub refused: Vec, /// What the run found for the role stack's WAF log group, so its update /// link names them: the Athena workgroup's results location @@ -600,6 +626,7 @@ pub fn evidence(alarm: &WafAlarm, mut lines: Vec, refused: Vec) } Gathered { text: render(alarm, &lines), + lines, refused, ..Default::default() } @@ -625,16 +652,15 @@ pub fn bucket_key_arn( crate::log_reader::is_kms_key(&arn).then_some(arn) } -/// 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 { +/// The web ACL's ARN, by its name. `None` (with why in `n`) when it isn't +/// there or may not be listed. +async fn find_web_acl( + waf: &aws_sdk_wafv2::Client, + alarm: &WafAlarm, + n: &mut Notes, +) -> Option { 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; let mut marker: Option = None; for _ in 0..10 { match waf @@ -646,17 +672,20 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> .await { Ok(o) => { - arn = o + let arn = o .web_acls() .iter() .find(|w| w.name() == Some(alarm.web_acl.as_str())) .and_then(|w| w.arn()) .map(str::to_string); + if arn.is_some() { + return arn; + } marker = o .next_marker() .filter(|m| !m.is_empty()) .map(str::to_string); - if arn.is_some() || marker.is_none() { + if marker.is_none() { break; } } @@ -667,87 +696,99 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> e.code(), e.message(), ); - break; + return None; } } } - let Some(arn) = arn else { - if n.lines.is_empty() { - n.lines - .push(format!("No web ACL named {} in {region}.", alarm.web_acl)); - } - return n.done(alarm); - }; + n.lines + .push(format!("No web ACL named {} in {region}.", alarm.web_acl)); + None +} - // The requests the rule matched. - let end = now.timestamp(); - let start = end - WINDOW_SECS + 60; +/// The requests the rule matched in `[start, end]` (WAF keeps three hours), +/// summarized into `n`. +async fn read_samples( + waf: &aws_sdk_wafv2::Client, + arn: &str, + alarm: &WafAlarm, + start: i64, + end: i64, + n: &mut Notes, +) { + use aws_sdk_wafv2::error::ProvideErrorMetadata; + let (scope, _) = alarm.scope_and_region(); let window = aws_sdk_wafv2::types::TimeWindow::builder() .start_time(aws_smithy_types::DateTime::from_secs(start)) .end_time(aws_smithy_types::DateTime::from_secs(end)) .build(); - match window { - Ok(window) => match waf - .get_sampled_requests() - .web_acl_arn(&arn) - .rule_metric_name(&alarm.rule) - .scope(scope.clone()) - .time_window(window) - .max_items(MAX_SAMPLES) - .send() - .await - { - Ok(o) => { - let samples: Vec = o - .sampled_requests() - .iter() - .map(|s| { - let r = s.request(); - let headers: Vec<(String, String)> = r - .map(|r| { - r.headers() - .iter() - .map(|h| { - ( - h.name().unwrap_or_default().to_string(), - h.value().unwrap_or_default().to_string(), - ) - }) - .collect() - }) - .unwrap_or_default(); - let labels: Vec = - s.labels().iter().map(|l| l.name().to_string()).collect(); - sample( - s.weight(), - &headers, - r.and_then(|r| r.method()).unwrap_or_default(), - r.and_then(|r| r.uri()).unwrap_or_default(), - r.and_then(|r| r.country()).unwrap_or_default(), - &labels, - ) - }) - .collect(); - n.lines - .push(format!("Sampled requests the rule {} matched:", alarm.rule)); - n.lines.extend(summarize(&samples)); - } - Err(e) => n.failed( - "read the sampled requests", - "wafv2:GetSampledRequests", - e.code(), - e.message(), - ), - }, - Err(e) => n - .lines - .push(format!("Couldn't read the sampled requests: {e}")), + let window = match window { + Ok(w) => w, + Err(e) => { + n.lines + .push(format!("Couldn't read the sampled requests: {e}")); + return; + } + }; + match waf + .get_sampled_requests() + .web_acl_arn(arn) + .rule_metric_name(&alarm.rule) + .scope(scope) + .time_window(window) + .max_items(MAX_SAMPLES) + .send() + .await + { + Ok(o) => { + let samples: Vec = o + .sampled_requests() + .iter() + .map(|s| { + let r = s.request(); + let headers: Vec<(String, String)> = r + .map(|r| { + r.headers() + .iter() + .map(|h| { + ( + h.name().unwrap_or_default().to_string(), + h.value().unwrap_or_default().to_string(), + ) + }) + .collect() + }) + .unwrap_or_default(); + let labels: Vec = + s.labels().iter().map(|l| l.name().to_string()).collect(); + sample( + s.weight(), + &headers, + r.and_then(|r| r.method()).unwrap_or_default(), + r.and_then(|r| r.uri()).unwrap_or_default(), + r.and_then(|r| r.country()).unwrap_or_default(), + &labels, + ) + }) + .collect(); + n.lines + .push(format!("Sampled requests the rule {} matched:", alarm.rule)); + n.lines.extend(summarize(&samples)); + } + Err(e) => n.failed( + "read the sampled requests", + "wafv2:GetSampledRequests", + e.code(), + e.message(), + ), } +} - // TLS fingerprints come only from the web ACL's logs. - let destinations: Vec = match waf +/// Where the web ACL logs: its destinations, or none (with why in `n`). +async fn log_destinations(waf: &aws_sdk_wafv2::Client, arn: &str, n: &mut Notes) -> Vec { + use aws_sdk_wafv2::error::ProvideErrorMetadata; + match waf .get_logging_configuration() - .resource_arn(&arn) + .resource_arn(arn) .send() .await { @@ -771,15 +812,107 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> ); vec![] } + } +} + +/// The rule's matches in the web ACL's log objects, read straight from its +/// bucket (no Athena); `true` when records naming the rule came back. +async fn read_log_objects( + session: &Session, + arn: &str, + destination: &str, + alarm: &WafAlarm, + start: i64, + end: i64, + n: &mut Notes, +) -> bool { + let Some(loc) = crate::waf_logs::LogLocation::of(arn, destination) else { + return false; }; + let got = crate::waf_logs::read(session, &loc, &alarm.rule, start, end).await; + for a in &got.refused { + if !n.refused.contains(a) { + n.refused.push(a.clone()); + } + } + n.lines.extend(got.lines.iter().cloned()); + got.found() +} + +/// The sampled requests the alarm's rule matched in the last three hours +/// (for an agent's lookup): the lines, and the IAM actions the role was +/// refused (the install's setup item). +pub async fn sampled_requests(session: &Session, alarm: &WafAlarm, now: DateTime) -> Gathered { + let (_, region) = alarm.scope_and_region(); + let waf = waf_client(&session_in(session, ®ion)); + let mut n = Notes::default(); + if let Some(arn) = find_web_acl(&waf, alarm, &mut n).await { + let end = now.timestamp(); + read_samples(&waf, &arn, alarm, end - WINDOW_SECS + 60, end, &mut n).await; + } + n.done(alarm) +} + +/// The rule's matches in the web ACL's log objects in `[start, end]` (for an +/// agent's lookup), read straight from its `aws-waf-logs-*` bucket: the +/// bucket named, else where the web ACL logs. +pub async fn log_objects( + session: &Session, + alarm: &WafAlarm, + bucket: Option<&str>, + start: i64, + end: i64, +) -> Gathered { + let (_, region) = alarm.scope_and_region(); + let waf = waf_client(&session_in(session, ®ion)); + let mut n = Notes::default(); + let Some(arn) = find_web_acl(&waf, alarm, &mut n).await else { + return n.done(alarm); + }; + let destinations: Vec = match bucket { + Some(b) => vec![format!("arn:aws:s3:::{b}")], + None => log_destinations(&waf, &arn, &mut n).await, + }; + match destinations.iter().find(|d| bucket_of(d).is_some()) { + Some(d) => { + read_log_objects(session, &arn, d, alarm, start, end, &mut n).await; + } + None if n.lines.is_empty() => n.lines.push( + "The web ACL doesn't log to an aws-waf-logs-* bucket; its sampled requests \ + (waf_sampled_requests) have the user agent and header order." + .into(), + ), + None => {} + } + n.done(alarm) +} + +/// Read the evidence for a WAF alarm. Every lookup that fails says why in +/// the result, so a missing permission is named, not silent. The logs held +/// in S3 are read straight from the bucket first; Athena only when that +/// found nothing. +pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> Gathered { + let (_, region) = alarm.scope_and_region(); + let waf = waf_client(&session_in(session, ®ion)); + let mut n = Notes::default(); + let Some(arn) = find_web_acl(&waf, alarm, &mut n).await else { + return n.done(alarm); + }; + let end = now.timestamp(); + let start = end - WINDOW_SECS + 60; + read_samples(&waf, &arn, alarm, start, end, &mut n).await; + + // TLS fingerprints come only from the web ACL's logs. + let destinations = log_destinations(&waf, &arn, &mut n).await; let group = destinations.iter().find_map(|d| log_group_of(d)); - let bucket = destinations.iter().find_map(|d| bucket_of(d)); - match (group, bucket, insights_query(&alarm.rule)) { + let s3_destination = destinations.iter().find(|d| bucket_of(d).is_some()); + match (group, s3_destination, insights_query(&alarm.rule)) { (Some((region, name)), _, Some(query)) => { n.lines .extend(fingerprints(session, ®ion, &name, &query, start, end).await); } - (None, Some(bucket), _) => { + (None, Some(destination), _) => { + let bucket = bucket_of(destination).unwrap_or_default(); n.logs_to_s3 = true; // The bucket's own KMS key, for the role stack's WafLogKey // (its settings, read with the role's settings reads). @@ -789,11 +922,16 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> let at = b.region.clone().unwrap_or_else(|| session.region.clone()); n.key = bucket_key_arn(rules, &at, account).unwrap_or_default(); } - let mut regions = vec![session.region.clone()]; - if region != session.region { - regions.push(region.clone()); + // The log objects themselves first: no Athena needed. + let found = + read_log_objects(session, &arn, destination, alarm, start, end, &mut n).await; + if !found { + 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; } - 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 \ diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index ede45349b..a99066a2e 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -74,6 +74,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "agent_resume_sweep", // A run waiting on a person: its reminder (from the stuck-run sweep). "run_waiting", + // A run waiting for the AWS role's reads: its re-check (`role_wait`). + "role_reads_wait", // A model call's usage, held because its counters couldn't be written. "usage_record", // Knowledge sources: the scheduled sweep, and one source's sync. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index bdfcb1d20..3afa3a5b2 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -79,7 +79,9 @@ pub mod coder_shell; /// channel, sealed webhook URLs. pub mod notify; pub mod role_move; +pub mod role_wait; pub mod tool_aliases; +pub mod waf_logs; /// The team's daily alert token budget (alerts route and Setup). pub mod alert_budget; diff --git a/services/common/src/live/aws_settings.rs b/services/common/src/live/aws_settings.rs index 1229bf3a8..05bea26c4 100644 --- a/services/common/src/live/aws_settings.rs +++ b/services/common/src/live/aws_settings.rs @@ -391,7 +391,7 @@ const NO_BUCKET: (&str, &str) = ( /// The region S3 says a bucket is in (`x-amz-bucket-region`), from a call /// made in another region. -fn bucket_region( +pub fn bucket_region( e: &aws_sdk_s3::error::SdkError, ) -> Option { let r = e diff --git a/services/common/src/live/metrics.rs b/services/common/src/live/metrics.rs index 4fdee2f05..7eea9c9fe 100644 --- a/services/common/src/live/metrics.rs +++ b/services/common/src/live/metrics.rs @@ -1,9 +1,15 @@ //! CloudWatch metrics in a team's AWS account, through its log reader role. //! //! Two calls only, both reads: ListMetrics (what exists, with its dimension -//! values) and GetMetricData (numbers over time). Only the AWS service -//! namespaces below can be read, a window is capped at 14 days and a query at -//! five metrics, so one lookup can't pull an account's whole history. +//! values) and GetMetricData (numbers over time). Any namespace may be read: +//! the team's role is the boundary (its policy allows +//! `cloudwatch:GetMetricData` and `cloudwatch:ListMetrics`), so a namespace +//! the role can't read comes back as AWS's refusal, named as the install's +//! setup item "AWS role reads", never as a refusal of ours. A run once +//! couldn't read an AWS WAF alarm's own metric (`AWS/WAFV2`) because a list +//! here left it out. A window is capped at 14 days and a query at five +//! metrics and ten dimensions, so one lookup can't pull an account's whole +//! history. use std::collections::BTreeMap; use std::time::Duration; @@ -14,22 +20,32 @@ use super::aws::Session; use super::http::window; use super::StepError; -/// Namespaces agents may read, with what they cover. -pub const NAMESPACES: &[(&str, &str)] = &[ +/// Common namespaces with what they cover: hints for the tool description, +/// never a limit (any namespace is read). +pub const NAMESPACE_HINTS: &[(&str, &str)] = &[ ("AWS/ECS", "ECS services: CPUUtilization, MemoryUtilization (ClusterName, ServiceName)"), ("ECS/ContainerInsights", "ECS Container Insights: RunningTaskCount, CpuUtilized, MemoryUtilized"), ("AWS/RDS", "RDS and Aurora: DatabaseConnections, CPUUtilization, ReadLatency, WriteLatency, FreeableMemory (DBInstanceIdentifier or DBClusterIdentifier)"), ("AWS/Lambda", "Lambda: Duration, Errors, Throttles, Invocations, ConcurrentExecutions (FunctionName)"), ("AWS/CloudFront", "CloudFront: Requests, 4xxErrorRate, 5xxErrorRate, CacheHitRate (DistributionId, Region=Global; read in us-east-1)"), + ("AWS/WAFV2", "AWS WAF: CountedRequests, BlockedRequests, AllowedRequests, CaptchaRequests, ChallengeRequests (WebACL, Rule, Region; a CloudFront web ACL has no Region and is read in us-east-1; Rule=ALL for the whole web ACL)"), ("AWS/ApplicationELB", "Load balancers: RequestCount, TargetResponseTime, HTTPCode_Target_5XX_Count, HealthyHostCount (LoadBalancer, TargetGroup)"), ("AWS/ELB", "Classic load balancers: RequestCount, Latency, HTTPCode_Backend_5XX"), + ("AWS/NetworkELB", "Network load balancers: ActiveFlowCount, ProcessedBytes, HealthyHostCount, UnHealthyHostCount (LoadBalancer, TargetGroup)"), + ("AWS/ApiGateway", "API Gateway: Count, Latency, 5XXError (ApiName)"), ("AWS/SQS", "SQS: ApproximateNumberOfMessagesVisible, ApproximateAgeOfOldestMessage (QueueName)"), + ("AWS/SNS", "SNS: NumberOfMessagesPublished, NumberOfNotificationsFailed (TopicName)"), + ("AWS/Events", "EventBridge: Invocations, FailedInvocations, TriggeredRules (RuleName)"), + ("AWS/States", "Step Functions: ExecutionsFailed, ExecutionsTimedOut, ExecutionTime (StateMachineArn)"), + ("AWS/Kinesis", "Kinesis streams: IncomingRecords, GetRecords.IteratorAgeMilliseconds (StreamName)"), + ("AWS/Firehose", "Firehose: IncomingRecords, DeliveryToS3.Success, DeliveryToS3.DataFreshness (DeliveryStreamName)"), ("AWS/DynamoDB", "DynamoDB: ConsumedReadCapacityUnits, ThrottledRequests, SuccessfulRequestLatency (TableName)"), ("AWS/ElastiCache", "ElastiCache: CPUUtilization, CurrConnections, Evictions (CacheClusterId)"), - ("AWS/ApiGateway", "API Gateway: Count, Latency, 5XXError (ApiName)"), ("AWS/EC2", "EC2 instances: CPUUtilization, NetworkIn, NetworkOut, StatusCheckFailed, CPUCreditBalance (InstanceId or AutoScalingGroupName)"), ("AWS/EBS", "EBS volumes: VolumeReadOps, VolumeWriteOps, VolumeQueueLength, BurstBalance (VolumeId)"), - ("AWS/NetworkELB", "Network load balancers: ActiveFlowCount, ProcessedBytes, HealthyHostCount, UnHealthyHostCount (LoadBalancer, TargetGroup)"), + ("AWS/NATGateway", "NAT gateways: BytesOutToDestination, ErrorPortAllocation, PacketsDropCount (NatGatewayId)"), + ("AWS/S3", "S3: BucketSizeBytes, NumberOfObjects (BucketName, StorageType; daily), 4xxErrors, 5xxErrors with request metrics (BucketName, FilterId)"), + ("AWS/Logs", "CloudWatch Logs: IncomingLogEvents, IncomingBytes (LogGroupName)"), ("AWS/ES", "OpenSearch: CPUUtilization, JVMMemoryPressure, FreeStorageSpace, ClusterStatus.red, SearchLatency (DomainName, ClientId)"), ]; const STATS: &[&str] = &[ @@ -53,16 +69,64 @@ fn refused(message: impl Into) -> StepError { StepError::new( "read_only", message, - "Read one of the AWS namespaces listed in the tool description, over 14 days at most.", + "Name the namespace, metric and dimensions (metrics_list shows what exists), over 14 days at most.", ) } -fn check_namespace(ns: &str) -> Result<&'static str, StepError> { - NAMESPACES +/// Pure: a namespace as CloudWatch allows it (ASCII letters, digits, +/// `.`, `-`, `_`, `/`, `#`, `:` and spaces, at most 255), with a hint's +/// spelling when it is one of the common ones (`aws/ecs` is `AWS/ECS`). +/// Every namespace passes: the team's role decides what it may read. +pub fn check_namespace(ns: &str) -> Result { + let ns = ns.trim(); + if let Some((n, _)) = NAMESPACE_HINTS .iter() - .find(|(n, _)| n.eq_ignore_ascii_case(ns.trim())) - .map(|(n, _)| *n) - .ok_or_else(|| refused(format!("{ns} isn't a namespace Coderhelm reads."))) + .find(|(n, _)| n.eq_ignore_ascii_case(ns)) + { + return Ok((*n).to_string()); + } + let ok = !ns.is_empty() + && ns.len() <= 255 + && ns + .chars() + .all(|c| c.is_ascii_alphanumeric() || "._-/#: ".contains(c)); + if ok { + Ok(ns.to_string()) + } else { + Err(refused(format!( + "{ns:?} isn't a CloudWatch namespace (letters, digits, . - _ / # : and spaces)." + ))) + } +} + +/// Pure: a region an agent named (`us-east-1`). +fn check_region(r: &str) -> Result { + let r = r.trim(); + let ok = !r.is_empty() + && r.len() <= 30 + && r.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + if ok { + Ok(r.to_string()) + } else { + Err(refused(format!("{r:?} isn't an AWS region."))) + } +} + +/// Pure: the region a metric is published in when it isn't the team's: +/// CloudFront's, and a CloudFront web ACL's WAF metrics (no `Region` +/// dimension, or `Region=Global`), live in us-east-1; a regional web ACL's +/// WAF metrics live in the region its `Region` dimension names. +pub fn metric_region(namespace: &str, dimensions: &BTreeMap) -> Option { + match namespace { + "AWS/CloudFront" => Some("us-east-1".to_string()), + "AWS/WAFV2" => match dimensions.get("Region") { + None => Some("us-east-1".to_string()), + Some(r) if r.eq_ignore_ascii_case("global") => Some("us-east-1".to_string()), + Some(r) => check_region(r).ok(), + }, + _ => None, + } } fn check_name(what: &str, s: &str) -> Result { @@ -99,7 +163,7 @@ fn dimensions(v: &Value) -> Result, StepError> { #[derive(Debug, Clone, PartialEq, Eq)] pub struct MetricQuery { pub id: String, - pub namespace: &'static str, + pub namespace: String, pub metric: String, pub dimensions: BTreeMap, pub stat: String, @@ -112,8 +176,9 @@ pub struct CheckedQuery { pub start: i64, pub end: i64, pub period: i32, - /// CloudFront's metrics live in us-east-1 whatever the team's region. - pub region: Option<&'static str>, + /// Where the metrics are read when it isn't the team's region: the + /// region asked for, else where they are published ([`metric_region`]). + pub region: Option, } impl CheckedQuery { @@ -145,12 +210,14 @@ impl CheckedQuery { /// Checks a request: `metrics` is a list of `{namespace, metric, dimensions, /// stat}`; `period` in seconds (a multiple of 60, default chosen to give at -/// most 120 points). +/// most 120 points); `region` where to read when it isn't the team's region +/// or where the metric is published. pub fn check_query( metrics: &[Value], period: Option, since: Option<&str>, until: Option<&str>, + region: Option<&str>, now: i64, ) -> Result { if metrics.is_empty() { @@ -177,15 +244,19 @@ pub fn check_query( "That asks for more than {MAX_POINTS} points. Use a longer period or a shorter window." ))); } + let asked = region + .map(str::trim) + .filter(|r| !r.is_empty()) + .map(check_region) + .transpose()?; let mut queries = Vec::new(); - let mut cloudfront = false; - let mut other = false; + let mut regions: Vec> = Vec::new(); for (i, m) in metrics.iter().enumerate() { let namespace = check_namespace(m["namespace"].as_str().unwrap_or(""))?; - if namespace == "AWS/CloudFront" { - cloudfront = true; - } else { - other = true; + let dims = dimensions(&m["dimensions"])?; + let at = metric_region(&namespace, &dims); + if !regions.contains(&at) { + regions.push(at); } let stat = m["stat"].as_str().unwrap_or("Average").trim().to_string(); if !STATS.contains(&stat.as_str()) { @@ -198,13 +269,14 @@ pub fn check_query( id: format!("m{i}"), namespace, metric: check_name("metric name", m["metric"].as_str().unwrap_or(""))?, - dimensions: dimensions(&m["dimensions"])?, + dimensions: dims, stat, }); } - if cloudfront && other { + if asked.is_none() && regions.len() > 1 { return Err(refused( - "Read CloudFront metrics in their own lookup (they live in us-east-1).", + "Read metrics published in different regions in their own lookups (CloudFront's \ + and a CloudFront web ACL's WAF metrics live in us-east-1).", )); } Ok(CheckedQuery { @@ -212,31 +284,42 @@ pub fn check_query( start, end, period: period as i32, - region: cloudfront.then_some("us-east-1"), + region: asked.or_else(|| regions.into_iter().next().flatten()), }) } /// A checked ListMetrics request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CheckedList { - pub namespace: &'static str, + pub namespace: String, pub metric: Option, pub dimensions: BTreeMap, + /// Where to list when it isn't the team's region (see [`CheckedQuery`]). + pub region: Option, } pub fn check_list( namespace: &str, metric: Option<&str>, dims: &Value, + region: Option<&str>, ) -> Result { + let namespace = check_namespace(namespace)?; + let dimensions = dimensions(dims)?; + let asked = region + .map(str::trim) + .filter(|r| !r.is_empty()) + .map(check_region) + .transpose()?; Ok(CheckedList { - namespace: check_namespace(namespace)?, + region: asked.or_else(|| metric_region(&namespace, &dimensions)), + namespace, metric: metric .map(str::trim) .filter(|m| !m.is_empty()) .map(|m| check_name("metric name", m)) .transpose()?, - dimensions: dimensions(dims)?, + dimensions, }) } @@ -351,7 +434,9 @@ fn client(s: &Session, region: Option<&str>) -> aws_sdk_cloudwatch::Client { ) } -fn aws_error(e: &aws_sdk_cloudwatch::error::SdkError) -> StepError +/// AWS's answer to a refused or failed call. A refusal is the role's: the +/// install's setup item for `action`, named in one line. +fn aws_error(e: &aws_sdk_cloudwatch::error::SdkError, action: &str) -> StepError where E: aws_sdk_cloudwatch::error::ProvideErrorMetadata + std::error::Error + 'static, R: std::fmt::Debug, @@ -359,12 +444,8 @@ where use aws_sdk_cloudwatch::error::ProvideErrorMetadata as _; let code = e.code().unwrap_or("").to_string(); let msg = e.message().unwrap_or("").to_string(); - if code.contains("AccessDenied") || code.contains("UnauthorizedOperation") { - return StepError::new( - "sign_in", - "The CoderHelm role in your AWS account can't read metrics yet.", - "Update the role from Settings under AWS (one click adds read access to metrics).", - ); + if is_denied(&code) { + return StepError::role_refused(&[action]); } StepError::new( "read", @@ -376,20 +457,27 @@ where ) } +/// Pure: an AWS error code that says the role may not make the call. +fn is_denied(code: &str) -> bool { + code.contains("AccessDenied") || code.contains("UnauthorizedOperation") +} + #[async_trait::async_trait] impl MetricsApi for Aws<'_> { async fn list(&self, q: &CheckedList) -> Result, StepError> { use aws_sdk_cloudwatch::types::DimensionFilter; - let region = (q.namespace == "AWS/CloudFront").then_some("us-east-1"); - let c = client(self.session, region); - let mut req = c.list_metrics().namespace(q.namespace); + let c = client(self.session, q.region.as_deref()); + let mut req = c.list_metrics().namespace(&q.namespace); if let Some(m) = &q.metric { req = req.metric_name(m); } for (k, v) in &q.dimensions { req = req.dimensions(DimensionFilter::builder().name(k).value(v).build()); } - let out = req.send().await.map_err(|e| aws_error(&e))?; + let out = req + .send() + .await + .map_err(|e| aws_error(&e, "cloudwatch:ListMetrics"))?; Ok(out .metrics() .iter() @@ -412,7 +500,7 @@ impl MetricsApi for Aws<'_> { async fn get(&self, q: &CheckedQuery) -> Result, StepError> { use aws_sdk_cloudwatch::primitives::DateTime; use aws_sdk_cloudwatch::types::{Dimension, Metric, MetricDataQuery, MetricStat}; - let c = client(self.session, q.region); + let c = client(self.session, q.region.as_deref()); let mut req = c .get_metric_data() .start_time(DateTime::from_secs(q.start)) @@ -420,7 +508,7 @@ impl MetricsApi for Aws<'_> { .max_datapoints(5_000); for mq in &q.queries { let mut metric = Metric::builder() - .namespace(mq.namespace) + .namespace(&mq.namespace) .metric_name(&mq.metric); for (k, v) in &mq.dimensions { metric = metric.dimensions(Dimension::builder().name(k).value(v).build()); @@ -439,7 +527,10 @@ impl MetricsApi for Aws<'_> { .build(), ); } - let out = req.send().await.map_err(|e| aws_error(&e))?; + let out = req + .send() + .await + .map_err(|e| aws_error(&e, "cloudwatch:GetMetricData"))?; let mut series = Vec::new(); for mq in &q.queries { let r = out @@ -472,8 +563,8 @@ pub async fn probe(session: &Session) -> Result { match c.list_metrics().namespace("AWS/Lambda").send().await { Ok(_) => Ok(true), Err(e) => { - let err = aws_error(&e); - if err.step == "sign_in" { + let err = aws_error(&e, "cloudwatch:ListMetrics"); + if !err.role_refused.is_empty() { Ok(false) } else { Err(err) @@ -491,71 +582,171 @@ mod tests { const NOW: i64 = 1_800_000_000; #[test] - fn only_listed_namespaces_and_stats_pass() { + fn any_namespace_passes_and_common_ones_keep_their_spelling() { let ok = check_query( &[json!({"namespace":"aws/ecs","metric":"CPUUtilization","dimensions":{"ClusterName":"prod","ServiceName":"api"},"stat":"p95"})], None, Some("2h"), None, + None, NOW, ) .unwrap(); assert_eq!(ok.queries[0].namespace, "AWS/ECS"); assert_eq!(ok.period, 60); + assert_eq!(ok.region, None); // An instance's CPU, as a reviewer checks before a resize. let ec2 = check_query( &[json!({"namespace":"AWS/EC2","metric":"CPUUtilization","dimensions":{"InstanceId":"i-0123456789abcdef0"},"stat":"Maximum"})], Some(86_400), Some("7d"), None, + None, NOW, ) .unwrap(); assert_eq!(ec2.queries[0].namespace, "AWS/EC2"); - for ns in ["AWS/EBS", "AWS/NetworkELB", "AWS/ES"] { - assert!(check_namespace(ns).is_ok(), "{ns}"); + // The role decides what it may read, not a list here: namespaces + // outside the hints, and custom ones, are read as asked. + for ns in [ + "AWS/WAFV2", + "AWS/Billing", + "AWS/Usage", + "Custom/Mine", + "Glue", + "CWAgent", + ] { + let q = check_query( + &[json!({"namespace": ns, "metric":"x"})], + None, + None, + None, + None, + NOW, + ); + assert!(q.is_ok(), "{ns}: {q:?}"); + assert!(check_list(ns, None, &json!({}), None).is_ok(), "{ns}"); + } + // What CloudWatch itself can't hold is refused before it is sent. + for bad in ["", "AWS/WAFV2\nRule", &"x".repeat(256), "a\u{0}b"] { + assert!(check_namespace(bad).is_err(), "{bad:?}"); } - assert_eq!(ok.region, None); assert!(check_query( - &[json!({"namespace":"AWS/Billing","metric":"EstimatedCharges"})], + &[json!({"namespace":"AWS/ECS","metric":"x","stat":"Median"})], + None, None, None, None, NOW ) .is_err()); - assert!(check_query( - &[json!({"namespace":"Custom/Mine","metric":"x"})], - None, + assert!(check_query(&[], None, None, None, None, NOW).is_err()); + } + + #[test] + fn the_waf_namespace_is_a_hint_with_its_dimensions() { + let (ns, what) = NAMESPACE_HINTS + .iter() + .find(|(n, _)| *n == "AWS/WAFV2") + .expect("AWS/WAFV2 is a hint"); + assert_eq!(*ns, "AWS/WAFV2"); + for word in [ + "CountedRequests", + "BlockedRequests", + "AllowedRequests", + "WebACL", + "Rule", + "Region", + ] { + assert!(what.contains(word), "{word}"); + } + } + + #[test] + fn waf_metrics_read_where_the_web_acl_publishes_them() { + // A CloudFront web ACL: no Region dimension, published in us-east-1. + let cf = json!({"namespace":"AWS/WAFV2","metric":"CountedRequests","dimensions":{"WebACL":"example-web-acl","Rule":"ExampleCrawlerCount"},"stat":"Sum"}); + let blocked = json!({"namespace":"AWS/WAFV2","metric":"BlockedRequests","dimensions":{"WebACL":"example-web-acl","Rule":"ExampleCrawlerBlock"},"stat":"Sum"}); + let q = check_query( + &[cf.clone(), blocked], + Some(3600), + Some("1d"), None, None, - NOW + NOW, ) - .is_err()); - assert!(check_query( - &[json!({"namespace":"AWS/ECS","metric":"x","stat":"Median"})], + .unwrap(); + assert_eq!(q.region.as_deref(), Some("us-east-1")); + assert!(q.describe().contains( + "AWS/WAFV2 CountedRequests Sum [Rule=ExampleCrawlerCount, WebACL=example-web-acl]" + )); + // A regional web ACL: its Region dimension. + let regional = json!({"namespace":"AWS/WAFV2","metric":"BlockedRequests","dimensions":{"WebACL":"api-acl","Rule":"ALL","Region":"eu-west-1"},"stat":"Sum"}); + let q = check_query(std::slice::from_ref(®ional), None, None, None, None, NOW).unwrap(); + assert_eq!(q.region.as_deref(), Some("eu-west-1")); + // Mixed regions go in their own lookups, unless a region is named. + assert!(check_query(&[cf.clone(), regional.clone()], None, None, None, None, NOW).is_err()); + let named = check_query( + &[cf.clone(), regional], None, None, None, - NOW + Some("eu-west-1"), + NOW, ) - .is_err()); - assert!(check_query(&[], None, None, None, NOW).is_err()); + .unwrap(); + assert_eq!(named.region.as_deref(), Some("eu-west-1")); + assert!(check_query(&[cf], None, None, None, Some("not a region"), NOW).is_err()); + let l = check_list( + "AWS/WAFV2", + Some("CountedRequests"), + &json!({"WebACL":"example-web-acl"}), + None, + ) + .unwrap(); + assert_eq!(l.region.as_deref(), Some("us-east-1")); } #[test] fn windows_points_and_counts_are_capped() { let m = json!({"namespace":"AWS/Lambda","metric":"Duration"}); - assert!(check_query(std::slice::from_ref(&m), None, Some("15d"), None, NOW).is_err()); - assert!(check_query(std::slice::from_ref(&m), Some(30), None, None, NOW).is_err()); + assert!(check_query(std::slice::from_ref(&m), None, Some("15d"), None, None, NOW).is_err()); + assert!(check_query(std::slice::from_ref(&m), Some(30), None, None, None, NOW).is_err()); assert!( - check_query(std::slice::from_ref(&m), Some(60), Some("7d"), None, NOW).is_err(), + check_query( + std::slice::from_ref(&m), + Some(60), + Some("7d"), + None, + None, + NOW + ) + .is_err(), "10080 points" ); - assert!(check_query(std::slice::from_ref(&m), Some(3600), Some("7d"), None, NOW).is_ok()); + assert!(check_query( + std::slice::from_ref(&m), + Some(3600), + Some("7d"), + None, + None, + NOW + ) + .is_ok()); let six: Vec = (0..6).map(|_| m.clone()).collect(); - assert!(check_query(&six, None, None, None, NOW).is_err()); - let auto = check_query(&[m], None, Some("7d"), None, NOW).unwrap(); + assert!(check_query(&six, None, None, None, None, NOW).is_err()); + let dims: serde_json::Map = + (0..11).map(|i| (format!("d{i}"), json!("v"))).collect(); + assert!(check_query( + &[json!({"namespace":"AWS/Lambda","metric":"Duration","dimensions":dims})], + None, + None, + None, + None, + NOW + ) + .is_err()); + let auto = check_query(&[m], None, Some("7d"), None, None, NOW).unwrap(); assert!((7 * 86_400) / i64::from(auto.period) <= 120); } @@ -563,13 +754,25 @@ mod tests { fn cloudfront_reads_in_us_east_1_on_its_own() { let cf = json!({"namespace":"AWS/CloudFront","metric":"CacheHitRate","dimensions":{"DistributionId":"E1","Region":"Global"}}); assert_eq!( - check_query(std::slice::from_ref(&cf), None, None, None, NOW) + check_query(std::slice::from_ref(&cf), None, None, None, None, NOW) .unwrap() - .region, + .region + .as_deref(), Some("us-east-1") ); let other = json!({"namespace":"AWS/ECS","metric":"CPUUtilization"}); - assert!(check_query(&[cf, other], None, None, None, NOW).is_err()); + assert!(check_query(&[cf, other], None, None, None, None, NOW).is_err()); + } + + #[test] + fn a_refused_read_is_the_roles_setup_item_not_a_refusal_of_ours() { + assert!(is_denied("AccessDenied") && is_denied("AccessDeniedException")); + assert!(!is_denied("InvalidParameterValue")); + let e = StepError::role_refused(&["cloudwatch:GetMetricData"]); + assert!(!e.is_refusal()); + assert_eq!(e.role_refused, vec!["cloudwatch:GetMetricData"]); + assert!(e.message.contains("\"AWS role reads\""), "{}", e.message); + assert!(!e.message.contains("isn't a namespace")); } struct Fake { @@ -607,6 +810,7 @@ mod tests { None, None, None, + None, NOW, ) .unwrap(); @@ -620,10 +824,10 @@ mod tests { "AWS/ECS", Some("CPUUtilization"), &json!({"ClusterName":"prod"}), + None, ) .unwrap(); assert!(format_list(&api.list(&l).await.unwrap()).contains("ServiceName=api")); assert_eq!(*api.calls.lock().unwrap(), 2); - assert!(check_list("AWS/Billing", None, &json!({})).is_err()); } } diff --git a/services/common/src/live/mod.rs b/services/common/src/live/mod.rs index 9665cc4c2..bb790bff8 100644 --- a/services/common/src/live/mod.rs +++ b/services/common/src/live/mod.rs @@ -116,6 +116,12 @@ pub struct StepError { /// ([`source_errors::for_source`] words it for the kind of source). #[serde(skip)] pub cause: Option, + /// The IAM actions AWS refused the team's connected role: reads the role + /// stack's template has that this account's deployed role lacks. They + /// are the install's setup item (`aws_role_reads`), never a refusal of + /// ours and never a question on a run. + #[serde(skip)] + pub role_refused: Vec, } impl StepError { @@ -125,6 +131,17 @@ impl StepError { message: message.into(), fix: fix.into(), cause: None, + role_refused: Vec::new(), + } + } + + /// AWS refused the team's connected role `actions`: the lookup names the + /// install's setup item "AWS role reads" in one line and goes on. + pub fn role_refused(actions: &[&str]) -> Self { + let actions: Vec = actions.iter().map(|a| a.to_string()).collect(); + Self { + role_refused: actions.clone(), + ..Self::new("sign_in", crate::aws_role_reads::run_line(&actions), "") } } diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 11fbe97af..49aa2d368 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -212,6 +212,12 @@ pub enum WorkerMessage { /// `run.needs_input` event (`common::run_wait`). #[serde(rename = "run_waiting")] RunWaiting(RunWaitingMessage), + /// A run waiting for the install's setup item "AWS role reads" + /// (`awaiting_setup`, `crate::role_wait`): re-check the role, and go on + /// once it reads (self-scheduled with SQS delay; the daily role check + /// sends one too). + #[serde(rename = "role_reads_wait")] + RoleReadsWait(RoleReadsWaitMessage), /// One plugin run: a brief, a schedule or a release (see /// `plugins::run`). #[serde(rename = "plugin_run")] @@ -460,6 +466,7 @@ impl WorkerMessage { | WorkerMessage::KnowledgeSyncSweep | WorkerMessage::AgentResumeSweep | WorkerMessage::RunWaiting(_) + | WorkerMessage::RoleReadsWait(_) | WorkerMessage::LogAutofix | WorkerMessage::AwsPermissionsSweep | WorkerMessage::HybridNameCheck @@ -536,6 +543,7 @@ impl WorkerMessage { | WorkerMessage::JiraComment(_) | WorkerMessage::AgentResumeSweep | WorkerMessage::RunWaiting(_) + | WorkerMessage::RoleReadsWait(_) | WorkerMessage::PluginRun(_) | WorkerMessage::PluginPublish(_) | WorkerMessage::PluginSync(_) @@ -812,6 +820,21 @@ pub struct RunWaitingMessage { pub why: String, } +/// Re-check the role of a run waiting for the install's "AWS role reads" +/// item (`crate::role_wait`). +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct RoleReadsWaitMessage { + pub team_id: String, + pub run_id: String, + /// Re-checks sent so far on the fast schedule. + #[serde(default)] + pub polls: u32, + /// Sent by the daily role check or by a read that worked again: it + /// checks once and sends no next check. + #[serde(default)] + pub once: bool, +} + /// One webhook delivery to try (again). #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] pub struct WebhookSendMessage { diff --git a/services/common/src/role_wait.rs b/services/common/src/role_wait.rs new file mode 100644 index 000000000..c11b1693a --- /dev/null +++ b/services/common/src/role_wait.rs @@ -0,0 +1,301 @@ +//! A run whose missing data is only behind a read the team's AWS role +//! lacks waits for the install's setup item "AWS role reads", and goes on +//! by itself once the role has the read. +//! +//! An AWS WAF alarm run read the alarm's metrics, could not read the +//! requests the rule matched (the account's role stack predated the WAF +//! reads its template has), and ended `needs_outside_change` with "Needed +//! from you: Nothing" and a request that a person run an Athena query. The +//! read was the install's setup item, so no person had anything to do on +//! the run, and nothing would ever take the run up again once the role +//! could read. +//! +//! Now a run that stops without a code change ends by [`ending`]: +//! +//! - a person has an item (a decision, a credential, a change only they can +//! make): `needs_outside_change`, as before; +//! - nothing is left for a person and the run was refused reads by the +//! team's role ([`refused_this_run`]): it waits, `awaiting_setup`. It +//! says so in one paragraph ([`waiting_note`]), records the wait +//! ([`Waiting`], one record per run), and the worker re-checks the role +//! every [`POLL_SECS`] for [`FAST_POLLS`] checks, then once a day with +//! the role check, and at once when a read that was refused works again +//! in another run. When the role reads, the run starts again from the +//! ticket, reads the data and opens its pull request; +//! - nothing is left for a person and nothing to wait for: the plan is +//! CoderHelm's to make again, never a report that asks nobody for +//! anything under a status that says a person must act. + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; +use serde::{Deserialize, Serialize}; + +use crate::aws_role_reads::{Gap, ITEM_LABEL}; + +/// One record per waiting run, in the settings table under the team. +pub const SK_PREFIX: &str = "ROLE_WAIT#"; +/// Seconds between re-checks on the fast schedule (SQS's longest delay). +pub const POLL_SECS: i32 = 900; +/// Re-checks on the fast schedule (two days); then the daily role check. +pub const FAST_POLLS: u32 = 192; + +/// How a run whose plan changes no code ends. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Ending { + /// A person has an item: `needs_outside_change`. + Person, + /// Nothing for a person; the role lacks reads the data is behind: + /// `awaiting_setup` until a re-check shows the role has them. + AwaitRole(Vec), + /// Nothing for a person and nothing to wait for: plan again. + PlanAgain, +} + +/// Pure: how the run ends. `person_items` are the items left for a person +/// after the final check (`person_gate::sink`); `refused` the reads the +/// team's role was refused during this run ([`refused_this_run`]). +pub fn ending(person_items: &[String], refused: Vec) -> Ending { + if !person_items.is_empty() { + Ending::Person + } else if !refused.is_empty() { + Ending::AwaitRole(refused) + } else { + Ending::PlanAgain + } +} + +/// Pure: the install's recorded gaps this run met: refused at or after +/// `run_started` (RFC 3339). A gap is written again each time a read is +/// refused, so one older than the run was not this run's. +pub fn refused_this_run(gaps: &[Gap], run_started: &str) -> Vec { + let started = chrono::DateTime::parse_from_rfc3339(run_started).ok(); + gaps.iter() + .filter(|g| !g.actions.is_empty()) + .filter(|g| { + match ( + started, + chrono::DateTime::parse_from_rfc3339(&g.seen_at).ok(), + ) { + (Some(s), Some(seen)) => seen >= s, + _ => false, + } + }) + .cloned() + .collect() +} + +/// What a waiting run waits for. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Waiting { + pub run_id: String, + /// The accounts whose role lacks the reads. + pub accounts: Vec, + /// The reads, once each. + pub actions: Vec, + /// When the wait started (RFC 3339). + pub since: String, +} + +impl Waiting { + pub fn of(run_id: &str, gaps: &[Gap], now: &str) -> Waiting { + let mut w = Waiting { + run_id: run_id.to_string(), + since: now.to_string(), + ..Default::default() + }; + for g in gaps { + if !w.accounts.contains(&g.account) { + w.accounts.push(g.account.clone()); + } + for a in &g.actions { + if !w.actions.contains(a) { + w.actions.push(a.clone()); + } + } + } + w + } +} + +/// Pure: a read the data is not only behind: Athena and the Glue catalog +/// are one way to query WAF logs, and the log objects read straight from +/// the bucket are the other (`crate::waf_logs`), so a run never waits on +/// them alone once the other reads work. +pub fn optional(action: &str) -> bool { + action.starts_with("athena:") || action.starts_with("glue:") +} + +/// Pure: whether a re-check lets the run go on: none of the reads it waits +/// for was refused again (`still_refused` are the reads the re-check was +/// refused, in any order). Athena and Glue reads count only for a run that +/// waits for nothing else. +pub fn ready(w: &Waiting, still_refused: &[String]) -> bool { + let needed: Vec<&String> = w.actions.iter().filter(|a| !optional(a)).collect(); + let needed = if needed.is_empty() { + w.actions.iter().collect() + } else { + needed + }; + !needed.iter().any(|a| still_refused.contains(a)) +} + +/// Pure: the paragraph a waiting run's report ends with: what it waits for, +/// that it asks nobody, and what it does once the role reads. +pub fn waiting_note(w: &Waiting) -> String { + format!( + "**Waiting for the install's setup item \"{ITEM_LABEL}\".** The data this needs is \ + behind reads that the role stack's template has and the role in account {} lacks: {}. \ + CoderHelm read what the role allows and asks nobody on this run: the item's one-click \ + update of the role stack, which an AWS admin of the account creates, is listed once \ + for the whole install. CoderHelm checks the role every {} minutes, then daily, and \ + goes on by itself as soon as it reads: it reads the data, makes the change and opens \ + the pull request.", + w.accounts.join(", "), + w.actions.join(", "), + POLL_SECS / 60 + ) +} + +fn attr(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +/// Records the wait (best effort). +pub async fn record(dynamo: &DynamoClient, table: &str, team_id: &str, w: &Waiting) { + let Ok(json) = serde_json::to_string(w) else { + return; + }; + let res = dynamo + .put_item() + .table_name(table) + .item("pk", attr(team_id)) + .item("sk", attr(&format!("{SK_PREFIX}{}", w.run_id))) + .item("waiting", attr(&json)) + .send() + .await; + if let Err(e) = res { + tracing::warn!(team_id, run_id = %w.run_id, error = %e, "Could not record the run's wait for the AWS role's reads"); + } +} + +/// The run's wait, when it has one. +pub async fn get( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + run_id: &str, +) -> Option { + let out = dynamo + .get_item() + .table_name(table) + .key("pk", attr(team_id)) + .key("sk", attr(&format!("{SK_PREFIX}{run_id}"))) + .send() + .await + .ok()?; + let json = out.item()?.get("waiting")?.as_s().ok()?.clone(); + serde_json::from_str(&json).ok() +} + +/// Every run of the team waiting for the role's reads. +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(); + }; + out.items() + .iter() + .filter_map(|i| i.get("waiting")?.as_s().ok()) + .filter_map(|j| serde_json::from_str(j).ok()) + .collect() +} + +/// The wait is over (the run went on, or ended another way). +pub async fn remove(dynamo: &DynamoClient, table: &str, team_id: &str, run_id: &str) { + let _ = dynamo + .delete_item() + .table_name(table) + .key("pk", attr(team_id)) + .key("sk", attr(&format!("{SK_PREFIX}{run_id}"))) + .send() + .await; +} + +#[cfg(test)] +mod tests { + use super::*; + + fn gap(seen_at: &str) -> Gap { + Gap { + account: "111122223333".into(), + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + actions: vec![ + "wafv2:ListWebACLs".into(), + "wafv2:GetSampledRequests".into(), + ], + needed_for: "an AWS WAF alarm's evidence".into(), + seen_at: seen_at.into(), + ..Default::default() + } + } + + #[test] + fn a_run_with_nothing_for_a_person_waits_for_the_role_or_plans_again() { + let refused = vec![gap("2026-11-18T12:57:36Z")]; + assert_eq!( + ending( + &["Choose which page the banner goes on".into()], + refused.clone() + ), + Ending::Person + ); + assert_eq!(ending(&[], refused.clone()), Ending::AwaitRole(refused)); + assert_eq!(ending(&[], vec![]), Ending::PlanAgain); + } + + #[test] + fn only_refusals_this_run_met_count() { + let gaps = vec![gap("2026-11-18T12:57:36Z"), gap("2026-11-01T00:00:00Z")]; + let this = refused_this_run(&gaps, "2026-11-18T12:57:29Z"); + assert_eq!(this.len(), 1); + assert!(refused_this_run(&gaps, "2026-11-19T00:00:00Z").is_empty()); + assert!(refused_this_run(&gaps, "not a time").is_empty()); + } + + #[test] + fn the_wait_names_its_reads_and_goes_on_once_none_is_refused() { + let w = Waiting::of("run-1", &[gap("t"), gap("t")], "2026-11-18T13:04:33Z"); + assert_eq!(w.accounts, vec!["111122223333"]); + assert_eq!( + w.actions, + vec!["wafv2:ListWebACLs", "wafv2:GetSampledRequests"] + ); + assert!(!ready(&w, &["wafv2:GetSampledRequests".into()])); + assert!(ready(&w, &["athena:StartQueryExecution".into()])); + assert!(ready(&w, &[])); + // Athena stays optional: the log objects are read without it. + let mut logs = w.clone(); + logs.actions.push("athena:StartQueryExecution".into()); + assert!(ready(&logs, &["athena:StartQueryExecution".into()])); + let athena_only = Waiting { + actions: vec!["athena:StartQueryExecution".into()], + ..w.clone() + }; + assert!(!ready(&athena_only, &["athena:StartQueryExecution".into()])); + let note = waiting_note(&w); + assert!(note.contains("\"AWS role reads\""), "{note}"); + assert!(note.contains("asks nobody"), "{note}"); + assert!(note.contains("opens the pull request"), "{note}"); + // Never an ask that a person act on the run. + assert!(!crate::person_gate::grant_backed(¬e)); + let back: Waiting = serde_json::from_str(&serde_json::to_string(&w).unwrap()).unwrap(); + assert_eq!(back, w); + } +} diff --git a/services/common/src/run_status.rs b/services/common/src/run_status.rs index 2be4be7cb..76a79857e 100644 --- a/services/common/src/run_status.rs +++ b/services/common/src/run_status.rs @@ -20,6 +20,12 @@ pub const PENDING: &str = "pending"; pub const QUEUED: &str = "queued"; pub const RUNNING: &str = "running"; pub const AWAITING_CI: &str = "awaiting_ci"; +/// Waiting for the install's setup item "AWS role reads": the run read what +/// the team's AWS role allows, the rest needs a read the role stack's +/// template has and the account's role lacks, and nothing else would get +/// the data. It asks nobody and goes on by itself once a re-check shows +/// the role has the read (`role_wait`). +pub const AWAITING_SETUP: &str = "awaiting_setup"; pub const NEEDS_INPUT: &str = "needs_input"; pub const NEEDS_OUTSIDE_CHANGE: &str = "needs_outside_change"; /// An open pull request (anyone's) already does the work: the run linked it @@ -39,11 +45,12 @@ pub const RETRIED: &str = "retried"; pub const ARCHIVED: &str = "archived"; /// Every status a run record carries. -pub const ALL: [&str; 15] = [ +pub const ALL: [&str; 16] = [ PENDING, QUEUED, RUNNING, AWAITING_CI, + AWAITING_SETUP, NEEDS_INPUT, NEEDS_OUTSIDE_CHANGE, COVERED_BY_PR, @@ -218,6 +225,7 @@ mod tests { QUEUED, RUNNING, AWAITING_CI, + AWAITING_SETUP, NEEDS_INPUT, NEEDS_OUTSIDE_CHANGE, COVERED_BY_PR, @@ -250,6 +258,9 @@ mod tests { assert_eq!(reopen_status(NEEDS_OUTSIDE_CHANGE), NEEDS_OUTSIDE_CHANGE); assert_eq!(reopen_status(COVERED_BY_PR), COVERED_BY_PR); assert_eq!(reopen_status(NEEDS_INPUT), NEEDS_INPUT); + // A reopened run waiting for the role's reads waits again: the + // daily role check still finds it. + assert_eq!(reopen_status(AWAITING_SETUP), AWAITING_SETUP); for s in IN_FLIGHT { assert_eq!(reopen_status(s), NEEDS_INPUT, "{s}"); } diff --git a/services/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index 1c0ccccea..209ee96f6 100644 --- a/services/common/src/tool_registry.rs +++ b/services/common/src/tool_registry.rs @@ -80,6 +80,8 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("aws_identity", Risk::Read), ("aws_bucket_settings", Risk::Read), ("aws_kms_key", Risk::Read), + ("waf_sampled_requests", Risk::Read), + ("waf_log_objects", Risk::Read), ("newrelic_accounts", Risk::Read), ("newrelic_nrql", Risk::Read), ("newrelic_entities", Risk::Read), diff --git a/services/common/src/waf_logs.rs b/services/common/src/waf_logs.rs new file mode 100644 index 000000000..1830ff609 --- /dev/null +++ b/services/common/src/waf_logs.rs @@ -0,0 +1,847 @@ +//! A web ACL's log records read straight from its `aws-waf-logs-*` bucket: +//! no Athena, no Glue table, no query results location. +//! +//! An AWS WAF alarm run once ended asking a person to run an Athena query +//! for "which attribute of the crawler's requests changed", while the log +//! objects that hold the answer sat in a bucket the team's role may read +//! (`s3:ListBucket` and `s3:GetObject` on `aws-waf-logs-*`, the role stack's +//! `WafLogs` group). WAF writes them as gzip files of JSON lines, one file +//! every five minutes under +//! `AWSLogs//WAFLogs///YYYY/MM/dd/HH/mm/`. +//! This module lists the hours of a window newest first, reads the objects +//! within a bound (objects, compressed and uncompressed bytes), keeps the +//! records the rule matched (terminating, counted, or inside a rule group) +//! and groups them in the process: by JA4, user agent, accept language, +//! path and whether a cookie was sent, with countries, labels and actions +//! counted, and the matches per hour. Nothing else of a request is kept: no +//! client address, no cookie or other header value, no query string. + +use std::collections::BTreeMap; +use std::io::{BufRead, BufReader, Read as _}; + +use chrono::{DateTime, TimeZone, Utc}; +use serde_json::Value; + +use crate::live::aws::Session; + +/// Most objects read in one lookup (four hours of five-minute files). +pub const MAX_OBJECTS: usize = 48; +/// Most compressed bytes downloaded in one lookup. +pub const MAX_COMPRESSED_BYTES: i64 = 64 * 1024 * 1024; +/// Most uncompressed bytes read in one lookup. +pub const MAX_UNCOMPRESSED_BYTES: u64 = 512 * 1024 * 1024; +/// Longest window read in one lookup. +pub const MAX_WINDOW_SECS: i64 = 24 * 3600; +/// Rows shown, most requests first. +const TOP_ROWS: usize = 20; +/// Values shown per counted kind. +const TOP: usize = 8; +/// Longest value kept. +const MAX_VALUE: usize = 200; +/// Keys listed per hour. +const MAX_KEYS_PER_HOUR: i32 = 1000; + +fn clip(v: &str) -> String { + crate::truncate_str(v.trim(), MAX_VALUE).replace("```", "'''") +} + +/// Where a web ACL's log objects are. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LogLocation { + pub bucket: String, + /// The destination's own prefix (empty, or ending in `/`). + pub prefix: String, + pub account: String, + /// `cloudfront` for a CloudFront web ACL, else its region. + pub scope: String, + pub web_acl: String, +} + +/// Pure: the bucket and prefix of an S3 logging destination +/// (`arn:aws:s3:::aws-waf-logs-example` or `.../aws-waf-logs-example/some/prefix`). +pub fn destination(arn: &str) -> Option<(String, String)> { + let rest = arn.strip_prefix("arn:aws:s3:::")?; + let (bucket, prefix) = match rest.split_once('/') { + Some((b, p)) => (b, p.trim_matches('/')), + None => (rest, ""), + }; + if !is_bucket(bucket) { + return None; + } + let prefix = if prefix.is_empty() { + String::new() + } else { + format!("{prefix}/") + }; + Some((bucket.to_string(), prefix)) +} + +/// Pure: a bucket WAF may log to (its name must start with `aws-waf-logs-`). +pub fn is_bucket(b: &str) -> bool { + b.starts_with("aws-waf-logs-") + && b.len() <= 63 + && b.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '.') +} + +impl LogLocation { + /// Pure: from a web ACL's ARN + /// (`arn:aws:wafv2:::global/webacl//` for + /// CloudFront, `.../regional/webacl/...` otherwise) and its S3 logging + /// destination. + pub fn of(web_acl_arn: &str, destination_arn: &str) -> Option { + let (bucket, prefix) = destination(destination_arn)?; + let parts: Vec<&str> = web_acl_arn.splitn(6, ':').collect(); + if parts.len() != 6 || parts[2] != "wafv2" { + return None; + } + let (region, account, res) = (parts[3], parts[4], parts[5]); + let mut r = res.split('/'); + let scope = match r.next()? { + "global" => "cloudfront".to_string(), + "regional" => region.to_string(), + _ => return None, + }; + if r.next()? != "webacl" { + return None; + } + let web_acl = r.next()?.to_string(); + let ok = account.len() == 12 && account.chars().all(|c| c.is_ascii_digit()); + (ok && !web_acl.is_empty()).then(|| LogLocation { + bucket, + prefix, + account: account.to_string(), + scope, + web_acl, + }) + } + + /// Pure: the prefix of one hour's objects. + pub fn hour_prefix(&self, at: DateTime) -> String { + format!( + "{}AWSLogs/{}/WAFLogs/{}/{}/{}/", + self.prefix, + self.account, + self.scope, + self.web_acl, + at.format("%Y/%m/%d/%H") + ) + } + + /// Pure: each hour's prefix from `end` back to `start`, newest first. + pub fn hour_prefixes(&self, start: i64, end: i64) -> Vec { + let hour = |t: i64| t - t.rem_euclid(3600); + let mut out = Vec::new(); + let mut t = hour(end); + while t >= hour(start) && out.len() < 25 { + if let Some(at) = Utc.timestamp_opt(t, 0).single() { + out.push(self.hour_prefix(at)); + } + t -= 3600; + } + out + } +} + +/// Pure: the minute an object's key says it starts at +/// (`.../YYYY/MM/dd/HH/mm/`). +pub fn key_minute(key: &str) -> Option { + let parts: Vec<&str> = key.rsplit('/').skip(1).take(5).collect(); + if parts.len() != 5 { + return None; + } + let n = |s: &str| s.parse::().ok(); + let (mi, h, d, mo, y) = ( + n(parts[0])?, + n(parts[1])?, + n(parts[2])?, + n(parts[3])?, + parts[4].parse::().ok()?, + ); + Utc.with_ymd_and_hms(y, mo, d, h, mi, 0) + .single() + .map(|t| t.timestamp()) +} + +/// Pure: whether an object can hold records of `[start, end]` (a file holds +/// the five minutes after its folder's minute, so one that starts up to ten +/// minutes before the window is read too). +pub fn key_in_window(key: &str, start: i64, end: i64) -> bool { + key_minute(key).is_some_and(|m| m >= start - 600 && m <= end) +} + +/// Pure: whether a log record names `rule` as matched: its terminating rule, +/// a counted rule, or either inside a rule group. +pub fn matches_rule(v: &Value, rule: &str) -> bool { + let id = |x: &Value| x["ruleId"].as_str() == Some(rule); + if v["terminatingRuleId"].as_str() == Some(rule) { + return true; + } + let list = |x: &Value| x.as_array().is_some_and(|a| a.iter().any(id)); + if list(&v["nonTerminatingMatchingRules"]) { + return true; + } + v["ruleGroupList"].as_array().is_some_and(|groups| { + groups.iter().any(|g| { + id(&g["terminatingRule"]) + || list(&g["nonTerminatingMatchingRules"]) + || list(&g["excludedRules"]) + }) + }) +} + +/// One group of matching requests. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct RowKey { + pub ja4: String, + pub user_agent: String, + pub accept_language: String, + pub path: String, + pub cookie: bool, +} + +/// What the records read so far say about the rule's matches. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Tally { + pub records: i64, + pub matched: i64, + pub rows: BTreeMap, + pub countries: BTreeMap, + pub labels: BTreeMap, + pub actions: BTreeMap, + /// Matches per hour (`YYYY-MM-DD HH:00`). + pub hours: BTreeMap, + /// JA4 prefixes (the first two of its three parts), which change less + /// often than the whole fingerprint. + pub ja4_prefixes: BTreeMap, +} + +fn header<'a>(headers: &'a [Value], name: &str) -> Option<&'a str> { + headers + .iter() + .find(|h| { + h["name"] + .as_str() + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + }) + .and_then(|h| h["value"].as_str()) +} + +/// Pure: a JA4 fingerprint's first two parts (`t13d1516h2_8daaf6152771`). +pub fn ja4_prefix(ja4: &str) -> String { + let mut p = ja4.splitn(3, '_'); + match (p.next(), p.next()) { + (Some(a), Some(b)) if !a.is_empty() && !b.is_empty() => format!("{a}_{b}"), + _ => ja4.to_string(), + } +} + +impl Tally { + /// Counts one log line: a record in `[start_ms, end_ms]` that names + /// `rule`. Lines that aren't records are skipped. + pub fn add(&mut self, line: &str, rule: &str, start_ms: i64, end_ms: i64) { + let Ok(v) = serde_json::from_str::(line) else { + return; + }; + let at = v["timestamp"].as_i64().unwrap_or(0); + if at < start_ms || at > end_ms { + return; + } + self.records += 1; + if !matches_rule(&v, rule) { + return; + } + self.matched += 1; + let req = &v["httpRequest"]; + let empty = Vec::new(); + let headers = req["headers"].as_array().unwrap_or(&empty); + let ja4 = clip(v["ja4Fingerprint"].as_str().unwrap_or("")); + let key = RowKey { + ja4: ja4.clone(), + user_agent: clip(header(headers, "user-agent").unwrap_or("")), + accept_language: clip(header(headers, "accept-language").unwrap_or("")), + path: clip( + req["uri"] + .as_str() + .unwrap_or("") + .split(['?', '#']) + .next() + .unwrap_or(""), + ), + cookie: header(headers, "cookie").is_some(), + }; + *self.rows.entry(key).or_default() += 1; + if !ja4.is_empty() { + *self.ja4_prefixes.entry(ja4_prefix(&ja4)).or_default() += 1; + } + let country = clip(req["country"].as_str().unwrap_or("")); + *self.countries.entry(country).or_default() += 1; + if let Some(labels) = v["labels"].as_array() { + for l in labels.iter().filter_map(|l| l["name"].as_str()) { + *self.labels.entry(clip(l)).or_default() += 1; + } + } + *self + .actions + .entry(clip(v["action"].as_str().unwrap_or(""))) + .or_default() += 1; + if let Some(t) = Utc.timestamp_millis_opt(at).single() { + *self + .hours + .entry(t.format("%Y-%m-%d %H:00").to_string()) + .or_default() += 1; + } + } + + /// Pure: the evidence lines, most requests first. + pub fn lines(&self, rule: &str) -> Vec { + let mut out = vec![format!( + "{} of {} log records named the rule {rule}.", + self.matched, self.records + )]; + if self.matched == 0 { + out.push(format!( + " - none (the alarm's Rule dimension is the rule's metric name; when the rule's \ + own name differs, read the logs for that name: {rule} is what was looked for)" + )); + return out; + } + let total = self.matched.max(1); + let pct = |n: i64| (n * 100) / total; + let mut rows: Vec<(&RowKey, &i64)> = self.rows.iter().collect(); + rows.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); + out.push( + "By JA4, user agent, accept language, path and cookie presence, most requests first:" + .into(), + ); + let dash = |s: &str| { + if s.is_empty() { + "-".to_string() + } else { + s.to_string() + } + }; + for (k, n) in rows.iter().take(TOP_ROWS) { + out.push(format!( + " - {n} requests ({}%): JA4 {} · {} · Accept-Language {} · {} · {}", + pct(**n), + dash(&k.ja4), + dash(&k.user_agent), + dash(&k.accept_language), + dash(&k.path), + if k.cookie { "a cookie" } else { "no cookie" } + )); + } + if rows.len() > TOP_ROWS { + out.push(format!(" - and {} more groups", rows.len() - TOP_ROWS)); + } + let mut counted = |label: &str, m: &BTreeMap| { + let mut v: Vec<(&String, &i64)> = m.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); + if v.is_empty() { + return; + } + out.push(format!( + "{label}: {}", + v.iter() + .take(TOP) + .map(|(k, n)| format!("{} {n} ({}%)", dash(k), pct(**n))) + .collect::>() + .join("; ") + )); + }; + counted("JA4 prefixes", &self.ja4_prefixes); + counted("Countries", &self.countries); + counted("Labels", &self.labels); + counted("Actions", &self.actions); + if !self.hours.is_empty() { + out.push(format!( + "Matches per hour (UTC): {}", + self.hours + .iter() + .map(|(h, n)| format!("{h} {n}")) + .collect::>() + .join("; ") + )); + } + out + } +} + +/// What a read of the log objects found. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LogRead { + pub lines: Vec, + /// IAM actions AWS refused the role (the install's setup item). + pub refused: Vec, + pub tally: Tally, + pub objects_read: usize, +} + +impl LogRead { + /// Records came back that name the rule. + pub fn found(&self) -> bool { + self.tally.matched > 0 + } +} + +/// Pure: whether an S3 error code means the role may not make the call. +pub fn is_denied(code: Option<&str>) -> bool { + crate::log_repo::live::is_refusal(code) || code == Some("AllAccessDisabled") +} + +/// Pure: the lines of a gzip object, uncompressed up to `left` bytes, into +/// the tally. Returns the bytes read. +pub fn tally_object( + gz: &[u8], + tally: &mut Tally, + rule: &str, + start_ms: i64, + end_ms: i64, + left: u64, +) -> u64 { + let decoder = flate2::read::MultiGzDecoder::new(gz).take(left); + let mut reader = BufReader::new(decoder); + let mut read = 0u64; + let mut line = String::new(); + loop { + line.clear(); + match reader.read_line(&mut line) { + Ok(0) | Err(_) => break, + Ok(n) => { + read += n as u64; + tally.add(&line, rule, start_ms, end_ms); + } + } + } + read +} + +fn s3_client(s: &Session, region: &str) -> aws_sdk_s3::Client { + use aws_sdk_s3::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_s3::Client::from_conf( + aws_sdk_s3::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(region.to_string())) + .credentials_provider(creds) + .build(), + ) +} + +/// Reads the rule's matches from the log objects in `[start, end]` (at +/// most [`MAX_WINDOW_SECS`], newest first, within the bounds above). +pub async fn read( + session: &Session, + loc: &LogLocation, + rule: &str, + start: i64, + end: i64, +) -> LogRead { + use aws_sdk_s3::error::ProvideErrorMetadata; + let start = start.max(end - MAX_WINDOW_SECS); + let mut out = LogRead::default(); + let mut region = session.region.clone(); + let mut s3 = s3_client(session, ®ion); + let mut keys: Vec<(String, i64)> = Vec::new(); + for prefix in loc.hour_prefixes(start, end) { + let mut token: Option = None; + loop { + let mut res = s3 + .list_objects_v2() + .bucket(&loc.bucket) + .prefix(&prefix) + .max_keys(MAX_KEYS_PER_HOUR) + .set_continuation_token(token.clone()) + .send() + .await; + if let Err(e) = &res { + // A bucket in another region: S3 names it; ask there. + let moved = crate::live::aws_settings::bucket_region(e).filter(|r| *r != region); + if let Some(r) = moved { + region = r; + s3 = s3_client(session, ®ion); + res = s3 + .list_objects_v2() + .bucket(&loc.bucket) + .prefix(&prefix) + .max_keys(MAX_KEYS_PER_HOUR) + .set_continuation_token(token.clone()) + .send() + .await; + } + } + match res { + Ok(o) => { + keys.extend(o.contents().iter().filter_map(|c| { + let k = c.key()?.to_string(); + key_in_window(&k, start, end).then(|| (k, c.size().unwrap_or(0))) + })); + token = o + .next_continuation_token() + .filter(|t| !t.is_empty() && o.is_truncated() == Some(true)) + .map(str::to_string); + if token.is_none() { + break; + } + } + Err(e) if is_denied(e.code()) => { + out.refused.push("s3:ListBucket".into()); + out.lines.push(format!( + "Couldn't list the web ACL's log objects in {}: CoderHelm's AWS role \ + doesn't allow s3:ListBucket there yet.", + loc.bucket + )); + return out; + } + Err(e) => { + out.lines.push(format!( + "Couldn't list the web ACL's log objects in {}: {}", + loc.bucket, + clip(e.message().or(e.code()).unwrap_or("no answer")) + )); + return out; + } + } + } + if keys.len() >= MAX_OBJECTS * 4 { + break; + } + } + if keys.is_empty() { + out.lines.push(format!( + "No log objects for the web ACL {} in {} between {} and {} UTC (under {}).", + loc.web_acl, + loc.bucket, + fmt(start), + fmt(end), + loc.hour_prefixes(start, end) + .last() + .cloned() + .unwrap_or_default() + )); + return out; + } + // Newest first, so a bound leaves out the oldest records. + keys.sort_by(|a, b| b.0.cmp(&a.0)); + let listed = keys.len(); + let (start_ms, end_ms) = (start * 1000, end * 1000); + let mut compressed = 0i64; + let mut uncompressed = 0u64; + let mut oldest_read: Option = None; + for (key, size) in keys.iter().take(MAX_OBJECTS) { + if compressed + size > MAX_COMPRESSED_BYTES && out.objects_read > 0 { + break; + } + let got = s3.get_object().bucket(&loc.bucket).key(key).send().await; + let body = match got { + Ok(o) => match o.body.collect().await { + Ok(b) => b.into_bytes(), + Err(_) => continue, + }, + Err(e) if is_denied(e.code()) => { + out.refused.push("s3:GetObject".into()); + out.lines.push(format!( + "Couldn't read the web ACL's log objects in {}: CoderHelm's AWS role doesn't \ + allow s3:GetObject (or decrypting with the bucket's KMS key) there yet.", + loc.bucket + )); + break; + } + Err(_) => continue, + }; + compressed += body.len() as i64; + let left = MAX_UNCOMPRESSED_BYTES.saturating_sub(uncompressed); + uncompressed += tally_object(&body, &mut out.tally, rule, start_ms, end_ms, left); + out.objects_read += 1; + oldest_read = key_minute(key); + if uncompressed >= MAX_UNCOMPRESSED_BYTES { + break; + } + } + if out.objects_read == 0 { + return out; + } + let mut head = format!( + "The web ACL's log objects in {} ({} of {} objects between {} and {} UTC, newest first", + loc.bucket, + out.objects_read, + listed, + fmt(start), + fmt(end) + ); + if out.objects_read < listed { + head.push_str(&format!( + "; the bound stopped at the objects from {} UTC", + oldest_read.map(fmt).unwrap_or_default() + )); + } + head.push_str("):"); + out.lines.push(head); + out.lines.extend(out.tally.lines(rule)); + out +} + +fn fmt(t: i64) -> String { + Utc.timestamp_opt(t, 0) + .single() + .map(|d| d.format("%Y-%m-%d %H:%M").to_string()) + .unwrap_or_default() +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::io::Write as _; + + pub const ACL_ARN: &str = + "arn:aws:wafv2:us-east-1:111122223333:global/webacl/example-web-acl/0123abcd"; + + /// One WAF log record, in the shape WAF writes it. + pub fn record( + at_ms: i64, + terminating: &str, + counted: &[&str], + ja4: &str, + ua: &str, + lang: &str, + cookie: bool, + ) -> String { + let mut headers = vec![ + serde_json::json!({"name": "Host", "value": "www.example.com"}), + serde_json::json!({"name": "User-Agent", "value": ua}), + serde_json::json!({"name": "Accept-Language", "value": lang}), + ]; + if cookie { + headers.push(serde_json::json!({"name": "Cookie", "value": "session=secret-value"})); + } + serde_json::json!({ + "timestamp": at_ms, + "terminatingRuleId": terminating, + "action": if terminating == "Default_Action" { "ALLOW" } else { "BLOCK" }, + "nonTerminatingMatchingRules": counted.iter().map(|r| serde_json::json!({"ruleId": r, "action": "COUNT"})).collect::>(), + "ruleGroupList": [], + "httpRequest": { + "clientIp": "198.51.100.7", + "country": "US", + "headers": headers, + "uri": "/listings", + "args": "sport=a&sport=b&token=secret", + "httpMethod": "GET" + }, + "labels": [{"name": "awswaf:clientip:geo:country:US"}], + "ja3Fingerprint": "773906b0efdefa24a7f2b8eb6985bf37", + "ja4Fingerprint": ja4 + }) + .to_string() + } + + pub fn gz(lines: &[String]) -> Vec { + let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + for l in lines { + e.write_all(l.as_bytes()).unwrap(); + e.write_all(b"\n").unwrap(); + } + e.finish().unwrap() + } + + #[test] + fn a_web_acls_log_objects_are_found_by_its_arn_and_destination() { + let loc = LogLocation::of(ACL_ARN, "arn:aws:s3:::aws-waf-logs-example").unwrap(); + assert_eq!(loc.scope, "cloudfront"); + assert_eq!(loc.prefix, ""); + // 2026-11-18 12:59 UTC back to 10:00. + let end = Utc + .with_ymd_and_hms(2026, 11, 18, 12, 59, 0) + .unwrap() + .timestamp(); + let p = loc.hour_prefixes(end - 3 * 3600 + 60, end); + assert_eq!( + p, + vec![ + "AWSLogs/111122223333/WAFLogs/cloudfront/example-web-acl/2026/11/18/12/", + "AWSLogs/111122223333/WAFLogs/cloudfront/example-web-acl/2026/11/18/11/", + "AWSLogs/111122223333/WAFLogs/cloudfront/example-web-acl/2026/11/18/10/", + ] + ); + let regional = LogLocation::of( + "arn:aws:wafv2:eu-west-1:111122223333:regional/webacl/api-acl/9", + "arn:aws:s3:::aws-waf-logs-example/edge", + ) + .unwrap(); + assert_eq!(regional.scope, "eu-west-1"); + assert!(regional + .hour_prefix(Utc.with_ymd_and_hms(2026, 1, 2, 3, 0, 0).unwrap()) + .starts_with("edge/AWSLogs/111122223333/WAFLogs/eu-west-1/api-acl/2026/01/02/03/")); + // Only WAF's buckets. + assert_eq!( + LogLocation::of(ACL_ARN, "arn:aws:s3:::another-bucket"), + None + ); + assert_eq!( + LogLocation::of( + ACL_ARN, + "arn:aws:logs:us-east-1:111122223333:log-group:aws-waf-logs-x" + ), + None + ); + let key = "AWSLogs/111122223333/WAFLogs/cloudfront/example-web-acl/2026/11/18/12/55/111122223333_waflogs_cloudfront_example-web-acl_20261118T1255Z_abc.log.gz"; + assert_eq!( + key_minute(key), + Some( + Utc.with_ymd_and_hms(2026, 11, 18, 12, 55, 0) + .unwrap() + .timestamp() + ) + ); + assert!(key_in_window(key, end - 3600, end)); + assert!(!key_in_window(key, end - 7200, end - 3600)); + } + + #[test] + fn the_rules_matches_are_grouped_by_what_tells_a_client_apart() { + let t0 = 1_795_000_000_000; + let new_ja4 = "t13d1517h2_8daaf6152771_b6f405a00624"; + let old_ja4 = "t13d1516h2_8daaf6152771_02713d6af862"; + let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"; + let mut lines = Vec::new(); + for i in 0..6 { + lines.push(record( + t0 + i, + "Default_Action", + &["ExampleCrawlerCount"], + new_ja4, + ua, + "en-US,en;q=0.9", + false, + )); + } + for i in 0..2 { + lines.push(record( + t0 + i, + "ExampleCrawlerBlock", + &[], + old_ja4, + ua, + "en-US,en;q=0.9", + false, + )); + } + lines.push(record( + t0, + "Default_Action", + &["ExampleCrawlerCount"], + new_ja4, + ua, + "en-US,en;q=0.9", + true, + )); + lines.push(record( + t0, + "Default_Action", + &[], + new_ja4, + ua, + "de-DE", + false, + )); + lines.push("not a record".into()); + let body = gz(&lines); + let mut t = Tally::default(); + let read = tally_object( + &body, + &mut t, + "ExampleCrawlerCount", + t0 - 1, + t0 + 1000, + u64::MAX, + ); + assert!(read > 0); + assert_eq!(t.records, 10); + assert_eq!(t.matched, 7); + let text = t.lines("ExampleCrawlerCount").join("\n"); + assert!( + text.contains("7 of 10 log records named the rule ExampleCrawlerCount"), + "{text}" + ); + assert!( + text.contains(&format!("6 requests (85%): JA4 {new_ja4} · {ua} · Accept-Language en-US,en;q=0.9 · /listings · no cookie")), + "{text}" + ); + assert!( + text.contains("1 requests (14%)") && text.contains("a cookie"), + "{text}" + ); + assert!( + text.contains("JA4 prefixes: t13d1517h2_8daaf6152771 7 (100%)"), + "{text}" + ); + // Nothing private is kept. + for never in ["198.51.100.7", "secret", "token=", "www.example.com"] { + assert!(!text.contains(never), "{never}: {text}"); + } + // The block rule's own matches are its rule's. + let mut b = Tally::default(); + tally_object( + &body, + &mut b, + "ExampleCrawlerBlock", + t0 - 1, + t0 + 1000, + u64::MAX, + ); + assert_eq!(b.matched, 2); + // Out of the window, or the bound reached: nothing more is counted. + let mut late = Tally::default(); + tally_object( + &body, + &mut late, + "ExampleCrawlerCount", + t0 + 10_000, + t0 + 20_000, + u64::MAX, + ); + assert_eq!((late.records, late.matched), (0, 0)); + let mut capped = Tally::default(); + tally_object( + &body, + &mut capped, + "ExampleCrawlerCount", + t0 - 1, + t0 + 1000, + 10, + ); + assert_eq!(capped.records, 0); + } + + #[test] + fn a_rule_inside_a_rule_group_counts() { + let v = serde_json::json!({ + "terminatingRuleId": "Default_Action", + "ruleGroupList": [{ + "ruleGroupId": "arn:aws:wafv2:us-east-1:111122223333:global/rulegroup/g/1", + "terminatingRule": null, + "nonTerminatingMatchingRules": [{"ruleId": "InGroup", "action": "COUNT"}], + "excludedRules": null + }] + }); + assert!(matches_rule(&v, "InGroup")); + assert!(!matches_rule(&v, "Other")); + assert_eq!( + ja4_prefix("t13d1516h2_8daaf6152771_e5627efa2ab1"), + "t13d1516h2_8daaf6152771" + ); + assert_eq!(ja4_prefix("odd"), "odd"); + let none = Tally::default().lines("ExampleCrawlerCount").join("\n"); + assert!( + none.contains("0 of 0") && none.contains("metric name"), + "{none}" + ); + } +} diff --git a/services/gateway/src/mcp_server.rs b/services/gateway/src/mcp_server.rs index 195967c6f..19a0b827f 100644 --- a/services/gateway/src/mcp_server.rs +++ b/services/gateway/src/mcp_server.rs @@ -215,7 +215,7 @@ pub const TOOLS: &[Tool] = &[ schema: || { obj( json!({ - "status": { "type": "string", "description": "Only runs in these statuses, comma separated: pending, running, awaiting_ci, completed, failed, needs_input, needs_outside_change, covered_by_pr, cancelled, retried, closed." }, + "status": { "type": "string", "description": "Only runs in these statuses, comma separated: pending, running, awaiting_ci, awaiting_setup, completed, failed, needs_input, needs_outside_change, covered_by_pr, cancelled, retried, closed." }, "repo": { "type": "string", "description": "Only runs in this repository, owner/name." }, "since": { "type": "string", "description": "Only runs started at or after this time (RFC 3339, or a date like 2026-11-01)." }, "limit": { "type": "integer", "minimum": 1, "maximum": 100, "description": "Most runs to return. Default 20." }, diff --git a/services/gateway/src/routes/chat_work_runs.rs b/services/gateway/src/routes/chat_work_runs.rs index 5fe995f38..cdc8d6ff4 100644 --- a/services/gateway/src/routes/chat_work_runs.rs +++ b/services/gateway/src/routes/chat_work_runs.rs @@ -51,7 +51,11 @@ impl Group { fn holds(self, status: &str) -> bool { use common::run_status as rs; - let waiting = [rs::NEEDS_INPUT, rs::NEEDS_OUTSIDE_CHANGE]; + let waiting = [ + rs::NEEDS_INPUT, + rs::NEEDS_OUTSIDE_CHANGE, + rs::AWAITING_SETUP, + ]; match self { // Archived runs show only when asked for by run id. Group::Any => status != rs::ARCHIVED, diff --git a/services/gateway/src/routes/trigger_gate.rs b/services/gateway/src/routes/trigger_gate.rs index b9fa22fdb..4840306b1 100644 --- a/services/gateway/src/routes/trigger_gate.rs +++ b/services/gateway/src/routes/trigger_gate.rs @@ -7,6 +7,8 @@ //! //! - a run in flight (running / queued / awaiting_ci) always blocks — a new //! run would force-reset the branch out from under the active one +//! - a run waiting for the install's "AWS role reads" item +//! (`awaiting_setup`) blocks too: it goes on by itself once the role reads //! - a completed latest run whose PR is still open (auto-merge armed //! included) has handled the ticket: no new run starts. An edit that //! changes the ticket's CONTENT goes to that PR's feedback path @@ -236,6 +238,9 @@ pub async fn gate_ticket_trigger( match status_of(i).as_str() { "running" | "queued" => h < 2, "awaiting_ci" => h < 26, + // Waiting for the role's reads goes on by itself (`role_wait`); + // a second run would wait for the same item. + "awaiting_setup" => h < 24 * 14, _ => false, } }) { diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 6d8c9ef0d..ae0f19bdb 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -1021,6 +1021,9 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe models::WorkerMessage::RunWaiting(msg) => { passes::webhooks::run_waiting(&state, &msg).await; } + models::WorkerMessage::RoleReadsWait(msg) => { + passes::role_wait::check(&state, &msg).await; + } // Handled in `handle_sqs`, where a failure fails the message. models::WorkerMessage::UsageRecord(_) => {} } diff --git a/services/worker/src/passes/aws_permissions.rs b/services/worker/src/passes/aws_permissions.rs index 3819410f6..cf0ed4d31 100644 --- a/services/worker/src/passes/aws_permissions.rs +++ b/services/worker/src/passes/aws_permissions.rs @@ -9,6 +9,10 @@ //! (`common::role_move`): a source switches only when the stack's role //! passed the source's own connection check end to end. //! +//! The same sweep sends a re-check of every run waiting for the role's +//! reads (`role_wait`), so a run whose fast re-checks are over still goes +//! on the day the role stack is updated. +//! //! "Once" is a team record (`AWS_PERMS_NOTICE`) holding the permissions id //! it was told about, written with a condition before the message is sent, //! so two sweeps never post twice. @@ -186,6 +190,9 @@ pub async fn run(state: &WorkerState) -> Result { checks.push(c); } report.sources_moved += move_sources(state, team_id, accounts).await; + // Runs waiting for the role's reads (`awaiting_setup`) check the + // role again now: the daily check after their fast re-checks. + super::role_wait::wake(state, team_id, None).await; let last = told(state, team_id).await; if !should_tell(&checks, last.as_deref()) || !claim_notice(state, team_id).await { continue; diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index f27b6c195..d925e04c6 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -608,6 +608,13 @@ pub fn mark_untraced(mut d: FixDecision, gaps: &[String]) -> FixDecision { d } +/// Pure: every lookup a planner made, from the data sources (`live`) and +/// the monitoring tools (`ops`: CloudWatch metrics, New Relic, AWS WAF, +/// Airflow). A decision is "unchecked" only when this is zero. +pub fn lookups_made(live: usize, ops: usize) -> usize { + live + ops +} + /// A decision still unchecked after being sent back: no code is written on /// it. It becomes `unknown`, saying the data wasn't checked. pub fn mark_unchecked(mut d: FixDecision) -> FixDecision { diff --git a/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs b/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs new file mode 100644 index 000000000..fc37dc185 --- /dev/null +++ b/services/worker/src/passes/incidents/cx_role_reads_wait_then_finish.rs @@ -0,0 +1,248 @@ +//! cx. An AWS WAF signature-drift alarm (a Count rule counting a crawler's +//! requests that got past a Block rule) reached a team's terraform +//! repository. The account's role stack predated the template's WAF reads, +//! so the alarm's evidence was refused; CoderHelm refused the alarm's own +//! metric itself ("AWS/WAFV2 isn't a namespace Coderhelm reads"); five +//! New Relic lookups were labelled "no lookups were made"; and the run +//! ended `needs_outside_change` with "Needed from you: Nothing", asking a +//! person to run an Athena query. +//! +//! Guarantee: any namespace is read (the role is the boundary); the rule's +//! matches are read without Athena (sampled requests, the log objects in +//! the bucket); every lookup counts; and a run with nothing left for a +//! person waits for the install's "AWS role reads" item (`awaiting_setup`) +//! and goes on by itself to its pull request once the role reads. + +use common::alarm_evidence as ae; +use common::aws_role_reads::{self, Gap}; +use common::live::metrics; +use common::role_wait::{self, Ending, Waiting}; +use common::run_status; +use common::waf_logs::{LogLocation, Tally}; +use serde_json::json; + +use crate::passes::fix_location::{self, FixDecision, Route}; + +const OLD_REFUSAL: &str = "isn't a namespace Coderhelm reads"; +const OLD_LABEL: &str = "Not checked against the data (no lookups were made)"; +const ACCOUNT: &str = "111122223333"; +const ROLE: &str = "arn:aws:iam::111122223333:role/CoderHelmLogReader"; + +/// The ticket the alert route wrote, in the run's shape. +const TICKET: &str = "ALARM: example-crawler-signature-drift\n\n\ + - Alarm: example-crawler-signature-drift\n\ + - State: ALARM (was OK)\n\ + - Description: ExampleCrawlerCount (Count) counts listing loads ExampleCrawlerBlock didn't block.\n\ + - Metric: AWS/WAFV2 / CountedRequests\n\ + - Dimensions: WebACL=example-web-acl, Rule=ExampleCrawlerCount\n\ + - Statistic: SUM\n"; + +/// The decision the planner wrote, in the run's shape: data-backed, its +/// one person step the role's reads. +fn decision() -> FixDecision { + serde_json::from_value(json!({ + "fix_location": "outside_code", + "intent": "bug", + "cause": "Since 10:00 UTC both the block rule's blocks and the count rule's counts rose: part of the crawler's traffic no longer matches the identity. Which attribute changed is only in the WAF request logs.", + "evidence": { + "basis": "data", + "looked_up": [ + "T2 metrics_query AWS/WAFV2 CountedRequests: refused", + "T3 NRQL aws.wafv2 hourly: count rule 277, 357, 422; block rule 234, 447, 330", + "T4 aws_identity: neither role lists Athena" + ], + "code_rule": "The block rule blocks listing loads that match the crawler's identity; the count rule counts what it misses.", + "data_shows": "T3: counts rose from 104-199 an hour to 277-422.", + "producer": {"kind": "source", "where": "Requests to web ACL example-web-acl that match the count rule but not the block rule; recorded in the WAF logs (S3 aws-waf-logs-example), unread"}, + "scope": "About 150-300 requests an hour above the overnight residual" + }, + "outside_change": { + "system": "AWS Athena, workgroup waf_logs", + "change": "Run the query on the WAF logs for the count rule's matches grouped by JA4 prefix, User-Agent, Accept-Language and cookie presence. Or grant CoderHelm's role Athena read so CoderHelm runs it.", + "where": "An engineer with the Athena workgroup, or an AWS admin approving CoderHelm's role stack update", + "verify": "The result names one identity that makes up most of the rule's matches", + "steps": [ + { + "step": "Read the crawler's new identity from the WAF logs", + "by": "person", + "owner": "an engineer with Athena access", + "how": "Athena workgroup waf_logs", + "why_person": "CoderHelm's roles (CoderHelmLogReader, CoderhelmReadOnly) have no athena:StartQueryExecution or s3:GetObject on the WAF log bucket, and wafv2:GetSampledRequests is refused", + "grant": "Approve the 'AWS role reads' update of CoderHelm's role stack, adding athena, glue and s3 read on the WAF logs and wafv2:GetSampledRequests", + "kind": "other" + }, + { + "step": "Edit the identity values in envs/prod/main.tf and open the PR with the numbers", + "by": "coderhelm", + "owner": "CoderHelm", + "how": "a CoderHelm run with the result", + "kind": "other" + } + ] + } + })) + .expect("the run's decision") +} + +fn gap(seen_at: &str) -> Gap { + aws_role_reads::gap( + ACCOUNT, + ROLE, + &[ + "wafv2:ListWebACLs".to_string(), + "wafv2:GetSampledRequests".to_string(), + ], + "an AWS WAF alarm's evidence", + seen_at, + ) + .expect("a gap") +} + +#[test] +fn the_waf_metric_is_read_and_every_lookup_counts() { + let alarm = ae::waf_alarm(TICKET).expect("a WAF alarm"); + // T2 again: the alarm's own metric, both rules, read in us-east-1. + let q = metrics::check_query( + &[ + json!({"namespace":"AWS/WAFV2","metric":"CountedRequests","dimensions":{"WebACL":alarm.web_acl,"Rule":alarm.rule},"stat":"Sum"}), + json!({"namespace":"AWS/WAFV2","metric":"BlockedRequests","dimensions":{"WebACL":alarm.web_acl,"Rule":"ExampleCrawlerBlock"},"stat":"Sum"}), + ], + Some(3600), + Some("1d"), + None, + None, + 1_795_007_000, + ) + .expect("AWS/WAFV2 is read"); + assert_eq!(q.region.as_deref(), Some("us-east-1")); + let any = metrics::check_namespace("Custom/Anything").unwrap(); + assert_eq!(any, "Custom/Anything"); + let src = include_str!("../../../../common/src/live/metrics.rs"); + assert!(!src.contains(&format!("\"{{ns}} {OLD_REFUSAL}"))); + // AWS's own refusal is the role's setup item, never ours. + let e = common::live::StepError::role_refused(&["cloudwatch:GetMetricData"]); + assert!(!e.is_refusal() && e.message.contains(aws_role_reads::ITEM_LABEL)); + // Five monitoring lookups are lookups: the decision is not "unchecked". + let d = decision(); + let made = fix_location::lookups_made(0, 5); + assert!(!fix_location::needs_lookup(Some(&d), true, made, &[])); + assert!(fix_location::needs_lookup( + Some(&d), + true, + fix_location::lookups_made(0, 0), + &[] + )); + let plan = include_str!("../plan.rs"); + assert!(plan.contains("ops.as_ref().map_or(0, |o| o.lookups().len())")); + assert!(!fix_location::outside_report(&d, true).contains(OLD_LABEL)); +} + +#[test] +fn without_the_roles_waf_reads_the_run_waits_and_raises_the_item() { + let d = decision(); + let report = fix_location::outside_report(&d, true); + let left = common::person_gate::sink(&report); + // The run's report: nothing for a person. + assert!(left.human.is_empty(), "{:?}", left.human); + // It met the role's refusals this run, so it waits; never an outside + // change with nobody to make it. + let started = "2026-11-18T12:57:29Z"; + let gaps = vec![gap("2026-11-18T12:57:36Z"), gap("2026-10-01T00:00:00Z")]; + let refused = role_wait::refused_this_run(&gaps, started); + let Ending::AwaitRole(waiting_on) = role_wait::ending(&left.human, refused) else { + panic!("the run waits for the role's reads"); + }; + let w = Waiting::of("run-1", &waiting_on, "2026-11-18T13:04:33Z"); + assert_eq!(w.accounts, vec![ACCOUNT]); + let note = role_wait::waiting_note(&w); + assert!(note.contains("\"AWS role reads\"") && note.contains("goes on by itself")); + assert!(run_status::ALL.contains(&run_status::AWAITING_SETUP)); + // The one install-level item, with the role stack's update. + let account = common::live::aws_account::AwsAccount { + account: ACCOUNT.into(), + role_arn: ROLE.into(), + region: "us-east-1".into(), + ..Default::default() + }; + assert!(aws_role_reads::role_update( + &account, + Some(&waiting_on[0]), + 0, + "https://b/launch/v1/coderhelm-log-reader-update.yaml" + ) + .is_some()); + // Nothing for a person and nothing to wait for: plan again. + assert_eq!(role_wait::ending(&[], vec![]), Ending::PlanAgain); + // The pipeline decides this way, and the re-checks are armed and sent. + let m = include_str!("../mod.rs"); + let body = &m[m.find("async fn finish_without_code(").unwrap()..]; + assert!(body.contains("common::role_wait::ending(&left.human")); + assert!(body.contains("common::run_status::AWAITING_SETUP")); + assert!(body.contains("role_wait::arm(")); + assert!(m.contains("NoCodeEnd::PlanAgain(why)")); + assert!(include_str!("../../main.rs").contains("passes::role_wait::check(&state, &msg)")); + assert!(include_str!("../aws_permissions.rs").contains("role_wait::wake(state, team_id, None)")); +} + +#[test] +fn once_the_role_reads_the_run_reads_the_logs_and_plans_its_pr() { + let alarm = ae::waf_alarm(TICKET).unwrap(); + let w = Waiting::of("run-1", &[gap("t")], "t"); + // A re-check refused nothing: the run goes on. + assert!(role_wait::ready(&w, &[])); + assert!(!role_wait::ready(&w, &["wafv2:GetSampledRequests".into()])); + // The sampled requests and the log objects, read without Athena. + let samples = vec![ae::sample( + 40, + &[ + ("User-Agent".into(), "Mozilla/5.0 Chrome/131.0.0.0".into()), + ("Accept-Language".into(), "en-US,en;q=0.9".into()), + ], + "GET", + "/listings?sport=a", + "US", + &[], + )]; + let loc = LogLocation::of( + "arn:aws:wafv2:us-east-1:111122223333:global/webacl/example-web-acl/0abc", + "arn:aws:s3:::aws-waf-logs-example", + ) + .unwrap(); + assert!(loc.hour_prefixes(1_795_000_000, 1_795_007_000)[0] + .starts_with("AWSLogs/111122223333/WAFLogs/cloudfront/example-web-acl/")); + let mut t = Tally::default(); + for i in 0..3 { + let line = json!({ + "timestamp": 1_795_000_000_000i64 + i, + "terminatingRuleId": "Default_Action", + "action": "ALLOW", + "nonTerminatingMatchingRules": [{"ruleId": alarm.rule, "action": "COUNT"}], + "httpRequest": {"clientIp": "198.51.100.7", "country": "US", "uri": "/listings", + "headers": [{"name": "User-Agent", "value": "Mozilla/5.0 Chrome/131.0.0.0"}, + {"name": "Accept-Language", "value": "en-US,en;q=0.9"}]}, + "ja4Fingerprint": "t13d1517h2_8daaf6152771_b6f405a00624" + }); + t.add(&line.to_string(), &alarm.rule, 0, i64::MAX); + } + let mut lines = ae::summarize(&samples); + lines.extend(t.lines(&alarm.rule)); + let got = ae::evidence(&alarm, lines, vec![]); + assert!(got.refused.is_empty()); + assert!(got.text.contains("t13d1517h2_8daaf6152771")); + assert!(!got.text.contains("198.51.100.7")); + assert!(!got.text.contains(aws_role_reads::ITEM_LABEL)); + // With the data, the plan is a code change: the run opens its PR. + let mut d = decision(); + d.fix_location = fix_location::FixLocation::Code; + d.outside_change = None; + d.evidence.producer.kind = "source".into(); + assert_eq!( + fix_location::route_for_plan(Some(&d), "1. Update the identity in envs/prod/main.tf"), + Route::Code + ); + // The waiting run starts again from its ticket, with its sender, so the + // alarm's evidence is read again. + let src = include_str!("../role_wait.rs"); + assert!(src.contains("stop_judge::restart_message(item")); + assert!(src.contains("ticket.sender = sender")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index d09b4c4c7..50f9e3146 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1409,6 +1409,7 @@ pub mod review_tidy; pub mod review_verdict; mod reviewer_guide; pub mod rewards; +pub mod role_wait; pub(crate) mod round; pub(crate) mod round_agree; pub mod run_ceiling; @@ -2027,6 +2028,8 @@ async fn alarm_evidence_for_run(state: &WorkerState, msg: &TicketMessage) -> Opt 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; + // The role reads again: runs waiting for it check now. + role_wait::wake(state, &msg.team_id, Some(&account)).await; } else { let role_arn = common::log_findings::connection_role( &state.dynamo, @@ -3489,7 +3492,9 @@ async fn run_passes( ) .await; if !judged.proceeds() { - finish_without_code( + // An ask (`Route::Ask` with a judged stop): never the + // outside path, so it always ends here. + let _ = finish_without_code( state, msg, run_id, @@ -3657,7 +3662,7 @@ async fn run_passes( .trim() .to_string(); } - finish_without_code( + let ended = finish_without_code( state, msg, run_id, @@ -3672,6 +3677,9 @@ async fn run_passes( ) .await; close_memory(state, agent_memory.take()).await; + if let NoCodeEnd::PlanAgain(why) = ended { + return plan_again_or_stop(state, msg, run_id, &mut ps, &why).await; + } return Ok(()); } @@ -9040,10 +9048,39 @@ pub(crate) async fn record_ci_outcome( } } +/// How [`finish_without_code`] ended the run. +#[derive(Debug, Clone, PartialEq, Eq)] +enum NoCodeEnd { + /// Reported and recorded: `needs_outside_change`, `needs_input` or + /// `awaiting_setup`. + Ended, + /// Nothing was left for a person and nothing to wait for: a report + /// would have said "Needed from you: Nothing" under a status that says + /// a person must act. The plan is CoderHelm's to make again, for this + /// reason. + PlanAgain(String), +} + +/// When the run started (RFC 3339): its first attempt when the message +/// says, else when this step started. +fn run_started_at(msg: &TicketMessage, start: &std::time::Instant) -> String { + if msg.first_attempt_ms > 0 { + if let Some(t) = chrono::DateTime::from_timestamp_millis(msg.first_attempt_ms as i64) { + return t.to_rfc3339(); + } + } + (chrono::Utc::now() - chrono::Duration::from_std(start.elapsed()).unwrap_or_default()) + .to_rfc3339() +} + /// Ends a run whose fix is not (or not yet known to be) in the code: posts /// the findings on the ticket the run came from and records them on the run, /// with no branch and no pull request. A change outside the code ends the run -/// as `needs_outside_change`; not knowing where the fix belongs ends it as +/// as `needs_outside_change` when a person has an item in it; with nothing +/// for a person, a run the team's AWS role was refused reads waits for the +/// install's setup item "AWS role reads" (`awaiting_setup`, going on by +/// itself once the role reads, `role_wait`), and any other run plans again +/// ([`NoCodeEnd::PlanAgain`]). Not knowing where the fix belongs ends it as /// `needs_input`, so a reply picks it up again. #[allow(clippy::too_many_arguments)] async fn finish_without_code( @@ -9058,12 +9095,55 @@ async fn finish_without_code( start: &std::time::Instant, mcp_ids: &[String], judged: Option<&stop_judge::Judged>, -) { +) -> NoCodeEnd { // Asking needs a judged ask or hold; without one the run reports what it // found and asks nothing. let judged = judged.filter(|j| !j.proceeds()); let outside = route == fix_location::Route::OutsideOnly || judged.is_none(); - let (report, jira_title, jira_type) = if outside { + // A change outside the code waits on a person only for an item the + // final check leaves them; with none, the run waits for the role's + // reads it was refused, or plans again. + let mut waiting: Option = None; + if outside { + let report = fix_location::outside_report(decision, false); + let left = + common::person_gate::sink(&format!("**Needs a change outside the code**\n\n{report}")); + let gaps = common::aws_role_reads::list( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + ) + .await; + let refused = common::role_wait::refused_this_run(&gaps, &run_started_at(msg, start)); + match common::role_wait::ending(&left.human, refused) { + common::role_wait::Ending::Person => {} + common::role_wait::Ending::AwaitRole(gaps) => { + waiting = Some(common::role_wait::Waiting::of( + run_id, + &gaps, + &chrono::Utc::now().to_rfc3339(), + )); + } + common::role_wait::Ending::PlanAgain => { + return NoCodeEnd::PlanAgain(format!( + "the plan stopped on a change outside the code that leaves nothing for a \ + person and waits for nothing ({})", + common::truncate_str(decision.cause.trim(), 300) + )); + } + } + } + let (report, jira_title, jira_type) = if let Some(w) = &waiting { + ( + format!( + "{}\n\n{}", + fix_location::outside_report(decision, false), + common::role_wait::waiting_note(w) + ), + "Waiting for the AWS role's reads", + "clarification", + ) + } else if outside { ( fix_location::outside_report(decision, false), "Needs a change outside the code", @@ -9153,7 +9233,9 @@ async fn finish_without_code( ) .await; } - let status = if outside { + let status = if waiting.is_some() { + common::run_status::AWAITING_SETUP + } else if outside { fix_location::STATUS_OUTSIDE } else { "needs_input" @@ -9198,6 +9280,11 @@ async fn finish_without_code( if usage_res.is_ok() { usage.mark_recorded(&delta); } + if let Some(w) = &waiting { + info!(run_id, actions = ?w.actions, "Waiting for the AWS role's reads: re-checks armed"); + role_wait::arm(state, &msg.team_id, w).await; + return NoCodeEnd::Ended; + } if outside { let analytics_month = chrono::Utc::now().format("%Y-%m").to_string(); @@ -9214,6 +9301,7 @@ async fn finish_without_code( .await; } } + NoCodeEnd::Ended } /// Tells the ticket about the part of the fix that has to be made outside the diff --git a/services/worker/src/passes/ops_tools.rs b/services/worker/src/passes/ops_tools.rs index fd62678ae..777a75227 100644 --- a/services/worker/src/passes/ops_tools.rs +++ b/services/worker/src/passes/ops_tools.rs @@ -281,6 +281,12 @@ fn is_settings_tool(name: &str) -> bool { matches!(name, "aws_bucket_settings" | "aws_kms_key") } +/// The AWS WAF tools' names: a rule's sampled requests and its matches in +/// the web ACL's log objects, read without Athena. +fn is_waf_tool(name: &str) -> bool { + matches!(name, "waf_sampled_requests" | "waf_log_objects") +} + /// What the last permission check of `account` found about `action`: /// `Some(false)` the role lacks it, `Some(true)` it has it, `None` unknown /// (never checked, the check couldn't run, or it was for another release's @@ -452,7 +458,7 @@ fn describe_metrics(aws: &AwsAbilities) -> String { .map(|m| format!("account {} ({})", m.account(), m.target.region)) .collect(); format!( - "CloudWatch metrics in {}: ECS, RDS, Lambda, CloudFront, load balancers, SQS, DynamoDB", + "CloudWatch metrics in {}: any namespace the role may read (ECS, RDS, Lambda, CloudFront, AWS WAF, load balancers, SQS, DynamoDB and more)", where_.join(", ") ) } @@ -666,6 +672,28 @@ impl OpsTools { "Read a KMS key's description (customer or AWS managed, state, spec, origin) and its key policy in the team's AWS account. Never encrypts or decrypts. When access is denied the result names the missing permission.", json!({ "type": "object", "properties": key_props, "required": ["key"] }), )); + let mut waf_props = json!({ + "web_acl": { "type": "string", "description": "the web ACL's name (the WebACL dimension of its metrics)" }, + "rule": { "type": "string", "description": "the rule's metric name (the Rule dimension); for the log objects, the rule's name when it differs" }, + "region": { "type": "string", "description": "the web ACL's region; leave out for a CloudFront web ACL" }, + }); + if self.aws.accounts.len() > 1 { + waf_props["account"] = json!({ "type": "string", "description": format!("AWS account: {}", self.aws.accounts.iter().map(|a| a.account.clone()).collect::>().join(", ")) }); + } + out.push(tool( + "waf_sampled_requests", + "AWS WAF's sampled requests for one rule of a web ACL over the last three hours (wafv2:GetSampledRequests): user agents, Accept-Language, header order (names only), paths, countries and labels, each with its share. No Athena. Client addresses, cookies, other header values and query strings are never kept.", + json!({ "type": "object", "properties": waf_props.clone(), "required": ["web_acl", "rule"] }), + )); + let mut log_props = waf_props; + log_props["bucket"] = json!({ "type": "string", "description": "the aws-waf-logs-* bucket; default where the web ACL logs" }); + log_props["since"] = since.clone(); + log_props["until"] = until.clone(); + out.push(tool( + "waf_log_objects", + &format!("Read a web ACL's log records straight from its aws-waf-logs-* bucket (s3:ListBucket, s3:GetObject; no Athena, no query results location) and group one rule's matches by JA4, user agent, Accept-Language, path and cookie presence, with JA4 prefixes, countries, labels, actions and matches per hour. Default window the last 3 hours, at most 24; at most {} objects, newest first. Read two windows (before and after a rise) to see which attribute changed. Client addresses, cookies, other header values and query strings are never kept.", common::waf_logs::MAX_OBJECTS), + json!({ "type": "object", "properties": log_props, "required": ["web_acl", "rule"] }), + )); } if let Some(l) = self.get(ConnKind::NewRelic) { let account = json!({ "type": "string", "description": format!("New Relic account id{}", if l.conn.account_ids.is_empty() { String::new() } else { format!(": {}", l.conn.account_ids.join(", ")) }) }); @@ -731,16 +759,17 @@ impl OpsTools { // `search_read`): connections of those kinds are moved at load and // never give tools here. if !self.aws.metrics.is_empty() { - let ns: Vec = metrics::NAMESPACES + let ns: Vec = metrics::NAMESPACE_HINTS .iter() .map(|(n, w)| format!("{n} ({w})")) .collect(); - let mut list_props = json!({ "namespace": { "type": "string" }, "metric": { "type": "string" }, "dimensions": { "type": "object" } }); + let region = json!({ "type": "string", "description": "AWS region to read in, when it isn't where the metric is published (CloudFront and a CloudFront web ACL's WAF metrics are read in us-east-1 by themselves)" }); + let mut list_props = json!({ "namespace": { "type": "string" }, "metric": { "type": "string" }, "dimensions": { "type": "object" }, "region": region }); let mut query_props = json!({ "metrics": { "type": "array", "items": { "type": "object", "properties": { "namespace": { "type": "string" }, "metric": { "type": "string" }, "dimensions": { "type": "object" }, "stat": { "type": "string" } }, "required": ["namespace", "metric"] } }, "period": { "type": "integer", "description": "seconds per point, a multiple of 60" }, - "since": since, "until": until }); + "since": since, "until": until, "region": region }); if self.aws.metrics.len() > 1 { let account = json!({ "type": "string", "description": format!("AWS account: {}", self.aws.metric_accounts().join(", ")) }); list_props["account"] = account.clone(); @@ -748,12 +777,12 @@ impl OpsTools { } out.push(tool( "metrics_list", - &format!("List CloudWatch metrics that exist in a namespace, with their dimension values (find the ClusterName, ServiceName, DBInstanceIdentifier, FunctionName, DistributionId to query). Namespaces: {}", ns.join("; ")), + &format!("List CloudWatch metrics that exist in a namespace, with their dimension values (find the ClusterName, ServiceName, DBInstanceIdentifier, FunctionName, DistributionId, WebACL and Rule to query). Any namespace can be read; what the team's AWS role may read decides. Common ones: {}", ns.join("; ")), json!({ "type": "object", "properties": list_props, "required": ["namespace"] }), )); out.push(tool( "metrics_query", - "Read up to 5 CloudWatch metrics over a window (at most 14 days): e.g. ECS CPUUtilization/MemoryUtilization, RDS DatabaseConnections, Lambda Duration/Throttles, CloudFront CacheHitRate, ALB TargetResponseTime. Each metric is {namespace, metric, dimensions, stat} with stat Average, Sum, Minimum, Maximum, SampleCount, p50, p90, p95 or p99.", + "Read up to 5 CloudWatch metrics over a window (at most 14 days), in any namespace: e.g. ECS CPUUtilization/MemoryUtilization, RDS DatabaseConnections, Lambda Duration/Throttles, CloudFront CacheHitRate, ALB TargetResponseTime, AWS/WAFV2 CountedRequests/BlockedRequests by WebACL and Rule. Each metric is {namespace, metric, dimensions, stat} with stat Average, Sum, Minimum, Maximum, SampleCount, p50, p90, p95 or p99.", json!({ "type": "object", "properties": query_props, "required": ["metrics"] }), )); } @@ -792,6 +821,7 @@ impl OpsTools { s.push_str("- `aws_identity`: which AWS account, role and region Coderhelm uses, and whether each works.\n"); } if !self.aws.accounts.is_empty() { + s.push_str("- `waf_sampled_requests` and `waf_log_objects`: what an AWS WAF rule matched, from WAF's sampled requests and from the web ACL's log objects in its bucket (JA4, user agent, Accept-Language, path, cookie presence), with no Athena. For a WAF alarm, read these before deciding what changed, and read the rule's metrics (`metrics_query`, namespace AWS/WAFV2) for the counts. A read the role lacks comes back as the install's setup item; say what was read and go on.\n"); s.push_str("- `aws_bucket_settings` and `aws_kms_key`: an S3 bucket's encryption, bucket policy and public status, and a KMS key's manager, state and key policy. When a finding or an answer hinges on such a setting (is the bucket encrypted with a customer-managed key, does the key policy let a role decrypt, is the bucket public), look it up FIRST and state what came back, citing the lookup; never ask a person for something these can read. Ask a person only when the lookup can't be made, and then say exactly why, quoting the missing permission the result names.\n"); } for l in &self.loaded { @@ -817,6 +847,7 @@ impl OpsTools { let kind = match name { "aws_identity" => None, n if is_settings_tool(n) => None, + n if is_waf_tool(n) => None, n if is_report_tool(n) => None, n if n.starts_with("newrelic_") => Some(ConnKind::NewRelic), n if n.starts_with("confluence_") => Some(ConnKind::Confluence), @@ -847,6 +878,7 @@ impl OpsTools { None if is_settings_tool(name) => { ("connector-aws".to_string(), "AWS settings".to_string()) } + None if is_waf_tool(name) => ("connector-aws".to_string(), "AWS WAF".to_string()), None => ("connector-aws".to_string(), "AWS identity".to_string()), }; let logged = store::log_activity_in( @@ -878,6 +910,8 @@ impl OpsTools { "Test reports".to_string() } else if is_settings_tool(name) { "AWS settings".to_string() + } else if is_waf_tool(name) { + "AWS WAF".to_string() } else { lookup_source(kind, input) }; @@ -994,17 +1028,128 @@ impl OpsTools { } let now = chrono::Utc::now().timestamp(); let actor = format!("{}-pr{}", self.actor, self.pr); - let pretty = |v: &Value| serde_json::to_string_pretty(v).unwrap_or_default(); + if is_waf_tool(name) { + return self.read_waf(state, name, input, &actor).await; + } if kind == Some(ConnKind::Metrics) { let target = &self.aws.metrics_for(s_in(input, "account"))?.target; - return match name { + let read = self + .read_metrics(state, name, input, target, &actor, now) + .await; + if let Err(e) = &read { + self.note_refused( + state, + target, + &e.role_refused, + "a CloudWatch metrics lookup", + ) + .await; + } + return read; + } + self.run_rest(state, kind, name, input, &actor, now).await + } + + /// Reads the team's role was refused (`actions`): the install's setup + /// item, recorded once for the account (best effort). + async fn note_refused( + &self, + state: &WorkerState, + target: &AwsTarget, + actions: &[String], + needed_for: &str, + ) { + let table = &state.config.settings_table_name; + if actions.is_empty() || table.is_empty() { + return; + } + if let Some(gap) = common::aws_role_reads::gap( + target.account(), + &target.role_arn, + actions, + needed_for, + &chrono::Utc::now().to_rfc3339(), + ) { + common::aws_role_reads::record(&state.dynamo, table, &self.team_id, &gap).await; + } + } + + /// A WAF rule's sampled requests, or its matches in the web ACL's log + /// objects. Reads the role is refused are named in the result and + /// recorded as the install's setup item; what could be read comes back. + async fn read_waf( + &self, + state: &WorkerState, + name: &str, + input: &Value, + actor: &str, + ) -> Result<(String, String, bool), StepError> { + use common::alarm_evidence as ae; + let alarm = ae::WafAlarm::new( + s_in(input, "web_acl").unwrap_or(""), + s_in(input, "rule").unwrap_or(""), + s_in(input, "region"), + ) + .ok_or_else(|| { + StepError::new( + "read_only", + "Name the web ACL and the rule (letters, digits, - and _).", + "The alarm's WebACL and Rule dimensions name them.", + ) + })?; + let account = self.aws.settings_account(s_in(input, "account"), None)?; + let target = account.target(); + let session = assume(&state.sts, &target, actor).await?; + let now = chrono::Utc::now(); + let got = if name == "waf_sampled_requests" { + ae::sampled_requests(&session, &alarm, now).await + } else { + let bucket = s_in(input, "bucket"); + if let Some(b) = bucket.filter(|b| !common::waf_logs::is_bucket(b)) { + return Err(StepError::new( + "read_only", + format!("{b} isn't a WAF log bucket (its name starts with aws-waf-logs-)."), + "Leave the bucket out to read where the web ACL logs.", + )); + } + let (start, end) = common::live::http::window( + s_in(input, "since"), + s_in(input, "until"), + now.timestamp(), + std::time::Duration::from_secs(3 * 3600), + std::time::Duration::from_secs(common::waf_logs::MAX_WINDOW_SECS as u64), + )?; + ae::log_objects(&session, &alarm, bucket, start, end).await + }; + self.note_refused(state, &target, &got.refused, "an AWS WAF rule's requests") + .await; + let note = format!("{name} {} {}", alarm.web_acl, alarm.rule); + if got.lines.is_empty() { + return Ok(("Nothing came back.".into(), note, true)); + } + Ok((got.lines.join("\n"), note, false)) + } + + /// One CloudWatch metrics read. + async fn read_metrics( + &self, + state: &WorkerState, + name: &str, + input: &Value, + target: &AwsTarget, + actor: &str, + now: i64, + ) -> Result<(String, String, bool), StepError> { + { + match name { "metrics_list" => { let q = metrics::check_list( s_in(input, "namespace").unwrap_or(""), s_in(input, "metric"), &input["dimensions"], + s_in(input, "region"), )?; - let session = assume(&state.sts, target, &actor).await?; + let session = assume(&state.sts, target, actor).await?; let list = metrics::MetricsApi::list(&metrics::Aws { session: &session }, &q).await?; Ok(( @@ -1020,15 +1165,30 @@ impl OpsTools { input["period"].as_i64(), s_in(input, "since"), s_in(input, "until"), + s_in(input, "region"), now, )?; - let session = assume(&state.sts, target, &actor).await?; + let session = assume(&state.sts, target, actor).await?; let series = metrics::MetricsApi::get(&metrics::Aws { session: &session }, &q).await?; Ok((metrics::format_series(&q, &series), q.describe(), false)) } - }; + } } + } + + /// The other tools: Airflow, New Relic, Confluence, identity, settings. + async fn run_rest( + &self, + state: &WorkerState, + kind: Option, + name: &str, + input: &Value, + actor: &str, + now: i64, + ) -> Result<(String, String, bool), StepError> { + let actor = actor.to_string(); + let pretty = |v: &Value| serde_json::to_string_pretty(v).unwrap_or_default(); if kind == Some(ConnKind::Airflow) { let what = name.trim_start_matches("airflow_"); let envs = self.aws.environments(); diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 8b3a4ab68..fcf44a62c 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -911,7 +911,16 @@ Then the ```fix_location.json block described above."#, let model_id = provider.judgment_model_id(); let can_look_up = live.as_ref().is_some_and(|l| !l.tools().is_empty()); - let lookups = || live.as_ref().map_or(0, |l| l.lookups_made()); + // Every lookup the planner made counts: the data sources' and the + // monitoring tools' (metrics, New Relic, AWS WAF, Airflow). A decision + // backed by five NRQL and metric lookups was once marked "no lookups + // were made" because only the data sources' were counted. + let lookups = || { + super::fix_location::lookups_made( + live.as_ref().map_or(0, |l| l.lookups_made()), + ops.as_ref().map_or(0, |o| o.lookups().len()), + ) + }; let response = provider::converse_document( state, provider, @@ -1153,9 +1162,16 @@ Then the ```fix_location.json block described above."#, // Held-back questions send the plan back once; what is still not // admissible after that never reaches a person. let lookup_lines = || { - live.as_ref() + let mut lines: Vec = live + .as_ref() .map(|l| l.lookups().into_iter().map(|x| x.line).collect::>()) - .unwrap_or_default() + .unwrap_or_default(); + lines.extend( + ops.as_ref() + .map(|o| o.lookups().into_iter().map(|x| x.line).collect::>()) + .unwrap_or_default(), + ); + lines }; let reads = can_read(&team_repos, &tools); let asked = clarification_of(&files.tasks); diff --git a/services/worker/src/passes/role_wait.rs b/services/worker/src/passes/role_wait.rs new file mode 100644 index 000000000..4c742a125 --- /dev/null +++ b/services/worker/src/passes/role_wait.rs @@ -0,0 +1,284 @@ +//! A run waiting for the install's setup item "AWS role reads" +//! (`awaiting_setup`, `common::role_wait`): the re-checks of the role, and +//! the run going on by itself once the role reads. +//! +//! [`arm`] records the wait and sends the first re-check; [`check`] reads +//! the reads the run waited for again (for an AWS WAF alarm, the alarm's +//! own evidence; for metrics, a ListMetrics; otherwise the role's +//! permission check) and, when none is refused, starts the run again from +//! its ticket: the new run reads the data and opens its pull request. +//! [`wake`] sends a re-check of every waiting run of a team at once: the +//! daily role check, and a read that worked again in another run. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::messages::{RoleReadsWaitMessage, WorkerMessage}; +use common::role_wait::{self, Waiting, FAST_POLLS, POLL_SECS}; +use common::run_status::{AWAITING_SETUP, CLOSED, RETRIED}; +use tracing::{info, warn}; + +use super::attr_s; +use crate::WorkerState; + +type Item = HashMap; + +fn text(item: &Item, k: &str) -> String { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +/// Sends a re-check, after `delay` seconds. +async fn send(state: &WorkerState, m: RoleReadsWaitMessage, delay: i32) { + let Ok(body) = serde_json::to_string(&WorkerMessage::RoleReadsWait(m.clone())) else { + return; + }; + let res = state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .delay_seconds(delay.clamp(0, 900)) + .send() + .await; + if let Err(e) = res { + warn!(run_id = %m.run_id, error = %e, "Could not send the AWS role re-check"); + } +} + +/// Records the run's wait and sends its first re-check. +pub async fn arm(state: &WorkerState, team_id: &str, w: &Waiting) { + role_wait::record(&state.dynamo, &state.config.settings_table_name, team_id, w).await; + send( + state, + RoleReadsWaitMessage { + team_id: team_id.to_string(), + run_id: w.run_id.clone(), + polls: 0, + once: false, + }, + POLL_SECS, + ) + .await; +} + +/// Sends a re-check of every run of the team waiting for reads in +/// `account` (every account when `None`), now. +pub async fn wake(state: &WorkerState, team_id: &str, account: Option<&str>) { + let waits = role_wait::list(&state.dynamo, &state.config.settings_table_name, team_id).await; + for w in waits + .iter() + .filter(|w| account.is_none_or(|a| w.accounts.iter().any(|x| x == a))) + { + send( + state, + RoleReadsWaitMessage { + team_id: team_id.to_string(), + run_id: w.run_id.clone(), + polls: 0, + once: true, + }, + 0, + ) + .await; + } +} + +/// The reads the role is still refused in `account`, of those the run +/// waits for. `None` when the role couldn't be taken on (still waiting). +async fn still_refused( + state: &WorkerState, + team_id: &str, + account: &str, + item: &Item, + w: &Waiting, +) -> Option> { + let session = common::log_findings::session_for( + &state.dynamo, + &state.sts, + &state.config.aws_insights_table_name, + team_id, + account, + ) + .await + .ok() + .flatten()?; + let mut refused: Vec = Vec::new(); + // An AWS WAF alarm: its own evidence, read again. + if let Some(alarm) = common::alarm_evidence::waf_alarm(&text(item, "ticket_body")) { + let got = common::alarm_evidence::gather(&session, &alarm, chrono::Utc::now()).await; + refused.extend(got.refused); + } + // Metrics: one ListMetrics. + if w.actions.iter().any(|a| a.starts_with("cloudwatch:")) + && !matches!(common::live::metrics::probe(&session).await, Ok(true)) + { + refused.extend( + w.actions + .iter() + .filter(|a| a.starts_with("cloudwatch:")) + .cloned(), + ); + } + // Anything else: the role's permission check, for the actions it covers. + let other: Vec<&String> = w + .actions + .iter() + .filter(|a| !a.starts_with("cloudwatch:")) + .filter(|a| !refused.contains(a)) + .collect(); + let covered_by_alarm = common::alarm_evidence::waf_alarm(&text(item, "ticket_body")).is_some(); + if !other.is_empty() && !covered_by_alarm { + let accounts = common::live::aws_account::list( + &state.dynamo, + &state.config.aws_insights_table_name, + team_id, + ) + .await + .unwrap_or_default(); + let target = accounts.iter().find(|a| a.account == account)?.target(); + let c = common::live::permissions::check( + &state.sts, + &target, + "role-wait", + &chrono::Utc::now().to_rfc3339(), + ) + .await; + if !c.works { + return None; + } + refused.extend(other.into_iter().filter(|a| c.missing.contains(a)).cloned()); + } + Some(refused) +} + +/// One re-check of a waiting run. +pub async fn check(state: &WorkerState, m: &RoleReadsWaitMessage) { + let table = &state.config.settings_table_name; + let Some(w) = role_wait::get(&state.dynamo, table, &m.team_id, &m.run_id).await else { + return; + }; + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&m.team_id)) + .key("run_id", attr_s(&m.run_id)) + .send() + .await + .ok() + .and_then(|o| o.item); + let Some(item) = item else { + role_wait::remove(&state.dynamo, table, &m.team_id, &m.run_id).await; + return; + }; + let status = text(&item, "status"); + if status != AWAITING_SETUP { + // A closed run may be reopened and wait again: the daily check + // finds it then. Anything else ended the wait. + if status != CLOSED { + role_wait::remove(&state.dynamo, table, &m.team_id, &m.run_id).await; + } + return; + } + let mut refused: Vec = Vec::new(); + let mut reachable = true; + for account in &w.accounts { + match still_refused(state, &m.team_id, account, &item, &w).await { + Some(r) => refused.extend(r), + None => reachable = false, + } + } + if reachable && role_wait::ready(&w, &refused) { + go_on(state, &m.team_id, &m.run_id, &item, &w).await; + return; + } + info!(run_id = %m.run_id, refused = ?refused, polls = m.polls, "The AWS role still lacks reads the run waits for"); + if !m.once && m.polls + 1 < FAST_POLLS { + send( + state, + RoleReadsWaitMessage { + polls: m.polls + 1, + ..m.clone() + }, + POLL_SECS, + ) + .await; + } +} + +/// The role reads now: the run starts again from its ticket (a new run that +/// reads the data and opens the pull request), once. +async fn go_on(state: &WorkerState, team_id: &str, run_id: &str, item: &Item, w: &Waiting) { + let Some(mut ticket) = super::stop_judge::restart_message(item, Vec::new()) else { + warn!(run_id, "The waiting run's ticket couldn't be rebuilt"); + return; + }; + ticket.team_id = team_id.to_string(); + // The same sender: an alert's run reads the alarm's evidence again. + let sender = text(item, "sender"); + if !sender.is_empty() { + ticket.sender = sender; + } + ticket.requester = Some(common::requester::Requester::coderhelm("role reads")); + let new_run = ticket.new_run_id.clone().unwrap_or_default(); + let now = chrono::Utc::now().to_rfc3339(); + // Only while it still waits: one re-check goes on, never two. + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #s = :r, status_run_id = :sri, retried_as = :n, updated_at = :t") + .condition_expression("#s = :w") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":r", attr_s(RETRIED)) + .expression_attribute_values(":sri", attr_s(&format!("{RETRIED}#{run_id}"))) + .expression_attribute_values(":n", attr_s(&new_run)) + .expression_attribute_values(":t", attr_s(&now)) + .expression_attribute_values(":w", attr_s(AWAITING_SETUP)) + .send() + .await + .is_ok(); + if !claimed { + return; + } + let table = &state.config.settings_table_name; + role_wait::remove(&state.dynamo, table, team_id, run_id).await; + for a in &w.accounts { + common::aws_role_reads::clear(&state.dynamo, table, team_id, a).await; + } + let Ok(body) = serde_json::to_string(&WorkerMessage::Ticket(ticket)) else { + return; + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + super::add_progress_note( + state, + team_id, + run_id, + &format!( + "The AWS role reads {} now: going on in run {new_run}, which reads the data \ + and opens the pull request.", + w.actions.join(", ") + ), + ) + .await; + info!( + run_id, + new_run, "AWS role reads arrived: the waiting run goes on" + ); + } + Err(e) => warn!(run_id, error = %e, "Could not queue the waiting run's ticket"), + } +}