Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/incidents.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ pipeline still calls it there.
| 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. |
| bl. `bl_description_final_review` | A pull request description showed six checks as "still running when this was written" in its results and never changed them, asked a person for deploy credentials or to run the staging deploy in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id beside its name, and listed still-running and did-not-run checks on one line. The repository's template only guided the first draft. A run could also end as needing an outside change instead of delivering the code. | Every description passes a final review in the one save (`common::pr_review`): a running check reads Running and is never a result, and the stamp keeps the description rebuilt until the checks end; nothing the gate does not let through reaches a person, and a staging deploy the repository lets CoderHelm start (a dispatchable workflow, or a job a pull request label starts) is CoderHelm's step: the gate is told it can deploy, and the executor adds the label or dispatches, waits for the run and records its end; nothing is said twice; no filler; no raw id beside a name; running and did-not-run are said apart. The repository's template is the visible structure, filled with CoderHelm's content (`common::pr_template`). A plan with code is implemented and its pull request opened whatever outside work it needs, a person's feedback that part of the fix is outside the code keeps the code and its open pull request with the outside part attached, and the run ends delivered with only person-only items listed once under Needed from you. |
| 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

Expand Down
1 change: 1 addition & 0 deletions services/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,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.
Expand Down
200 changes: 200 additions & 0 deletions services/common/src/plugins/flag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<(String, u64)>, 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<String> {
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();
Expand Down
54 changes: 46 additions & 8 deletions services/common/src/reply_compose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,13 +918,20 @@ pub fn finish(
pub static CACHE: LazyLock<Mutex<HashMap<String, Composed>>> =
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()))
)
}

Expand All @@ -937,14 +944,12 @@ pub async fn composed(
place: &Place,
meta: &Meta,
) -> Option<Composed> {
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 {
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading