From fad99e6e008541d12804b29fb76fe27bceebdacc Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 11:56:05 -0500 Subject: [PATCH 1/4] Keep every event path inside its team An audit of inbound webhooks, live streams, queues, notifications, team knowledge and caches found four keys that named a shared thing instead of the team. Each is proven by a test that failed before the fix. - Slack workspace and Teams webhook links are claimed by one team at a time (flag::claim_chat); another team's link is refused, an unlink only drops the caller's own, and inbound routing requires the team's settings to still name the key. - Run page GitHub check reads are cached per installation (read_key), so a same-named repository never gets another installation's cached checks. - Composed replies are cached by the full prompt they were written from, so two Jira sites sharing a ticket key and comment id never share one. - Run event rows carry team_id; every read keeps only the asking team's rows, all through common::run_events. - The plan chat stream token is scoped to its stream, like the brain's. Incident case bm_teams_never_cross scans for new inbound routes, process-wide caches and direct events table access that don't say how they stay in their team. --- docs/incidents.md | 1 + services/common/src/lib.rs | 1 + services/common/src/plugins/flag.rs | 200 ++++++++ services/common/src/reply_compose.rs | 54 ++- services/common/src/run_events.rs | 125 +++++ services/gateway/src/auth/jwt.rs | 17 + services/gateway/src/routes/api.rs | 19 +- services/gateway/src/routes/github_webhook.rs | 70 +-- services/gateway/src/routes/plans.rs | 25 +- services/gateway/src/routes/plugin_pkgs.rs | 43 +- services/gateway/src/routes/run_checks.rs | 61 ++- services/worker/src/passes/implement.rs | 9 +- .../src/passes/incidents/ax_github_budget.rs | 2 +- .../passes/incidents/bm_teams_never_cross.rs | 435 ++++++++++++++++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/mod.rs | 2 +- services/worker/src/passes/outside_exec.rs | 41 +- services/worker/src/passes/resume.rs | 158 ++++--- 18 files changed, 1063 insertions(+), 201 deletions(-) create mode 100644 services/common/src/run_events.rs create mode 100644 services/worker/src/passes/incidents/bm_teams_never_cross.rs diff --git a/docs/incidents.md b/docs/incidents.md index 775c06be5..74d54f4ff 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -89,6 +89,7 @@ pipeline still calls it there. | bi. `bi_own_review_finishes` | A run's own review asked for changes; its fix rounds were blocked by a refused edit, checks skipped for time and a tool input error, the loop called that "no progress" at its cap of two, deferred a one-line config omission and a placeholder line, and marked the run completed while the run page said a fix round was taking them. The finding contradicted a comment on the ticket, and an outside step asked a person to add labels. | Each finding is tracked on its own: a blocked round is not a stall and the next one removes the block; a stalled finding climbs its own ladder; a finding the ticket, its comments or the plan rule out is settled by their words; only a person-gate reason defers one. A run is never completed while its own review asks for changes on the head or with a deferred item lacking such a reason. A finished run's card never says it is working. CoderHelm adds pull request labels itself. | | bj. `bj_release_through_a_busy_hour` | Two repositories' Security pages read hundreds of findings "in a pull request" for two days, through two releases meant to give them back. The sweep that compares findings with GitHub logged only when it changed something, so a sweep that found every pull request still open left no trace; and while GitHub's budget was low it was held before its first read, three sweeps in a row. Both pull requests were in fact open. | Every sweep leaves one line with what it read, what GitHub said (open, merged, closed, unanswered), what it changed and what it left. A held budget slows the release and never stops it: a few reads a sweep go on a small allowance of their own (`github_budget::caller::FLOOR`), in a turn that reaches every pull request within a few sweeps. | | bk. `bk_owns_the_outside_work` | A run with its pull request open ended waiting on people and its ticket comment handed over work CoderHelm could do: reading workflow runs, a lint, page checks (all failing on one 400 because a page check written as the confirm "query" was sent to the CMS's GROQ API), the production release (a tag after one approval), a review look, and a step number the ticket never showed; it opened on a raw Jira account id and counted nothing as handed over. | Each outside step's action comes from its own words; a failed attempt reaches a person only for a permission or credential in its own cause; a tool failure is diagnosed and reported once and its steps take another way; the release is one approval; a run waits on a person only with a gate-approved item and nothing it can still do; every comment, description, chat message and outside report passes the sink check; replies show names, never account ids; the team's history replays with no doable item reaching a person. | +| bm. `bm_teams_never_cross` | An audit of every event path found four keys that named a shared thing instead of the team: any team admin could point a Slack workspace at their own team and take another team's slash commands; the run page's GitHub check reads were cached by repository name, so a same-named repository was served another installation's cached checks; model-written replies were cached by Jira ticket key and comment id, which two Jira sites can share; and run events were keyed by run id with no team on the row. | Every inbound route resolves its team from something only that team holds (a signed installation, a per-team token or secret, a claim no other team can overwrite) and drops an event no team owns. A Slack workspace or Teams webhook is claimed by one team at a time (`common::plugins::flag::claim_chat`) and routes only while that team still names it. Every process-wide cache is keyed by the credential or team that read it, and a reply is reused only for the exact prompt it was written from. Every run event row names its team and reads keep only the asking team's rows (`common::run_events`). Source scans fail on a new inbound route, a new cache or a direct events table access that does not say how it stays in its team. | ## Adding a case diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 4f9c3fc6b..9f5a16d3b 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -245,6 +245,7 @@ pub mod reviewer_prefs; /// examples and evidence-backed lessons, per team. pub mod rewards; /// The one way a run is marked failed: always with a reason and a pass. +pub mod run_events; pub mod run_fail; /// The questions a run asks when it needs a person's answer, and the /// answers people give in CoderHelm. diff --git a/services/common/src/plugins/flag.rs b/services/common/src/plugins/flag.rs index 2531c139c..f1243dd01 100644 --- a/services/common/src/plugins/flag.rs +++ b/services/common/src/plugins/flag.rs @@ -119,11 +119,211 @@ pub async fn save_settings(kv: &dyn Kv, team: &str, s: &TeamSettings) -> Result< Ok(()) } +/// The chat index key for a Slack workspace. +pub fn slack_key(workspace: &str) -> String { + format!("slack|{workspace}") +} + +/// The chat index key for a Teams outgoing webhook token. +pub fn teams_key(token: &str) -> String { + format!("teams|{token}") +} + +/// The team a chat index key points at, with the record's revision. +async fn chat_owner(kv: &dyn Kv, key: &str) -> Result, Refusal> { + Ok(kv + .get(super::kv::CHAT_INDEX, key) + .await + .map_err(store_err)? + .and_then(|r| Some((r.data["team"].as_str()?.to_string(), r.rev)))) +} + +/// True when `team`'s own settings still name `key` (the index is only a +/// pointer; the team's settings are the truth). +async fn still_names(kv: &dyn Kv, team: &str, key: &str) -> bool { + match settings(kv, team).await { + Ok(s) => { + (!s.slack_team_id.is_empty() && slack_key(&s.slack_team_id) == key) + || (!s.teams_token.is_empty() && teams_key(&s.teams_token) == key) + } + // Unreadable: treat the claim as standing rather than hand it over. + Err(_) => true, + } +} + +/// Claims `key` in the chat index for `team`. A key another team holds, +/// and still names in its settings, is refused: one workspace or webhook +/// routes to one team. A pointer its team no longer names is taken over. +pub async fn claim_chat(kv: &dyn Kv, team: &str, key: &str) -> Result<(), Refusal> { + use super::kv::{KvError, CHAT_INDEX}; + let taken = || { + Refusal::new( + code::CONFLICT, + "That Slack workspace or Teams webhook is already linked to another CoderHelm team. Unlink it there first.", + ) + }; + let data = serde_json::json!({ "team": team }); + let expect = match chat_owner(kv, key).await? { + None => Expect::Absent, + Some((owner, _)) if owner == team => return Ok(()), + Some((owner, rev)) => { + if still_names(kv, &owner, key).await { + return Err(taken()); + } + Expect::Rev(rev) + } + }; + match kv.put(CHAT_INDEX, key, &data, expect).await { + Ok(_) => Ok(()), + // Someone claimed it meanwhile: theirs. + Err(KvError::Conflict) => match chat_owner(kv, key).await? { + Some((owner, _)) if owner == team => Ok(()), + _ => Err(taken()), + }, + Err(e) => Err(store_err(e)), + } +} + +/// Drops `key` from the chat index, only while it points at `team`. +pub async fn release_chat(kv: &dyn Kv, team: &str, key: &str) -> Result<(), Refusal> { + if let Some((owner, _)) = chat_owner(kv, key).await? { + if owner == team { + kv.delete(super::kv::CHAT_INDEX, key) + .await + .map_err(store_err)?; + } + } + Ok(()) +} + +/// Points the Slack workspace `id` at `team` in the chat index, and drops the +/// team's previous workspace from it. Empty `id` unlinks. A workspace +/// another team holds is refused and the settings are left as they were. +pub async fn link_slack( + kv: &dyn Kv, + team: &str, + s: &mut TeamSettings, + id: &str, +) -> Result<(), Refusal> { + if id == s.slack_team_id { + if !id.is_empty() { + claim_chat(kv, team, &slack_key(id)).await?; + } + return Ok(()); + } + if !id.is_empty() { + claim_chat(kv, team, &slack_key(id)).await?; + } + if !s.slack_team_id.is_empty() { + release_chat(kv, team, &slack_key(&s.slack_team_id)).await?; + } + s.slack_team_id = id.to_string(); + Ok(()) +} + +/// Gives the team a fresh Teams webhook token and claims it. +pub async fn link_teams(kv: &dyn Kv, team: &str, s: &mut TeamSettings) -> Result<(), Refusal> { + let token = super::new_id(); + claim_chat(kv, team, &teams_key(&token)).await?; + s.teams_token = token; + Ok(()) +} + +/// The team an inbound chat message is for: the index's team, only while +/// that team's settings still name the key. +pub async fn chat_team(kv: &dyn Kv, key: &str) -> Option { + let (team, _) = chat_owner(kv, key).await.ok().flatten()?; + let s = settings(kv, &team).await.ok()?; + let named = (!s.slack_team_id.is_empty() && slack_key(&s.slack_team_id) == key) + || (!s.teams_token.is_empty() && teams_key(&s.teams_token) == key); + named.then_some(team) +} + #[cfg(test)] mod tests { use super::*; use crate::plugins::kv::Memory; + /// Team B naming team A's Slack workspace must not take A's slash + /// commands, and B unlinking must not cut A off. + #[tokio::test] + async fn a_slack_workspace_belongs_to_the_team_that_linked_it() { + let kv = Memory::new(); + let mut a = TeamSettings::default(); + link_slack(&kv, "TEAM#a", &mut a, "T0SHARED").await.unwrap(); + save_settings(&kv, "TEAM#a", &a).await.unwrap(); + + let mut b = TeamSettings::default(); + let taken = link_slack(&kv, "TEAM#b", &mut b, "T0SHARED").await; + assert!(taken.is_err(), "B may not claim A's workspace"); + assert_eq!(b.slack_team_id, "", "B's settings keep no claim"); + assert_eq!( + chat_team(&kv, &slack_key("T0SHARED")).await.as_deref(), + Some("TEAM#a") + ); + + // B pretends it had the workspace and unlinks it: A keeps it. + let mut forged = TeamSettings { + slack_team_id: "T0SHARED".into(), + ..Default::default() + }; + link_slack(&kv, "TEAM#b", &mut forged, "").await.unwrap(); + assert_eq!( + chat_team(&kv, &slack_key("T0SHARED")).await.as_deref(), + Some("TEAM#a") + ); + } + + /// A pointer the old team no longer names (it moved to another + /// workspace, or the record was left behind) is taken over, and a + /// pointer that disagrees with its team's settings routes nowhere. + #[tokio::test] + async fn a_stale_pointer_routes_nowhere_and_can_be_claimed() { + use crate::plugins::kv::CHAT_INDEX; + let kv = Memory::new(); + // Left behind by an older build: points at A, A's settings say nothing. + kv.put( + CHAT_INDEX, + &slack_key("T0MOVED"), + &serde_json::json!({"team": "TEAM#a"}), + Expect::Any, + ) + .await + .unwrap(); + assert_eq!(chat_team(&kv, &slack_key("T0MOVED")).await, None); + let mut b = TeamSettings::default(); + link_slack(&kv, "TEAM#b", &mut b, "T0MOVED").await.unwrap(); + save_settings(&kv, "TEAM#b", &b).await.unwrap(); + assert_eq!( + chat_team(&kv, &slack_key("T0MOVED")).await.as_deref(), + Some("TEAM#b") + ); + } + + #[tokio::test] + async fn a_teams_webhook_token_routes_to_its_own_team() { + let kv = Memory::new(); + let mut a = TeamSettings::default(); + link_teams(&kv, "TEAM#a", &mut a).await.unwrap(); + save_settings(&kv, "TEAM#a", &a).await.unwrap(); + let mut b = TeamSettings::default(); + link_teams(&kv, "TEAM#b", &mut b).await.unwrap(); + save_settings(&kv, "TEAM#b", &b).await.unwrap(); + assert_ne!(a.teams_token, b.teams_token); + assert_eq!( + chat_team(&kv, &teams_key(&a.teams_token)).await.as_deref(), + Some("TEAM#a") + ); + assert_eq!( + chat_team(&kv, &teams_key(&b.teams_token)).await.as_deref(), + Some("TEAM#b") + ); + // B can't claim A's token. + assert!(claim_chat(&kv, "TEAM#b", &teams_key(&a.teams_token)) + .await + .is_err()); + } + #[tokio::test] async fn off_by_default_and_per_team() { let kv = Memory::new(); diff --git a/services/common/src/reply_compose.rs b/services/common/src/reply_compose.rs index 19c4be805..10d8c699b 100644 --- a/services/common/src/reply_compose.rs +++ b/services/common/src/reply_compose.rs @@ -918,13 +918,20 @@ pub fn finish( pub static CACHE: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); -fn cache_key(place: &Place, to: Option<&Heard>, say: &Say, meta: &Meta) -> String { +/// The cache key: the thread, the comment, the slot and the draft, plus a +/// hash of the whole prompt the reply is written from. Thread keys are not +/// unique across teams (two Jira sites can both have `ABC-1` and the same +/// comment id), so a reply is only ever reused for the exact thread text, +/// draft and facts it was written from. +fn cache_key(place: &Place, to: Option<&Heard>, say: &Say, meta: &Meta, prompt: &str) -> String { + use sha2::{Digest, Sha256}; format!( - "{}#{}#{}#{}", + "{}#{}#{}#{}#{}", place.key(), to.map(|h| h.id.as_str()).unwrap_or("-"), say.slot, - meta.fp + meta.fp, + hex::encode(Sha256::digest(prompt.as_bytes())) ) } @@ -937,14 +944,12 @@ pub async fn composed( place: &Place, meta: &Meta, ) -> Option { - let key = cache_key(place, to, say, meta); + let asked = prompt(view, to, say, c.facts, place); + let key = cache_key(place, to, say, meta, &asked); if let Some(hit) = CACHE.lock().ok().and_then(|m| m.get(&key).cloned()) { return Some(hit); } - let v = c - .composer - .compose(SYSTEM, &prompt(view, to, say, c.facts, place), &schema()) - .await?; + let v = c.composer.compose(SYSTEM, &asked, &schema()).await?; let (act, raw) = parse(&v)?; let g = Grounds::new(c.facts, &say.body, view, &say.asks); let out = match act { @@ -1170,6 +1175,39 @@ mod tests { assert_eq!(without_greeting("@dana-reyes: done.", Some(&to)), "Done."); } + /// Two teams on different Jira sites can both have ticket `ABC-1` and a + /// comment with the same id. A reply written from team A's thread must + /// never be served for team B's. + #[test] + fn a_cached_reply_never_crosses_threads_with_the_same_ticket_key() { + let place = Place::jira("ABC-1"); + let heard = |text: &str| Heard { + id: "10001".into(), + author: "pat".into(), + text: text.into(), + ..Default::default() + }; + let say = Say::reply_all("run", "Working on it."); + let meta = Meta { + slot: "run".into(), + fp: "same".into(), + ..Default::default() + }; + let key = |to: &Heard| { + let view = View { + said: vec![], + heard: vec![to.clone()], + }; + let p = prompt(&view, Some(to), &say, &Facts::default(), &place); + cache_key(&place, Some(to), &say, &meta, &p) + }; + let a_to = heard("Team A: the invoice totals are off by a cent."); + let b_to = heard("Team B: please rename the onboarding banner."); + assert_ne!(key(&a_to), key(&b_to), "team B would get team A's reply"); + // The same thread asks again: the cached reply is reused. + assert_eq!(key(&a_to), key(&a_to)); + } + #[test] fn the_prompt_is_bounded() { let long = "word ".repeat(5_000); diff --git a/services/common/src/run_events.rs b/services/common/src/run_events.rs new file mode 100644 index 000000000..6a5bf6a7a --- /dev/null +++ b/services/common/src/run_events.rs @@ -0,0 +1,125 @@ +//! A run's events (CI results, live tool calls) in the events table, under +//! `RUN#`, each row stamped with the team that owns the run. +//! +//! The key holds only the run id, so a run id that ever named runs of two +//! teams would share one partition. Every row therefore carries `team_id`, +//! and every read keeps only the rows of the team that asked +//! ([`owned_by`]). All access goes through this module: a source scan +//! (incident case `bl_team_isolation`) fails on a direct read or write of the +//! events table anywhere else. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; + +/// The attribute that names the run's team on every row. +pub const TEAM_ATTR: &str = "team_id"; + +/// Rows written before every row carried a team are kept until this day; +/// the table's 30-day TTL has removed them all by then. After it, a row +/// with no team is never shown. +pub const UNSTAMPED_UNTIL: &str = "2026-12-20"; + +/// The partition of one run's events. +pub fn pk(run_id: &str) -> String { + format!("RUN#{run_id}") +} + +/// A write of one event row for `team`'s run, with its key and team set. +pub fn put( + client: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + run_id: &str, + sk: &str, +) -> aws_sdk_dynamodb::operation::put_item::builders::PutItemFluentBuilder { + client + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(pk(run_id))) + .item("sk", AttributeValue::S(sk.to_string())) + .item(TEAM_ATTR, AttributeValue::S(team_id.to_string())) +} + +/// A query of one run's rows whose sort key starts with `prefix`. The rows +/// it returns must pass [`owned_by`] before they are used. +pub fn query( + client: &aws_sdk_dynamodb::Client, + table: &str, + run_id: &str, + prefix: &str, +) -> aws_sdk_dynamodb::operation::query::builders::QueryFluentBuilder { + client + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :prefix)") + .expression_attribute_values(":pk", AttributeValue::S(pk(run_id))) + .expression_attribute_values(":prefix", AttributeValue::S(prefix.to_string())) +} + +/// An update of one row, by the key a read that passed [`owned_by`] gave. +pub fn update( + client: &aws_sdk_dynamodb::Client, + table: &str, + run_id: &str, + sk: &str, +) -> aws_sdk_dynamodb::operation::update_item::builders::UpdateItemFluentBuilder { + client + .update_item() + .table_name(table) + .key("pk", AttributeValue::S(pk(run_id))) + .key("sk", AttributeValue::S(sk.to_string())) +} + +/// True when the row belongs to `team_id`. A row from before rows were +/// stamped counts as the asking team's only until [`UNSTAMPED_UNTIL`] +/// (`today` is `YYYY-MM-DD`); the caller has already checked that the run +/// itself is the team's. +pub fn owned_by(item: &HashMap, team_id: &str, today: &str) -> bool { + match item.get(TEAM_ATTR).and_then(|v| v.as_s().ok()) { + Some(t) => !team_id.is_empty() && t == team_id, + None => today < UNSTAMPED_UNTIL, + } +} + +/// Today as `YYYY-MM-DD`, for [`owned_by`]. +pub fn today() -> String { + chrono::Utc::now().format("%Y-%m-%d").to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(team: Option<&str>) -> HashMap { + let mut m = HashMap::from([("pk".to_string(), AttributeValue::S(pk("01RUN")))]); + if let Some(t) = team { + m.insert(TEAM_ATTR.to_string(), AttributeValue::S(t.to_string())); + } + m + } + + #[test] + fn a_row_is_only_ever_its_teams() { + let a = row(Some("TEAM#a")); + assert!(owned_by(&a, "TEAM#a", "2026-11-15")); + assert!( + !owned_by(&a, "TEAM#b", "2026-11-15"), + "B never sees A's row" + ); + assert!(!owned_by(&a, "", "2026-11-15")); + } + + #[test] + fn unstamped_rows_expire_with_the_ttl() { + let old = row(None); + assert!(owned_by(&old, "TEAM#a", "2026-11-15")); + assert!(!owned_by(&old, "TEAM#a", UNSTAMPED_UNTIL)); + assert!(!owned_by(&old, "TEAM#a", "2027-01-01")); + } + + #[test] + fn the_partition_is_the_run() { + assert_eq!(pk("01RUN"), "RUN#01RUN"); + } +} diff --git a/services/gateway/src/auth/jwt.rs b/services/gateway/src/auth/jwt.rs index 46c25a02c..c5bcad85d 100644 --- a/services/gateway/src/auth/jwt.rs +++ b/services/gateway/src/auth/jwt.rs @@ -167,6 +167,10 @@ pub fn validate_second_step( /// `/api/brain/stream`, never as a session or a plan chat token. pub const BRAIN_AUDIENCE: &str = "coderhelm-brain"; +/// Audience of the plan chat's short-lived stream token: accepted only by +/// `/api/plans/chat/stream`, never as a session or a brain token. +pub const PLAN_CHAT_AUDIENCE: &str = "coderhelm-plan-chat"; + /// A short-lived token for `audience` carrying the member's stored role. pub fn create_scoped_token( claims: &Claims, @@ -316,6 +320,19 @@ mod tests { assert_eq!((back.sub.as_str(), back.role.as_str()), ("u", "member")); } + #[test] + fn a_plan_chat_token_opens_only_the_plan_chat_stream() { + let secret = "test-jwt-secret-at-least-32-chars!"; + let session = create_token("u", "TEAM#a", "e@x.com", "member", None, secret, 300).unwrap(); + let claims = validate_token(&session, secret).unwrap(); + let plan = create_scoped_token(&claims, PLAN_CHAT_AUDIENCE, secret, 300).unwrap(); + assert!(validate_token(&plan, secret).is_err(), "never a session"); + assert!(validate_scoped_token(&plan, BRAIN_AUDIENCE, secret).is_err()); + assert!(validate_scoped_token(&session, PLAN_CHAT_AUDIENCE, secret).is_err()); + let back = validate_scoped_token(&plan, PLAN_CHAT_AUDIENCE, secret).unwrap(); + assert_eq!(back.team_id, "TEAM#a"); + } + #[test] fn a_session_carries_its_sign_in_proof_and_old_tokens_have_none() { let secret = "test-jwt-secret-at-least-32-chars!"; diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index d49ec6915..8b4d20237 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -2068,13 +2068,12 @@ pub async fn get_agent_log( let mut live_events: Vec = Vec::new(); let mut live_events_truncated = false; if !state.config.events_table_name.is_empty() { - let query = state - .dynamo - .query() - .table_name(&state.config.events_table_name) - .key_condition_expression("pk = :pk AND begins_with(sk, :prefix)") - .expression_attribute_values(":pk", attr_s(&format!("RUN#{run_id}"))) - .expression_attribute_values(":prefix", attr_s("TOOL#")); + let query = common::run_events::query( + &state.dynamo, + &state.config.events_table_name, + &run_id, + "TOOL#", + ); match common::paged::all_pages( |start| { let q = query.clone().set_exclusive_start_key(start); @@ -2092,7 +2091,11 @@ pub async fn get_agent_log( { Ok((items, more)) => { live_events_truncated = more; - for item in &items { + let today = common::run_events::today(); + for item in items + .iter() + .filter(|item| common::run_events::owned_by(item, &claims.team_id, &today)) + { let payload: Value = item .get("payload") .and_then(|v| v.as_s().ok()) diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 890b0636c..1c88858a0 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1488,6 +1488,7 @@ async fn handle_issue_comment( // Write event for resume flow write_run_event( state, + team_id, &run_id, "pr_comment", &serde_json::json!({ @@ -1746,6 +1747,7 @@ async fn resume_outstanding( } write_run_event( state, + team_id, run_id, "pr_comment", &serde_json::json!({ @@ -2859,6 +2861,7 @@ async fn handle_pr_review( let review_id = payload["review"]["id"].as_u64().unwrap_or(0); write_run_event( state, + team_id, &run_id, "pr_review", &serde_json::json!({ @@ -3483,22 +3486,23 @@ async fn handle_workflow_run( "head_sha": wf["head_sha"].as_str().unwrap_or(""), }); - if let Err(e) = state - .dynamo - .put_item() - .table_name(&state.config.events_table_name) - .item("pk", attr_s(&format!("RUN#{run_id}"))) - .item("sk", attr_s(&event_sk)) - .item("event_type", attr_s(event_type)) - .item("payload", attr_s(&event_payload.to_string())) - .item( - "processed", - aws_sdk_dynamodb::types::AttributeValue::Bool(false), - ) - .item("created_at", attr_s(&now.to_rfc3339())) - .item("expires_at", attr_n(now.timestamp() as u64 + 30 * 86400)) - .send() - .await + if let Err(e) = common::run_events::put( + &state.dynamo, + &state.config.events_table_name, + team_id, + &run_id, + &event_sk, + ) + .item("event_type", attr_s(event_type)) + .item("payload", attr_s(&event_payload.to_string())) + .item( + "processed", + aws_sdk_dynamodb::types::AttributeValue::Bool(false), + ) + .item("created_at", attr_s(&now.to_rfc3339())) + .item("expires_at", attr_n(now.timestamp() as u64 + 30 * 86400)) + .send() + .await { error!("Failed to write CI event: {e}"); return Err(StatusCode::INTERNAL_SERVER_ERROR); @@ -4649,6 +4653,7 @@ pub(crate) async fn send_to_queue_after( /// Write a run event to the events table for the resume flow. async fn write_run_event( state: &AppState, + team_id: &str, run_id: &str, event_type: &str, payload: &serde_json::Value, @@ -4659,22 +4664,23 @@ async fn write_run_event( let now = chrono::Utc::now(); let event_sk = format!("EVENT#{}#{}", now.format("%Y%m%dT%H%M%S%.3fZ"), event_type); - if let Err(e) = state - .dynamo - .put_item() - .table_name(&state.config.events_table_name) - .item("pk", attr_s(&format!("RUN#{run_id}"))) - .item("sk", attr_s(&event_sk)) - .item("event_type", attr_s(event_type)) - .item("payload", attr_s(&payload.to_string())) - .item( - "processed", - aws_sdk_dynamodb::types::AttributeValue::Bool(false), - ) - .item("created_at", attr_s(&now.to_rfc3339())) - .item("expires_at", attr_n(now.timestamp() as u64 + 30 * 86400)) - .send() - .await + if let Err(e) = common::run_events::put( + &state.dynamo, + &state.config.events_table_name, + team_id, + run_id, + &event_sk, + ) + .item("event_type", attr_s(event_type)) + .item("payload", attr_s(&payload.to_string())) + .item( + "processed", + aws_sdk_dynamodb::types::AttributeValue::Bool(false), + ) + .item("created_at", attr_s(&now.to_rfc3339())) + .item("expires_at", attr_n(now.timestamp() as u64 + 30 * 86400)) + .send() + .await { error!("Failed to write run event: {e}"); } diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index b80c82e5e..4ac5fc438 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -2375,12 +2375,11 @@ pub async fn stream_token( // Mint a short-lived token (5 minutes) scoped for streaming // The record's role, never the role this request runs as: the token // must not carry more than the member's own role. - let token = crate::auth::jwt::create_token( - &claims.sub, - &claims.team_id, - &claims.email, - claims.session_role(), - claims.github_login.as_deref(), + // Scoped to the plan chat stream: it is never a session, and a session + // is never a stream token. + let token = crate::auth::jwt::create_scoped_token( + &claims, + crate::auth::jwt::PLAN_CHAT_AUDIENCE, &state.secrets.jwt_secret, 300, // 5 minutes ) @@ -3562,11 +3561,15 @@ pub async fn plan_chat_stream( StatusCode::UNAUTHORIZED })?; - let claims = - crate::auth::jwt::validate_token(token, &state.secrets.jwt_secret).map_err(|e| { - warn!("plan_chat_stream: JWT validation failed: {e}"); - StatusCode::UNAUTHORIZED - })?; + let claims = crate::auth::jwt::validate_scoped_token( + token, + crate::auth::jwt::PLAN_CHAT_AUDIENCE, + &state.secrets.jwt_secret, + ) + .map_err(|e| { + warn!("plan_chat_stream: JWT validation failed: {e}"); + StatusCode::UNAUTHORIZED + })?; let messages_input = body["messages"].as_array().ok_or_else(|| { warn!("plan_chat_stream: missing messages array in body"); diff --git a/services/gateway/src/routes/plugin_pkgs.rs b/services/gateway/src/routes/plugin_pkgs.rs index dc6611c44..ad8ef4919 100644 --- a/services/gateway/src/routes/plugin_pkgs.rs +++ b/services/gateway/src/routes/plugin_pkgs.rs @@ -20,7 +20,6 @@ use axum::{ response::{Html, IntoResponse, Response}, Extension, Json, }; -use common::plugins::kv::Kv; use common::plugins::source::{self, Track}; use common::plugins::{ audit, brain, chat, code, drafts, flag, install, kv, limits, run, schedule, signed, Refusal, @@ -294,22 +293,9 @@ pub async fn put_settings( "That isn't a Slack workspace id.", ))); } - if !s.slack_team_id.is_empty() { - let _ = kv - .delete(kv::CHAT_INDEX, &format!("slack|{}", s.slack_team_id)) - .await; - } - if !id.is_empty() { - kv.put( - kv::CHAT_INDEX, - &format!("slack|{id}"), - &json!({ "team": team }), - kv::Expect::Any, - ) + flag::link_slack(&kv, team, &mut s, &id) .await - .map_err(|e| refused(Refusal::new(code::STORE, e.to_string())))?; - } - s.slack_team_id = id; + .map_err(refused)?; } if let Some(sec) = body.slack_signing_secret.filter(|x| !x.trim().is_empty()) { s.slack_signing_secret_sealed = seal("plugin-slack", sec.trim().to_string()).await?; @@ -317,15 +303,7 @@ pub async fn put_settings( if let Some(sec) = body.teams_secret.filter(|x| !x.trim().is_empty()) { s.teams_secret_sealed = seal("plugin-teams", sec.trim().to_string()).await?; if s.teams_token.is_empty() { - s.teams_token = common::plugins::new_id(); - kv.put( - kv::CHAT_INDEX, - &format!("teams|{}", s.teams_token), - &json!({ "team": team }), - kv::Expect::Any, - ) - .await - .map_err(|e| refused(Refusal::new(code::STORE, e.to_string())))?; + flag::link_teams(&kv, team, &mut s).await.map_err(refused)?; } } flag::save_settings(&kv, team, &s).await.map_err(refused)?; @@ -1624,17 +1602,6 @@ pub async fn email_approve( // ── Public: briefs from Slack and Teams (signature verified) ──────────────── -async fn chat_team(state: &AppState, key: &str) -> Option { - kv(state) - .get(kv::CHAT_INDEX, key) - .await - .ok() - .flatten()? - .data["team"] - .as_str() - .map(str::to_string) -} - async fn open_secret(state: &AppState, team: &str, purpose: &str, sealed: &str) -> Option { use base64::Engine; use common::mcp_credentials::Cipher; @@ -1700,7 +1667,7 @@ pub async fn slack_command( let form = chat::slack_form(&text); let slack_team = form.get("team_id").cloned().unwrap_or_default(); let refuse = || (StatusCode::UNAUTHORIZED, "Not verified").into_response(); - let Some(team) = chat_team(&state, &format!("slack|{slack_team}")).await else { + let Some(team) = flag::chat_team(&kv(&state), &flag::slack_key(&slack_team)).await else { return refuse(); }; let Ok(s) = flag::settings(&kv(&state), &team).await else { @@ -1765,7 +1732,7 @@ pub async fn teams_message( body: axum::body::Bytes, ) -> Response { let refuse = || (StatusCode::UNAUTHORIZED, "Not verified").into_response(); - let Some(team) = chat_team(&state, &format!("teams|{token}")).await else { + let Some(team) = flag::chat_team(&kv(&state), &flag::teams_key(&token)).await else { return refuse(); }; let Ok(s) = flag::settings(&kv(&state), &team).await else { diff --git a/services/gateway/src/routes/run_checks.rs b/services/gateway/src/routes/run_checks.rs index 6e7df7093..999374564 100644 --- a/services/gateway/src/routes/run_checks.rs +++ b/services/gateway/src/routes/run_checks.rs @@ -9,7 +9,9 @@ //! read goes through short in-memory caches: the pull request's head for //! [`PR_TTL`], the checks on a commit for [`CHECKS_TTL`] (keyed by repository //! and commit, see [`cache_key`]), the branch's required checks for -//! [`REQUIRED_TTL`], and the installation token for [`TOKEN_TTL`]. A read +//! [`REQUIRED_TTL`], and the installation token for [`TOKEN_TTL`]. Every +//! cached read is keyed by the installation that made it ([`read_key`]), so +//! a team only ever sees what its own installation could read. A read //! GitHub refused is cached as "nothing" for as long, so a limited install is //! not asked again on every poll. Anything that can't be read is `None`: the //! run itself is always returned. @@ -272,6 +274,13 @@ pub fn cache_key(repo: &str, sha: &str) -> String { format!("{}@{sha}", repo.to_ascii_lowercase()) } +/// Pure: the key of a cached GitHub read: the installation whose token made +/// it, then what was read. Two teams with a repository of the same name +/// (or one that lost access) never share an entry. +pub fn read_key(installation_id: u64, what: &str) -> String { + format!("{installation_id}|{what}") +} + /// Pure: the pull request the run's checks are for: its primary one, while /// it is open. `None` when the run has none or it has ended. pub fn open_pr(prs: &[common::run_prs::RunPr], run_repo: &str) -> Option<(String, u64)> { @@ -432,8 +441,17 @@ async fn get_ok(state: &AppState, token: &str, path: &str) -> Option { } } -async fn pr_head(state: &AppState, token: &str, repo: &str, pr: u64) -> Option { - let key = format!("{}#{pr}", repo.to_ascii_lowercase()); +async fn pr_head( + state: &AppState, + installation_id: u64, + token: &str, + repo: &str, + pr: u64, +) -> Option { + let key = read_key( + installation_id, + &format!("{}#{pr}", repo.to_ascii_lowercase()), + ); if let Some(h) = PR_HEADS.get(&key, Instant::now()) { return h; } @@ -452,8 +470,17 @@ async fn pr_head(state: &AppState, token: &str, repo: &str, pr: u64) -> Option

Vec { - let key = format!("{}:{base}", repo.to_ascii_lowercase()); +async fn required_checks( + state: &AppState, + installation_id: u64, + token: &str, + repo: &str, + base: &str, +) -> Vec { + let key = read_key( + installation_id, + &format!("{}:{base}", repo.to_ascii_lowercase()), + ); if let Some(r) = REQUIRED.get(&key, Instant::now()) { return r; } @@ -472,11 +499,12 @@ async fn required_checks(state: &AppState, token: &str, repo: &str, base: &str) async fn commit_checks( state: &AppState, + installation_id: u64, token: &str, repo: &str, sha: &str, ) -> Option> { - let key = cache_key(repo, sha); + let key = read_key(installation_id, &cache_key(repo, sha)); if let Some(c) = CHECKS.get(&key, Instant::now()) { return c; } @@ -506,13 +534,13 @@ async fn read_checks( pr: u64, ) -> Option { let token = token(state, installation_id).await?; - let head = pr_head(state, &token, repo, pr).await?; + let head = pr_head(state, installation_id, &token, repo, pr).await?; if !head.open || !head.sha.chars().all(|c| c.is_ascii_hexdigit()) { return None; } let (items, required) = tokio::join!( - commit_checks(state, &token, repo, &head.sha), - required_checks(state, &token, repo, &head.base), + commit_checks(state, installation_id, &token, repo, &head.sha), + required_checks(state, installation_id, &token, repo, &head.base), ); Some(with_required(&head.sha, items?, &required)) } @@ -551,7 +579,10 @@ pub async fn for_run( } async fn read_asks(state: &AppState, installation_id: u64, repo: &str, pr: u64) -> Option { - let key = format!("{}#{pr}", repo.to_ascii_lowercase()); + let key = read_key( + installation_id, + &format!("{}#{pr}", repo.to_ascii_lowercase()), + ); if let Some(n) = ASKS.get(&key, Instant::now()) { return n; } @@ -828,6 +859,16 @@ mod tests { assert_eq!(none.counts, RunCheckCounts::default()); } + #[test] + fn a_cached_read_belongs_to_the_installation_that_made_it() { + // Team A (installation 7) read acme/web's checks; team B (installation + // 8) asks about the same repository name. B must not get A's read. + let a = read_key(7, &cache_key("acme/web", "9fceb02")); + let b = read_key(8, &cache_key("acme/web", "9fceb02")); + assert_ne!(a, b, "team B would be served team A's cached checks"); + assert_eq!(a, read_key(7, &cache_key("Acme/Web", "9fceb02"))); + } + #[test] fn the_cache_key_is_the_repository_and_the_commit() { assert_eq!(cache_key("Acme/Web", "9fceb02"), "acme/web@9fceb02"); diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 73fa420ce..e7edc521c 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -931,14 +931,7 @@ pub async fn run( "started_at": started_at, "outcome": outcome, }); - let _ = dynamo - .put_item() - .table_name(&events_table) - .item( - "pk", - aws_sdk_dynamodb::types::AttributeValue::S(format!("RUN#{rid}")), - ) - .item("sk", aws_sdk_dynamodb::types::AttributeValue::S(sk)) + let _ = common::run_events::put(&dynamo, &events_table, &team, &rid, &sk) .item( "event_type", aws_sdk_dynamodb::types::AttributeValue::S("tool_call".to_string()), diff --git a/services/worker/src/passes/incidents/ax_github_budget.rs b/services/worker/src/passes/incidents/ax_github_budget.rs index 07139ac33..652ad845e 100644 --- a/services/worker/src/passes/incidents/ax_github_budget.rs +++ b/services/worker/src/passes/incidents/ax_github_budget.rs @@ -163,7 +163,7 @@ fn a_fix_round_that_meets_the_limit_waits_and_lands_after_the_reset() { assert!( known < run - .find("load_unprocessed_events(state, &msg.run_id)") + .find("load_unprocessed_events(state, &msg.team_id, &msg.run_id)") .unwrap() ); assert!( diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs new file mode 100644 index 000000000..102167902 --- /dev/null +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -0,0 +1,435 @@ +//! bm. An audit of every way an event reaches CoderHelm or leaves it found +//! four places where one team's data could reach another team, each through +//! a key that named a shared thing (a Slack workspace, a repository name, a +//! Jira ticket key, a run id) instead of the team: +//! +//! - Any team admin could point a Slack workspace id at their own team +//! (the chat index was overwritten), taking another team's slash commands +//! and cutting that team off. +//! - The run page's GitHub check reads were cached by repository name only: +//! a team asking about a repository with the same name was served another +//! installation's cached pull request head, checks and review asks. +//! - Replies the model wrote were cached by `JIRA#` and comment id: +//! two Jira sites with ticket `ABC-1` and the same comment id could get one +//! another's reply. +//! - A run's events (CI results, live tool calls) were keyed by run id only, +//! with no team on the row. +//! +//! Guarantee: every inbound event path resolves its team from something +//! only that team holds (a signed installation, a per-team token or secret, +//! a claim another team cannot overwrite) and drops an event no team owns; +//! a shared identifier is claimed by one team at a time; every process-wide +//! cache is keyed by the credential or team that read it; every run event +//! row names its team and every read keeps only the asking team's rows. The +//! scans below fail when a new inbound route, a new cache, or a direct +//! events table access is added without saying how it stays in its team. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use common::plugins::flag::{self, TeamSettings}; +use common::plugins::kv::Memory; + +use crate::team_installation::{claims, decide, single_team, Verdict}; + +const TEAM_A: &str = "TEAM#a"; +const TEAM_B: &str = "TEAM#b"; + +fn services() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("services dir") + .to_path_buf() +} + +fn read(rel: &str) -> String { + std::fs::read_to_string(services().join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}")) +} + +/// Every `.rs` file under `dir` (relative to services/), tests and the +/// incident cases left out. +fn sources(dir: &str) -> Vec<(String, String)> { + fn walk(root: &Path, p: &Path, out: &mut Vec<(String, String)>) { + let Ok(entries) = std::fs::read_dir(p) else { + return; + }; + for e in entries.flatten() { + let path = e.path(); + if path.is_dir() { + if path.file_name().is_some_and(|n| n == "incidents") { + continue; + } + walk(root, &path, out); + } else if path.extension().is_some_and(|x| x == "rs") { + let rel = path + .strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + out.push((rel, std::fs::read_to_string(&path).unwrap_or_default())); + } + } + } + let root = services(); + let mut out = Vec::new(); + walk(&root, &root.join(dir), &mut out); + out.sort(); + out +} + +/// The source of `name`'s body, from its signature to the next top-level +/// item. +fn body<'a>(src: &'a str, signature: &str) -> &'a str { + let at = src + .find(signature) + .unwrap_or_else(|| panic!("{signature} not found")); + let rest = &src[at..]; + let end = rest[1..].find("\n}\n").map(|e| e + 3).unwrap_or(rest.len()); + &rest[..end] +} + +// ── Inbound event paths ───────────────────────────────────────────────────── + +/// Every public inbound route, how it finds its team, and a line of its +/// handler that does it. A new route under `/webhooks` fails until it is +/// added here with its team check. +const INBOUND: &[(&str, &str, &str, &str)] = &[ + ( + "routes::github_webhook::handle", + "gateway/src/routes/github_webhook.rs", + "verify_github_signature(", + "the app's signature; the installation's recorded owner team (resolve_team_by_installation); no team, dropped", + ), + ( + "routes::jira_webhook::handle", + "gateway/src/routes/jira_webhook.rs", + ".key(\"token\", attr_s(&token))", + "a random per-team token claimed once, and the team's HMAC secret", + ), + ( + "routes::jira_webhook::handle_forge", + "gateway/src/routes/jira_webhook.rs", + "forge_secret_matches(stored_secret, request_secret)", + "the team named, proven by that team's own Forge secret; the work runs under the team's stored installation", + ), + ( + "routes::alerts::handle_sns", + "gateway/src/routes/alerts.rs", + "sns::verify(&state.http, &msg)", + "SNS signature; the topic's route, which one team claims at a time", + ), + ( + "routes::knowledge_sources::webhook", + "gateway/src/routes/knowledge_sources.rs", + "hook_target(&state, &token)", + "a per-source token and its signature; each team syncs only its own sources", + ), + ( + "routes::plugin_pkgs::slack_command", + "gateway/src/routes/plugin_pkgs.rs", + "flag::chat_team(", + "the workspace's one claiming team (flag::link_slack) and that team's signing secret", + ), + ( + "routes::plugin_pkgs::teams_message", + "gateway/src/routes/plugin_pkgs.rs", + "s.teams_token.as_bytes()", + "a random per-team token, matched to the team's current one, and its HMAC secret", + ), + ( + "routes::tests::ci_upload", + "gateway/src/routes/tests.rs", + "teams_for(&state, &claims)", + "a GitHub Actions OIDC token; only teams whose repo has the token's repository id", + ), + ( + "routes::tests::ci_quarantine", + "gateway/src/routes/tests.rs", + "teams_for(&state, &claims)", + "the same OIDC repository id match", + ), + ( + "routes::hybrid_install::intake", + "gateway/src/routes/hybrid_install.rs", + "only_team(&state)", + "the relay's signature; a self-hosted install has one team", + ), + ( + "routes::hybrid_install::proof", + "gateway/src/routes/hybrid_install.rs", + "pub async fn proof", + "returns the install's own ownership proof; no team data", + ), +]; + +#[test] +fn every_inbound_route_names_how_it_finds_its_team() { + let main = read("gateway/src/main.rs"); + let start = main + .find("let webhook_routes = Router::new()") + .expect("the webhook routes"); + let block: String = main[start..start + main[start..].find(";\n").unwrap()] + .lines() + .filter(|l| !l.trim_start().starts_with("//")) + .collect::>() + .join("\n"); + let handlers: Vec<&str> = block + .split(|c: char| c == '(' || c == ')' || c.is_whitespace() || c == ',') + .filter(|w| w.starts_with("routes::")) + .collect(); + assert!(handlers.len() >= 8, "{handlers:?}"); + for h in &handlers { + let known = INBOUND.iter().find(|(name, ..)| name == h); + assert!( + known.is_some(), + "{h} takes events from outside without a team check listed here (bm_teams_never_cross::INBOUND)" + ); + } + for (name, file, check, how) in INBOUND { + assert!(!how.is_empty()); + assert!( + read(file).contains(check), + "{name}: its team check `{check}` is gone from {file}" + ); + } +} + +#[test] +fn an_event_for_an_installation_no_team_owns_is_dropped() { + let src = read("gateway/src/routes/github_webhook.rs"); + let route = body(&src, "async fn route("); + let resolve = route + .find("resolve_team_by_installation(state, installation_id)") + .expect("routing resolves the installation's team"); + let dropped = route + .find("\"no_team\"") + .expect("no team is a failed, unrouted delivery"); + let dispatched = route.find("dispatch(").expect("dispatch"); + assert!(resolve < dropped && dropped < dispatched); + assert!( + route.contains("return (Ok(StatusCode::OK), String::new());"), + "an unowned event is recorded under no team" + ); +} + +// ── Queued work ───────────────────────────────────────────────────────────── + +#[test] +fn a_message_pairing_one_team_with_another_teams_installation_is_refused() { + // Team A owns installation 7, team B owns 8 (same repository name on both). + let forged = serde_json::json!({ + "type": "ticket", + "team_id": TEAM_A, + "installation_id": 8, + "repo_name": "web", + }); + let (ids, teams) = claims(&forged); + let team = single_team(&teams).unwrap(); + assert!(matches!(decide(&ids, team, Some(7)), Verdict::Refuse(_))); + // A message that names both teams never runs. + let mixed = serde_json::json!({"team_id": TEAM_A, "action": {"team_id": TEAM_B}}); + assert!(single_team(&claims(&mixed).1).is_err()); + // The check runs at dispatch for every message. + let main = include_str!("../../main.rs"); + assert!(main.contains("installation_is_teams_own(&state, &raw)")); +} + +// ── Shared identifiers are claimed by one team ────────────────────────────── + +#[tokio::test] +async fn one_slack_workspace_routes_to_one_team() { + let kv = Memory::new(); + let mut a = TeamSettings::default(); + flag::link_slack(&kv, TEAM_A, &mut a, "T0SHARED") + .await + .unwrap(); + flag::save_settings(&kv, TEAM_A, &a).await.unwrap(); + + let mut b = TeamSettings::default(); + assert!(flag::link_slack(&kv, TEAM_B, &mut b, "T0SHARED") + .await + .is_err()); + assert_eq!( + flag::chat_team(&kv, &flag::slack_key("T0SHARED")) + .await + .as_deref(), + Some(TEAM_A), + "team B never receives team A's slash commands" + ); + + // Only flag.rs writes the chat index. + for (file, src) in sources("gateway/src") + .into_iter() + .chain(sources("worker/src")) + .chain(sources("common/src")) + { + if file.ends_with("plugins/flag.rs") || file.ends_with("plugins/kv.rs") { + continue; + } + assert!( + !src.contains("CHAT_INDEX"), + "{file} touches the chat index outside flag::link_slack / link_teams" + ); + } +} + +// ── Run events ────────────────────────────────────────────────────────────── + +#[test] +fn a_reused_run_id_never_shows_another_teams_events() { + use aws_sdk_dynamodb::types::AttributeValue; + use std::collections::HashMap; + let row = |team: &str| { + HashMap::from([ + ( + "pk".to_string(), + AttributeValue::S(common::run_events::pk("01SAME")), + ), + ( + common::run_events::TEAM_ATTR.to_string(), + AttributeValue::S(team.to_string()), + ), + ]) + }; + let today = "2026-11-15"; + assert!(common::run_events::owned_by(&row(TEAM_A), TEAM_A, today)); + assert!(!common::run_events::owned_by(&row(TEAM_B), TEAM_A, today)); +} + +#[test] +fn the_events_table_is_only_reached_through_run_events() { + for (file, src) in sources("gateway/src") + .into_iter() + .chain(sources("worker/src")) + .chain(sources("common/src")) + { + if file.ends_with("common/src/run_events.rs") { + continue; + } + for needle in [ + ".table_name(&state.config.events_table_name)", + ".table_name(&events_table)", + ] { + assert!( + !src.contains(needle), + "{file} reads or writes the events table directly; use common::run_events" + ); + } + if src.contains("run_events::query(") { + assert!( + src.contains("run_events::owned_by("), + "{file} reads run events without keeping only its team's rows" + ); + } + } +} + +// ── Process-wide caches ───────────────────────────────────────────────────── + +/// Every process-wide map or cache, and what keeps one team out of +/// another's entries. A new one fails until it is listed with its key. +const CACHES: &[(&str, &str)] = &[ + ("common/src/agent_policy/registry.rs::REGISTERED", "tool registrations by provider; no team data"), + ("common/src/github_grants.rs::KNOWN", "installation id"), + ("common/src/hybrid/client.rs::TOKENS", "installation id"), + ("common/src/hybrid/client.rs::FAILING", "installation id"), + ("common/src/knowledge/search.rs::C", "S3 key under `{team}/knowledge/`, checked by owns_key before the lookup"), + ("common/src/knowledge/sources/pace.rs::GATES", "provider rate gate; no data"), + ("common/src/reply_compose.rs::CACHE", "thread key plus a hash of the whole prompt it was written from"), + ("common/src/review_check.rs::REFUSED", "installation id"), + ("common/src/usage.rs::P", "model prices; install-wide config"), + ("common/src/usage.rs::WARNED", "model id; log throttle"), + ("gateway/src/mcp_server.rs::SEEN", "grant or key id; throttle"), + ("gateway/src/middleware/auth.rs::SEEN", "(team, user); throttle"), + ("gateway/src/middleware/rate_limit.rs::RATE_STORE", "client or grant id; counts only"), + ("gateway/src/permissions.rs::ROUTES", "route table; no data"), + ("gateway/src/routes/chat_work_prs.rs::CACHE", "URL, reused only on a 304 to the team's own token; repo checked against the team's repos first"), + ("gateway/src/routes/github_webhook.rs::SEEN", "installation id; log throttle"), + ("gateway/src/routes/roles.rs::CACHE", "(team, role)"), + ("gateway/src/routes/run_checks.rs::TOKENS", "installation id"), + ("gateway/src/routes/run_checks.rs::PR_HEADS", "installation id (read_key)"), + ("gateway/src/routes/run_checks.rs::CHECKS", "installation id (read_key)"), + ("gateway/src/routes/run_checks.rs::REQUIRED", "installation id (read_key)"), + ("gateway/src/routes/run_checks.rs::ASKS", "installation id (read_key)"), + ("gateway/src/routes/sns.rs::CACHE", "SNS certificate URL; public keys"), + ("gateway/src/routes/support_access.rs::C", "team id"), + ("worker/src/agent/run_log.rs::CURRENT", "run id (a ULID)"), + ("worker/src/clients/github.rs::BUDGETS", "installation id"), + ("worker/src/clients/github.rs::LIMITED", "installation id"), + ("worker/src/clients/github_budget.rs::LEDGER", "installation id"), + ("worker/src/passes/conversation.rs::CACHE", "GitHub `owner/repo#n`: the thread itself, read with the run's own installation"), + ("worker/src/passes/conversation.rs::REPLIED", "GitHub `owner/repo#n`: the thread itself"), + ("worker/src/passes/conversation.rs::REVIEW_COMMENTS", "GitHub `owner/repo#n`: the thread itself"), + ("worker/src/passes/run_guard.rs::REENTRY", "run id (a ULID)"), + ("worker/src/passes/stop_gate.rs::DIAGNOSES", "run id (a ULID)"), +]; + +#[test] +fn every_process_wide_cache_is_keyed_by_its_team_or_credential() { + let mut found: BTreeMap = BTreeMap::new(); + for (file, src) in sources("gateway/src") + .into_iter() + .chain(sources("worker/src")) + .chain(sources("common/src")) + { + let lines: Vec<&str> = src.lines().collect(); + for (i, line) in lines.iter().enumerate() { + let t = line.trim_start(); + let t = t + .strip_prefix("pub(crate) ") + .or_else(|| t.strip_prefix("pub ")) + .unwrap_or(t); + let Some(rest) = t.strip_prefix("static ") else { + continue; + }; + let name: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + let decl = lines[i..lines.len().min(i + 3)].join(" "); + let decl = &decl[..decl.find(" = ").unwrap_or(decl.len())]; + let keyed = [ + "HashMap<", + "HashSet<", + "BTreeMap<", + "TtlCache<", + "IndexCache", + "PackCache", + "Cache>", + ] + .iter() + .any(|k| decl.contains(k)); + if keyed { + found.insert(format!("{file}::{name}"), decl.to_string()); + } + } + } + for (key, decl) in &found { + assert!( + CACHES.iter().any(|(k, why)| k == key && !why.is_empty()), + "{key} is a process-wide cache with no listed key scope (bm_teams_never_cross::CACHES): {decl}" + ); + } + for (k, _) in CACHES { + assert!(found.contains_key(*k), "{k} is listed but no longer exists"); + } +} + +#[test] +fn run_check_reads_are_keyed_by_the_installation() { + let src = read("gateway/src/routes/run_checks.rs"); + for cache in ["PR_HEADS", "CHECKS", "REQUIRED", "ASKS"] { + for (i, _) in src.match_indices(&format!("{cache}.get(")) { + let before = &src[..i]; + let fn_start = before.rfind("\nasync fn ").unwrap_or(0); + let fn_src: String = src[fn_start..i] + .chars() + .filter(|c| !c.is_whitespace()) + .collect(); + assert!( + fn_src.contains("read_key(installation_id"), + "{cache} is read with a key that doesn't name the installation" + ); + } + } +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index d47aa93f0..aec95158f 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -51,6 +51,7 @@ mod bh_round_checks_and_scope; mod bi_own_review_finishes; mod bj_release_through_a_busy_hour; mod bk_owns_the_outside_work; +mod bm_teams_never_cross; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index f3cf96975..9e4d8be11 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -9163,7 +9163,7 @@ async fn after_pr_outside_work( ) .await; if let Some(f) = &p.failed_e2e { - outside_exec::record_failed(state, run_id, f).await; + outside_exec::record_failed(state, &msg.team_id, run_id, f).await; } outside_exec::report_problems(state, &msg.team_id, run_id, &p).await; } diff --git a/services/worker/src/passes/outside_exec.rs b/services/worker/src/passes/outside_exec.rs index 1938e2b17..7ff1fa119 100644 --- a/services/worker/src/passes/outside_exec.rs +++ b/services/worker/src/passes/outside_exec.rs @@ -1382,7 +1382,7 @@ pub async fn retry_own(state: &WorkerState, team_id: &str, run_id: &str) -> bool /// Writes a `ci_failed` event for a started end-to-end run that failed, with /// its workflow run id, so the resume's CI fix round reads its logs. -pub async fn record_failed(state: &WorkerState, run_id: &str, f: &FailedRun) { +pub async fn record_failed(state: &WorkerState, team_id: &str, run_id: &str, f: &FailedRun) { if state.config.events_table_name.is_empty() { return; } @@ -1395,25 +1395,26 @@ pub async fn record_failed(state: &WorkerState, run_id: &str, f: &FailedRun) { "conclusion": "failure", "failing_tests": f.failing, }); - if let Err(e) = state - .dynamo - .put_item() - .table_name(&state.config.events_table_name) - .item("pk", super::attr_s(&format!("RUN#{run_id}"))) - .item("sk", super::attr_s(&sk)) - .item("event_type", super::attr_s("ci_failed")) - .item("payload", super::attr_s(&payload.to_string())) - .item( - "processed", - aws_sdk_dynamodb::types::AttributeValue::Bool(false), - ) - .item("created_at", super::attr_s(&now.to_rfc3339())) - .item( - "expires_at", - super::attr_n((now.timestamp() as u64 + 30 * 86400).to_string()), - ) - .send() - .await + if let Err(e) = common::run_events::put( + &state.dynamo, + &state.config.events_table_name, + team_id, + run_id, + &sk, + ) + .item("event_type", super::attr_s("ci_failed")) + .item("payload", super::attr_s(&payload.to_string())) + .item( + "processed", + aws_sdk_dynamodb::types::AttributeValue::Bool(false), + ) + .item("created_at", super::attr_s(&now.to_rfc3339())) + .item( + "expires_at", + super::attr_n((now.timestamp() as u64 + 30 * 86400).to_string()), + ) + .send() + .await { warn!(run_id, error = %e, "Could not record the failed end-to-end run"); } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 36d02f03e..7d749cf74 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -435,27 +435,33 @@ async fn current_branch_head( /// that failed after a `ci_passed` already landed. The empty payload carries no /// `workflow_run_id`, so the fix path falls back to check-run annotations for the /// failure detail (see the log-collection block in the fix path). -async fn record_synthetic_ci_failed(state: &WorkerState, run_id: &str, head_sha: Option<&str>) { +async fn record_synthetic_ci_failed( + state: &WorkerState, + team_id: &str, + run_id: &str, + head_sha: Option<&str>, +) { let now = chrono::Utc::now(); let event_sk = format!("EVENT#{}#ci_failed", now.format("%Y%m%dT%H%M%S%.3fZ")); let payload = serde_json::json!({ "head_sha": head_sha.unwrap_or("") }); - if let Err(e) = state - .dynamo - .put_item() - .table_name(&state.config.events_table_name) - .item("pk", attr_s(&format!("RUN#{run_id}"))) - .item("sk", attr_s(&event_sk)) - .item("event_type", attr_s("ci_failed")) - .item("payload", attr_s(&payload.to_string())) - .item("processed", AttributeValue::Bool(false)) - .item("created_at", attr_s(&now.to_rfc3339())) - // The events table's TTL attribute (infra database-stack). - .item( - "expires_at", - attr_n((now.timestamp() as u64 + 30 * 86400).to_string()), - ) - .send() - .await + if let Err(e) = common::run_events::put( + &state.dynamo, + &state.config.events_table_name, + team_id, + run_id, + &event_sk, + ) + .item("event_type", attr_s("ci_failed")) + .item("payload", attr_s(&payload.to_string())) + .item("processed", AttributeValue::Bool(false)) + .item("created_at", attr_s(&now.to_rfc3339())) + // The events table's TTL attribute (infra database-stack). + .item( + "expires_at", + attr_n((now.timestamp() as u64 + 30 * 86400).to_string()), + ) + .send() + .await { warn!(run_id, error = %e, "Failed to write synthetic ci_failed event"); } @@ -1639,7 +1645,7 @@ pub async fn run( // Load all unprocessed events info!(run_id = %msg.run_id, events_table = %state.config.events_table_name, "Loading events"); - let events = match load_unprocessed_events(state, &msg.run_id).await { + let events = match load_unprocessed_events(state, &msg.team_id, &msg.run_id).await { Ok(evts) => evts, Err(e) => { error!(run_id = %msg.run_id, "Failed to load events: {e:?}"); @@ -1672,7 +1678,7 @@ pub async fn run( workflow_run_id = f.workflow_run_id, "Started end-to-end run failed — sending it to the CI fix round" ); - super::outside_exec::record_failed(state, &msg.run_id, &f).await; + super::outside_exec::record_failed(state, &msg.team_id, &msg.run_id, &f).await; send_delayed_resume(state, &msg, 0).await; return Ok(()); } @@ -1808,7 +1814,13 @@ pub async fn run( run_id = msg.run_id, "CI failed (missed webhook) — writing the event and starting the fix" ); - record_synthetic_ci_failed(state, &msg.run_id, branch_head.as_deref()).await; + record_synthetic_ci_failed( + state, + &msg.team_id, + &msg.run_id, + branch_head.as_deref(), + ) + .await; send_delayed_resume(state, &msg, 0).await; return Ok(()); } @@ -3080,8 +3092,13 @@ pub async fn run( super::round::clear(state, &msg.team_id, &msg.run_id).await; super::webhooks::emit_ci_fix_completed(state, &ci_fix, "failed", 0).await; mark_events_processed(state, &msg.run_id, &events).await; - record_synthetic_ci_failed(state, &msg.run_id, branch_head.as_deref()) - .await; + record_synthetic_ci_failed( + state, + &msg.team_id, + &msg.run_id, + branch_head.as_deref(), + ) + .await; if set_run_awaiting_ci( state, &ticket_msg, @@ -3273,7 +3290,13 @@ pub async fn run( run_id = msg.run_id, "A workflow passed but another check failed — routing to the fix path" ); - record_synthetic_ci_failed(state, &msg.run_id, branch_head.as_deref()).await; + record_synthetic_ci_failed( + state, + &msg.team_id, + &msg.run_id, + branch_head.as_deref(), + ) + .await; let still_active = set_run_awaiting_ci( state, &ticket_msg, @@ -5152,27 +5175,29 @@ async fn recheck_security( async fn load_unprocessed_events( state: &WorkerState, + team_id: &str, run_id: &str, ) -> Result, Box> { if state.config.events_table_name.is_empty() { return Ok(vec![]); } - let result = state - .dynamo - .query() - .table_name(&state.config.events_table_name) - .key_condition_expression("pk = :pk AND begins_with(sk, :prefix)") - .filter_expression("#p = :false") - .expression_attribute_names("#p", "processed") - .expression_attribute_values(":pk", attr_s(&format!("RUN#{run_id}"))) - .expression_attribute_values(":prefix", attr_s("EVENT#")) - .expression_attribute_values(":false", AttributeValue::Bool(false)) - .send() - .await?; + let result = common::run_events::query( + &state.dynamo, + &state.config.events_table_name, + run_id, + "EVENT#", + ) + .filter_expression("#p = :false") + .expression_attribute_names("#p", "processed") + .expression_attribute_values(":false", AttributeValue::Bool(false)) + .send() + .await?; + let today = common::run_events::today(); let events = result .items() .iter() + .filter(|item| common::run_events::owned_by(item, team_id, &today)) .filter_map(|item| { let sk = item.get("sk")?.as_s().ok()?.clone(); let event_type = item.get("event_type")?.as_s().ok()?.clone(); @@ -5198,17 +5223,17 @@ async fn mark_events_processed(state: &WorkerState, run_id: &str, events: &[RunE return; } for event in events { - if let Err(e) = state - .dynamo - .update_item() - .table_name(&state.config.events_table_name) - .key("pk", attr_s(&format!("RUN#{run_id}"))) - .key("sk", attr_s(&event.sk)) - .update_expression("SET #p = :true") - .expression_attribute_names("#p", "processed") - .expression_attribute_values(":true", AttributeValue::Bool(true)) - .send() - .await + if let Err(e) = common::run_events::update( + &state.dynamo, + &state.config.events_table_name, + run_id, + &event.sk, + ) + .update_expression("SET #p = :true") + .expression_attribute_names("#p", "processed") + .expression_attribute_values(":true", AttributeValue::Bool(true)) + .send() + .await { warn!(error = %e, "Failed to mark event processed: {}", event.sk); } @@ -5296,6 +5321,7 @@ async fn record_flaky_pass( /// Workflows that passed at least once on this run's PR, any commit. async fn ci_passed_workflows( state: &WorkerState, + team_id: &str, run_id: &str, ) -> std::collections::HashSet { let mut out = std::collections::HashSet::new(); @@ -5304,22 +5330,26 @@ async fn ci_passed_workflows( } let mut start = None; loop { - let resp = state - .dynamo - .query() - .table_name(&state.config.events_table_name) - .key_condition_expression("pk = :pk AND begins_with(sk, :prefix)") - .filter_expression("event_type = :t") - .expression_attribute_values(":pk", attr_s(&format!("RUN#{run_id}"))) - .expression_attribute_values(":prefix", attr_s("EVENT#")) - .expression_attribute_values(":t", attr_s("ci_passed")) - .set_exclusive_start_key(start.take()) - .send() - .await; + let resp = common::run_events::query( + &state.dynamo, + &state.config.events_table_name, + run_id, + "EVENT#", + ) + .filter_expression("event_type = :t") + .expression_attribute_values(":t", attr_s("ci_passed")) + .set_exclusive_start_key(start.take()) + .send() + .await; let Ok(resp) = resp else { return out; }; - for item in resp.items() { + let today = common::run_events::today(); + for item in resp + .items() + .iter() + .filter(|item| common::run_events::owned_by(item, team_id, &today)) + { let payload: Value = item .get("payload") .and_then(|v| v.as_s().ok()) @@ -5410,7 +5440,7 @@ async fn try_rerun_once( .iter() .filter_map(|e| e.payload["workflow_name"].as_str().map(str::to_string)) .collect(); - let passed_before = ci_passed_workflows(state, &msg.run_id).await; + let passed_before = ci_passed_workflows(state, &msg.team_id, &msg.run_id).await; if !should_rerun( head, &rerun_heads(run_record), @@ -5484,7 +5514,7 @@ async fn record_late_green(state: &WorkerState, msg: &ResumeMessage, run_record: if last.map(String::as_str) != Some("failed") { return; } - let Ok(events) = load_unprocessed_events(state, &msg.run_id).await else { + let Ok(events) = load_unprocessed_events(state, &msg.team_id, &msg.run_id).await else { return; }; let ci: Vec = events @@ -7352,7 +7382,7 @@ async fn redrive_red_ci( return Ok(false); } add_run_number(state, &msg.team_id, run_id, "red_redrives").await; - record_synthetic_ci_failed(state, run_id, None).await; + record_synthetic_ci_failed(state, &msg.team_id, run_id, None).await; if !set_run_awaiting_ci( state, msg, run_id, pr_url, pr_number, branch, usage, duration, ) @@ -8020,7 +8050,7 @@ async fn resume_multi_repo( } open.push((owner, name, number)); } - let events = load_unprocessed_events(state, &msg.run_id) + let events = load_unprocessed_events(state, &msg.team_id, &msg.run_id) .await .unwrap_or_default(); let n_open = open.len(); From a1c71b12aa8058da6dffde991786ac098012e650 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 12:15:43 -0500 Subject: [PATCH 2/4] Keep the plain session token builder for tests only The plan chat stream was its last caller outside tests; streams now use scoped tokens. --- services/gateway/src/auth/jwt.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/gateway/src/auth/jwt.rs b/services/gateway/src/auth/jwt.rs index c5bcad85d..00801d1d8 100644 --- a/services/gateway/src/auth/jwt.rs +++ b/services/gateway/src/auth/jwt.rs @@ -32,6 +32,10 @@ struct SessionToken<'a> { proof: &'a SignInProof, } +/// A plain session token with no sign-in proof (tests only: the dashboard +/// signs people in through the session code, and streams use +/// [`create_scoped_token`]). +#[cfg(test)] pub fn create_token( user_id: &str, team_id: &str, From 2b42d0417d9691e888fd1edaeffd584863736fdc Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 13:23:08 -0500 Subject: [PATCH 3/4] Key the PR template cache by installation, as every process-wide cache is --- .../worker/src/passes/incidents/bm_teams_never_cross.rs | 1 + services/worker/src/passes/pr.rs | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs index 102167902..0acdebea9 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -358,6 +358,7 @@ const CACHES: &[(&str, &str)] = &[ ("worker/src/clients/github.rs::LIMITED", "installation id"), ("worker/src/clients/github_budget.rs::LEDGER", "installation id"), ("worker/src/passes/conversation.rs::CACHE", "GitHub `owner/repo#n`: the thread itself, read with the run's own installation"), + ("worker/src/passes/pr.rs::CACHE", "installation id plus `owner/repo@branch`: the PR template read with that installation"), ("worker/src/passes/conversation.rs::REPLIED", "GitHub `owner/repo#n`: the thread itself"), ("worker/src/passes/conversation.rs::REVIEW_COMMENTS", "GitHub `owner/repo#n`: the thread itself"), ("worker/src/passes/run_guard.rs::REENTRY", "run id (a ULID)"), diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 4b878d120..9fe72ba29 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -2265,15 +2265,17 @@ fn template_cache() -> &'static std::sync::Mutex { /// The repository's pull request template, from its common locations: the /// first draft is written to it, and every rebuild lays the description into -/// it (`common::pr_template`). Kept for a few minutes per repository and -/// branch. +/// it (`common::pr_template`). Kept for a few minutes per installation, +/// repository and branch. pub(crate) async fn fetch_pr_template( github: &GitHubClient, owner: &str, repo: &str, base_branch: &str, ) -> Option { - let key = format!("{owner}/{repo}@{base_branch}").to_lowercase(); + // Keyed by the installation that read it, so one team never reuses + // another team's read (bm_teams_never_cross). + let key = format!("{}:{owner}/{repo}@{base_branch}", github.installation_id).to_lowercase(); if let Ok(c) = template_cache().lock() { if let Some((at, t)) = c.get(&key) { if at.elapsed() < TEMPLATE_TTL { From 09b99fe7f58c711e93ee861a442f33b6652291df Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 15 Nov 2026 14:09:15 -0500 Subject: [PATCH 4/4] Read the installation through its accessor --- services/worker/src/passes/pr.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 9fe72ba29..9f67529ea 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -2275,7 +2275,7 @@ pub(crate) async fn fetch_pr_template( ) -> Option { // Keyed by the installation that read it, so one team never reuses // another team's read (bm_teams_never_cross). - let key = format!("{}:{owner}/{repo}@{base_branch}", github.installation_id).to_lowercase(); + let key = format!("{}:{owner}/{repo}@{base_branch}", github.installation_id()).to_lowercase(); if let Ok(c) = template_cache().lock() { if let Some((at, t)) = c.get(&key) { if at.elapsed() < TEMPLATE_TTL {