From ec2e56fd5b289c820252155d261217121d0a0258 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 24 Nov 2026 14:47:22 -0500 Subject: [PATCH] Alert channel takes alerts only: every team message routed by kind Every team-wide message is an alert, action or update, and picks its channels through notify::route by that kind. An alert channel saved before kinds existed takes alerts only; action and updates go to a new updates channel. The merge gate never posts waits on people's reviews to a channel and posts a conflict that needs a person once per PR and reason. --- .../nt_alerts_channel_alerts_only.md | 5 + lambda/log-analyzer/handler.py | 37 +- lambda/tests/test_log_analyzer.py | 18 + services/common/src/alert_notify.rs | 32 +- services/common/src/log_findings.rs | 145 ++--- services/common/src/notify/mod.rs | 5 +- services/common/src/notify/route.rs | 501 ++++++++++++++++++ services/common/src/security_fixes.rs | 18 + services/gateway/src/main.rs | 4 + services/gateway/src/permissions.rs | 2 + services/gateway/src/routes/alerts.rs | 144 ++++- services/gateway/src/routes/log_findings.rs | 9 +- services/worker/src/passes/await_merge.rs | 59 ++- .../mx_gate_keeps_the_branch_current.rs | 7 +- .../nt_alerts_channel_alerts_only.rs | 137 +++++ services/worker/src/passes/infra_findings.rs | 17 + services/worker/src/passes/knowledge_sync.rs | 22 +- services/worker/src/passes/log_autofix.rs | 2 + services/worker/src/passes/plugins.rs | 30 +- services/worker/src/passes/security_fixes.rs | 39 +- .../worker/src/passes/security_release.rs | 2 +- services/worker/src/passes/webhooks.rs | 34 +- 22 files changed, 1057 insertions(+), 212 deletions(-) create mode 100644 docs/incidents/nt_alerts_channel_alerts_only.md create mode 100644 services/common/src/notify/route.rs create mode 100644 services/worker/src/passes/incidents/nt_alerts_channel_alerts_only.rs diff --git a/docs/incidents/nt_alerts_channel_alerts_only.md b/docs/incidents/nt_alerts_channel_alerts_only.md new file mode 100644 index 000000000..1019ad5cf --- /dev/null +++ b/docs/incidents/nt_alerts_channel_alerts_only.md @@ -0,0 +1,5 @@ +# nt. `nt_alerts_channel_alerts_only` + +**What happened:** A team's alert channel, set up for production alarms, also got routine auto-merge status cards: a merge conflict that needed a person's call, and a wait on an approving review the branch's rules ask for. Every sender that wanted "the team's channel" opened the alert channel's settings item (`ALERT_NOTIFY`) itself: the merge gate, security and infrastructure cards, plugin reviews, turned-off webhook endpoints, knowledge sign-ins, and log findings whose own setting was never saved. The merge gate posted once per commit and wording, so each push could post again, and it posted a wait on a person's review, which is a pull request's normal state. + +**The guarantee:** Every team-wide message has a kind: alert (a production alarm or incident and its follow-ups, a critical security finding), action (a person has to do something CoderHelm can't) or update (news). Its channels come from `common::notify::route` by that kind, and a test fails if any other file reads the alert channel's item. An alert channel saved before kinds existed takes alerts only; action and updates go to the team's updates channel (`UPDATES_NOTIFY`), or nowhere when there is none, and a team can tick more kinds for either channel in Settings, Alerts. The merge gate never posts a wait on people's reviews to a channel (the PR's status comment says it once), posts a conflict that needs a person only where action messages go, and posts it once per PR and reason (`await_merge::told_sk`). The log analyzer Lambda follows the same rule for new findings (`team_update_channels`). diff --git a/lambda/log-analyzer/handler.py b/lambda/log-analyzer/handler.py index 636a6a258..c85c515ae 100644 --- a/lambda/log-analyzer/handler.py +++ b/lambda/log-analyzer/handler.py @@ -1380,6 +1380,7 @@ def record_connection_success(team_id, account_id): REC_NOTIFY_SK = "REC_NOTIFY" TEAM_CHANNEL_SK = "ALERT_NOTIFY" # the team's alert channel (common::alert_notify) +UPDATES_CHANNEL_SK = "UPDATES_NOTIFY" # the team's updates channel (common::notify::route) WEBHOOK_HOST_SUFFIXES = (".powerplatform.com", ".logic.azure.com", ".webhook.office.com") SLACK_PREFIX = "https://hooks.slack.com/services/" SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2} @@ -1462,6 +1463,30 @@ def pick_channels(mode, own, team, team_enabled): return {} +def channel_kinds(sk, item): + """The kinds of message a team channel takes: its saved `kinds`, or, saved + before kinds existed, alerts only for the alert channel and action and + updates for the updates channel. Matches common::notify::route::kinds.""" + saved = item.get("kinds") + if saved is None: + return {"action", "update"} if sk == UPDATES_CHANNEL_SK else {"alert"} + return {k for k in saved if k in ("alert", "action", "update")} + + +def team_update_channels(team_id, alerts_item, updates_item): + """{channel: url} a findings update posts to with the team's channels: + the updates channel first, then the alert channel only when it was set to + take updates; never an alert channel that takes alerts only. Matches + common::notify::route::pick for Kind::Update.""" + out = {} + for sk, item in ((UPDATES_CHANNEL_SK, updates_item), (TEAM_CHANNEL_SK, alerts_item)): + if not item or not bool(item.get("enabled", False)) or "update" not in channel_kinds(sk, item): + continue + for ch, url in open_channels(team_id, item).items(): + out.setdefault(ch, url) + return out + + def pick_webhook(mode, own_url, team_url, team_enabled): """One Teams URL (kept for callers of the single-channel shape).""" own = {"teams": own_url} if valid_webhook_url(own_url) else {} @@ -1680,13 +1705,17 @@ def notify_new_recommendations(team_id, account_id, recs): mode = effective_mode(own.get("notify_mode")) if mode == "off": return - team = settings_table.get_item(Key={"pk": team_id, "sk": TEAM_CHANNEL_SK}).get("Item") or {} - enabled = bool(team.get("enabled", False)) + team = {} + if mode == "team": + alerts = settings_table.get_item(Key={"pk": team_id, "sk": TEAM_CHANNEL_SK}).get("Item") or {} + updates = settings_table.get_item(Key={"pk": team_id, "sk": UPDATES_CHANNEL_SK}).get("Item") or {} + # Findings are updates: never in an alert channel that takes alerts only. + team = team_update_channels(team_id, alerts, updates) channels = pick_channels( mode, open_channels(team_id, own) if mode == "custom" else {}, - open_channels(team_id, team) if mode == "team" and enabled else {}, - enabled, + team, + bool(team), ) if channels: deliver(channels, account_id, recs) diff --git a/lambda/tests/test_log_analyzer.py b/lambda/tests/test_log_analyzer.py index 7ecd36a0b..9906b242c 100644 --- a/lambda/tests/test_log_analyzer.py +++ b/lambda/tests/test_log_analyzer.py @@ -97,6 +97,24 @@ def test_only_microsoft_webhook_hosts(self): self.assertFalse(h.valid_webhook_url("https://evil.com@prod-1.logic.azure.com/x")) self.assertFalse(h.valid_webhook_url("http://prod-1.logic.azure.com/x")) + def test_findings_never_reach_an_alerts_only_channel(self): + teams = "https://prod-1.westus.logic.azure.com/workflows/t" + other = "https://prod-2.westus.logic.azure.com/workflows/u" + alerts = {"enabled": True, "teams_webhook_url": teams} + # Saved before kinds existed: alerts only. + self.assertEqual(h.channel_kinds(h.TEAM_CHANNEL_SK, alerts), {"alert"}) + self.assertEqual(h.team_update_channels("TEAM#a", alerts, {}), {}) + # The updates channel takes them. + updates = {"enabled": True, "teams_webhook_url": other} + self.assertEqual(h.channel_kinds(h.UPDATES_CHANNEL_SK, updates), {"action", "update"}) + self.assertEqual(h.team_update_channels("TEAM#a", alerts, updates), {"teams": other}) + # An alert channel set to take updates does, after the updates channel. + more = dict(alerts, kinds=["alert", "update"]) + self.assertEqual(h.team_update_channels("TEAM#a", more, {}), {"teams": teams}) + self.assertEqual(h.team_update_channels("TEAM#a", more, updates), {"teams": other}) + # Off takes nothing. + self.assertEqual(h.team_update_channels("TEAM#a", more, dict(updates, enabled=False)), {"teams": teams}) + def test_channel_choice(self): team = "https://prod-1.westus.logic.azure.com/workflows/t" own = "https://prod-2.westus.logic.azure.com/workflows/o" diff --git a/services/common/src/alert_notify.rs b/services/common/src/alert_notify.rs index d8764a7f9..8552705ec 100644 --- a/services/common/src/alert_notify.rs +++ b/services/common/src/alert_notify.rs @@ -1,7 +1,9 @@ //! Chat notifications for alerts. //! //! A team sets one alert channel (Teams, Slack or both) that every alert route -//! notifies; a route can instead use its own channels or notify nowhere. Each +//! notifies; a route can instead use its own channels or notify nowhere. The +//! alert channel takes alerts only unless the team chose more kinds +//! (`crate::notify::route`). Each //! alert posts a message, and when CoderHelm opens a pull request for an alert //! a follow-up message links it (or, when the run finds that no code change //! is needed, says why: [`no_change_message`]). Webhooks can't edit a posted message, so the @@ -59,10 +61,7 @@ pub async fn notify_target( .key("sk", AttributeValue::S(sk.to_string())) .send() }; - let (route, team) = tokio::join!( - get(format!("ALERTTOPIC#{topic_arn}"), "ROUTE"), - get(team_id.to_string(), TEAM_SETTINGS_SK), - ); + let route = get(format!("ALERTTOPIC#{topic_arn}"), "ROUTE").await; let Some(route) = route.ok().and_then(|r| r.item().cloned()) else { return Channels::default(); }; @@ -74,32 +73,31 @@ pub async fn notify_target( { return Channels::default(); } - let team = team - .ok() - .and_then(|t| t.item().cloned()) - .unwrap_or_default(); let mode = route .get("notify_mode") .and_then(|v| v.as_s().ok()) .cloned() .unwrap_or_default(); - let enabled = team - .get("enabled") - .and_then(|v| v.as_bool().ok()) - .copied() - .unwrap_or(false); let (route_channels, team_channels) = match mode.as_str() { MODE_OFF => return Channels::default(), MODE_CUSTOM => ( store::open_all(cipher, team_id, &route).await, Channels::default(), ), - _ if enabled => ( + // The team's channel for alerts (`notify::route`). + _ => ( Channels::default(), - store::open_all(cipher, team_id, &team).await, + crate::notify::route::team_channels( + dynamo, + cipher, + table, + team_id, + crate::notify::route::Kind::Alert, + ) + .await, ), - _ => return Channels::default(), }; + let enabled = !team_channels.is_empty(); pick(&mode, route_channels, team_channels, enabled) } diff --git a/services/common/src/log_findings.rs b/services/common/src/log_findings.rs index 4593fad80..e9edd5215 100644 --- a/services/common/src/log_findings.rs +++ b/services/common/src/log_findings.rs @@ -17,7 +17,8 @@ //! `LOG_FIX_CARD#` (the fix PR card posted, so it posts once //! and its merged or closed follow-up posts once). //! - Where findings and fix PR cards post: `REC_NOTIFY` when a person saved -//! it, otherwise the team's alert channel (`ALERT_NOTIFY`), see +//! it, otherwise the team channel that takes their kind (an incident is an +//! alert; findings and fix PRs are updates; see `notify::route`), see //! [`effective_mode`]. //! //! Every rule that decides whether a run may start is here, so the gateway @@ -2246,9 +2247,9 @@ pub async fn teams_with_setting( // ─── Chat ─────────────────────────────────────────────────────────────────── /// Pure: the findings' notify mode in effect. A setting never saved (no -/// `REC_NOTIFY`, or no `notify_mode` on it) follows the team's alert channel, -/// so findings and their fix PRs post where production alerts post; a saved -/// "off" or "custom" stands. The log analyzer Lambda has the same rule +/// `REC_NOTIFY`, or no `notify_mode` on it) follows the team's channels by +/// kind (`notify::route`): an incident goes where production alerts go, +/// findings and fix PRs where updates go; a saved "off" or "custom" stands. The log analyzer Lambda has the same rule /// (`effective_mode` in `lambda/log-analyzer/handler.py`). pub fn effective_mode(saved: &str) -> &str { match saved.trim() { @@ -2258,7 +2259,8 @@ pub fn effective_mode(saved: &str) -> &str { } /// Pure: where findings post, from the findings setting (`notify_mode`) and -/// the team's alert channel (`enabled`), each already opened. +/// the team's channel for the message's kind (`team_enabled`: one takes +/// it), each already opened. pub fn pick_channels(mode: &str, own: Channels, team: Channels, team_enabled: bool) -> Channels { match effective_mode(mode) { crate::alert_notify::MODE_CUSTOM => own, @@ -2277,7 +2279,9 @@ pub struct PostsTo { pub saved: bool, /// The chat apps it posts to ("Microsoft Teams", "Slack"); empty = none. pub channels: Vec<&'static str>, - /// The team's alert channel is on and has a channel set. + /// A team channel takes findings (the updates channel, or an alert + /// channel set to take updates) and has an app set. The name is kept + /// for the pages that read it. pub team_alerts: bool, } @@ -2289,25 +2293,18 @@ fn kinds_set(item: &Item) -> Vec<&'static str> { .collect() } -fn enabled(item: &Item) -> bool { - item.get("enabled") - .and_then(|v| v.as_bool().ok()) - .copied() - .unwrap_or(false) -} - -/// Pure: [`PostsTo`] from the findings' setting and the team's alert channel. -pub fn posts_to(own: Option<&Item>, team: Option<&Item>) -> PostsTo { +/// Pure: [`PostsTo`] from the findings' setting and the team's channels +/// (`notify::route`): findings are updates. +pub fn posts_to(own: Option<&Item>, team: &[(&str, Item)]) -> PostsTo { let empty = Item::new(); let own_item = own.unwrap_or(&empty); - let team_item = team.unwrap_or(&empty); let saved_mode = s(own_item, "notify_mode"); let mode = effective_mode(&saved_mode).to_string(); - let team_kinds = if enabled(team_item) { - kinds_set(team_item) - } else { - vec![] - }; + let team_kinds: Vec<&'static str> = + crate::notify::route::apps(crate::notify::route::Kind::Update, team) + .iter() + .map(|k| k.label()) + .collect(); let channels = match mode.as_str() { crate::alert_notify::MODE_CUSTOM => kinds_set(own_item), crate::alert_notify::MODE_TEAM => team_kinds.clone(), @@ -2321,58 +2318,60 @@ pub fn posts_to(own: Option<&Item>, team: Option<&Item>) -> PostsTo { } } -/// The findings' notify setting and the team's alert channel, as stored. +/// The findings' notify setting and the team's channels, as stored. async fn notify_items( dynamo: &DynamoClient, settings_table: &str, team_id: &str, -) -> (Option, Option) { - let get = |sk: &'static str| { - dynamo - .get_item() - .table_name(settings_table) - .key("pk", attr(team_id)) - .key("sk", attr(sk)) - .send() - }; +) -> (Option, Vec<(&'static str, Item)>) { + let own = dynamo + .get_item() + .table_name(settings_table) + .key("pk", attr(team_id)) + .key("sk", attr(REC_NOTIFY_SK)) + .send(); let (own, team) = tokio::join!( - get(REC_NOTIFY_SK), - get(crate::alert_notify::TEAM_SETTINGS_SK) + own, + crate::notify::route::load(dynamo, settings_table, team_id) ); - ( - own.ok().and_then(|o| o.item().cloned()), - team.ok().and_then(|o| o.item().cloned()), - ) + (own.ok().and_then(|o| o.item().cloned()), team) } /// Where findings post, in words, for the Logs page. pub async fn load_posts_to(dynamo: &DynamoClient, settings_table: &str, team_id: &str) -> PostsTo { let (own, team) = notify_items(dynamo, settings_table, team_id).await; - posts_to(own.as_ref(), team.as_ref()) + posts_to(own.as_ref(), &team) } -/// The channels new findings post to (Teams, Slack), opened. Empty = none. -/// Every sender of a findings message (the repo check, the fix PR card and -/// its follow-up, AWS permission notes) reads its channels here. +/// The channels a findings message of `kind` posts to (Teams, Slack), +/// opened. Empty = none. Every sender of a findings message (an incident, +/// the fix PR card and its follow-up) reads its channels here. With the +/// team's channels, an incident (an alert) goes where alerts go and a fix +/// PR (an update) where updates go: never to an alert channel that takes +/// alerts only. pub async fn channels( dynamo: &DynamoClient, cipher: &dyn crate::mcp_credentials::Cipher, settings_table: &str, team_id: &str, + kind: crate::notify::route::Kind, ) -> Channels { let (own, team) = notify_items(dynamo, settings_table, team_id).await; let own = own.unwrap_or_default(); - let team = team.unwrap_or_default(); let mode = s(&own, "notify_mode"); - let team_on = enabled(&team); - let opened = - |item: Item| async move { crate::notify::store::open_all(cipher, team_id, &item).await }; match effective_mode(&mode) { - crate::alert_notify::MODE_CUSTOM => { - pick_channels(&mode, opened(own).await, Channels::default(), team_on) - } - crate::alert_notify::MODE_TEAM if team_on => { - pick_channels(&mode, Channels::default(), opened(team).await, team_on) + crate::alert_notify::MODE_CUSTOM => pick_channels( + &mode, + crate::notify::store::open_all(cipher, team_id, &own).await, + Channels::default(), + false, + ), + crate::alert_notify::MODE_TEAM => { + let team = crate::notify::route::TeamChannels::open(cipher, team_id, team) + .await + .get(kind); + let on = !team.is_empty(); + pick_channels(&mode, Channels::default(), team, on) } _ => Channels::default(), } @@ -4122,7 +4121,7 @@ mod tests { assert_eq!(pick_channels("team", own.clone(), team.clone(), true), team); assert!(pick_channels("team", own.clone(), team.clone(), false).is_empty()); assert!(pick_channels("off", own.clone(), team.clone(), true).is_empty()); - // Never saved: the team's alert channel, when it is on. + // Never saved: the team's channel for the kind, when one takes it. assert_eq!(pick_channels("", own.clone(), team.clone(), true), team); assert!(pick_channels("", own.clone(), team.clone(), false).is_empty()); assert_eq!(effective_mode(""), "team"); @@ -4306,40 +4305,62 @@ mod fix_card_tests { channel_item(kinds, &[("enabled", AttributeValue::Bool(true))]) } + fn updates(item: Item) -> Vec<(&'static str, Item)> { + vec![(crate::notify::route::UPDATES_SK, item)] + } + #[test] - fn never_saved_posts_to_the_team_alert_channel() { - let team = team_on(&["teams", "slack"]); - let p = posts_to(None, Some(&team)); + fn never_saved_posts_to_the_team_updates_channel() { + let team = updates(team_on(&["teams", "slack"])); + let p = posts_to(None, &team); assert_eq!(p.mode, "team"); assert!(!p.saved); assert_eq!(p.channels, vec!["Microsoft Teams", "Slack"]); assert!(p.team_alerts); // A record without a mode is the same as none. let blank = channel_item(&[], &[("updated_at", sv("x"))]); - assert_eq!(posts_to(Some(&blank), Some(&team)).channels.len(), 2); + assert_eq!(posts_to(Some(&blank), &team).channels.len(), 2); + } + + #[test] + fn findings_never_reach_an_alert_channel_that_takes_alerts_only() { + let alerts = vec![(crate::notify::route::ALERTS_SK, team_on(&["teams"]))]; + let p = posts_to(None, &alerts); + assert!(p.channels.is_empty() && !p.team_alerts); + // Set to take updates too, it does. + let mut more = team_on(&["teams"]); + more.insert( + crate::notify::route::KINDS_ATTR.into(), + crate::notify::route::kinds_attr(&[ + crate::notify::route::Kind::Alert, + crate::notify::route::Kind::Update, + ]), + ); + let p = posts_to(None, &[(crate::notify::route::ALERTS_SK, more)]); + assert_eq!(p.channels, vec!["Microsoft Teams"]); } #[test] fn a_saved_choice_stands() { - let team = team_on(&["teams"]); + let team = updates(team_on(&["teams"])); let off = channel_item(&[], &[("notify_mode", sv("off"))]); - let p = posts_to(Some(&off), Some(&team)); + let p = posts_to(Some(&off), &team); assert_eq!((p.mode.as_str(), p.saved), ("off", true)); assert!(p.channels.is_empty()); let own = channel_item(&["slack"], &[("notify_mode", sv("custom"))]); - let p = posts_to(Some(&own), Some(&team)); + let p = posts_to(Some(&own), &team); assert_eq!(p.mode, "custom"); assert_eq!(p.channels, vec!["Slack"]); } #[test] - fn no_alert_channel_posts_nowhere() { - assert!(posts_to(None, None).channels.is_empty()); + fn no_team_channel_posts_nowhere() { + assert!(posts_to(None, &[]).channels.is_empty()); let disabled = channel_item(&["teams"], &[("enabled", AttributeValue::Bool(false))]); - let p = posts_to(None, Some(&disabled)); + let p = posts_to(None, &updates(disabled)); assert!(p.channels.is_empty() && !p.team_alerts); // On, but no channel saved. - assert!(!posts_to(None, Some(&team_on(&[]))).team_alerts); + assert!(!posts_to(None, &updates(team_on(&[]))).team_alerts); } #[derive(Default)] diff --git a/services/common/src/notify/mod.rs b/services/common/src/notify/mod.rs index 840d42abe..87c6edc30 100644 --- a/services/common/src/notify/mod.rs +++ b/services/common/src/notify/mod.rs @@ -6,12 +6,15 @@ //! and link buttons. [`teams`] renders it as an Adaptive Card for a Teams //! Workflows or incoming webhook, [`slack`] as Block Kit for a Slack incoming //! webhook. A destination ([`Channels`]) posts to Teams, Slack or both, and a -//! failure on one channel never stops the other ([`deliver`]). +//! failure on one channel never stops the other ([`deliver`]). Which team +//! channel a message goes to depends on its kind (alert, action or update): +//! [`route`]. //! //! Webhook URLs post as the team, so they are secrets: [`store`] seals them //! with KMS and API answers only ever show a hint. pub mod messages; +pub mod route; pub mod slack; pub mod store; pub mod teams; diff --git a/services/common/src/notify/route.rs b/services/common/src/notify/route.rs new file mode 100644 index 000000000..3ac937d34 --- /dev/null +++ b/services/common/src/notify/route.rs @@ -0,0 +1,501 @@ +//! Which team channel a message goes to, by what kind of message it is. +//! +//! Every chat message CoderHelm sends to a team-wide channel is one of three +//! kinds ([`Kind`]): +//! +//! - **Alert**: a production alarm or incident, its follow-ups, a failed +//! deploy, a critical security finding. Something is wrong now. +//! - **Action**: a person has to do something CoderHelm can't (resolve a +//! conflict that needs a call, reconnect a sign-in, approve a plugin). +//! - **Update**: news. A fix PR opened or merged, new log findings. +//! +//! A team has two team-wide destinations: the alert channel +//! ([`ALERTS_SK`], set up under Alerts) and the updates channel +//! ([`UPDATES_SK`]). Each saves the kinds it takes (`kinds`). Saved before +//! kinds existed, the alert channel takes alerts only and the updates +//! channel takes action and updates: reading the old items this way is the +//! migration, so an alert channel saved last month stops getting anything +//! but alerts without a write. +//! +//! Every sender of a team-wide message picks its channels here, with its +//! kind ([`team_channels`]). Nothing else opens the alert channel's webhooks +//! for a message that is not an alert (`tests::only_the_router_opens_the_alert_channel`). +//! Destinations of their own (an alert route's channels, the reviewer's +//! per-repository channels, the agent approval channel) are not team-wide +//! and are not routed here. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use aws_sdk_dynamodb::Client as DynamoClient; + +use super::{store, ChannelKind, Channels}; +use crate::mcp_credentials::Cipher; + +type Item = HashMap; + +/// Settings-table sort key of the team's alert channel. +pub const ALERTS_SK: &str = crate::alert_notify::TEAM_SETTINGS_SK; +/// Settings-table sort key of the team's updates channel. +pub const UPDATES_SK: &str = "UPDATES_NOTIFY"; +/// The attribute on a destination item listing the kinds it takes. +pub const KINDS_ATTR: &str = "kinds"; + +/// What a message is, for where it may go. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Kind { + Alert, + Action, + Update, +} + +impl Kind { + pub const ALL: [Kind; 3] = [Kind::Alert, Kind::Action, Kind::Update]; + + pub fn key(self) -> &'static str { + match self { + Kind::Alert => "alert", + Kind::Action => "action", + Kind::Update => "update", + } + } + + pub fn parse(s: &str) -> Option { + match s.trim() { + "alert" => Some(Kind::Alert), + "action" => Some(Kind::Action), + "update" => Some(Kind::Update), + _ => None, + } + } +} + +/// Pure: the kind of every message label a sender passes to +/// [`super::deliver`]. `None` for a label not listed, which a test keeps +/// from happening. +pub fn kind_of(what: &str) -> Option { + Some(match what { + // A production alarm, its recovery and what CoderHelm did about it. + "alert" | "alert_pr" | "alert_no_change" | "log_incident" => Kind::Alert, + // A person has to act. + "merge_gate_wait" | "webhook_disabled" | "knowledge sign-in" | "plugin review" + | "aws_permissions" | "agent approval" | "review_reminder" | "release_notes" => { + Kind::Action + } + // News. + "log_fix_pr" | "log_fix_pr_closed" | "findings" | "agent notice" => Kind::Update, + // Security cards are an alert or an update by tier and stage + // (`security_fixes::card_kind`); the label alone says neither. + _ => return None, + }) +} + +/// The kinds a destination takes when it never saved its own. +pub fn default_kinds(sk: &str) -> Vec { + if sk == UPDATES_SK { + vec![Kind::Action, Kind::Update] + } else { + vec![Kind::Alert] + } +} + +/// Pure: the kinds `item` (stored under `sk`) takes: its saved `kinds`, or +/// the destination's default when none were saved. +pub fn kinds(item: &Item, sk: &str) -> Vec { + let saved: Option> = match item.get(KINDS_ATTR) { + Some(AttributeValue::L(l)) => { + Some(l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + } + Some(AttributeValue::Ss(s)) => Some(s.clone()), + _ => None, + }; + let Some(saved) = saved else { + return default_kinds(sk); + }; + let mut out: Vec = saved.iter().filter_map(|s| Kind::parse(s)).collect(); + out.sort(); + out.dedup(); + out +} + +/// Pure: the attribute that saves `kinds` on a destination item. +pub fn kinds_attr(kinds: &[Kind]) -> AttributeValue { + let mut k = kinds.to_vec(); + k.sort(); + k.dedup(); + AttributeValue::L( + k.iter() + .map(|k| AttributeValue::S(k.key().to_string())) + .collect(), + ) +} + +/// Pure: `kinds` from a request, checked: known keys, at least one. +pub fn parse_kinds(keys: &[String]) -> Result, String> { + let mut out = Vec::new(); + for k in keys { + out.push(Kind::parse(k).ok_or_else(|| format!("unknown message kind {k:?}"))?); + } + out.sort(); + out.dedup(); + if out.is_empty() { + return Err("a channel takes at least one kind of message".into()); + } + Ok(out) +} + +fn enabled(item: &Item) -> bool { + item.get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false) +} + +/// Pure: whether the destination saved under `sk` posts a `kind` message. +pub fn takes(item: &Item, sk: &str, kind: Kind) -> bool { + enabled(item) && kinds(item, sk).contains(&kind) +} + +/// Pure: the order destinations are tried for a kind. An alert goes to the +/// alert channel; action and updates go to the updates channel first, and +/// to the alert channel only when it was set to take them. +pub fn order(kind: Kind) -> [&'static str; 2] { + match kind { + Kind::Alert => [ALERTS_SK, UPDATES_SK], + Kind::Action | Kind::Update => [UPDATES_SK, ALERTS_SK], + } +} + +/// Pure: per chat app, the first destination in [`order`] that takes `kind` +/// and has that app set. `opened` pairs each destination's sort key with its +/// item and its opened channels. +pub fn pick(kind: Kind, opened: &[(&str, &Item, Channels)]) -> Channels { + let mut out = Channels::default(); + for sk in order(kind) { + let Some((_, item, channels)) = opened.iter().find(|(k, _, _)| *k == sk) else { + continue; + }; + if !takes(item, sk, kind) { + continue; + } + for app in ChannelKind::ALL { + if out.get(app).is_none() { + out.set(app, channels.get(app).map(str::to_string)); + } + } + } + out.usable() +} + +/// Pure: the chat apps a `kind` message posts to, from the stored items +/// (for a settings page; never opens a webhook). +pub fn apps(kind: Kind, items: &[(&str, Item)]) -> Vec { + let mut out = Vec::new(); + for sk in order(kind) { + let Some((_, item)) = items.iter().find(|(k, _)| *k == sk) else { + continue; + }; + if !takes(item, sk, kind) { + continue; + } + for app in ChannelKind::ALL { + if store::stored(item, app).is_set() && !out.contains(&app) { + out.push(app); + } + } + } + out.sort_by_key(|a| ChannelKind::ALL.iter().position(|b| b == a)); + out +} + +/// The team's destination items, as stored (sort key, item). +pub async fn load(dynamo: &DynamoClient, table: &str, team_id: &str) -> Vec<(&'static str, Item)> { + let get = |sk: &'static str| { + dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(sk.to_string())) + .send() + }; + let (alerts, updates) = tokio::join!(get(ALERTS_SK), get(UPDATES_SK)); + [(ALERTS_SK, alerts), (UPDATES_SK, updates)] + .into_iter() + .map(|(sk, r)| { + ( + sk, + r.ok().and_then(|o| o.item().cloned()).unwrap_or_default(), + ) + }) + .collect() +} + +/// The team's channels, opened once, for picking per message. No `Debug`: +/// the items hold webhooks. +#[derive(Clone, Default)] +pub struct TeamChannels { + opened: Vec<(&'static str, Item, Channels)>, +} + +impl TeamChannels { + /// Opens every destination that takes any kind. + pub async fn open( + cipher: &dyn Cipher, + team_id: &str, + items: Vec<(&'static str, Item)>, + ) -> Self { + let mut opened = Vec::new(); + for (sk, item) in items { + let channels = if enabled(&item) && !kinds(&item, sk).is_empty() { + store::open_all(cipher, team_id, &item).await + } else { + Channels::default() + }; + opened.push((sk, item, channels)); + } + TeamChannels { opened } + } + + /// No kind of message goes anywhere. + pub fn is_empty(&self) -> bool { + Kind::ALL.iter().all(|k| self.get(*k).is_empty()) + } + + /// Where a `kind` message goes. Empty = nowhere. + pub fn get(&self, kind: Kind) -> Channels { + let view: Vec<(&str, &Item, Channels)> = self + .opened + .iter() + .map(|(sk, item, c)| (*sk, item, c.clone())) + .collect(); + pick(kind, &view) + } +} + +/// The team's channels, read and opened: [`TeamChannels::get`] per message. +pub async fn team( + dynamo: &DynamoClient, + cipher: &dyn Cipher, + table: &str, + team_id: &str, +) -> TeamChannels { + TeamChannels::open(cipher, team_id, load(dynamo, table, team_id).await).await +} + +/// Where one `kind` message goes, read and opened. Empty = nowhere. +pub async fn team_channels( + dynamo: &DynamoClient, + cipher: &dyn Cipher, + table: &str, + team_id: &str, + kind: Kind, +) -> Channels { + team(dynamo, cipher, table, team_id).await.get(kind) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ALERTS_TEAMS: &str = "https://acme.webhook.office.com/webhookb2/alerts"; + const UPDATES_TEAMS: &str = "https://acme.webhook.office.com/webhookb2/updates"; + const SLACK: &str = "https://hooks.slack.com/services/T000/B000/XXXX"; + + fn item(on: bool, kinds: Option<&[&str]>) -> Item { + let mut i = Item::new(); + i.insert("enabled".into(), AttributeValue::Bool(on)); + if let Some(k) = kinds { + i.insert( + KINDS_ATTR.into(), + AttributeValue::L(k.iter().map(|s| AttributeValue::S(s.to_string())).collect()), + ); + } + i + } + + fn teams(url: &str) -> Channels { + Channels { + teams: Some(url.into()), + slack: None, + } + } + + #[test] + fn an_alert_channel_saved_before_kinds_takes_alerts_only() { + let alerts = item(true, None); + assert_eq!(kinds(&alerts, ALERTS_SK), vec![Kind::Alert]); + let opened = [(ALERTS_SK, &alerts, teams(ALERTS_TEAMS))]; + assert_eq!( + pick(Kind::Alert, &opened).teams.as_deref(), + Some(ALERTS_TEAMS) + ); + assert!(pick(Kind::Action, &opened).is_empty()); + assert!(pick(Kind::Update, &opened).is_empty()); + } + + #[test] + fn action_and_updates_go_to_the_updates_channel() { + let alerts = item(true, None); + let updates = item(true, None); + let opened = [ + (ALERTS_SK, &alerts, teams(ALERTS_TEAMS)), + (UPDATES_SK, &updates, teams(UPDATES_TEAMS)), + ]; + assert_eq!( + pick(Kind::Alert, &opened).teams.as_deref(), + Some(ALERTS_TEAMS) + ); + assert_eq!( + pick(Kind::Action, &opened).teams.as_deref(), + Some(UPDATES_TEAMS) + ); + assert_eq!( + pick(Kind::Update, &opened).teams.as_deref(), + Some(UPDATES_TEAMS) + ); + } + + #[test] + fn an_alert_channel_set_to_take_more_gets_them() { + let alerts = item(true, Some(&["alert", "action"])); + let opened = [(ALERTS_SK, &alerts, teams(ALERTS_TEAMS))]; + assert_eq!( + pick(Kind::Action, &opened).teams.as_deref(), + Some(ALERTS_TEAMS) + ); + assert!(pick(Kind::Update, &opened).is_empty()); + // The updates channel still wins for action when both take it. + let updates = item(true, None); + let both = [ + (ALERTS_SK, &alerts, teams(ALERTS_TEAMS)), + (UPDATES_SK, &updates, teams(UPDATES_TEAMS)), + ]; + assert_eq!( + pick(Kind::Action, &both).teams.as_deref(), + Some(UPDATES_TEAMS) + ); + } + + #[test] + fn a_channel_that_is_off_or_takes_nothing_gets_nothing() { + let off = item(false, Some(&["alert", "action", "update"])); + let none = item(true, Some(&[])); + for k in Kind::ALL { + assert!(pick(k, &[(ALERTS_SK, &off, teams(ALERTS_TEAMS))]).is_empty()); + assert!(pick(k, &[(UPDATES_SK, &none, teams(UPDATES_TEAMS))]).is_empty()); + } + } + + #[test] + fn each_app_comes_from_the_first_destination_that_has_it() { + let alerts = item(true, Some(&["alert", "update"])); + let updates = item(true, None); + let opened = [ + ( + ALERTS_SK, + &alerts, + Channels { + teams: Some(ALERTS_TEAMS.into()), + slack: Some(SLACK.into()), + }, + ), + (UPDATES_SK, &updates, teams(UPDATES_TEAMS)), + ]; + let c = pick(Kind::Update, &opened); + assert_eq!(c.teams.as_deref(), Some(UPDATES_TEAMS)); + assert_eq!(c.slack.as_deref(), Some(SLACK)); + } + + #[test] + fn kinds_parse_and_save_round_trip() { + let k = parse_kinds(&["update".into(), "alert".into(), "alert".into()]).unwrap(); + assert_eq!(k, vec![Kind::Alert, Kind::Update]); + assert!(parse_kinds(&[]).is_err()); + assert!(parse_kinds(&["everything".into()]).is_err()); + let mut i = item(true, None); + i.insert(KINDS_ATTR.into(), kinds_attr(&k)); + assert_eq!(kinds(&i, ALERTS_SK), k); + // A string set reads the same. + i.insert( + KINDS_ATTR.into(), + AttributeValue::Ss(vec!["action".into(), "bogus".into()]), + ); + assert_eq!(kinds(&i, ALERTS_SK), vec![Kind::Action]); + } + + #[test] + fn every_label_has_a_kind() { + for (what, kind) in [ + ("alert", Kind::Alert), + ("alert_pr", Kind::Alert), + ("alert_no_change", Kind::Alert), + ("log_incident", Kind::Alert), + ("merge_gate_wait", Kind::Action), + ("webhook_disabled", Kind::Action), + ("knowledge sign-in", Kind::Action), + ("plugin review", Kind::Action), + ("aws_permissions", Kind::Action), + ("log_fix_pr", Kind::Update), + ("log_fix_pr_closed", Kind::Update), + ("findings", Kind::Update), + ] { + assert_eq!(kind_of(what), Some(kind), "{what}"); + } + assert_eq!(kind_of("security"), None); + } + + /// Every file that names the alert channel's settings item. Each reads + /// it for alerts, for its settings page, or through this router; a new + /// sender reaches it only by picking a kind here. + #[test] + fn only_the_router_opens_the_alert_channel() { + let services = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let allowed = [ + "common/src/alert_notify.rs", + "common/src/notify/route.rs", + // The settings API and the alert card's own route. + "gateway/src/routes/alerts.rs", + // Asserts its approval channel is not the alert channel. + "worker/src/agent/policy.rs", + ]; + let mut found = Vec::new(); + let mut stack = vec![services.clone()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for e in entries.flatten() { + let p = e.path(); + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if p.is_dir() { + if name != "target" && !name.starts_with('.') { + stack.push(p); + } + continue; + } + if !name.ends_with(".rs") { + continue; + } + let rel = p + .strip_prefix(&services) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + if rel.contains("/incidents/") { + continue; + } + let src = std::fs::read_to_string(&p).unwrap_or_default(); + if (src.contains("TEAM_SETTINGS_SK") || src.contains("\"ALERT_NOTIFY\"")) + && !allowed.contains(&rel.as_str()) + { + found.push(rel); + } + } + } + found.sort(); + assert!( + found.is_empty(), + "these read the alert channel directly; pick a kind through notify::route instead: {found:?}" + ); + } +} diff --git a/services/common/src/security_fixes.rs b/services/common/src/security_fixes.rs index 1886bf65b..c7c4635de 100644 --- a/services/common/src/security_fixes.rs +++ b/services/common/src/security_fixes.rs @@ -1444,6 +1444,24 @@ impl Stage { } } +/// Pure: what a card is, for where it may go. A critical (P0) finding's +/// new card, its rise to P0 and its deadlines are alerts: something is wrong +/// now. Every other card (a lower tier, a pull request opened, CI passing, +/// merged, withdrawn) is an update, and never reaches an alert channel that +/// takes alerts only. +pub fn card_kind(f: &Finding, stage: Stage) -> crate::notify::route::Kind { + use crate::notify::route::Kind; + let urgent = matches!( + stage, + Stage::New | Stage::RaisedP0 | Stage::Half | Stage::Deadline + ); + if urgent && f.tier == Some(Tier::P0) { + Kind::Alert + } else { + Kind::Update + } +} + /// Whether a finding's tier posts cards at all. pub fn posts(f: &Finding, cfg: &SecurityConfig) -> bool { !f.private_report && f.tier.is_some_and(|t| cfg.post_alerts.get(t)) diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 18c0427ee..4b413375f 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -669,6 +669,10 @@ fn build_app(state: Arc) -> Router { get(routes::alerts::get_notify).put(routes::alerts::put_notify), ) .route("/alert-notify/test", post(routes::alerts::test_notify)) + .route( + "/updates-notify", + get(routes::alerts::get_updates_notify).put(routes::alerts::put_updates_notify), + ) .route("/notify/test", post(routes::alerts::test_notify)) .route("/alerts", get(routes::alerts::list_events)) .route("/alerts/event", get(routes::alerts::get_event)) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 9f0d9ebb1..366ccff0a 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -749,6 +749,8 @@ pub const CAPABILITIES: &[Capability] = &[ "alerts::delete_route", "alerts::get_notify", "alerts::put_notify", + "alerts::get_updates_notify", + "alerts::put_updates_notify", "alerts::get_budget", "alerts::put_budget", "alerts::test_notify", diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index d6a78b169..035d5f06f 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -1227,12 +1227,17 @@ async fn route_channels(state: &AppState, route: &Route) -> Channels { match route.notify_mode.as_str() { alert_notify::MODE_OFF => Channels::default(), alert_notify::MODE_CUSTOM => store::open_all(&c, &route.team_id, &route.webhooks).await, + // The team's channel for alerts (`notify::route`): the alert + // channel, unless it was set not to take them. _ => { - let team = team_notify_settings(state, &route.team_id).await; - if !team.enabled { - return Channels::default(); - } - store::open_all(&c, &route.team_id, &team.item).await + notify::route::team_channels( + &state.dynamo, + &c, + &state.config.settings_table_name, + &route.team_id, + notify::route::Kind::Alert, + ) + .await } } } @@ -2444,46 +2449,122 @@ pub(crate) fn save_error(e: store::SaveError) -> StatusCode { } } -/// GET /api/alert-notify — the team's alert channels (admin+). Webhooks are +/// Pure: a team channel's settings as the API shows them: on or off, the +/// kinds of message it takes (`notify::route`), and its webhooks as hints. +pub(crate) fn notify_view(item: &HashMap, sk: &str) -> Value { + let on = item + .get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + let kinds: Vec<&str> = notify::route::kinds(item, sk) + .iter() + .map(|k| k.key()) + .collect(); + let defaults: Vec<&str> = notify::route::default_kinds(sk) + .iter() + .map(|k| k.key()) + .collect(); + json!({ + "enabled": on, + "kinds": kinds, + "default_kinds": defaults, + "webhooks": store::view(item), + }) +} + +async fn notify_item(state: &AppState, team_id: &str, sk: &str) -> HashMap { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(sk)) + .send() + .await + .ok() + .and_then(|o| o.item().cloned()) + .unwrap_or_default() +} + +/// GET /api/alert-notify — the team's alert channel (admin+). Webhooks are /// shown only as a hint. pub async fn get_notify( State(state): State>, Extension(claims): Extension, ) -> Result, StatusCode> { claims.require_role(3)?; - let t = team_notify_settings(&state, &claims.team_id).await; - Ok(Json( - json!({ "enabled": t.enabled, "webhooks": store::view(&t.item) }), - )) + let sk = notify::route::ALERTS_SK; + Ok(Json(notify_view( + ¬ify_item(&state, &claims.team_id, sk).await, + sk, + ))) +} + +/// GET /api/updates-notify — the team's channel for updates and for things +/// a person has to do (admin+). +pub async fn get_updates_notify( + State(state): State>, + Extension(claims): Extension, +) -> Result, StatusCode> { + claims.require_role(3)?; + let sk = notify::route::UPDATES_SK; + Ok(Json(notify_view( + ¬ify_item(&state, &claims.team_id, sk).await, + sk, + ))) } #[derive(Deserialize)] pub struct PutNotifyRequest { #[serde(default)] enabled: bool, + /// The kinds of message the channel takes ("alert", "action", + /// "update"). Left out, the saved kinds (or the channel's default) stay. + #[serde(default)] + kinds: Option>, /// Each webhook is kept unless the request sets or clears it. #[serde(flatten)] channels: store::ChannelsInput, } -/// PUT /api/alert-notify — set the team's alert channels (admin+). On needs at -/// least one channel. +/// PUT /api/alert-notify — set the team's alert channel (admin+). On needs +/// at least one channel. pub async fn put_notify( State(state): State>, Extension(claims): Extension, Json(req): Json, +) -> Result, StatusCode> { + claims.require_role(3)?; + save_notify(&state, &claims, notify::route::ALERTS_SK, req).await +} + +/// PUT /api/updates-notify — set the team's updates channel (admin+). +pub async fn put_updates_notify( + State(state): State>, + Extension(claims): Extension, + Json(req): Json, +) -> Result, StatusCode> { + claims.require_role(3)?; + save_notify(&state, &claims, notify::route::UPDATES_SK, req).await +} + +async fn save_notify( + state: &AppState, + claims: &Claims, + sk: &str, + req: PutNotifyRequest, ) -> Result, StatusCode> { claims.require_role(3)?; req.channels.check().map_err(save_error)?; - let prior = team_notify_settings(&state, &claims.team_id).await; - let attrs = store::save_attrs( - &cipher(&state), - &claims.team_id, - Some(&prior.item), - &req.channels, - ) - .await - .map_err(save_error)?; + let prior = notify_item(state, &claims.team_id, sk).await; + let kinds = match &req.kinds { + Some(keys) => notify::route::parse_kinds(keys).map_err(|_| StatusCode::BAD_REQUEST)?, + None => notify::route::kinds(&prior, sk), + }; + let attrs = store::save_attrs(&cipher(state), &claims.team_id, Some(&prior), &req.channels) + .await + .map_err(save_error)?; if req.enabled && !store::any_set(&store::as_item(&attrs)) { return Err(StatusCode::BAD_REQUEST); } @@ -2492,18 +2573,19 @@ pub async fn put_notify( .put_item() .table_name(&state.config.settings_table_name) .item("pk", attr_s(&claims.team_id)) - .item("sk", attr_s(alert_notify::TEAM_SETTINGS_SK)) + .item("sk", attr_s(sk)) .item("enabled", AttributeValue::Bool(req.enabled)) + .item(notify::route::KINDS_ATTR, notify::route::kinds_attr(&kinds)) .item("updated_at", attr_s(&chrono::Utc::now().to_rfc3339())) .item("updated_by", attr_s(&claims.email)); for (k, v) in attrs { put = put.item(k, v); } put.send().await.map_err(|e| { - error!(error = %e, "Could not save alert channel"); + error!(error = %e, sk, "Could not save a team channel"); StatusCode::INTERNAL_SERVER_ERROR })?; - info!(team_id = %claims.team_id, enabled = req.enabled, "Alert channel saved"); + info!(team_id = %claims.team_id, sk, enabled = req.enabled, ?kinds, "Team channel saved"); Ok(Json(json!({ "ok": true }))) } @@ -2574,8 +2656,9 @@ pub struct TestNotifyRequest { #[serde(default)] teams_webhook_url: String, /// Whose saved webhook to test: "alerts" (the team alert channel), - /// "route" (with `topic_arn`), "recommendations", or "reviewer" (with - /// `repo`). Also picks the sample message. + /// "updates" (the team updates channel), "route" (with `topic_arn`), + /// "recommendations", or "reviewer" (with `repo`). Also picks the sample + /// message. #[serde(default)] destination: String, #[serde(default)] @@ -2588,6 +2671,7 @@ pub struct TestNotifyRequest { fn destination_sk(req: &TestNotifyRequest) -> Option { match req.destination.as_str() { "" | "alerts" => Some(alert_notify::TEAM_SETTINGS_SK.to_string()), + "updates" => Some(notify::route::UPDATES_SK.to_string()), "route" if !req.topic_arn.trim().is_empty() => Some(team_route_sk(req.topic_arn.trim())), "recommendations" => Some(super::log_analyzer::REC_NOTIFY_SK.to_string()), "reviewer" @@ -2662,6 +2746,10 @@ pub async fn test_notify( context: "us-east-1 · test", }), "recommendations" => notify::messages::test_message("New log findings", &format!("{base}/logs")), + "updates" => notify::messages::test_message( + "Updates and requests for a person", + &format!("{base}/settings/alerts"), + ), _ => notify::messages::test_message("Review reminders", &format!("{base}/reviewer")), }; use notify::Poster; @@ -2899,6 +2987,10 @@ mod tests { destination_sk(&req("recommendations", "", "")).as_deref(), Some("REC_NOTIFY") ); + assert_eq!( + destination_sk(&req("updates", "", "")).as_deref(), + Some("UPDATES_NOTIFY") + ); assert_eq!( destination_sk(&req("reviewer", "", "acme/web")).as_deref(), Some("REVIEW_CONFIG#REPO#acme/web") diff --git a/services/gateway/src/routes/log_findings.rs b/services/gateway/src/routes/log_findings.rs index 0608a9f0c..45bec0966 100644 --- a/services/gateway/src/routes/log_findings.rs +++ b/services/gateway/src/routes/log_findings.rs @@ -852,7 +852,14 @@ pub async fn on_fix_pr_closed( return; }; let cipher = super::alerts::cipher(state); - let channels = lf::channels(&state.dynamo, &cipher, table, team_id).await; + let channels = lf::channels( + &state.dynamo, + &cipher, + table, + team_id, + common::notify::route::Kind::Update, + ) + .await; let cards = lf::DynamoFixCards { dynamo: &state.dynamo, table, diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index a08e5cb03..012b1627a 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -1605,17 +1605,15 @@ async fn evaluate( ); set_state(state, msg, decision.state, &detail).await; // A person's approval that no longer counts is never waited on - // silently: the PR's one status comment, and the team's channel - // once per commit. + // silently: the PR's one status comment says so. Waiting on + // people's reviews is a PR's normal state, so it never goes to a + // team channel (`incidents::nt_alerts_channel_alerts_only`). let person_gap = view.require_human && !person_key(&view) && (!view.approvals.approved_by.is_empty() || !view.approvals.dismissed.is_empty()); if watched || person_gap { publish_status(state, github, msg, record, &status).await; } - if person_gap { - tell_team(state, msg, &pr, &detail).await; - } Ok(Next::Recheck) } Action::ReadCi => Err("the gate asked for CI after reading it".into()), @@ -2026,7 +2024,7 @@ async fn keep_current( BaseMerge::Unresolved { .. } | BaseMerge::CannotPush => { set_state(state, msg, common::merge_gate::STATE_CONFLICT, &line.1).await; publish_status(state, github, msg, record, &body).await; - tell_team(state, msg, pr, &line.1).await; + tell_team(state, msg, pr, TeamNotice::Conflict, &line.1).await; } } Ok(Next::Stop) @@ -2228,26 +2226,53 @@ async fn read_review_rules( review_rules(protection.as_ref(), rulesets.as_ref()) } -/// One message to the team's channel, once per PR commit and wait: what -/// the merge waits on. Silent where no channel is set up. +/// Why the gate tells the team, beyond the PR's own status comment. Only +/// a wait a person has to end is here: a review the branch's rules ask for +/// is the PR's normal state, and CI, labels and CoderHelm's own review end +/// by themselves, so none of those is ever posted to a channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum TeamNotice { + /// A merge conflict CoderHelm could not resolve, or could not push. + Conflict, +} + +impl TeamNotice { + fn key(self) -> &'static str { + match self { + TeamNotice::Conflict => "conflict", + } + } +} + +/// Pure: the claim that makes a notice go out once per PR and reason, ever +/// (for the record's life): not once per commit or per wording. +pub(crate) fn told_sk(owner: &str, repo: &str, pr: u64, notice: TeamNotice) -> String { + format!( + "MERGEGATETOLD#{}/{}#{pr}#{}", + owner.to_ascii_lowercase(), + repo.to_ascii_lowercase(), + notice.key() + ) +} + +/// One "needs you" message, once per PR and reason: what a person has to +/// do before the merge can go on. It goes only where the team takes action +/// messages (`common::notify::route`), never to an alert channel that takes +/// alerts only, and nowhere when none is set up. async fn tell_team( state: &WorkerState, msg: &AwaitMergeMessage, pr: &serde_json::Value, + notice: TeamNotice, line: &str, ) { - let channels = super::security_fixes::team_channels(state, &msg.team_id).await; + let channels = super::security_fixes::team_channels(state, &msg.team_id) + .await + .get(common::notify::route::Kind::Action); if channels.is_empty() { return; } - let sk = format!( - "MERGEGATETOLD#{}/{}#{}#{}#{}", - msg.repo_owner, - msg.repo_name, - msg.pr_number, - msg.head_sha, - common::content_hash(line) - ); + let sk = told_sk(&msg.repo_owner, &msg.repo_name, msg.pr_number, notice); let claim = common::claim::claim( &state.dynamo, &state.config.settings_table_name, diff --git a/services/worker/src/passes/incidents/mx_gate_keeps_the_branch_current.rs b/services/worker/src/passes/incidents/mx_gate_keeps_the_branch_current.rs index 09c53d0f6..fd3d84c78 100644 --- a/services/worker/src/passes/incidents/mx_gate_keeps_the_branch_current.rs +++ b/services/worker/src/passes/incidents/mx_gate_keeps_the_branch_current.rs @@ -173,13 +173,14 @@ fn a_wait_on_a_person_names_exactly_what_is_missing() { let mut v = view("APPROVED", Some("APPROVED")); v.requested = vec!["a-reviewer".into()]; assert!(person_key(&v)); - // The same line goes to the team's channel. + // The line goes on the run page (the record's detail) and the one + // status comment; waiting on people never goes to a team channel + // (`nt_alerts_channel_alerts_only`). let m = wait_message("acme", "web", 7, "Fix the schedule", "https://x/7", &line); assert!(m.summary.contains("acme/web#7")); assert_eq!(m.buttons.len(), 1); - // And on the run page (the record's detail) and the one status comment. let eval = fn_src(src(), "async fn evaluate("); - assert!(eval.contains("tell_team(")); + assert!(!eval.contains("tell_team(")); assert!(eval.contains("find(|(m, _)| *m != Mark::Done)")); } diff --git a/services/worker/src/passes/incidents/nt_alerts_channel_alerts_only.rs b/services/worker/src/passes/incidents/nt_alerts_channel_alerts_only.rs new file mode 100644 index 000000000..9d4100be5 --- /dev/null +++ b/services/worker/src/passes/incidents/nt_alerts_channel_alerts_only.rs @@ -0,0 +1,137 @@ +//! nt. A team's alert channel, set up for production alarms, also got +//! routine auto-merge status cards: a merge conflict that needed a person's +//! call, and a wait on an approving review the branch's rules ask for. +//! Every sender that wanted "the team's channel" opened the alert channel's +//! settings item (`ALERT_NOTIFY`) itself: the merge gate, security and +//! infrastructure cards, plugin reviews, turned-off webhook endpoints, +//! knowledge sign-ins, and log findings whose own setting was never saved. +//! The merge gate posted once per commit and wording, so each push could +//! post again, and it posted a wait on a person's review, which is a pull +//! request's normal state. +//! +//! Guarantee: every team-wide message has a kind (alert, action or update), +//! and its channels come from `common::notify::route` by that kind. An alert +//! channel saved before kinds existed takes alerts only; action and updates +//! go to the team's updates channel, or nowhere when there is none. The +//! merge gate never posts a wait on people's reviews to a channel (the PR's +//! status comment says it once), posts a conflict that needs a person only +//! where action messages go, and posts it once per PR and reason. + +use super::fixture::fn_src; +use crate::passes::await_merge::{told_sk, TeamNotice}; +use aws_sdk_dynamodb::types::AttributeValue; +use common::notify::route::{self, Kind, TeamChannels}; +use common::notify::Channels; +use std::collections::HashMap; + +const ALERTS: &str = "https://acme.webhook.office.com/webhookb2/alerts"; +const UPDATES: &str = "https://acme.webhook.office.com/webhookb2/updates"; + +fn src() -> &'static str { + include_str!("../await_merge.rs") +} + +fn on(kinds: Option<&[&str]>) -> HashMap { + let mut i = HashMap::from([("enabled".to_string(), AttributeValue::Bool(true))]); + if let Some(k) = kinds { + i.insert( + route::KINDS_ATTR.into(), + AttributeValue::L(k.iter().map(|s| AttributeValue::S(s.to_string())).collect()), + ); + } + i +} + +fn teams(url: &str) -> Channels { + Channels { + teams: Some(url.into()), + slack: None, + } +} + +#[test] +fn the_alert_channel_as_it_was_saved_takes_alerts_only() { + // The item as the team saved it: on, a Teams webhook, no kinds. + let alerts = on(None); + let only = [(route::ALERTS_SK, &alerts, teams(ALERTS))]; + assert_eq!( + route::pick(Kind::Alert, &only).teams.as_deref(), + Some(ALERTS) + ); + assert!( + route::pick(Kind::Action, &only).is_empty(), + "a merge conflict card never reaches the alert channel" + ); + assert!(route::pick(Kind::Update, &only).is_empty()); + // With an updates channel, action and updates go there. + let updates = on(None); + let both = [ + (route::ALERTS_SK, &alerts, teams(ALERTS)), + (route::UPDATES_SK, &updates, teams(UPDATES)), + ]; + assert_eq!( + route::pick(Kind::Action, &both).teams.as_deref(), + Some(UPDATES) + ); + assert_eq!( + route::pick(Kind::Update, &both).teams.as_deref(), + Some(UPDATES) + ); + assert_eq!( + route::pick(Kind::Alert, &both).teams.as_deref(), + Some(ALERTS) + ); + // A team that wants requests for a person in its alert channel says so. + let more = on(Some(&["alert", "action"])); + let chose = [(route::ALERTS_SK, &more, teams(ALERTS))]; + assert_eq!( + route::pick(Kind::Action, &chose).teams.as_deref(), + Some(ALERTS) + ); + assert!(route::pick(Kind::Update, &chose).is_empty()); + // Nothing set up: nothing posts. + assert!(TeamChannels::default().is_empty()); +} + +#[test] +fn the_merge_gate_never_posts_a_review_wait_and_posts_a_conflict_once() { + // Waiting on people: the status comment, never a channel. + let eval = fn_src(src(), "async fn evaluate("); + let people = &eval[eval.find("Action::WaitForPeople =>").unwrap()..]; + let people = &people[..people.find("Ok(Next::Recheck)").unwrap()]; + assert!(people.contains("publish_status(")); + assert!(!people.contains("tell_team("), "{people}"); + // A conflict a person must resolve: action, never the alert kind. + let tell = fn_src(src(), "async fn tell_team("); + assert!(tell.contains(".get(common::notify::route::Kind::Action)")); + assert!(!tell.contains("Kind::Alert")); + assert!(src().contains("tell_team(state, msg, pr, TeamNotice::Conflict, &line.1)")); + // Once per PR and reason: not per commit or per wording. + let a = told_sk("Acme", "web-api", 12, TeamNotice::Conflict); + assert_eq!(a, told_sk("acme", "Web-API", 12, TeamNotice::Conflict)); + assert_eq!(a, "MERGEGATETOLD#acme/web-api#12#conflict"); + assert!(tell.contains("told_sk(&msg.repo_owner, &msg.repo_name, msg.pr_number, notice)")); + assert!(!tell.contains("head_sha")); + assert!(!tell.contains("content_hash")); +} + +#[test] +fn every_team_channel_sender_picks_a_kind() { + // The senders that opened the alert channel themselves now pick by kind. + for (file, kind) in [ + (include_str!("../plugins.rs"), "Kind::Action"), + (include_str!("../webhooks.rs"), "Kind::Action"), + (include_str!("../knowledge_sync.rs"), "Kind::Action"), + (include_str!("../log_autofix.rs"), "Kind::Update"), + (include_str!("../infra_findings.rs"), "Kind::Update"), + ] { + let code = &file[..file.find("#[cfg(test)]").unwrap_or(file.len())]; + assert!(code.contains(kind), "{kind}"); + assert!(!code.contains("TEAM_SETTINGS_SK")); + } + // Security cards: a critical finding's urgent card is an alert; a pull + // request opened, merged or withdrawn is an update. + let sec = include_str!("../security_fixes.rs"); + assert!(sec.contains("channels.get(sec::card_kind(f, stage))")); + assert!(!sec[..sec.find("#[cfg(test)]").unwrap()].contains("TEAM_SETTINGS_SK")); +} diff --git a/services/worker/src/passes/infra_findings.rs b/services/worker/src/passes/infra_findings.rs index 6fcfa3dd2..3efca22ec 100644 --- a/services/worker/src/passes/infra_findings.rs +++ b/services/worker/src/passes/infra_findings.rs @@ -556,6 +556,23 @@ async fn cards( r.finding.id ); let msg = records::card(r, &url); + // A P0 is an alert; a P1 is news for the updates channel. + let kind = if r.tier() == Some(Tier::P0) { + common::notify::route::Kind::Alert + } else { + common::notify::route::Kind::Update + }; + let channels = channels.get(kind); + if channels.is_empty() { + common::claim::release( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &sk, + ) + .await; + continue; + } let sent = common::notify::deliver_recorded( &common::notify::Http(&state.http), &channels, diff --git a/services/worker/src/passes/knowledge_sync.rs b/services/worker/src/passes/knowledge_sync.rs index ec9a5af6c..0f8bda212 100644 --- a/services/worker/src/passes/knowledge_sync.rs +++ b/services/worker/src/passes/knowledge_sync.rs @@ -310,25 +310,21 @@ async fn after_sync(state: &WorkerState, st: &AwsSyncStore, msg: &SyncMessage) { /// The team's chat channels and an email to each owner and admin. async fn tell_admins(state: &WorkerState, team: &str, src: &Source) { - use aws_sdk_dynamodb::types::AttributeValue as Av; let Some(e) = src.error.as_ref() else { return }; let app = common::public_urls::app_url(&state.config.stage); - let item = state - .dynamo - .get_item() - .table_name(&state.config.settings_table_name) - .key("pk", Av::S(team.to_string())) - .key("sk", Av::S(common::alert_notify::TEAM_SETTINGS_SK.into())) - .send() - .await - .ok() - .and_then(|o| o.item().cloned()) - .unwrap_or_default(); let cipher = common::mcp_credentials::Kms { client: &state.kms, key_id: "", }; - let channels = common::notify::store::open_all(&cipher, team, &item).await; + // A sign-in to renew is a person's to do: the "needs you" channel. + let channels = common::notify::route::team_channels( + &state.dynamo, + &cipher, + &state.config.settings_table_name, + team, + common::notify::route::Kind::Action, + ) + .await; if !channels.is_empty() { common::notify::deliver( &common::notify::Http(&state.http), diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 78b4aa2e5..4bfccf0c3 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -405,6 +405,7 @@ async fn post_card( &cipher, &state.config.settings_table_name, team_id, + common::notify::route::Kind::Alert, ) .await; if channels.is_empty() { @@ -997,6 +998,7 @@ pub async fn notify_pr( &cipher, &state.config.settings_table_name, team_id, + common::notify::route::Kind::Update, ) .await; if channels.is_empty() { diff --git a/services/worker/src/passes/plugins.rs b/services/worker/src/passes/plugins.rs index 09080bf40..9cd60b326 100644 --- a/services/worker/src/passes/plugins.rs +++ b/services/worker/src/passes/plugins.rs @@ -739,26 +739,16 @@ pub async fn notify_review(state: &WorkerState, team: &str, artifact: &str) { .unwrap_or_default(); let base = common::plugins::chat::dashboard(&state.config.stage); if !p.notify.is_empty() { - let item = state - .dynamo - .get_item() - .table_name(&state.config.settings_table_name) - .key( - "pk", - aws_sdk_dynamodb::types::AttributeValue::S(team.to_string()), - ) - .key( - "sk", - aws_sdk_dynamodb::types::AttributeValue::S( - common::alert_notify::TEAM_SETTINGS_SK.into(), - ), - ) - .send() - .await - .ok() - .and_then(|o| o.item().cloned()) - .unwrap_or_default(); - let mut channels = common::notify::store::open_all(&cipher(state), team, &item).await; + // A review request is for a person to act on: the team's "needs + // you" channel, never an alert channel that takes alerts only. + let mut channels = common::notify::route::team_channels( + &state.dynamo, + &cipher(state), + &state.config.settings_table_name, + team, + common::notify::route::Kind::Action, + ) + .await; if p.notify == "teams" { channels.slack = None; } else if p.notify == "slack" { diff --git a/services/worker/src/passes/security_fixes.rs b/services/worker/src/passes/security_fixes.rs index dbb2a0f87..0f951ddf0 100644 --- a/services/worker/src/passes/security_fixes.rs +++ b/services/worker/src/passes/security_fixes.rs @@ -1910,31 +1910,23 @@ async fn triage_tick(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) -> // ── Cards ─────────────────────────────────────────────────────────────── -pub(crate) async fn team_channels(state: &WorkerState, team_id: &str) -> common::notify::Channels { - let item = state - .dynamo - .get_item() - .table_name(&state.config.settings_table_name) - .key("pk", attr_s(team_id)) - .key("sk", attr_s(common::alert_notify::TEAM_SETTINGS_SK)) - .send() - .await - .ok() - .and_then(|o| o.item().cloned()) - .unwrap_or_default(); - let enabled = item - .get("enabled") - .and_then(|v| v.as_bool().ok()) - .copied() - .unwrap_or(false); - if !enabled { - return Default::default(); - } +/// The team's channels, opened once: each message picks its own by kind +/// (`common::notify::route`), so only alerts reach an alert channel. +pub(crate) async fn team_channels( + state: &WorkerState, + team_id: &str, +) -> common::notify::route::TeamChannels { let cipher = common::mcp_credentials::Kms { client: &state.kms, key_id: "", }; - common::notify::store::open_all(&cipher, team_id, &item).await + common::notify::route::team( + &state.dynamo, + &cipher, + &state.config.settings_table_name, + team_id, + ) + .await } fn finding_url(state: &WorkerState, id: &str) -> String { @@ -1949,11 +1941,12 @@ fn finding_url(state: &WorkerState, id: &str) -> String { async fn post_card( state: &WorkerState, team_id: &str, - channels: &common::notify::Channels, + channels: &common::notify::route::TeamChannels, thing: &str, stage: Stage, f: &Finding, ) -> bool { + let channels = &channels.get(sec::card_kind(f, stage)); if channels.is_empty() { return false; } @@ -2735,7 +2728,7 @@ async fn cards(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) -> usize let msg = sec::digest_card(&waiting, &url, cx.cfg.max_cards_per_day); let sent = common::notify::deliver_recorded( &common::notify::Http(&cx.state.http), - &channels, + &channels.get(common::notify::route::Kind::Update), &msg, "security", &cx.state.dynamo, diff --git a/services/worker/src/passes/security_release.rs b/services/worker/src/passes/security_release.rs index b10eebf65..9741daaeb 100644 --- a/services/worker/src/passes/security_release.rs +++ b/services/worker/src/passes/security_release.rs @@ -482,7 +482,7 @@ pub(super) struct Live<'a, 'c> { pub cx: &'a Ctx<'c>, pub started: Instant, pub budget_secs: u64, - channels: tokio::sync::OnceCell, + channels: tokio::sync::OnceCell, } impl<'a, 'c> Live<'a, 'c> { diff --git a/services/worker/src/passes/webhooks.rs b/services/worker/src/passes/webhooks.rs index ab367d67c..758677df6 100644 --- a/services/worker/src/passes/webhooks.rs +++ b/services/worker/src/passes/webhooks.rs @@ -500,34 +500,20 @@ async fn notify_disabled(state: &WorkerState, team_id: &str, ep: &endpoint::Endp if let Err(e) = crate::clients::email::send_notification(state, team_id, event).await { warn!(team_id, error = %e, "Could not email admins about a turned-off webhook endpoint"); } - // The team's chat channel, when alert notifications are on for it. + // The team's channel for things a person has to act on, when one takes + // them; never an alert channel that takes alerts only. let cipher = common::mcp_credentials::Kms { client: &state.kms, key_id: "", }; - let item = state - .dynamo - .get_item() - .table_name(&state.config.settings_table_name) - .key("pk", AttributeValue::S(team_id.into())) - .key( - "sk", - AttributeValue::S(common::alert_notify::TEAM_SETTINGS_SK.into()), - ) - .send() - .await - .ok() - .and_then(|r| r.item().cloned()); - let Some(item) = item else { return }; - let on = item - .get("enabled") - .and_then(|v| v.as_bool().ok()) - .copied() - .unwrap_or(false); - if !on { - return; - } - let channels = common::notify::store::open_all(&cipher, team_id, &item).await; + let channels = common::notify::route::team_channels( + &state.dynamo, + &cipher, + &state.config.settings_table_name, + team_id, + common::notify::route::Kind::Action, + ) + .await; if channels.is_empty() { return; }