diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index c175691ed..149895605 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -91,3 +91,16 @@ Resources: - "ecr:BatchGetImage" - "ecr:ListTagsForResource" Resource: "*" + # Settings only, so a review can check a fact instead of asking: a + # bucket's default encryption, its bucket policy and whether that + # policy makes it public; a KMS key's description and key policy. + # Never an object in a bucket, never an encrypt or decrypt call. + - Sid: ReadBucketAndKeySettings + Effect: Allow + Action: + - "s3:GetEncryptionConfiguration" + - "s3:GetBucketPolicy" + - "s3:GetBucketPolicyStatus" + - "kms:DescribeKey" + - "kms:GetKeyPolicy" + Resource: "*" diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 0609263bf..b59e53495 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -154,6 +154,24 @@ Resources: - "ecr:BatchGetImage" - "ecr:ListTagsForResource" Resource: "*" + - PolicyName: BucketAndKeySettingsReadOnly + PolicyDocument: + Version: "2012-10-17" + Statement: + # Settings only, so a review can check a fact instead of asking: + # a bucket's default encryption, its bucket policy and whether + # that policy makes it public; a KMS key's description and key + # policy. Never an object in a bucket, never an encrypt or + # decrypt call. + - Sid: ReadBucketAndKeySettings + Effect: Allow + Action: + - "s3:GetEncryptionConfiguration" + - "s3:GetBucketPolicy" + - "s3:GetBucketPolicyStatus" + - "kms:DescribeKey" + - "kms:GetKeyPolicy" + Resource: "*" Outputs: RoleArn: diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 5ab074826..2cb5765b5 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -76,6 +76,8 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("opensearch_search", Risk::Read), ("opensearch_count", Risk::Read), ("aws_identity", Risk::Read), + ("aws_bucket_settings", Risk::Read), + ("aws_kms_key", Risk::Read), ("newrelic_accounts", Risk::Read), ("newrelic_nrql", Risk::Read), ("newrelic_entities", Risk::Read), @@ -211,6 +213,8 @@ const DATA_SOURCE_TOOLS: &[(&str, &str)] = &[ ("rest_get", "rest"), ("opensearch_", "opensearch"), ("aws_identity", "aws"), + ("aws_bucket_settings", "aws"), + ("aws_kms_key", "aws"), ("newrelic_", "newrelic"), ("confluence_", "confluence"), ("metrics_", "cloudwatch"), diff --git a/services/common/src/live/aws_settings.rs b/services/common/src/live/aws_settings.rs new file mode 100644 index 000000000..1229bf3a8 --- /dev/null +++ b/services/common/src/live/aws_settings.rs @@ -0,0 +1,721 @@ +//! Settings of S3 buckets and KMS keys in a team's AWS account, read through +//! its CoderHelmLogReader role, so the reviewer can check a fact about them +//! instead of asking a person. +//! +//! Metadata only: a bucket's default encryption, its bucket policy and +//! whether that policy makes the bucket public; a KMS key's description and +//! key policy. Never an object in a bucket, and never an encrypt or decrypt +//! call. Each read is separate, so a refused one doesn't hide the others, +//! and a refusal names the exact IAM action that was refused. + +use super::aws::Session; +use super::StepError; + +pub const BUCKET_ENCRYPTION: &str = "s3:GetEncryptionConfiguration"; +pub const BUCKET_POLICY: &str = "s3:GetBucketPolicy"; +pub const BUCKET_POLICY_STATUS: &str = "s3:GetBucketPolicyStatus"; +pub const KEY_DESCRIBE: &str = "kms:DescribeKey"; +pub const KEY_POLICY: &str = "kms:GetKeyPolicy"; + +/// Every action these lookups use (the role's `settings` ability). +pub const ACTIONS: &[&str] = &[ + BUCKET_ENCRYPTION, + BUCKET_POLICY, + BUCKET_POLICY_STATUS, + KEY_DESCRIBE, + KEY_POLICY, +]; + +fn refused(message: impl Into) -> StepError { + StepError::new( + "read_only", + message, + "Give a bucket name (or s3://bucket, or its ARN) or a KMS key id, alias or ARN.", + ) +} + +/// A bucket name from a name, an `s3://bucket/…` URL or an +/// `arn:aws:s3:::bucket/…` ARN. +pub fn check_bucket(input: &str) -> Result { + let t = input.trim(); + let t = t + .strip_prefix("s3://") + .or_else(|| t.strip_prefix("arn:aws:s3:::")) + .or_else(|| t.strip_prefix("arn:aws-us-gov:s3:::")) + .or_else(|| t.strip_prefix("arn:aws-cn:s3:::")) + .unwrap_or(t); + let name = t.split('/').next().unwrap_or(""); + let ok = (3..=255).contains(&name.len()) + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) + && name + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric()); + if ok { + Ok(name.to_string()) + } else { + Err(refused(format!("`{input}` isn't an S3 bucket name."))) + } +} + +/// A KMS key as given: its id, alias or ARN, with the region and account +/// an ARN names. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyRef { + pub id: String, + pub region: Option, + pub account: Option, +} + +pub fn check_key(input: &str) -> Result { + let t = input.trim(); + let ok = !t.is_empty() + && t.len() <= 300 + && t.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '-' | ':')); + if !ok { + return Err(refused(format!( + "`{input}` isn't a KMS key id, alias or ARN." + ))); + } + if t.starts_with("arn:") { + let parts: Vec<&str> = t.splitn(6, ':').collect(); + let good = parts.len() == 6 + && parts[2] == "kms" + && !parts[3].is_empty() + && parts[4].len() == 12 + && (parts[5].starts_with("key/") || parts[5].starts_with("alias/")); + if !good { + return Err(refused(format!("`{input}` isn't a KMS key or alias ARN."))); + } + return Ok(KeyRef { + id: t.to_string(), + region: Some(parts[3].to_string()), + account: Some(parts[4].to_string()), + }); + } + Ok(KeyRef { + id: t.to_string(), + region: None, + account: None, + }) +} + +/// How one read ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Read { + Got(T), + /// The thing read doesn't exist (no bucket policy, no such key). + Absent(String), + /// AWS refused the action. + Denied, + Failed(String), +} + +impl Read { + pub fn denied(&self) -> bool { + matches!(self, Read::Denied) + } +} + +/// One default-encryption rule of a bucket. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncryptionRule { + /// `AES256`, `aws:kms` or `aws:kms:dsse`. + pub algorithm: String, + pub kms_key: Option, + pub bucket_key: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BucketSettings { + pub bucket: String, + /// The region the bucket is in, when it isn't the role's. + pub region: Option, + pub encryption: Read>, + pub policy: Read, + pub public: Read, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyFacts { + pub key_id: String, + pub arn: String, + /// `CUSTOMER` (customer managed) or `AWS` (AWS managed). + pub manager: String, + pub state: String, + pub enabled: bool, + pub spec: String, + pub usage: String, + pub origin: String, + pub multi_region: Option, + pub description: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeySettings { + pub key: String, + pub facts: Read, + pub policy: Read, +} + +/// What a refused action reads, in plain words. +fn reads(action: &str) -> &'static str { + match action { + BUCKET_ENCRYPTION => "the bucket's default encryption", + BUCKET_POLICY => "the bucket policy", + BUCKET_POLICY_STATUS => "whether the bucket policy makes it public", + KEY_DESCRIBE => "the key's description (who manages it, its state)", + KEY_POLICY => "the key policy", + _ => "this setting", + } +} + +/// The sentence for a refused action. `role_has` is what the last check of +/// the role found: `Some(false)` it lacks the action, `Some(true)` it has +/// it (so something else refused it), `None` unknown. +pub fn denied_line(action: &str, resource: &str, role_has: Option) -> String { + let what = reads(action); + match role_has { + Some(false) => format!( + "Access denied: the CoderHelmLogReader role is missing `{action}`, so I couldn't read {what} for {resource}. An admin adds it with Update on the AWS page (Settings, Integrations, AWS)." + ), + Some(true) => format!( + "Access denied for `{action}` on {resource}: the role allows it, so the resource's own policy, a permissions boundary or an organization policy refused it; I couldn't read {what}." + ), + None => format!( + "Access denied for `{action}` on {resource}: the CoderHelmLogReader role is missing `{action}` (Update on the AWS page in Settings, Integrations, AWS adds it), or the resource's own policy refuses it. I couldn't read {what}." + ), + } +} + +fn line_for( + r: &Read, + action: &str, + resource: &str, + role_has: &dyn Fn(&str) -> Option, + got: impl Fn(&T) -> String, +) -> String { + match r { + Read::Got(v) => got(v), + Read::Absent(why) => why.clone(), + Read::Denied => denied_line(action, resource, role_has(action)), + Read::Failed(why) => format!("Couldn't read {} ({why}).", reads(action)), + } +} + +fn encryption_text(rules: &[EncryptionRule]) -> String { + if rules.is_empty() { + return "Default encryption: no rule set.".to_string(); + } + rules + .iter() + .map(|r| { + let what = match (r.algorithm.as_str(), r.kms_key.as_deref()) { + ("AES256", _) => { + "SSE-S3 (AES256): keys managed by S3, not a KMS key".to_string() + } + (alg, Some(k)) if alg.starts_with("aws:kms") => format!( + "{} with KMS key `{k}` (read it with aws_kms_key to see whether it is customer managed)", + if alg == "aws:kms:dsse" { "DSSE-KMS" } else { "SSE-KMS" } + ), + (alg, None) if alg.starts_with("aws:kms") => format!( + "{} with the AWS managed key `aws/s3` (not customer managed)", + if alg == "aws:kms:dsse" { "DSSE-KMS" } else { "SSE-KMS" } + ), + (alg, _) => format!("algorithm {alg}"), + }; + let bk = match r.bucket_key { + Some(true) => ", S3 Bucket Key on", + Some(false) => ", S3 Bucket Key off", + None => "", + }; + format!("Default encryption: {what}{bk}.") + }) + .collect::>() + .join("\n") +} + +/// The bucket's settings as the agent reads them, with each refusal named. +pub fn format_bucket(b: &BucketSettings, role_has: &dyn Fn(&str) -> Option) -> String { + let res = format!("bucket `{}`", b.bucket); + let mut out = vec![format!( + "S3 bucket `{}`{}", + b.bucket, + b.region + .as_deref() + .map(|r| format!(" (in {r})")) + .unwrap_or_default() + )]; + out.push(line_for( + &b.encryption, + BUCKET_ENCRYPTION, + &res, + role_has, + |r| encryption_text(r), + )); + out.push(line_for( + &b.public, + BUCKET_POLICY_STATUS, + &res, + role_has, + |p| { + if *p { + "Bucket policy status: PUBLIC (the policy grants public access).".to_string() + } else { + "Bucket policy status: not public.".to_string() + } + }, + )); + out.push(line_for(&b.policy, BUCKET_POLICY, &res, role_has, |p| { + format!( + "Bucket policy:\n{}", + crate::truncate_str(&pretty_policy(p), 6000) + ) + })); + out.join("\n") +} + +/// The key's settings as the agent reads them, with each refusal named. +pub fn format_key(k: &KeySettings, role_has: &dyn Fn(&str) -> Option) -> String { + let res = format!("KMS key `{}`", k.key); + let mut out = vec![format!("KMS key `{}`", k.key)]; + out.push(line_for(&k.facts, KEY_DESCRIBE, &res, role_has, |f| { + let managed = match f.manager.as_str() { + "CUSTOMER" => "customer managed", + "AWS" => "AWS managed (not customer managed)", + _ => "managed by an unknown party", + }; + format!( + "Key {} ({}): {managed}; state {}{}; spec {}, usage {}, origin {}{}{}", + f.key_id, + f.arn, + f.state, + if f.enabled { ", enabled" } else { ", disabled" }, + f.spec, + f.usage, + f.origin, + match f.multi_region { + Some(true) => ", multi-Region", + _ => "", + }, + if f.description.trim().is_empty() { + String::new() + } else { + format!("; description: {}", f.description.trim()) + } + ) + })); + out.push(line_for(&k.policy, KEY_POLICY, &res, role_has, |p| { + format!( + "Key policy:\n{}", + crate::truncate_str(&pretty_policy(p), 6000) + ) + })); + out.join("\n") +} + +fn pretty_policy(p: &str) -> String { + serde_json::from_str::(p) + .ok() + .and_then(|v| serde_json::to_string_pretty(&v).ok()) + .unwrap_or_else(|| p.to_string()) +} + +/// The actions refused in a bucket read. +pub fn bucket_denied(b: &BucketSettings) -> Vec<&'static str> { + let mut out = Vec::new(); + if b.encryption.denied() { + out.push(BUCKET_ENCRYPTION); + } + if b.policy.denied() { + out.push(BUCKET_POLICY); + } + if b.public.denied() { + out.push(BUCKET_POLICY_STATUS); + } + out +} + +pub fn key_denied(k: &KeySettings) -> Vec<&'static str> { + let mut out = Vec::new(); + if k.facts.denied() { + out.push(KEY_DESCRIBE); + } + if k.policy.denied() { + out.push(KEY_POLICY); + } + out +} + +/// Pure: an AWS error code as the end of a read. +pub fn classify(code: Option<&str>, message: &str, absent: &[(&str, &str)]) -> Read { + if crate::log_repo::live::is_refusal(code) { + return Read::Denied; + } + if let Some((_, why)) = absent.iter().find(|(c, _)| Some(*c) == code) { + return Read::Absent(why.to_string()); + } + Read::Failed(super::error_detail(code.unwrap_or(""), message)) +} + +macro_rules! client { + ($krate:ident, $s:expr, $region:expr) => {{ + use $krate::config::{BehaviorVersion, Credentials, Region}; + let s: &Session = $s; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + $krate::Client::from_conf( + $krate::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new($region)) + .credentials_provider(creds) + .build(), + ) + }}; +} + +use aws_sdk_s3::error::ProvideErrorMetadata; + +const NO_BUCKET: (&str, &str) = ( + "NoSuchBucket", + "There is no bucket by that name (check the name, or it is in another account).", +); + +/// The region S3 says a bucket is in (`x-amz-bucket-region`), from a call +/// made in another region. +fn bucket_region( + e: &aws_sdk_s3::error::SdkError, +) -> Option { + let r = e + .raw_response()? + .headers() + .get("x-amz-bucket-region")? + .trim(); + let ok = (5..=30).contains(&r.len()) + && r.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + ok.then(|| r.to_string()) +} + +/// Reads a bucket's encryption, policy and policy status. A call made in the +/// role's region for a bucket elsewhere is made again in the bucket's. +pub async fn read_bucket(s: &Session, bucket: &str) -> BucketSettings { + let mut region = s.region.clone(); + let mut moved = None; + let mut s3 = client!(aws_sdk_s3, s, region.clone()); + let mut enc = s3.get_bucket_encryption().bucket(bucket).send().await; + if let Err(e) = &enc { + let wrong_region = matches!( + e.code(), + Some( + "PermanentRedirect" + | "AuthorizationHeaderMalformed" + | "IllegalLocationConstraintException" + ) + ) || e.code().is_none(); + if let Some(r) = bucket_region(e).filter(|r| *r != region && wrong_region) { + region = r.clone(); + moved = Some(r); + s3 = client!(aws_sdk_s3, s, region.clone()); + enc = s3.get_bucket_encryption().bucket(bucket).send().await; + } + } + let encryption = match enc { + Ok(o) => Read::Got( + o.server_side_encryption_configuration() + .map(|c| { + c.rules() + .iter() + .filter_map(|r| { + let d = r.apply_server_side_encryption_by_default()?; + Some(EncryptionRule { + algorithm: d.sse_algorithm().as_str().to_string(), + kms_key: d.kms_master_key_id().map(str::to_string), + bucket_key: r.bucket_key_enabled(), + }) + }) + .collect() + }) + .unwrap_or_default(), + ), + Err(e) => classify( + e.code(), + e.message().unwrap_or(""), + &[ + NO_BUCKET, + ( + "ServerSideEncryptionConfigurationNotFoundError", + "Default encryption: none configured.", + ), + ], + ), + }; + let policy = match s3.get_bucket_policy().bucket(bucket).send().await { + Ok(o) => match o.policy() { + Some(p) if !p.trim().is_empty() => Read::Got(p.to_string()), + _ => Read::Absent("Bucket policy: none.".into()), + }, + Err(e) => classify( + e.code(), + e.message().unwrap_or(""), + &[NO_BUCKET, ("NoSuchBucketPolicy", "Bucket policy: none.")], + ), + }; + let public = match s3.get_bucket_policy_status().bucket(bucket).send().await { + Ok(o) => Read::Got( + o.policy_status() + .and_then(|p| p.is_public()) + .unwrap_or(false), + ), + Err(e) => classify( + e.code(), + e.message().unwrap_or(""), + &[ + NO_BUCKET, + ( + "NoSuchBucketPolicy", + "Bucket policy status: no bucket policy, so the policy makes nothing public.", + ), + ], + ), + }; + BucketSettings { + bucket: bucket.to_string(), + region: moved, + encryption, + policy, + public, + } +} + +/// Reads a key's description and its key policy. +pub async fn read_key(s: &Session, key: &KeyRef) -> KeySettings { + let region = key.region.clone().unwrap_or_else(|| s.region.clone()); + let kms = client!(aws_sdk_kms, s, region); + const NOT_FOUND: (&str, &str) = ( + "NotFoundException", + "There is no KMS key by that id or alias here (check it, its region and its account).", + ); + let described = kms.describe_key().key_id(&key.id).send().await; + let mut key_id = key.id.clone(); + let facts = match described { + Ok(o) => match o.key_metadata() { + Some(m) => { + key_id = m.key_id().to_string(); + Read::Got(KeyFacts { + key_id: m.key_id().to_string(), + arn: m.arn().unwrap_or("").to_string(), + manager: m + .key_manager() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + state: m + .key_state() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + enabled: m.enabled(), + spec: m + .key_spec() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + usage: m + .key_usage() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + origin: m + .origin() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + multi_region: m.multi_region(), + description: m.description().unwrap_or("").to_string(), + }) + } + None => Read::Failed("AWS returned no key description".into()), + }, + Err(e) => classify(e.code(), e.message().unwrap_or(""), &[NOT_FOUND]), + }; + // A key policy is read by key id or ARN, never by alias: an alias the + // description resolved is read by its key id. + let policy = if key_id.contains("alias/") { + Read::Failed("an alias can't be read for its key policy; give the key id".into()) + } else { + match kms + .get_key_policy() + .key_id(&key_id) + .policy_name("default") + .send() + .await + { + Ok(o) => match o.policy() { + Some(p) => Read::Got(p.to_string()), + None => Read::Absent("Key policy: none returned.".into()), + }, + Err(e) => classify(e.code(), e.message().unwrap_or(""), &[NOT_FOUND]), + } + }; + KeySettings { + key: key.id.clone(), + facts, + policy, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_bucket_is_named_by_name_url_or_arn() { + assert_eq!(check_bucket("data-in").unwrap(), "data-in"); + assert_eq!(check_bucket("s3://data-in/raw/2026/").unwrap(), "data-in"); + assert_eq!(check_bucket("arn:aws:s3:::data-in/*").unwrap(), "data-in"); + for bad in ["", "ab", "a b", "-x-bucket", "bucket;rm", "s3://"] { + assert!(check_bucket(bad).is_err(), "{bad}"); + } + } + + #[test] + fn a_key_arn_names_its_region_and_account() { + let k = check_key( + "arn:aws:kms:eu-west-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", + ) + .unwrap(); + assert_eq!(k.region.as_deref(), Some("eu-west-1")); + assert_eq!(k.account.as_deref(), Some("111122223333")); + let a = check_key("alias/data-copy").unwrap(); + assert_eq!((a.region, a.account), (None, None)); + assert!(check_key("arn:aws:s3:::bucket").is_err()); + assert!(check_key("key id with spaces").is_err()); + assert!(check_key("arn:aws:kms:eu-west-1:1:key/x").is_err()); + } + + #[test] + fn a_refusal_names_the_missing_permission() { + let missing = denied_line(BUCKET_ENCRYPTION, "bucket `data-in`", Some(false)); + assert!(missing.contains("missing `s3:GetEncryptionConfiguration`")); + assert!(missing.contains("Update")); + let elsewhere = denied_line(KEY_POLICY, "KMS key `k`", Some(true)); + assert!(elsewhere.contains("`kms:GetKeyPolicy`")); + assert!(elsewhere.contains("the role allows it")); + let unknown = denied_line(BUCKET_POLICY, "bucket `b`", None); + assert!(unknown.contains("missing `s3:GetBucketPolicy`")); + for l in [missing, elsewhere, unknown] { + assert!(!l.contains('\u{2192}'), "{l}"); + } + } + + #[test] + fn a_bucket_reads_as_evidence_with_each_refusal_named() { + let b = BucketSettings { + bucket: "data-in".into(), + region: Some("eu-west-1".into()), + encryption: Read::Got(vec![EncryptionRule { + algorithm: "aws:kms".into(), + kms_key: Some("arn:aws:kms:eu-west-1:111122223333:key/abc".into()), + bucket_key: Some(true), + }]), + policy: Read::Denied, + public: Read::Got(false), + }; + let has = |a: &str| Some(a != BUCKET_POLICY); + let t = format_bucket(&b, &has); + assert!(t.contains("S3 bucket `data-in` (in eu-west-1)")); + assert!(t.contains("SSE-KMS with KMS key `arn:aws:kms:eu-west-1:111122223333:key/abc`")); + assert!(t.contains("S3 Bucket Key on")); + assert!(t.contains("not public")); + assert!(t.contains("missing `s3:GetBucketPolicy`"), "{t}"); + assert_eq!(bucket_denied(&b), vec![BUCKET_POLICY]); + + let sse_s3 = BucketSettings { + encryption: Read::Got(vec![EncryptionRule { + algorithm: "AES256".into(), + kms_key: None, + bucket_key: None, + }]), + policy: Read::Absent("Bucket policy: none.".into()), + ..b + }; + let t = format_bucket(&sse_s3, &|_| None); + assert!(t.contains("SSE-S3 (AES256): keys managed by S3, not a KMS key")); + assert!(t.contains("Bucket policy: none.")); + assert!(bucket_denied(&sse_s3).is_empty()); + } + + #[test] + fn a_key_says_who_manages_it() { + let k = KeySettings { + key: "alias/data-copy".into(), + facts: Read::Got(KeyFacts { + key_id: "abc".into(), + arn: "arn:aws:kms:eu-west-1:111122223333:key/abc".into(), + manager: "CUSTOMER".into(), + state: "Enabled".into(), + enabled: true, + spec: "SYMMETRIC_DEFAULT".into(), + usage: "ENCRYPT_DECRYPT".into(), + origin: "AWS_KMS".into(), + multi_region: Some(false), + description: "copy job".into(), + }), + policy: Read::Got(r#"{"Version":"2012-10-17","Statement":[]}"#.into()), + }; + let t = format_key(&k, &|_| None); + assert!(t.contains("customer managed; state Enabled, enabled")); + assert!(t.contains("\"Version\": \"2012-10-17\"")); + let denied = KeySettings { + facts: Read::Denied, + policy: Read::Denied, + ..k + }; + assert_eq!(key_denied(&denied), vec![KEY_DESCRIBE, KEY_POLICY]); + let t = format_key(&denied, &|_| Some(false)); + assert!(t.contains("missing `kms:DescribeKey`")); + assert!(t.contains("missing `kms:GetKeyPolicy`")); + } + + #[test] + fn errors_are_read_as_refused_absent_or_failed() { + let absent = [("NoSuchBucketPolicy", "Bucket policy: none.")]; + assert_eq!( + classify::(Some("AccessDenied"), "", &absent), + Read::Denied + ); + assert_eq!( + classify::(Some("NoSuchBucketPolicy"), "", &absent), + Read::Absent("Bucket policy: none.".into()) + ); + assert!(matches!( + classify::(Some("SlowDown"), "too fast", &absent), + Read::Failed(_) + )); + } + + #[test] + fn every_action_is_a_read_of_settings() { + for a in ACTIONS { + let verb = a.split(':').nth(1).unwrap(); + assert!( + verb.starts_with("Get") || verb.starts_with("Describe"), + "{a}" + ); + } + // No object reads, no encrypt or decrypt. + for a in ACTIONS { + let verb = a.split(':').nth(1).unwrap(); + assert!( + !verb.contains("Object") + && !verb.starts_with("Encrypt") + && !verb.starts_with("Decrypt"), + "{a}" + ); + } + } +} diff --git a/services/common/src/live/mod.rs b/services/common/src/live/mod.rs index feb3fcd3e..d20551111 100644 --- a/services/common/src/live/mod.rs +++ b/services/common/src/live/mod.rs @@ -26,6 +26,7 @@ pub mod airflow; pub mod api; pub mod aws; pub mod aws_account; +pub mod aws_settings; pub mod catalog; pub mod confluence; pub mod connectors; diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index fe51590b1..1667250c1 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -107,6 +107,18 @@ pub const ABILITIES: &[Ability] = &[ "ecr:ListTagsForResource", ], }, + Ability { + key: "settings", + name: "Bucket and key settings", + why: "Reads an S3 bucket's default encryption, its bucket policy and whether that policy makes it public, and a KMS key's description and key policy, so a review can check a fact like \"is this bucket encrypted with our own key\" instead of asking. Settings only: never an object in a bucket, and never encrypts or decrypts anything.", + actions: &[ + "s3:GetEncryptionConfiguration", + "s3:GetBucketPolicy", + "s3:GetBucketPolicyStatus", + "kms:DescribeKey", + "kms:GetKeyPolicy", + ], + }, ]; /// Every action of [`ABILITIES`], once each, in order. @@ -393,6 +405,29 @@ mod tests { assert!(update_stack_name().starts_with("CoderHelmLogReaderUpdate-")); } + /// The reviewer's bucket and key lookups use exactly the settings + /// ability's actions, all reads of settings: no object reads, no + /// encrypt or decrypt. + #[test] + fn the_settings_ability_is_what_the_lookups_use() { + let a = ability("settings").unwrap(); + assert_eq!(a.actions, crate::live::aws_settings::ACTIONS); + for t in [ROLE_TEMPLATE, UPDATE_TEMPLATE] { + let all = template_actions(t); + for x in a.actions { + assert!(all.iter().any(|y| y == x), "{x}"); + } + for no in [ + "s3:GetObject", + "s3:ListBucket", + "kms:Decrypt", + "kms:Encrypt", + ] { + assert!(!all.iter().any(|y| y == no), "{no}"); + } + } + } + #[test] fn missing_actions_follow_the_abilities() { assert!(missing_actions(&[]).is_empty()); diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 676becb38..3f32cf1ab 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -611,6 +611,16 @@ pub struct ReviewMessage { /// answer is posted back into that thread instead of the conversation. #[serde(default)] pub reply_to_comment_id: Option, + /// Set for a reply inside an inline review thread (trigger + /// `thread_reply`): the id of the thread's first comment. When CoderHelm + /// wrote that comment, the reply is an answer to its finding and is + /// handled with or without a mention. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thread_root_id: Option, + /// The reply addressed CoderHelm (`@coderhelm …`). A thread reply that + /// doesn't is handled only in CoderHelm's own threads. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub mentioned: bool, /// Login of the person whose comment asked for this job (empty for /// label, push and sweep triggers). On CoderHelm's own PRs a fix request /// goes on to the fix loop, which answers this person on the PR. diff --git a/services/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index e174e0066..c3472873f 100644 --- a/services/common/src/tool_registry.rs +++ b/services/common/src/tool_registry.rs @@ -77,6 +77,8 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("api_get", Risk::Read), ("search_read", Risk::Read), ("aws_identity", Risk::Read), + ("aws_bucket_settings", Risk::Read), + ("aws_kms_key", Risk::Read), ("newrelic_accounts", Risk::Read), ("newrelic_nrql", Risk::Read), ("newrelic_entities", Risk::Read), diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index dc04110d7..96462b0c9 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -677,115 +677,299 @@ pub(crate) fn ask_added_by_edit(old_body: &str, new_body: &str) -> Option` — -/// and the answer goes back into that thread. On CoderHelm's own PRs only a -/// re-review ask is handled here; other thread replies there are fix requests, -/// handled by the feedback path (pull_request_review). +/// A CoderHelm account (the app's bot user), read from GitHub's structured +/// user type and the app's login. A person whose login happens to contain +/// "coderhelm" is still a person. +pub(crate) fn is_coderhelm_user(user: &Value) -> bool { + let login = user["login"].as_str().unwrap_or("").to_ascii_lowercase(); + login.contains("coderhelm") + && (user["type"].as_str() == Some("Bot") || login.ends_with("[bot]")) +} + +/// What a reply's words say, for telling two versions of a reply apart: +/// the text without quoted lines and without any `@coderhelm` address, +/// lower case, letters and digits only. Adding or removing a mention, a +/// space or punctuation leaves it unchanged. +pub(crate) fn reply_fingerprint(body: &str) -> String { + use sha2::{Digest, Sha256}; + let text: String = body + .lines() + .filter(|l| !l.trim_start().starts_with('>')) + .collect::>() + .join("\n") + .to_ascii_lowercase() + .replace("@coderhelm[bot]", " ") + .replace("@coderhelm", " ") + .replace("/coderhelm", " "); + let key: String = text.chars().filter(|c| c.is_alphanumeric()).collect(); + hex::encode(&Sha256::digest(key.as_bytes())[..6]) +} + +/// What to do with a `pull_request_review_comment` event, decided from the +/// payload alone. Every way out names its reason, so a reply that isn't +/// handled is never dropped without a log line. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum ReviewCommentRoute { + Ignore(&'static str), + /// A reply in a thread (`root` is the thread's first comment). Handled + /// in CoderHelm's own threads with or without a mention, and in other + /// threads only when it addresses CoderHelm (the worker checks whose + /// thread it is). + ThreadReply { + comment_id: u64, + root: u64, + ask: Option, + fingerprint: String, + }, + /// A new top-level inline comment that addresses CoderHelm. + Ask { + comment_id: u64, + ask: ReviewerAsk, + }, +} + +/// The worker's claim key for a thread reply: the comment and the version +/// of its words. A duplicate delivery, or an edit that only adds a mention, +/// gives the same key and is handled once. +pub(crate) fn thread_reply_key(comment_id: u64, fingerprint: &str) -> String { + format!("thread#{comment_id}#{fingerprint}") +} + +pub(crate) fn route_review_comment(payload: &Value) -> ReviewCommentRoute { + use ReviewCommentRoute::*; + let action = payload["action"].as_str().unwrap_or(""); + if action != "created" && action != "edited" { + return Ignore("not a new or edited comment"); + } + let c = &payload["comment"]; + if is_coderhelm_user(&c["user"]) { + return Ignore("CoderHelm's own comment"); + } + if c["user"]["type"].as_str() == Some("Bot") { + return Ignore("written by a bot account"); + } + let body = c["body"].as_str().unwrap_or(""); + if body.trim().is_empty() { + return Ignore("empty comment"); + } + let comment_id = c["id"].as_u64().unwrap_or(0); + if comment_id == 0 { + return Ignore("no comment id"); + } + let ask = parse_reviewer_ask(body); + let root = c["in_reply_to_id"].as_u64().filter(|r| *r != 0); + let old = payload["changes"]["body"]["from"].as_str(); + match root { + Some(root) => { + let fingerprint = reply_fingerprint(body); + if action == "edited" { + // An edit counts when it changed what the reply says, or + // when it added the address (a reply in a person's thread + // is handled only once it addresses CoderHelm). Each version + // is handled once: the worker's claim is keyed by the + // comment and these words, so an edit that only adds a + // mention to a reply already answered is not answered again. + let Some(old) = old else { + return Ignore("an edit that didn't change the text"); + }; + let words_changed = reply_fingerprint(old) != fingerprint; + let address_added = ask_added_by_edit(old, body).is_some(); + if !words_changed && !address_added { + return Ignore("an edit that didn't change what the reply says"); + } + } + ThreadReply { + comment_id, + root, + ask, + fingerprint, + } + } + None => { + let ask = if action == "edited" { + ask_added_by_edit(old.unwrap_or(""), body) + } else { + ask + }; + match ask { + Some(ask) => Ask { comment_id, ask }, + None => Ignore("a new inline comment that doesn't address CoderHelm"), + } + } + } +} + +/// A comment inside an inline review thread (`pull_request_review_comment`). +/// +/// On a person's PR: a reply in a thread CoderHelm started (one of its +/// findings) is the author answering it, and is handled with or without a +/// mention: the reviewer acknowledges the answer, settles the finding +/// (resolving the thread when the answer settles it) and re-checks its +/// verdict. A reply in anyone else's thread, or a new inline comment, is +/// handled when it addresses CoderHelm (`@coderhelm re-review` / +/// `@coderhelm `). The answer goes back into that thread. On +/// CoderHelm's own PRs only a re-review ask is handled here; other thread +/// replies there are fix requests, handled by the feedback path +/// (pull_request_review). async fn handle_review_comment( state: &AppState, payload: &Value, installation_id: u64, team_id: &str, ) -> Result { - match payload["action"].as_str() { - Some("created") => {} - Some("edited") => { - let old = payload["changes"]["body"]["from"].as_str().unwrap_or(""); - let new = payload["comment"]["body"].as_str().unwrap_or(""); - if ask_added_by_edit(old, new).is_none() { - return Ok(StatusCode::OK); - } - } - _ => return Ok(StatusCode::OK), - } + let repo = &payload["repository"]; + let owner = repo["owner"]["login"].as_str().unwrap_or(""); + let name = repo["name"].as_str().unwrap_or(""); + let pr = &payload["pull_request"]; + let pr_number = pr["number"].as_u64().unwrap_or(0); let commenter = payload["comment"]["user"]["login"].as_str().unwrap_or(""); - if commenter.contains("coderhelm") { - return Ok(StatusCode::OK); - } - let body = payload["comment"]["body"].as_str().unwrap_or(""); - let Some(ask) = parse_reviewer_ask(body) else { - return Ok(StatusCode::OK); + let ignored = |reason: &str| { + info!( + owner, + name, + pr_number, + commenter, + action = payload["action"].as_str().unwrap_or(""), + reason, + "Reviewer: review comment not handled" + ); + Ok(StatusCode::OK) + }; + let route = route_review_comment(payload); + let (comment_id, ask, thread) = match route { + ReviewCommentRoute::Ignore(reason) => return ignored(reason), + ReviewCommentRoute::Ask { comment_id, ask } => (comment_id, Some(ask), None), + ReviewCommentRoute::ThreadReply { + comment_id, + root, + ask, + fingerprint, + } => (comment_id, ask, Some((root, fingerprint))), }; if !may_start_work(state, team_id, &payload["comment"], "review thread reply").await { - return Ok(StatusCode::OK); + return ignored("the author has no standing in the repository or on the team"); } - let pr = &payload["pull_request"]; - if let Some(control) = ask.question.as_deref().and_then(merge_gate::parse_control) { - let repo = &payload["repository"]; + if let Some(control) = ask + .as_ref() + .and_then(|a| a.question.as_deref()) + .and_then(merge_gate::parse_control) + { return super::merge_control::on_comment( state, team_id, installation_id, - repo["owner"]["login"].as_str().unwrap_or(""), - repo["name"].as_str().unwrap_or(""), - pr["number"].as_u64().unwrap_or(0), + owner, + name, + pr_number, commenter, control, - super::merge_control::CommentRef::ReviewThread( - payload["comment"]["id"].as_u64().unwrap_or(0), - ), + super::merge_control::CommentRef::ReviewThread(comment_id), ) .await; } - let bot_pr = pr["user"]["login"] - .as_str() - .unwrap_or("") - .contains("coderhelm"); - if bot_pr && !ask.rereview { - return Ok(StatusCode::OK); + let bot_pr = is_coderhelm_user(&pr["user"]) + || pr["user"]["login"] + .as_str() + .unwrap_or("") + .contains("coderhelm"); + let rereview = ask.as_ref().is_some_and(|a| a.rereview); + if bot_pr && !rereview { + return ignored("CoderHelm's own PR: thread replies there go to the fix loop"); } - let repo = &payload["repository"]; - let owner = repo["owner"]["login"].as_str().unwrap_or(""); - let name = repo["name"].as_str().unwrap_or(""); - let pr_number = pr["number"].as_u64().unwrap_or(0); - let comment_id = payload["comment"]["id"].as_u64().unwrap_or(0); let cfg = load_review_config(state, team_id, owner, name).await?; - if !cfg.enabled || cfg.killed || pr_number == 0 || comment_id == 0 { - info!( - owner, - name, pr_number, "Reviewer: thread reply ignored — review is off for this repo" - ); - return Ok(StatusCode::OK); + if !cfg.enabled || cfg.killed || pr_number == 0 { + return ignored("review is off for this repo"); } if let Some(reason) = check_run_budget(state, team_id).await { post_limit_comment(state, installation_id, owner, name, pr_number, &reason).await; - return Ok(StatusCode::OK); + return ignored("the team's token limit is reached"); } - info!( - owner, - name, - pr_number, - is_rereview = ask.rereview, - "Reviewer: thread reply → review job" - ); - if ask.rereview { - record_rereview( - state, - team_id, - owner, - name, - pr_number, - &format!("reply#{comment_id}"), - ) - .await; - } - let message = WorkerMessage::Review(ReviewMessage { - team_id: team_id.to_string(), - installation_id, - repo_owner: owner.to_string(), - repo_name: name.to_string(), - pr_number, - head_sha: String::new(), - label: cfg.label, - question: ask.question, - trigger: "reply".to_string(), - dedup_key: format!("reply#{comment_id}"), - reply_to_comment_id: Some(comment_id), - requested_by: commenter.to_string(), - ..Default::default() - }); - send_to_queue(state, &state.config.ticket_queue_url, &message).await + let body = payload["comment"]["body"].as_str().unwrap_or(""); + // A thread reply that isn't a re-review command goes to the worker as + // a thread reply: it checks whose thread it is and answers there. + let message = match thread { + Some((root, fingerprint)) if !rereview => { + let question = ask + .as_ref() + .and_then(|a| a.question.clone()) + .filter(|q| !q.trim().is_empty()) + .unwrap_or_else(|| body.trim().to_string()); + info!( + owner, + name, + pr_number, + comment_id, + root, + mentioned = ask.is_some(), + "Reviewer: thread reply → review job" + ); + ReviewMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + head_sha: String::new(), + label: cfg.label, + question: Some(question), + trigger: "thread_reply".to_string(), + // One job per version of the reply's words: a duplicate + // delivery, or an edit that only adds a mention, is the + // same job. + dedup_key: thread_reply_key(comment_id, &fingerprint), + reply_to_comment_id: Some(comment_id), + thread_root_id: Some(root), + mentioned: ask.is_some(), + requested_by: commenter.to_string(), + ..Default::default() + } + } + _ => { + let Some(ask) = ask else { + return ignored("not addressed to CoderHelm"); + }; + info!( + owner, + name, + pr_number, + is_rereview = ask.rereview, + "Reviewer: thread reply → review job" + ); + if ask.rereview { + record_rereview( + state, + team_id, + owner, + name, + pr_number, + &format!("reply#{comment_id}"), + ) + .await; + } + ReviewMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + head_sha: String::new(), + label: cfg.label, + question: ask.question, + trigger: "reply".to_string(), + dedup_key: format!("reply#{comment_id}"), + reply_to_comment_id: Some(comment_id), + mentioned: true, + requested_by: commenter.to_string(), + ..Default::default() + } + } + }; + send_to_queue( + state, + &state.config.ticket_queue_url, + &WorkerMessage::Review(message), + ) + .await } /// True when the comment's author is a bot account, read from GitHub's @@ -849,6 +1033,76 @@ async fn is_linked_team_member(state: &AppState, team_id: &str, github_id: u64) } } +/// The comment quotes something (a `> ` line) and says something of its own. +pub(crate) fn is_quote_reply(body: &str) -> bool { + let quoted = body.lines().any(|l| { + let t = l.trim_start(); + t.starts_with('>') && t.trim_start_matches('>').trim().len() >= 8 + }); + let own = addressed_text(body).trim().len() >= 2; + quoted && own +} + +/// A person's PR-conversation comment that quotes text: when the PR is one +/// CoderHelm reviewed, the worker checks whether the quote is from its +/// review or replies and, if so, answers it like a reply in its thread. +async fn handle_quote_reply( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, +) -> Result { + let repo = &payload["repository"]; + let owner = repo["owner"]["login"].as_str().unwrap_or(""); + let name = repo["name"].as_str().unwrap_or(""); + let pr_number = payload["issue"]["number"].as_u64().unwrap_or(0); + let comment_id = payload["comment"]["id"].as_u64().unwrap_or(0); + let commenter = payload["comment"]["user"]["login"].as_str().unwrap_or(""); + let ignored = |reason: &str| { + info!( + owner, + name, pr_number, commenter, reason, "Reviewer: quote reply not handled" + ); + Ok(StatusCode::OK) + }; + if pr_number == 0 || comment_id == 0 { + return ignored("no PR or comment id"); + } + if !super::review_lessons::reviewed_by_coderhelm(state, team_id, owner, name, pr_number).await { + return ignored("CoderHelm hasn't reviewed this PR"); + } + if !may_start_work(state, team_id, &payload["comment"], "quote reply").await { + return ignored("the author has no standing in the repository or on the team"); + } + let cfg = load_review_config(state, team_id, owner, name).await?; + if !cfg.enabled || cfg.killed { + return ignored("review is off for this repo"); + } + if check_run_budget(state, team_id).await.is_some() { + return ignored("the team's token limit is reached"); + } + let body = payload["comment"]["body"].as_str().unwrap_or(""); + info!( + owner, + name, pr_number, comment_id, "Reviewer: quote reply → review job" + ); + let message = WorkerMessage::Review(ReviewMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + head_sha: String::new(), + label: cfg.label, + question: Some(body.trim().to_string()), + trigger: "quote_reply".to_string(), + dedup_key: format!("quote#{comment_id}#{}", reply_fingerprint(body)), + requested_by: commenter.to_string(), + ..Default::default() + }); + send_to_queue(state, &state.config.ticket_queue_url, &message).await +} + async fn handle_issue_comment( state: &AppState, payload: &Value, @@ -856,8 +1110,18 @@ async fn handle_issue_comment( team_id: &str, ) -> Result { let action = payload["action"].as_str().unwrap_or(""); + let not_handled = |reason: &str| { + info!( + issue = payload["issue"]["number"].as_u64().unwrap_or(0), + commenter = payload["comment"]["user"]["login"].as_str().unwrap_or(""), + action, + reason, + "Comment not handled" + ); + Ok(StatusCode::OK) + }; if action != "created" && action != "edited" { - return Ok(StatusCode::OK); + return not_handled("not a new or edited comment"); } // An edit counts only when it adds a command to the reviewer; every // other edit is ignored (the original comment was already handled). @@ -865,7 +1129,7 @@ async fn handle_issue_comment( let old = payload["changes"]["body"]["from"].as_str().unwrap_or(""); let new = payload["comment"]["body"].as_str().unwrap_or(""); if ask_added_by_edit(old, new).is_none() { - return Ok(StatusCode::OK); + return not_handled("an edit that didn't add an ask to CoderHelm"); } } @@ -873,7 +1137,7 @@ async fn handle_issue_comment( // are never instructions. They used to reach the feedback fixer as // review_id 0 and spawn unbudgeted fix cycles. if is_bot_comment(payload) { - return Ok(StatusCode::OK); + return not_handled("written by a bot account"); } let body = payload["comment"]["body"].as_str().unwrap_or(""); let commenter = payload["comment"]["user"]["login"].as_str().unwrap_or(""); @@ -925,6 +1189,20 @@ async fn handle_issue_comment( || lower.trim_start().starts_with("/coderhelm") || lower.contains("@coderhelm"); if !on_bot_pr && !addressed { + // A person quoting CoderHelm's review in the PR conversation (GitHub's + // "Quote reply") is answering it, mention or not. + if action == "created" + && is_quote_reply(body) + && payload["issue"]["pull_request"].is_object() + { + return handle_quote_reply(state, payload, installation_id, team_id).await; + } + info!( + commenter, + issue = payload["issue"]["number"].as_u64().unwrap_or(0), + reason = "not on CoderHelm's PR, not addressed to it and not quoting it", + "Comment not handled" + ); return Ok(StatusCode::OK); } if !may_start_work(state, team_id, &payload["comment"], "comment").await { @@ -3983,3 +4261,186 @@ mod own_pr_ci_after_run_tests { } } } + +#[cfg(test)] +mod thread_reply_tests { + use super::{ + is_coderhelm_user, is_quote_reply, reply_fingerprint, route_review_comment, + thread_reply_key, ReviewCommentRoute, + }; + use serde_json::{json, Value}; + + fn fixture(name: &str) -> Value { + let text = match name { + "no_mention" => include_str!("testdata/review_reply_no_mention.json"), + "edited" => include_str!("testdata/review_reply_edited.json"), + "bot" => include_str!("testdata/review_reply_bot.json"), + _ => unreachable!(), + }; + serde_json::from_str(text).unwrap() + } + + fn key_of(r: &ReviewCommentRoute) -> String { + match r { + ReviewCommentRoute::ThreadReply { + comment_id, + fingerprint, + .. + } => thread_reply_key(*comment_id, fingerprint), + other => panic!("not a thread reply: {other:?}"), + } + } + + #[test] + fn a_reply_without_a_mention_in_a_thread_is_handled() { + let r = route_review_comment(&fixture("no_mention")); + match &r { + ReviewCommentRoute::ThreadReply { + comment_id, + root, + ask, + .. + } => { + assert_eq!(*comment_id, 2001); + assert_eq!(*root, 1999); + assert!(ask.is_none(), "no mention, still handled"); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn a_reply_with_a_mention_keeps_working() { + let mut p = fixture("no_mention"); + p["comment"]["body"] = json!("@CoderHelm yes, it's our own KMS key."); + match route_review_comment(&p) { + ReviewCommentRoute::ThreadReply { ask: Some(a), .. } => { + assert_eq!(a.question.as_deref(), Some("yes, it's our own KMS key.")); + } + other => panic!("{other:?}"), + } + // A new top-level inline comment needs the mention. + let mut top = fixture("no_mention"); + top["comment"]["in_reply_to_id"] = Value::Null; + assert!(matches!( + route_review_comment(&top), + ReviewCommentRoute::Ignore(_) + )); + top["comment"]["body"] = json!("@coderhelm re-review"); + assert!(matches!( + route_review_comment(&top), + ReviewCommentRoute::Ask { .. } + )); + } + + #[test] + fn an_edit_that_adds_the_answer_is_handled_once_per_version() { + let p = fixture("edited"); + let r = route_review_comment(&p); + let edited_key = key_of(&r); + // The created version had other words: a different job. + let mut created = p.clone(); + created["action"] = json!("created"); + created["comment"]["body"] = json!("Checking, one sec."); + assert_ne!(key_of(&route_review_comment(&created)), edited_key); + // An edit that only fixes spacing or punctuation is not handled. + let mut typo = p.clone(); + typo["changes"]["body"]["from"] = p["comment"]["body"].clone(); + typo["comment"]["body"] = json!(format!("{}!! ", p["comment"]["body"].as_str().unwrap())); + assert!(matches!( + route_review_comment(&typo), + ReviewCommentRoute::Ignore(_) + )); + // An edit that only adds the mention to an answered reply is routed, + // but with the same key as the version already answered. + let mut mention = p.clone(); + mention["changes"]["body"]["from"] = p["comment"]["body"].clone(); + mention["comment"]["body"] = json!(format!( + "@coderhelm {}", + p["comment"]["body"].as_str().unwrap() + )); + assert_eq!(key_of(&route_review_comment(&mention)), edited_key); + // An edit event without the old text changed nothing we can see. + let mut no_from = p.clone(); + no_from["changes"] = json!({}); + assert!(matches!( + route_review_comment(&no_from), + ReviewCommentRoute::Ignore(_) + )); + } + + #[test] + fn a_reply_from_a_bot_or_from_coderhelm_is_ignored() { + assert_eq!( + route_review_comment(&fixture("bot")), + ReviewCommentRoute::Ignore("written by a bot account") + ); + let mut own = fixture("no_mention"); + own["comment"]["user"] = json!({"login": "coderhelm[bot]", "type": "Bot"}); + assert_eq!( + route_review_comment(&own), + ReviewCommentRoute::Ignore("CoderHelm's own comment") + ); + // A person whose login contains the name is still a person. + let mut named = fixture("no_mention"); + named["comment"]["user"] = json!({"login": "coderhelm-fan", "type": "User"}); + assert!(matches!( + route_review_comment(&named), + ReviewCommentRoute::ThreadReply { .. } + )); + assert!(!is_coderhelm_user( + &json!({"login": "coderhelm-fan", "type": "User"}) + )); + assert!(is_coderhelm_user( + &json!({"login": "CoderHelm[bot]", "type": "Bot"}) + )); + } + + #[test] + fn a_duplicate_delivery_gives_the_same_job_key() { + let a = route_review_comment(&fixture("no_mention")); + let b = route_review_comment(&fixture("no_mention")); + assert_eq!(a, b); + assert_eq!(key_of(&a), key_of(&b)); + assert!(key_of(&a).starts_with("thread#2001#")); + } + + #[test] + fn every_other_action_is_ignored_with_a_reason() { + let mut p = fixture("no_mention"); + p["action"] = json!("deleted"); + assert_eq!( + route_review_comment(&p), + ReviewCommentRoute::Ignore("not a new or edited comment") + ); + p["action"] = json!("created"); + p["comment"]["body"] = json!(" "); + assert_eq!( + route_review_comment(&p), + ReviewCommentRoute::Ignore("empty comment") + ); + } + + #[test] + fn the_fingerprint_ignores_mentions_quotes_and_punctuation() { + assert_eq!( + reply_fingerprint("@CoderHelm Yes, it is."), + reply_fingerprint("yes it is") + ); + assert_eq!( + reply_fingerprint("> Is it encrypted?\n\nYes it is"), + reply_fingerprint("Yes, it is!") + ); + assert_ne!(reply_fingerprint("yes"), reply_fingerprint("no")); + } + + #[test] + fn a_quote_reply_quotes_and_adds_words() { + assert!(is_quote_reply( + "> Is the source bucket encrypted with a customer-managed key?\n\nYes." + )); + assert!(!is_quote_reply("> Is the source bucket encrypted?")); + assert!(!is_quote_reply("No quote, just words.")); + assert!(!is_quote_reply("> ok\n\nYes.")); + } +} diff --git a/services/gateway/src/routes/review_lessons.rs b/services/gateway/src/routes/review_lessons.rs index 806c593f5..a75ee0de4 100644 --- a/services/gateway/src/routes/review_lessons.rs +++ b/services/gateway/src/routes/review_lessons.rs @@ -58,7 +58,19 @@ pub fn detect(event_type: &str, payload: &Value) -> Option { // A reply inside a review thread. "pull_request_review_comment" => { let c = &payload["comment"]; - (action == "created" + // An edit counts when it changed what the reply says (an answer + // added after the first words); one that only adds a mention or + // fixes a typo doesn't. + let edited_words = action == "edited" + && payload["changes"]["body"]["from"] + .as_str() + .is_some_and(|old| { + super::github_webhook::reply_fingerprint(old) + != super::github_webhook::reply_fingerprint( + c["body"].as_str().unwrap_or(""), + ) + }); + ((action == "created" || edited_words) && is_person(&c["user"]) && c["in_reply_to_id"].as_u64().is_some() && has_body(&c["body"])) @@ -159,10 +171,33 @@ pub fn qualifies(verdicts_newest_first: &[String], needs_changes_requested: bool .is_some_and(|v| v == "REQUEST_CHANGES") } +/// CoderHelm reviewed this PR (it has a review record of it). +pub async fn reviewed_by_coderhelm( + state: &AppState, + team_id: &str, + owner: &str, + name: &str, + pr_number: u64, +) -> bool { + !pr_verdicts(state, team_id, owner, name, pr_number) + .await + .is_empty() +} + +async fn verdicts(state: &AppState, team_id: &str, t: &LessonTrigger) -> Vec { + pr_verdicts(state, team_id, &t.owner, &t.name, t.pr_number).await +} + /// CoderHelm's verdicts on this PR, newest first (empty when it never /// reviewed it). -async fn verdicts(state: &AppState, team_id: &str, t: &LessonTrigger) -> Vec { - let prefix = format!("REVIEW#{}/{}#{:06}#", t.owner, t.name, t.pr_number); +async fn pr_verdicts( + state: &AppState, + team_id: &str, + owner: &str, + name: &str, + pr_number: u64, +) -> Vec { + let prefix = format!("REVIEW#{owner}/{name}#{pr_number:06}#"); match state .dynamo .query() @@ -210,6 +245,7 @@ pub async fn on_webhook( }; if let Some(author) = pushback_author(event_type, payload) { if !super::github_webhook::may_start_work(state, team_id, author, "review pushback").await { + info!(owner = %t.owner, name = %t.name, pr = t.pr_number, trigger = t.trigger, reason = "the author has no standing", "Pushback on a review not judged"); return; } } @@ -217,6 +253,7 @@ pub async fn on_webhook( &verdicts(state, team_id, &t).await, t.needs_changes_requested, ) { + info!(owner = %t.owner, name = %t.name, pr = t.pr_number, trigger = t.trigger, reason = "CoderHelm hasn't reviewed this PR, or its verdict doesn't request changes", "Pushback on a review not judged"); return; } let event_at = match rl::mark_event( @@ -413,10 +450,20 @@ mod tests { p["comment"]["user"] = person("dev-one"); p["comment"]["in_reply_to_id"] = Value::Null; assert_eq!(detect("pull_request_review_comment", &p), None); - // An edit is not news. + // An edit that changes nothing is not news, nor is one that only + // adds a mention. p["comment"]["in_reply_to_id"] = json!(10); p["action"] = json!("edited"); assert_eq!(detect("pull_request_review_comment", &p), None); + p["changes"] = json!({"body": {"from": "This is intended."}}); + p["comment"]["body"] = json!("@coderhelm This is intended."); + assert_eq!(detect("pull_request_review_comment", &p), None); + // An edit that adds the answer is. + p["comment"]["body"] = json!("This is intended: the bucket uses our own KMS key."); + assert_eq!( + detect("pull_request_review_comment", &p).map(|t| t.trigger), + Some(rl::TRIGGER_THREAD_REPLY) + ); } #[test] diff --git a/services/gateway/src/routes/testdata/review_reply_bot.json b/services/gateway/src/routes/testdata/review_reply_bot.json new file mode 100644 index 000000000..d1dbb2d2b --- /dev/null +++ b/services/gateway/src/routes/testdata/review_reply_bot.json @@ -0,0 +1,19 @@ +{ + "action": "created", + "comment": { + "id": 2002, + "in_reply_to_id": 1999, + "body": "Coverage report: 81% (+0.2%)", + "author_association": "NONE", + "created_at": "2026-10-27T14:03:00Z", + "updated_at": "2026-10-27T14:03:00Z", + "user": { "login": "ci-reporter[bot]", "id": 900, "type": "Bot" } + }, + "pull_request": { + "number": 42, + "user": { "login": "pr-author", "type": "User" } + }, + "repository": { "name": "infra", "owner": { "login": "acme" } }, + "sender": { "login": "ci-reporter[bot]", "type": "Bot" }, + "installation": { "id": 7 } +} diff --git a/services/gateway/src/routes/testdata/review_reply_edited.json b/services/gateway/src/routes/testdata/review_reply_edited.json new file mode 100644 index 000000000..5ab96d0de --- /dev/null +++ b/services/gateway/src/routes/testdata/review_reply_edited.json @@ -0,0 +1,20 @@ +{ + "action": "edited", + "changes": { "body": { "from": "Checking, one sec." } }, + "comment": { + "id": 2001, + "in_reply_to_id": 1999, + "body": "Checking, one sec.\n\nUpdate: it's SSE-KMS with our own customer-managed key.", + "author_association": "MEMBER", + "created_at": "2026-10-27T14:02:11Z", + "updated_at": "2026-10-27T14:09:40Z", + "user": { "login": "pr-author", "id": 501, "type": "User" } + }, + "pull_request": { + "number": 42, + "user": { "login": "pr-author", "type": "User" } + }, + "repository": { "name": "infra", "owner": { "login": "acme" } }, + "sender": { "login": "pr-author", "type": "User" }, + "installation": { "id": 7 } +} diff --git a/services/gateway/src/routes/testdata/review_reply_no_mention.json b/services/gateway/src/routes/testdata/review_reply_no_mention.json new file mode 100644 index 000000000..aaf390ffd --- /dev/null +++ b/services/gateway/src/routes/testdata/review_reply_no_mention.json @@ -0,0 +1,19 @@ +{ + "action": "created", + "comment": { + "id": 2001, + "in_reply_to_id": 1999, + "body": "Yes. The source bucket uses SSE-KMS with our own customer-managed key, and the copy role has kms:Decrypt on it.", + "author_association": "MEMBER", + "created_at": "2026-10-27T14:02:11Z", + "updated_at": "2026-10-27T14:02:11Z", + "user": { "login": "pr-author", "id": 501, "type": "User" } + }, + "pull_request": { + "number": 42, + "user": { "login": "pr-author", "type": "User" } + }, + "repository": { "name": "infra", "owner": { "login": "acme" } }, + "sender": { "login": "pr-author", "type": "User" }, + "installation": { "id": 7 } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 9d03c73f2..aa5d4b3c7 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -2463,7 +2463,7 @@ impl GitHubClient { let mut cursor: Option = None; for _ in 0..10 { let query = serde_json::json!({ - "query": "query($owner:String!,$name:String!,$pr:Int!,$after:String){ repository(owner:$owner,name:$name){ pullRequest(number:$pr){ reviewThreads(first:100, after:$after){ pageInfo{ hasNextPage endCursor } nodes{ id isResolved isOutdated path line originalLine resolvedBy{ login } comments(first:30){ nodes{ author{ login } body } } } } } } }", + "query": "query($owner:String!,$name:String!,$pr:Int!,$after:String){ repository(owner:$owner,name:$name){ pullRequest(number:$pr){ reviewThreads(first:100, after:$after){ pageInfo{ hasNextPage endCursor } nodes{ id isResolved isOutdated path line originalLine resolvedBy{ login } comments(first:30){ nodes{ databaseId author{ login } body } } } } } } }", "variables": { "owner": owner, "name": repo, "pr": pr_number, "after": cursor } }); let resp = self.post("https://api.github.com/graphql", &query).await?; @@ -2487,6 +2487,7 @@ impl GitHubClient { let resolved = t["isResolved"].as_bool().unwrap_or(false); let resolved_by = t["resolvedBy"]["login"].as_str().unwrap_or(""); out.push(BotReviewThread { + root_id: first["databaseId"].as_u64().unwrap_or(0), replies: comments[1..] .iter() .map(|c| ThreadReply { @@ -3339,6 +3340,9 @@ pub struct ThreadReply { pub struct BotReviewThread { /// GraphQL node id (what resolveReviewThread takes). pub id: String, + /// The REST id of the thread's first comment (what a reply's + /// `in_reply_to_id` names); 0 when unknown. + pub root_id: u64, pub path: String, pub line: u64, /// GitHub marks a thread outdated when its anchored lines changed. diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 7ccea7661..ec9107836 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -753,6 +753,7 @@ pub mod review_reminder; pub mod review_risk; pub mod review_scope; pub mod review_sweep; +pub mod review_thread_reply; pub mod review_verdict; pub mod rewards; pub(crate) mod round; diff --git a/services/worker/src/passes/ops_tools.rs b/services/worker/src/passes/ops_tools.rs index c16204003..e17c0bde0 100644 --- a/services/worker/src/passes/ops_tools.rs +++ b/services/worker/src/passes/ops_tools.rs @@ -31,7 +31,7 @@ use common::live::newrelic::NewRelic; use common::live::opensearch::OpenSearch; use common::live::rest::Rest; use common::live::store::{self, Activity, RunRef}; -use common::live::{airflow, identity, metrics, secret, StepError}; +use common::live::{airflow, aws_settings, identity, metrics, secret, StepError}; use serde_json::{json, Value}; use tracing::{info, warn}; @@ -205,6 +205,48 @@ impl AwsAbilities { } } + /// The account to read bucket or key settings in: the one asked for, + /// the one a key's ARN names, or the only one. + pub fn settings_account( + &self, + asked: Option<&str>, + named: Option<&str>, + ) -> Result<&AwsAccount, StepError> { + let list = || { + self.accounts + .iter() + .map(|a| a.account.clone()) + .collect::>() + .join(", ") + }; + let want = asked + .map(str::trim) + .filter(|a| !a.is_empty()) + .or(named.filter(|a| !a.is_empty())); + match want { + Some(a) => self.accounts.iter().find(|x| x.account == a).ok_or_else(|| { + StepError::new( + "read_only", + format!("Account {a} isn't connected to CoderHelm, so its settings can't be read."), + format!("Connected accounts: {}.", list()), + ) + }), + None => match self.accounts.as_slice() { + [one] => Ok(one), + [] => Err(StepError::new( + "read_only", + "No AWS account is connected.", + "An admin connects one in Settings, Integrations, AWS.", + )), + _ => Err(StepError::new( + "read_only", + "Say which AWS account the bucket or key is in.", + format!("Accounts: {}.", list()), + )), + }, + } + } + fn metric_accounts(&self) -> Vec { self.metrics .iter() @@ -232,6 +274,21 @@ pub struct OpsTools { reports: Option, } +/// The bucket and key settings tools' names. +fn is_settings_tool(name: &str) -> bool { + matches!(name, "aws_bucket_settings" | "aws_kms_key") +} + +/// 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 +/// permissions). +pub fn role_has(account: &AwsAccount, action: &str) -> Option { + let c = account.permissions.as_ref()?; + (c.works && c.permissions_id == common::log_reader::permissions_id()) + .then(|| !c.missing.iter().any(|m| m == action)) +} + /// The test report tools' names. fn is_report_tool(name: &str) -> bool { matches!(name, "test_report" | "test_pass_counts") @@ -557,6 +614,31 @@ impl OpsTools { json!({ "type": "object", "properties": {} }), )); } + if !self.aws.accounts.is_empty() { + let mut bucket_props = json!({ "bucket": { "type": "string", "description": "bucket name, s3://bucket or its ARN" } }); + let mut key_props = json!({ "key": { "type": "string", "description": "KMS key id, alias (alias/name) or ARN" } }); + if self.aws.accounts.len() > 1 { + let accounts: Vec = self + .aws + .accounts + .iter() + .map(|a| a.account.clone()) + .collect(); + let account = json!({ "type": "string", "description": format!("AWS account: {}", accounts.join(", ")) }); + bucket_props["account"] = account.clone(); + key_props["account"] = account; + } + out.push(tool( + "aws_bucket_settings", + "Read an S3 bucket's settings in the team's AWS account: its default encryption (SSE-S3, SSE-KMS and which key), its bucket policy, and whether that policy makes it public. Settings only, never objects. When access is denied the result names the missing permission.", + json!({ "type": "object", "properties": bucket_props, "required": ["bucket"] }), + )); + out.push(tool( + "aws_kms_key", + "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"] }), + )); + } 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(", ")) }) }); out.push(tool( @@ -681,6 +763,9 @@ impl OpsTools { if !self.roles.is_empty() { 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("- `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 { s.push_str(&format!("- {}\n", describe(&l.conn))); } @@ -703,6 +788,7 @@ impl OpsTools { pub async fn handle(&self, state: &WorkerState, name: &str, input: &Value) -> Option { let kind = match name { "aws_identity" => None, + n if is_settings_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), @@ -730,6 +816,9 @@ impl OpsTools { None if is_report_tool(name) => { ("test-reports".to_string(), "Test reports".to_string()) } + None if is_settings_tool(name) => { + ("connector-aws".to_string(), "AWS settings".to_string()) + } None => ("connector-aws".to_string(), "AWS identity".to_string()), }; let logged = store::log_activity_in( @@ -759,6 +848,8 @@ impl OpsTools { } let source = if is_report_tool(name) { "Test reports".to_string() + } else if is_settings_tool(name) { + "AWS settings".to_string() } else { lookup_source(kind, input) }; @@ -823,6 +914,43 @@ impl OpsTools { out } + /// A bucket's or a key's settings. Every read refused: the lookup fails + /// with each missing permission named; some refused: the rest is shown + /// with those named. + async fn read_settings( + &self, + state: &WorkerState, + name: &str, + input: &Value, + actor: &str, + ) -> Result<(String, String, bool), StepError> { + if name == "aws_kms_key" { + let key = aws_settings::check_key(s_in(input, "key").unwrap_or(""))?; + let account = self + .aws + .settings_account(s_in(input, "account"), key.account.as_deref())?; + let session = assume(&state.sts, &account.target(), actor).await?; + let read = aws_settings::read_key(&session, &key).await; + let has = |a: &str| role_has(account, a); + let text = aws_settings::format_key(&read, &has); + let denied = aws_settings::key_denied(&read); + if denied.len() == 2 { + return Err(StepError::new("read", text, "")); + } + return Ok((text, format!("key {}", key.id), false)); + } + let bucket = aws_settings::check_bucket(s_in(input, "bucket").unwrap_or(""))?; + let account = self.aws.settings_account(s_in(input, "account"), None)?; + let session = assume(&state.sts, &account.target(), actor).await?; + let read = aws_settings::read_bucket(&session, &bucket).await; + let has = |a: &str| role_has(account, a); + let text = aws_settings::format_bucket(&read, &has); + if aws_settings::bucket_denied(&read).len() == 3 { + return Err(StepError::new("read", text, "")); + } + Ok((text, format!("bucket {bucket}"), false)) + } + /// The text that came back and a short note for the activity log. async fn run( &self, @@ -902,6 +1030,9 @@ impl OpsTools { let (text, _hidden) = airflow::read(&airflow::Mwaa { session: &session }, &get).await?; return Ok((text, get.describe(), false)); } + if is_settings_tool(name) { + return self.read_settings(state, name, input, &actor).await; + } let Some(kind) = kind else { let mut lines = Vec::new(); for r in &self.roles { @@ -1292,6 +1423,54 @@ mod tests { assert!(is_report_tool("test_report") && !is_report_tool("metrics_query")); } + #[test] + fn settings_are_read_in_the_named_or_only_account() { + let one = AwsAbilities::from_parts(vec![checked_account("111122223333", false, &[])], &[]); + assert_eq!( + one.settings_account(None, None).unwrap().account, + "111122223333" + ); + assert!(one.settings_account(Some("999988887777"), None).is_err()); + let two = AwsAbilities::from_parts( + vec![ + checked_account("111122223333", false, &[]), + checked_account("444455556666", false, &[]), + ], + &[], + ); + let e = two.settings_account(None, None).unwrap_err(); + assert!(e.fix.contains("111122223333, 444455556666"), "{}", e.fix); + // A key's ARN names its account. + assert_eq!( + two.settings_account(None, Some("444455556666")) + .unwrap() + .account, + "444455556666" + ); + assert!(AwsAbilities::default() + .settings_account(None, None) + .is_err()); + assert!(is_settings_tool("aws_kms_key") && is_settings_tool("aws_bucket_settings")); + assert!(!is_settings_tool("aws_identity")); + } + + #[test] + fn the_role_check_says_which_settings_permission_is_missing() { + use common::live::permissions::PermissionCheck; + let mut a = checked_account("111122223333", false, &[]); + assert_eq!(role_has(&a, "kms:GetKeyPolicy"), None); + let mut c = PermissionCheck::new(&a.target(), "2026-10-27T00:00:00Z"); + c.works = true; + c.missing = vec!["kms:GetKeyPolicy".into()]; + a.permissions = Some(c.clone()); + assert_eq!(role_has(&a, "kms:GetKeyPolicy"), Some(false)); + assert_eq!(role_has(&a, "s3:GetBucketPolicy"), Some(true)); + // A check of another release's permissions says nothing. + c.permissions_id = "00000000".into(); + a.permissions = Some(c); + assert_eq!(role_has(&a, "kms:GetKeyPolicy"), None); + } + fn checked_account(id: &str, metrics: bool, envs: &[&str]) -> AwsAccount { let mut a = AwsAccount { account: id.into(), diff --git a/services/worker/src/passes/review_agent.rs b/services/worker/src/passes/review_agent.rs index 712b82bfa..434da2b69 100644 --- a/services/worker/src/passes/review_agent.rs +++ b/services/worker/src/passes/review_agent.rs @@ -1969,6 +1969,9 @@ pub struct ReplyConclusion { pub new_nonblocking_items: bool, /// The reply without those new items (only meaningful when set). pub revised_reply: String, + /// The person was answering one of CoderHelm's findings, and the reply + /// accepts that the answer settles it (nothing about it is left to do). + pub settles_finding: bool, } /// What the reply-conclusion check is told. @@ -1985,7 +1988,11 @@ pub const REPLY_CONCLUSION_SYSTEM: &str = fine or ready to merge, and this reply brings up non-blocking items (description wording or \ counts, a file the description doesn't mention, style) that no earlier reply mentioned. \ revised_reply: when new_nonblocking_items is true, the reply with exactly those new items \ - removed and nothing else changed; otherwise an empty string."; + removed and nothing else changed; otherwise an empty string. \ + settles_finding: true only when what the person wrote answers one of CoderHelm's review \ + findings (the finding is quoted with it) and the reply accepts that the answer settles that \ + finding, so nothing about it is left to do; false when the reply says something about it is \ + still open, and false when the person wasn't answering a finding."; /// The JSON schema of the reply-conclusion answer. pub fn reply_conclusion_schema() -> serde_json::Value { @@ -1995,9 +2002,10 @@ pub fn reply_conclusion_schema() -> serde_json::Value { "verdict_change": {"type": "string", "enum": ["none", "clear", "block"]}, "reason": {"type": "string"}, "new_nonblocking_items": {"type": "boolean"}, - "revised_reply": {"type": "string"} + "revised_reply": {"type": "string"}, + "settles_finding": {"type": "boolean"} }, - "required": ["verdict_change", "reason", "new_nonblocking_items", "revised_reply"], + "required": ["verdict_change", "reason", "new_nonblocking_items", "revised_reply", "settles_finding"], "additionalProperties": false }) } @@ -2040,6 +2048,7 @@ pub fn parse_reply_conclusion(v: &serde_json::Value) -> ReplyConclusion { new_nonblocking_items: v["new_nonblocking_items"].as_bool().unwrap_or(false) && !revised_reply.is_empty(), revised_reply, + settles_finding: v["settles_finding"].as_bool().unwrap_or(false), } } diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index 722936197..9d1862444 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -367,6 +367,8 @@ impl Sim { trigger: "synchronize".into(), dedup_key: dedup_key.into(), reply_to_comment_id: None, + thread_root_id: None, + mentioned: false, requested_by: String::new(), attempt: 0, wait_secs: 0, @@ -1178,6 +1180,7 @@ fn live_violations(want: &LiveExpect, got: &LiveOutcome) -> Vec { /// The earlier-threads section for a re-review after `r`. fn prior_section(r: &AfterReply) -> String { let thread = crate::clients::github::BotReviewThread { + root_id: 0, id: "t1".into(), path: r.thread.path.clone(), line: r.thread.line, diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index aaea89e6b..ec42e1a29 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -721,6 +721,35 @@ async fn run_once( // (old in-flight messages) or a transient DynamoDB error falls through to // processing — `claim_once_ttl` fails OPEN, so a real review is never lost. The // short TTL lets a failed review be re-driven later. + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + )?; + + // A reply that may answer one of CoderHelm's findings, mention or not: + // what it answers, checked before the job is claimed so a reply in a + // person's own thread that didn't address CoderHelm leaves no claim + // (an edit that adds the mention is then handled). + let answered = if super::review_thread_reply::is_answer_trigger(&msg.trigger) { + match super::review_thread_reply::find(&github, &msg).await? { + Some(f) => Some(f), + None if msg.mentioned => None, + None => { + info!( + pr = msg.pr_number, + trigger = %msg.trigger, + reason = "it doesn't answer CoderHelm's review and doesn't address CoderHelm", + "Reviewer: reply not handled" + ); + return Ok(DONE); + } + } + } else { + None + }; + if !msg.dedup_key.is_empty() { let sk = format!( "REVIEWJOB#{}/{}#{:06}#{}", @@ -738,13 +767,6 @@ async fn run_once( } } - let github = GitHubClient::new( - &state.secrets.github_app_id, - &state.secrets.github_private_key, - msg.installation_id, - &state.http, - )?; - // PR metadata. head_sha may be empty on reply-triggered reviews — resolve it // from the PR so a reply always targets the latest commit. let pr = github @@ -939,6 +961,13 @@ async fn run_once( } s }; + // A person answering one of CoderHelm's findings: the finding, the + // thread so far and the answer, instead of a bare question. + let asked = match &answered { + Some(f) => super::review_thread_reply::answer_prompt(f, &msg.requested_by, question), + None => question.clone(), + }; + let question = &asked; let prompt = format!( "PR #{}: {title}\n\n{pr_body}{earlier_section}\n\n## Question from a reviewer\n{question}\n\n## Diff (base...head)\n{diff}", msg.pr_number, @@ -1154,18 +1183,54 @@ async fn run_once( }, ) }); + // An answered finding: recorded, and when the reply concludes the + // answer settles it, its thread is resolved. A settled finding while + // the standing verdict requests changes re-runs the formal review. + let mut decision = decision; + let mut settle_reason = String::new(); + if let Some(f) = &answered { + let settled = conclusion.as_ref().is_some_and(|c| c.settles_finding); + let mut resolved = f.thread.as_ref().is_some_and(|t| t.resolved); + if settled { + match super::review_thread_reply::settle(&github, &msg, f).await { + Some(note) => answer = format!("{}\n\n{note}", answer.trim_end()), + None => resolved = f.thread.is_some(), + } + let holds = standing + .as_ref() + .is_some_and(|s| s.verdict == "REQUEST_CHANGES"); + if holds && decision != Some(super::review_verdict::Decision::Review) { + decision = Some(super::review_verdict::Decision::Review); + settle_reason = + "A person's answer settled a finding while the review requested changes." + .to_string(); + } + } + super::review_thread_reply::record(state, &msg, f, settled, resolved, &answer).await; + info!( + pr = msg.pr_number, + settled, resolved, "Reviewer: answered a reply to its finding" + ); + } if decision == Some(super::review_verdict::Decision::Review) { - let c = conclusion.as_ref().expect("checked above"); + let reason = if settle_reason.is_empty() { + conclusion + .as_ref() + .map(|c| c.reason.clone()) + .unwrap_or_default() + } else { + settle_reason + }; info!( pr = msg.pr_number, head = %head_sha, - change = ?c.verdict_change, + change = ?conclusion.as_ref().map(|c| c.verdict_change), standing = ?standing, "Reply conclusion differs from the standing verdict; formal review runs first" ); record_review_usage(state, &msg.team_id, None, &usage).await; return Ok(Outcome::ReviewThenReply { - review: Box::new(reconcile_message(&msg, &head_sha, &c.reason)), + review: Box::new(reconcile_message(&msg, &head_sha, &reason)), reply: Box::new(PendingReply { head_sha: head_sha.clone(), answer, @@ -1426,7 +1491,7 @@ async fn run_once( bot_threads.iter().filter(|t| !t.resolved).collect(); let settled_threads: Vec<&crate::clients::github::BotReviewThread> = bot_threads .iter() - .filter(|t| t.resolved_by_person) + .filter(|t| settled_by_answer_or_person(t)) .collect(); // What people wrote in the PR conversation, including the text of a // re-review ask. @@ -2402,6 +2467,8 @@ pub async fn review_for_run( // The key the ready-for-review trigger uses for this head. dedup_key: format!("head#{head_sha}"), reply_to_comment_id: None, + thread_root_id: None, + mentioned: false, requested_by: String::new(), attempt: 0, wait_secs: 0, @@ -3257,6 +3324,13 @@ pub(crate) fn human_comments(comments: &[serde_json::Value], max: usize) -> Vec< human.into_iter().skip(skip).collect() } +/// A resolved thread a person settled: they resolved it, or they answered +/// it and CoderHelm resolved it on that answer. Shown to a re-review so the +/// same concern isn't raised again. +pub(crate) fn settled_by_answer_or_person(t: &crate::clients::github::BotReviewThread) -> bool { + t.resolved && (t.resolved_by_person || t.replies.iter().any(|r| !r.by_bot)) +} + /// Earlier threads the model reported fixed or answered. Indices that are out /// of range or duplicated are ignored; anything else stays open. fn settled_prior_threads<'a>( @@ -3311,6 +3385,7 @@ mod prior_thread_tests { fn t(id: &str) -> BotReviewThread { BotReviewThread { + root_id: 0, id: id.into(), path: "a.rs".into(), line: 1, @@ -3328,6 +3403,26 @@ mod prior_thread_tests { } } + #[test] + fn a_thread_coderhelm_resolved_on_a_persons_answer_counts_as_settled() { + use crate::clients::github::ThreadReply; + let mut a = t("A"); + assert!(!settled_by_answer_or_person(&a)); + a.resolved = true; + // Resolved by CoderHelm because the code fixed it: not a person's answer. + assert!(!settled_by_answer_or_person(&a)); + a.replies.push(ThreadReply { + author: "author".into(), + by_bot: false, + body: "Yes, it uses our own key.".into(), + }); + assert!(settled_by_answer_or_person(&a)); + let mut b = t("B"); + b.resolved = true; + b.resolved_by_person = true; + assert!(settled_by_answer_or_person(&b)); + } + #[test] fn only_explicit_fixed_or_answered_in_range_once() { let threads = [t("A"), t("B"), t("C"), t("D")]; @@ -3551,6 +3646,8 @@ mod superseded_tests { trigger: "synchronize".into(), dedup_key: String::new(), reply_to_comment_id: None, + thread_root_id: None, + mentioned: false, requested_by: String::new(), attempt: 0, wait_secs: 0, @@ -3877,6 +3974,8 @@ mod failure_tests { trigger: "synchronize".into(), dedup_key: "head#a1b2c3d4".into(), reply_to_comment_id: None, + thread_root_id: None, + mentioned: false, requested_by: String::new(), attempt: 0, wait_secs: 0, diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 049ee23a8..88e840397 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -403,6 +403,8 @@ fn sweep_message( trigger: "sweep".to_string(), dedup_key: format!("sweep#{head}"), reply_to_comment_id: None, + thread_root_id: None, + mentioned: false, requested_by: String::new(), attempt: 0, wait_secs: 0, diff --git a/services/worker/src/passes/review_thread_reply.rs b/services/worker/src/passes/review_thread_reply.rs new file mode 100644 index 000000000..ec65b54ba --- /dev/null +++ b/services/worker/src/passes/review_thread_reply.rs @@ -0,0 +1,328 @@ +//! A person answering one of the reviewer's findings, with or without +//! mentioning CoderHelm: a reply in a thread CoderHelm started (trigger +//! `thread_reply`), or a PR-conversation comment that quotes its review +//! (trigger `quote_reply`). +//! +//! The gateway sends every such reply on a PR CoderHelm reviewed; here the +//! worker checks it answers CoderHelm (the thread's first comment is +//! CoderHelm's, or the quote is from its review), so a reply in a person's +//! own thread is left alone unless it addressed CoderHelm. The answer is +//! acknowledged in place, the finding is recorded as answered, and when the +//! reply concludes the answer settles it the thread is resolved (or, when +//! the app may not resolve it, the reply says so in one line). A settled +//! finding while CoderHelm's standing verdict requests changes re-runs the +//! formal review, so the verdict follows the answer. + +use crate::clients::github::{BotReviewThread, GitHubClient}; +use crate::models::ReviewMessage; +use crate::WorkerState; +use aws_sdk_dynamodb::types::AttributeValue; +use tracing::{info, warn}; + +pub const TRIGGER_THREAD: &str = "thread_reply"; +pub const TRIGGER_QUOTE: &str = "quote_reply"; + +/// A reply trigger that may answer one of CoderHelm's findings. +pub fn is_answer_trigger(trigger: &str) -> bool { + trigger == TRIGGER_THREAD || trigger == TRIGGER_QUOTE +} + +/// The finding a person answered. +#[derive(Debug, Clone)] +pub struct AnsweredFinding { + /// The finding as CoderHelm wrote it. + pub finding: String, + /// Its inline thread, when it has one (a quote of a review body has none). + pub thread: Option, +} + +impl AnsweredFinding { + /// The record key: the thread's first comment, or the quoting comment. + fn key(&self, msg: &ReviewMessage) -> String { + match &self.thread { + Some(t) if t.root_id != 0 => format!("thread#{}", t.root_id), + _ => format!("quote#{}", msg.dedup_key), + } + } +} + +/// Letters and digits only, lower case: quotes keep or drop markdown, so +/// matching ignores it. +fn key_text(s: &str) -> String { + s.chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect() +} + +/// The quoted lines of a comment (`> …`), without the markers. +pub fn quoted_lines(body: &str) -> Vec { + body.lines() + .map(str::trim_start) + .filter(|l| l.starts_with('>')) + .map(|l| l.trim_start_matches('>').trim().to_string()) + .filter(|l| !l.is_empty()) + .collect() +} + +/// A quoted line long enough to say where it came from is in `text`. +pub fn quote_is_from(body: &str, text: &str) -> bool { + let hay = key_text(text); + if hay.is_empty() { + return false; + } + quoted_lines(body).iter().any(|l| { + let k = key_text(l); + k.len() >= 12 && hay.contains(&k) + }) +} + +/// CoderHelm's thread whose first comment is `root`. +pub fn thread_for_root(threads: &[BotReviewThread], root: u64) -> Option<&BotReviewThread> { + (root != 0) + .then(|| threads.iter().find(|t| t.root_id == root)) + .flatten() +} + +/// What the reviewer is asked to answer: its finding, the thread so far, +/// and the person's reply. +pub fn answer_prompt(f: &AnsweredFinding, author: &str, reply: &str) -> String { + let mut s = String::from( + "A person is answering one of your review findings. Acknowledge the answer in one or two \ + sentences. If it settles the finding, say so plainly, starting with \"Settled\" \ + (\"Settled, thanks: the bucket uses a customer-managed KMS key.\"). If something about \ + the finding is still open, say exactly what. If a fact in the answer can be checked with \ + your tools (the repository, a connected AWS account, a data source), check it first and \ + say what you found.\n\n## Your finding\n", + ); + s.push_str(common::truncate_str(f.finding.trim(), 4000)); + if let Some(t) = &f.thread { + if !t.path.is_empty() { + s.push_str(&format!("\n(on `{}` line {})", t.path, t.line)); + } + let earlier: Vec = t + .replies + .iter() + .filter(|r| r.body.trim() != reply.trim()) + .map(|r| { + format!( + "- {}: {}", + if r.by_bot { + "CoderHelm" + } else { + r.author.as_str() + }, + common::truncate_str(r.body.trim(), 1200).replace('\n', " ") + ) + }) + .collect(); + if !earlier.is_empty() { + s.push_str("\n\n## Earlier in the thread (oldest first)\n"); + s.push_str(&earlier.join("\n")); + } + } + s.push_str(&format!( + "\n\n## The answer from {author}\n{}", + common::truncate_str(reply.trim(), 4000) + )); + s +} + +/// The line added when the answer settled the finding but its thread +/// couldn't be resolved. +pub const COULD_NOT_RESOLVE: &str = + "I couldn't mark this thread resolved (the app may not have permission here), so please resolve it."; + +/// Finds what the reply answers. `Ok(None)`: it doesn't answer CoderHelm. +pub async fn find( + github: &GitHubClient, + msg: &ReviewMessage, +) -> Result, Box> { + let threads = github + .list_bot_review_threads(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await?; + if msg.trigger == TRIGGER_THREAD { + return Ok( + thread_for_root(&threads, msg.thread_root_id.unwrap_or(0)).map(|t| AnsweredFinding { + finding: t.body.clone(), + thread: Some(t.clone()), + }), + ); + } + let body = msg.question.as_deref().unwrap_or(""); + if let Some(t) = threads.iter().find(|t| quote_is_from(body, &t.body)) { + return Ok(Some(AnsweredFinding { + finding: t.body.clone(), + thread: Some(t.clone()), + })); + } + let reviews = github + .list_pr_reviews(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await?; + let own_review = reviews + .as_array() + .into_iter() + .flatten() + .filter(|r| { + r["user"]["login"] + .as_str() + .is_some_and(|l| l.contains("coderhelm")) + }) + .filter_map(|r| r["body"].as_str()) + .rev() + .find(|b| quote_is_from(body, b)); + if let Some(b) = own_review { + return Ok(Some(AnsweredFinding { + finding: b.to_string(), + thread: None, + })); + } + let comments = github + .list_issue_comments(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await?; + Ok(super::review_pr::own_comments(&comments, 20) + .into_iter() + .rev() + .find(|c| quote_is_from(body, c)) + .map(|c| AnsweredFinding { + finding: c, + thread: None, + })) +} + +/// Resolves the finding's thread when the answer settled it. `Some(note)` +/// when it couldn't be resolved and the reply should say so. +pub async fn settle( + github: &GitHubClient, + msg: &ReviewMessage, + f: &AnsweredFinding, +) -> Option<&'static str> { + let t = f.thread.as_ref()?; + if t.resolved || t.id.is_empty() { + return None; + } + match github.resolve_review_thread(&t.id).await { + Ok(_) => { + info!(pr = msg.pr_number, thread = %t.id, "Reviewer: answered finding settled, thread resolved"); + None + } + Err(e) => { + warn!(pr = msg.pr_number, thread = %t.id, error = %e, "Could not resolve a settled thread"); + Some(COULD_NOT_RESOLVE) + } + } +} + +/// Records the finding as answered (and whether it was settled): the +/// reviewer's outcome signal for this finding, next to the PR's review +/// records. Best-effort. +pub async fn record( + state: &WorkerState, + msg: &ReviewMessage, + f: &AnsweredFinding, + settled: bool, + resolved: bool, + reply: &str, +) { + let now = chrono::Utc::now(); + let sk = format!( + "REVIEWANSWER#{}/{}#{:06}#{}", + msg.repo_owner, + msg.repo_name, + msg.pr_number, + f.key(msg) + ); + let s = |v: &str| AttributeValue::S(v.to_string()); + let r = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(&msg.team_id)) + .item("sk", s(&sk)) + .item("status", s(if settled { "settled" } else { "answered" })) + .item("resolved", AttributeValue::Bool(resolved)) + .item("answered_by", s(&msg.requested_by)) + .item("trigger", s(&msg.trigger)) + .item("finding", s(common::truncate_str(f.finding.trim(), 1500))) + .item("reply", s(common::truncate_str(reply.trim(), 1500))) + .item("at", s(&now.to_rfc3339())) + .item( + "ttl", + AttributeValue::N((now.timestamp() + 180 * 86_400).to_string()), + ) + .send() + .await; + if let Err(e) = r { + warn!(pr = msg.pr_number, error = %e, "Could not record an answered finding"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::clients::github::ThreadReply; + + fn thread(root: u64, body: &str) -> BotReviewThread { + BotReviewThread { + id: format!("T_{root}"), + root_id: root, + path: "infra/copy.tf".into(), + line: 12, + outdated: false, + body: body.into(), + replies: vec![ThreadReply { + author: "author".into(), + by_bot: false, + body: "It uses our own KMS key, alias/data-copy.".into(), + }], + resolved: false, + resolved_by_person: false, + } + } + + #[test] + fn the_thread_is_found_by_its_first_comment() { + let ts = vec![thread(10, "a"), thread(11, "b")]; + assert_eq!(thread_for_root(&ts, 11).unwrap().body, "b"); + assert!(thread_for_root(&ts, 12).is_none()); + // An unknown root never matches a thread whose id is unknown. + assert!(thread_for_root(&[thread(0, "c")], 0).is_none()); + } + + #[test] + fn a_quote_reply_is_matched_to_coderhelms_text_whatever_the_markdown() { + let review = "**Is the source bucket encrypted with a customer-managed KMS key?** The copy job reads it."; + let body = + "> Is the source bucket encrypted with a customer-managed KMS key?\n\nYes, it is."; + assert!(quote_is_from(body, review)); + // A short quote says nothing about where it came from. + assert!(!quote_is_from("> Yes\n\nok", review)); + assert!(!quote_is_from("no quote here", review)); + assert!(!quote_is_from( + body, + "Something else entirely, about tests." + )); + } + + #[test] + fn the_prompt_carries_the_finding_the_thread_and_the_answer() { + let f = AnsweredFinding { + finding: "Is the source bucket encrypted with a customer-managed KMS key?".into(), + thread: Some(thread(10, "x")), + }; + let p = answer_prompt(&f, "author", "Yes: SSE-KMS with our own key."); + assert!(p.contains("## Your finding\nIs the source bucket")); + assert!(p.contains("infra/copy.tf")); + assert!(p.contains("- author: It uses our own KMS key")); + assert!(p.contains("## The answer from author\nYes: SSE-KMS")); + assert!(p.contains("Settled")); + } + + #[test] + fn only_the_answer_triggers_count() { + assert!(is_answer_trigger("thread_reply")); + assert!(is_answer_trigger("quote_reply")); + assert!(!is_answer_trigger("reply")); + assert!(!is_answer_trigger("label")); + } +} diff --git a/services/worker/src/passes/rewards.rs b/services/worker/src/passes/rewards.rs index 8126c087c..a45653f14 100644 --- a/services/worker/src/passes/rewards.rs +++ b/services/worker/src/passes/rewards.rs @@ -765,6 +765,7 @@ mod tests { #[test] fn only_untouched_threads_count_as_ignored() { let t = |resolved, outdated, replies: Vec| BotReviewThread { + root_id: 0, id: "T".into(), path: "a".into(), line: 1,