diff --git a/services/gateway/src/bases.rs b/services/gateway/src/bases.rs new file mode 100644 index 000000000..d9384ddba --- /dev/null +++ b/services/gateway/src/bases.rs @@ -0,0 +1,1021 @@ +//! The six built-in bases every team has with nothing to set up (Code, +//! Work, Infrastructure, Logs, Security, Knowledge; `lookups::BASES`): who +//! may read each, how much is in it and how fresh it is. +//! +//! **One permission decision** ([`decide`]) for every door a read comes +//! through: Chat, the Knowledge page, share links and the AI tools on +//! `/mcp`. A base is open to a person when +//! +//! 1. their role opens what the base holds in the dashboard (the same +//! `permissions::resolve_access` check the pages make), +//! 2. the base's audience includes them ([`Audience`]: roles, people, and +//! whether readers from AI tools may read it), and it isn't paused, +//! 3. on `/mcp`, the connection holds the base's scope. +//! +//! Items inside a base are then mirrored where a mapping exists: code is +//! read only from repositories the person's linked GitHub account can read +//! ([`visible_repos`]). Anything withheld is counted, never named. +//! +//! Storage, in the settings table, all under the team's own key: +//! - `pk = `, `sk = KB_BUILTIN#`: a base's audience, when an +//! admin changed it (otherwise [`default_audience`]); +//! - `pk = `, `sk = KB_READERS`: whether people may connect AI tools +//! as readers without an account; +//! - `pk = `, `sk = GH_REPO_ACCESS#`: which repositories a +//! GitHub login could read, checked within [`ACCESS_TTL_SECS`]. +//! +//! Nothing here is cached in the process: every read names its team. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::repo_read::RepoInfo; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use tracing::warn; + +use crate::lookups::{self, Base, BASES}; +use crate::permissions::{resolve_access, Access, Holder}; +use crate::routes::chat_work; +use crate::AppState; + +type Item = HashMap; + +pub const AUDIENCE_PREFIX: &str = "KB_BUILTIN#"; +pub const READERS_SK: &str = "KB_READERS"; +pub const REPO_ACCESS_PREFIX: &str = "GH_REPO_ACCESS#"; +/// A person's GitHub repository access is checked again after this long. +pub const ACCESS_TTL_SECS: i64 = 600; +/// Most repositories checked for one person in one read; the rest wait for +/// the next read (and are withheld meanwhile). +pub const MAX_ACCESS_CHECKS: usize = 60; +/// Most rows read to count one kind of record. +const MAX_COUNT_ROWS: usize = 5_000; + +/// The role a person connected from an AI tool gets: read-only, not a seat +/// (`routes::auth`, connected readers). +pub const READER_ROLE: &str = "reader"; + +/// The dashboard route that decides reading code and the team's documents: +/// reading knowledge, which every member may do (`brain_read`). +pub const READ_ROUTE: &str = "knowledge_ask::search_base"; + +// ── Audiences ─────────────────────────────────────────────────────────────── + +/// Who may read a base. It only narrows what roles already open: widening +/// past a role is done on the role, so the dashboard and the bases agree. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Audience { + /// Roles that may read it (`member`, `viewer`, `custom:`, ...). + /// Empty: every role that opens what it holds. + #[serde(default)] + pub roles: Vec, + /// People named by email, whatever their role. + #[serde(default)] + pub people: Vec, + /// Readers connected from AI tools may read it. + #[serde(default)] + pub readers: bool, + /// Nobody reads it while paused. + #[serde(default)] + pub paused: bool, +} + +/// What a base starts with: everyone whose role opens it; readers from AI +/// tools read code, work and the team's documents, never AWS, logs or +/// security findings until an admin says so. +pub fn default_audience(key: &str) -> Audience { + Audience { + readers: matches!(key, lookups::CODE | lookups::WORK | lookups::TEAM), + ..Default::default() + } +} + +fn is_admin(role: &str) -> bool { + matches!(role, "owner" | "admin") +} + +impl Audience { + /// Whether the audience names this person. Owners and admins are always + /// in it, so nobody can lock the team's admins out. + pub fn open_to(&self, role: &str, email: &str) -> bool { + let named = self + .people + .iter() + .any(|p| !email.is_empty() && p.eq_ignore_ascii_case(email.trim())); + if is_admin(role) || named { + return true; + } + if role == READER_ROLE { + return self.readers; + } + self.roles.is_empty() || self.roles.iter().any(|r| r == role) + } + + /// The audience in a few words, as the Knowledge page shows it. + pub fn label(&self) -> String { + let mut parts: Vec = Vec::new(); + if self.roles.is_empty() { + parts.push("Everyone whose role opens it".into()); + } else { + parts.push(format!("Admins and {}", self.roles.join(", "))); + } + if !self.people.is_empty() { + parts.push(format!( + "{} {} by name", + self.people.len(), + if self.people.len() == 1 { + "person" + } else { + "people" + } + )); + } + parts.push(if self.readers { + "readers from AI tools".into() + } else { + "not readers from AI tools".into() + }); + let mut s = parts.join("; "); + if self.paused { + s = format!("Paused. {s}"); + } + s + } + + /// Checks an edit: known roles, plain emails, at most 200 names. + pub fn checked(mut self) -> Result { + self.roles.retain(|r| !r.trim().is_empty()); + for r in &mut self.roles { + *r = r.trim().to_string(); + let known = crate::permissions::VALID_ROLES.contains(&r.as_str()) + || crate::permissions::custom_role_id(r).is_some(); + if !known { + return Err(format!("\"{r}\" isn't a role.")); + } + } + self.roles.sort(); + self.roles.dedup(); + let mut people = Vec::new(); + for p in &self.people { + let p = p.trim().to_ascii_lowercase(); + if p.is_empty() { + continue; + } + if !p.contains('@') || p.len() > 254 || p.contains(char::is_whitespace) { + return Err(format!("\"{p}\" isn't an email address.")); + } + people.push(p); + } + people.sort(); + people.dedup(); + if people.len() + self.roles.len() > 200 { + return Err("Name at most 200 roles and people.".into()); + } + self.people = people; + Ok(self) + } +} + +// ── The decision ──────────────────────────────────────────────────────────── + +/// Whether a person's role opens what a base holds, as the dashboard pages +/// decide it. +pub fn role_reads(holder: &Holder, base: &str) -> bool { + let route_ok = |h: &str| matches!(resolve_access(holder, Some(h)), Access::Allow { .. }); + match base { + lookups::CODE | lookups::TEAM => route_ok(READ_ROUTE), + b => chat_work::KINDS + .iter() + .filter(|k| lookups::base_of(k.key).key == b) + .any(|k| route_ok(k.handler)), + } +} + +/// Who is asking. +#[derive(Debug, Clone)] +pub struct Asker<'a> { + pub holder: &'a Holder, + pub email: &'a str, +} + +/// The answer for one person and one base. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Decision { + Open, + /// The connection to an AI tool doesn't hold the base's scope. + Scope(&'static str), + /// The person's role doesn't open what the base holds. + Role, + /// The base's audience doesn't include them. + Audience, + Paused, +} + +impl Decision { + pub fn is_open(&self) -> bool { + *self == Decision::Open + } + + /// Why it's closed, in one sentence; `None` when open. + pub fn why(&self, base: &Base) -> Option { + match self { + Decision::Open => None, + Decision::Scope(s) => Some(format!( + "This connection wasn't given {s}, which {} needs.", + base.name + )), + Decision::Role => Some(format!( + "Your role doesn't open what {} holds. Ask an admin.", + base.name + )), + Decision::Audience => Some(format!( + "{} is open to a narrower audience. Ask an admin for access.", + base.name + )), + Decision::Paused => Some(format!("An admin paused {}.", base.name)), + } + } +} + +/// THE decision, for every door: paused, then (on `/mcp`) the connection's +/// scope, then the role, then the audience. +pub fn decide( + base: &Base, + who: &Asker<'_>, + audience: &Audience, + scopes: Option<&BTreeSet<&'static str>>, +) -> Decision { + if audience.paused { + return Decision::Paused; + } + if let Some(s) = scopes { + if !s.contains(base.scope) { + return Decision::Scope(base.scope); + } + } + if !role_reads(who.holder, base.key) { + return Decision::Role; + } + if !audience.open_to(&who.holder.role, who.email) { + return Decision::Audience; + } + Decision::Open +} + +/// Every base's decision for one person. +pub fn decide_all( + who: &Asker<'_>, + audiences: &BTreeMap, + scopes: Option<&BTreeSet<&'static str>>, +) -> BTreeMap<&'static str, Decision> { + BASES + .iter() + .map(|b| { + let a = audiences + .get(b.key) + .cloned() + .unwrap_or_else(|| default_audience(b.key)); + (b.key, decide(b, who, &a, scopes)) + }) + .collect() +} + +/// The record kinds a person may read in Chat and on `/mcp`: those their +/// role opens (`chat_work::readable`) whose base is open to them. +pub fn readable_kinds( + holder: &Holder, + open: &BTreeMap<&'static str, Decision>, +) -> Vec<&'static str> { + chat_work::readable(holder) + .into_iter() + .filter(|k| { + open.get(lookups::base_of(k).key) + .is_some_and(Decision::is_open) + }) + .collect() +} + +// ── Storage ───────────────────────────────────────────────────────────────── + +fn s(v: impl Into) -> AttributeValue { + AttributeValue::S(v.into()) +} + +fn attr<'a>(i: &'a Item, k: &str) -> &'a str { + i.get(k) + .and_then(|v| v.as_s().ok()) + .map_or("", |v| v.as_str()) +} + +/// Every base's audience for a team: what admins saved, else the default. +pub async fn audiences(state: &AppState, team_id: &str) -> BTreeMap { + let mut out: BTreeMap = BASES + .iter() + .map(|b| (b.key.to_string(), default_audience(b.key))) + .collect(); + let rows = rows( + state, + &state.config.settings_table_name, + "pk", + team_id, + AUDIENCE_PREFIX, + 20, + ) + .await; + for i in rows { + let key = attr(&i, "sk").trim_start_matches(AUDIENCE_PREFIX); + if let (true, Ok(a)) = ( + lookups::base(key).is_some(), + serde_json::from_str::(attr(&i, "json")), + ) { + out.insert(key.to_string(), a); + } + } + out +} + +pub async fn save_audience( + state: &AppState, + team_id: &str, + key: &str, + a: &Audience, + by: &str, +) -> Result<(), String> { + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(team_id)) + .item("sk", s(format!("{AUDIENCE_PREFIX}{key}"))) + .item("json", s(serde_json::to_string(a).unwrap_or_default())) + .item("updated_by", s(by)) + .item("updated_at", s(chrono::Utc::now().to_rfc3339())) + .send() + .await + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +/// Whether the team lets people connect AI tools as readers. +pub async fn readers_enabled(state: &AppState, team_id: &str) -> bool { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(team_id)) + .key("sk", s(READERS_SK)) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get("enabled").and_then(|v| v.as_bool().ok()).copied()) + .unwrap_or(false) +} + +pub async fn set_readers( + state: &AppState, + team_id: &str, + enabled: bool, + by: &str, +) -> Result<(), String> { + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(team_id)) + .item("sk", s(READERS_SK)) + .item("enabled", AttributeValue::Bool(enabled)) + .item("updated_by", s(by)) + .item("updated_at", s(chrono::Utc::now().to_rfc3339())) + .send() + .await + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +/// The rows of one team under a key prefix, at most `max_pages` pages. +async fn rows( + state: &AppState, + table: &str, + pk_name: &str, + team_id: &str, + prefix: &str, + max_pages: usize, +) -> Vec { + let mut out = Vec::new(); + if table.is_empty() { + return out; + } + let mut start: Option = None; + for _ in 0..max_pages.max(1) { + let mut q = state + .dynamo + .query() + .table_name(table) + .expression_attribute_values(":pk", s(team_id)) + .set_exclusive_start_key(start.take()); + q = if prefix.is_empty() { + q.key_condition_expression(format!("{pk_name} = :pk")) + } else { + q.key_condition_expression(format!("{pk_name} = :pk AND begins_with(sk, :p)")) + .expression_attribute_values(":p", s(prefix)) + }; + match q.send().await { + Ok(r) => { + out.extend(r.items().iter().cloned()); + match r.last_evaluated_key() { + Some(k) if out.len() < MAX_COUNT_ROWS => start = Some(k.clone()), + _ => break, + } + } + Err(e) => { + warn!(error = %e, prefix, "bases: rows not read"); + break; + } + } + } + out +} + +// ── Counts and freshness ──────────────────────────────────────────────────── + +const TIME_FIELDS: &[&str] = &[ + "updated_at", + "last_seen_at", + "last_seen", + "seen_at", + "read_at", + "received_at", + "created_at", +]; + +/// The newest time a row carries, on the row or in its stored JSON. +pub fn row_time(i: &Item) -> Option { + let mut best: Option = None; + let mut see = |t: &str| { + if chrono::DateTime::parse_from_rfc3339(t).is_ok() && best.as_deref().is_none_or(|b| t > b) + { + best = Some(t.to_string()); + } + }; + for f in TIME_FIELDS { + see(attr(i, f)); + } + for k in ["json", "finding", "state"] { + if let Ok(v) = serde_json::from_str::(attr(i, k)) { + for f in TIME_FIELDS { + if let Some(t) = v[*f].as_str() { + see(t); + } + } + } + } + best +} + +fn newest(rows: &[Item]) -> Option { + rows.iter().filter_map(row_time).max() +} + +/// What a base holds now: counts by kind, and when it last changed. +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Size { + pub counts: Vec<(String, usize)>, + pub updated_at: Option, + /// Read live at the source on every question (code, tickets). + pub live: bool, +} + +impl Size { + fn add(&mut self, label: &str, rows: &[Item]) { + self.counts.push((label.to_string(), rows.len())); + if let Some(t) = newest(rows) { + if self.updated_at.as_deref().is_none_or(|u| t.as_str() > u) { + self.updated_at = Some(t); + } + } + } + + pub fn total(&self) -> usize { + self.counts.iter().map(|(_, n)| n).sum() + } +} + +/// How much one base holds for a team, read from the team's own records. +pub async fn size(state: &AppState, team_id: &str, key: &str) -> Size { + let settings = state.config.settings_table_name.as_str(); + let insights = state.config.aws_insights_table_name.as_str(); + let mut out = Size::default(); + match key { + lookups::CODE => { + let repos = crate::routes::brain::load_repos(state, team_id).await; + out.counts.push(("repositories".into(), repos.len())); + out.live = true; + } + lookups::WORK => { + let (runs, plans, reviews) = tokio::join!( + rows( + state, + &state.config.runs_table_name, + "team_id", + team_id, + "", + 10 + ), + rows( + state, + &state.config.plans_table_name, + "pk", + team_id, + "PLAN#", + 10 + ), + rows(state, settings, "pk", team_id, "REVIEW#", 10), + ); + let plans: Vec = plans + .into_iter() + .filter(|i| !attr(i, "sk").contains("#TASK#")) + .collect(); + out.add("runs", &runs); + out.add("plans", &plans); + out.add("reviews", &reviews); + out.live = true; + } + lookups::INFRA => { + let (res, reads, found) = tokio::join!( + rows(state, insights, "pk", team_id, "RES#", 20), + rows(state, insights, "pk", team_id, "RES_READ#", 2), + rows( + state, + settings, + "pk", + team_id, + common::infra_vuln::records::FINDING_PREFIX, + 10 + ), + ); + out.add("AWS resources", &res); + out.add("AWS accounts read", &reads); + out.add("infrastructure findings", &found); + } + lookups::LOGS => { + let (logs, alerts) = tokio::join!( + rows( + state, + insights, + "pk", + team_id, + common::log_findings::REC_PREFIX, + 10 + ), + rows(state, settings, "pk", team_id, "ALERT_EVENT#", 10), + ); + out.add("log findings", &logs); + out.add("alerts", &alerts); + } + lookups::SECURITY => { + let found = rows( + state, + settings, + "pk", + team_id, + common::security_fixes::FINDING_PREFIX, + 10, + ) + .await; + out.add("security findings", &found); + } + lookups::TEAM => { + use common::knowledge::search::Store; + let st = crate::routes::knowledge::store(state); + if let Ok(bases) = st.bases(team_id).await { + out.counts.push(("knowledge bases".into(), bases.len())); + out.updated_at = bases + .iter() + .map(|b| b.updated_at.clone()) + .filter(|t| !t.is_empty()) + .max(); + } + } + _ => {} + } + out +} + +// ── GitHub mirroring ──────────────────────────────────────────────────────── + +/// Whether GitHub's permission word lets a person read a repository. +pub fn grants_read(permission: &str) -> bool { + matches!( + permission, + "admin" | "maintain" | "write" | "triage" | "read" | "push" | "pull" + ) +} + +/// What was stored of a login's access: repository to may-read, and when. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct RepoAccess { + #[serde(default)] + pub repos: BTreeMap, + #[serde(default)] + pub checked_at: i64, +} + +impl RepoAccess { + pub fn fresh(&self, now: i64) -> bool { + now - self.checked_at < ACCESS_TTL_SECS + } +} + +/// The repositories to show, from what is known: a repository known to be +/// readable is kept; unknown and refused ones are withheld. +pub fn mirror(repos: Vec, known: &RepoAccess) -> (Vec, usize) { + let (keep, held): (Vec<_>, Vec<_>) = repos.into_iter().partition(|r| { + known + .repos + .get(&r.name.to_ascii_lowercase()) + .copied() + .unwrap_or(false) + }); + (keep, held.len()) +} + +/// The team's repositories this person may read: all of them when no +/// GitHub login is linked to a member (no mapping to mirror), only those +/// the login can read on GitHub otherwise. Readers without a login see none. +/// Gives the repositories and how many were withheld. +pub async fn visible_repos( + state: &AppState, + team_id: &str, + role: &str, + github_login: Option<&str>, + github_token: Option<&str>, + repos: Vec, +) -> (Vec, usize) { + let login = github_login + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(str::to_ascii_lowercase); + let Some(login) = login else { + if role == READER_ROLE { + let n = repos.len(); + return (Vec::new(), n); + } + return (repos, 0); + }; + let Some(token) = github_token else { + // GitHub can't be asked: what was checked before still counts. + let known = load_access(state, team_id, &login).await; + return mirror(repos, &known); + }; + let now = chrono::Utc::now().timestamp(); + let mut known = load_access(state, team_id, &login).await; + if !known.fresh(now) { + known = RepoAccess { + repos: BTreeMap::new(), + checked_at: now, + }; + } + let mut asked = 0usize; + let mut changed = false; + for r in &repos { + let name = r.name.to_ascii_lowercase(); + if known.repos.contains_key(&name) || asked >= MAX_ACCESS_CHECKS { + continue; + } + asked += 1; + if let Some(ok) = ask_permission(state, token, &r.name, &login).await { + known.repos.insert(name, ok); + changed = true; + } + } + if changed { + save_access(state, team_id, &login, &known).await; + } + mirror(repos, &known) +} + +/// GitHub's answer for one repository: `None` when GitHub couldn't say. +async fn ask_permission(state: &AppState, token: &str, repo: &str, login: &str) -> Option { + let url = format!( + "https://api.github.com/repos/{repo}/collaborators/{}/permission", + urlencoding::encode(login) + ); + let r = state + .http + .get(url) + .header("Authorization", format!("Bearer {token}")) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "Coderhelm") + .send() + .await + .ok()?; + match r.status().as_u16() { + 200 => { + let v: Value = r.json().await.ok()?; + let p = v["user"]["permissions"].clone(); + let by_flags = ["admin", "maintain", "push", "triage", "pull"] + .iter() + .any(|k| p[*k].as_bool() == Some(true)); + Some(by_flags || grants_read(v["permission"].as_str().unwrap_or(""))) + } + 403 | 404 => Some(false), + _ => None, + } +} + +async fn load_access(state: &AppState, team_id: &str, login: &str) -> RepoAccess { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(team_id)) + .key("sk", s(format!("{REPO_ACCESS_PREFIX}{login}"))) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| serde_json::from_str(attr(&i, "json")).ok()) + .unwrap_or_default() +} + +async fn save_access(state: &AppState, team_id: &str, login: &str, a: &RepoAccess) { + let ttl = a.checked_at + 86_400; + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(team_id)) + .item("sk", s(format!("{REPO_ACCESS_PREFIX}{login}"))) + .item("json", s(serde_json::to_string(a).unwrap_or_default())) + .item("ttl", AttributeValue::N(ttl.to_string())) + .send() + .await + { + warn!(error = %e, "bases: GitHub access not saved"); + } +} + +// ── The listing ───────────────────────────────────────────────────────────── + +/// What the mirroring note says for a base. +pub fn mirroring(key: &str) -> Option<&'static str> { + match key { + lookups::CODE => Some("Code is read only from repositories your linked GitHub account can read."), + lookups::WORK => Some("Pull requests follow your GitHub access; tickets follow your CoderHelm role until Jira project access is mapped."), + lookups::TEAM => Some("Each knowledge base keeps its own readers."), + _ => None, + } +} + +/// One base as the Knowledge page and `list_bases` show it. +pub fn view(base: &Base, size: &Size, audience: &Audience, decision: &Decision) -> Value { + json!({ + "key": base.key, + "name": base.name, + "about": base.about, + "scope": base.scope, + "builtin": true, + "counts": size.counts.iter().map(|(l, n)| json!({ "label": l, "count": n })).collect::>(), + "total": size.total(), + "updated_at": size.updated_at, + "live": size.live, + "access": { "open": decision.is_open(), "why": decision.why(base) }, + "audience": audience, + "audience_label": audience.label(), + "mirroring": mirroring(base.key), + }) +} + +/// Every base for one person: sizes are read only for bases open to them, +/// so a closed base shows its name and why, never what is in it. +pub async fn list( + state: &AppState, + team_id: &str, + who: &Asker<'_>, + scopes: Option<&BTreeSet<&'static str>>, +) -> Vec { + let auds = audiences(state, team_id).await; + let decisions = decide_all(who, &auds, scopes); + let mut out = Vec::new(); + for b in BASES.iter() { + let d = decisions.get(b.key).cloned().unwrap_or(Decision::Role); + let a = auds.get(b.key).cloned().unwrap_or_default(); + let sz = if d.is_open() { + Box::pin(size(state, team_id, b.key)).await + } else { + Size::default() + }; + out.push(view(b, &sz, &a, &d)); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn h(role: &str) -> Holder { + Holder::builtin(role) + } + + fn base(k: &str) -> &'static Base { + lookups::base(k).unwrap() + } + + #[test] + fn every_base_starts_open_to_every_role_that_opens_it() { + for role in ["owner", "admin", "member", "viewer"] { + let holder = h(role); + let who = Asker { + holder: &holder, + email: "dev@example.com", + }; + for b in BASES.iter() { + let d = decide(b, &who, &default_audience(b.key), None); + assert_eq!(d.is_open(), role_reads(&holder, b.key), "{role} {}", b.key); + } + } + // Everyone on the team reads code, work and the team's documents. + let v = h("viewer"); + for k in [lookups::CODE, lookups::WORK, lookups::TEAM] { + assert!(role_reads(&v, k), "{k}"); + } + } + + #[test] + fn readers_read_code_work_and_knowledge_until_an_admin_widens_it() { + let r = h(READER_ROLE); + let who = Asker { + holder: &r, + email: "reader@example.com", + }; + let open: Vec<&str> = BASES + .iter() + .filter(|b| decide(b, &who, &default_audience(b.key), None).is_open()) + .map(|b| b.key) + .collect(); + assert_eq!(open, [lookups::CODE, lookups::WORK, lookups::TEAM]); + // An admin names the reader on Security: still only what their role + // opens, never more. + let mut a = default_audience(lookups::SECURITY); + a.people = vec!["reader@example.com".into()]; + assert_eq!( + decide(base(lookups::SECURITY), &who, &a, None), + Decision::Open + ); + let mut a = default_audience(lookups::SECURITY); + a.readers = true; + assert!(decide(base(lookups::SECURITY), &who, &a, None).is_open()); + } + + #[test] + fn a_narrowed_audience_closes_a_base_but_never_to_admins() { + let mut a = default_audience(lookups::INFRA); + a.roles = vec!["member".into()]; + let (m, v, ad) = (h("member"), h("viewer"), h("admin")); + let ask = |holder: &Holder, a: &Audience| { + decide( + base(lookups::INFRA), + &Asker { + holder, + email: "x@example.com", + }, + a, + None, + ) + }; + assert_eq!(ask(&m, &a), Decision::Open); + assert_eq!(ask(&v, &a), Decision::Audience); + assert_eq!(ask(&ad, &a), Decision::Open); + // Named people are in, whatever their role. + a.people = vec!["x@example.com".into()]; + assert_eq!(ask(&v, &a), Decision::Open); + // Paused: closed to everyone. + a.paused = true; + assert_eq!(ask(&ad, &a), Decision::Paused); + assert!(Decision::Paused + .why(base(lookups::INFRA)) + .unwrap() + .contains("paused")); + } + + #[test] + fn a_connection_reads_only_the_bases_its_scopes_name() { + let ad = h("admin"); + let who = Asker { + holder: &ad, + email: "", + }; + let scopes: BTreeSet<&'static str> = [crate::mcp_oauth::CODE_SCOPE].into(); + let auds = BTreeMap::new(); + let d = decide_all(&who, &auds, Some(&scopes)); + for b in BASES.iter() { + let want = b.key == lookups::CODE; + assert_eq!(d[b.key].is_open(), want, "{}", b.key); + if !want { + assert_eq!(d[b.key], Decision::Scope(b.scope)); + } + } + } + + #[test] + fn closed_bases_take_their_kinds_out_of_chat() { + let ad = h("admin"); + let who = Asker { + holder: &ad, + email: "", + }; + let mut auds = BTreeMap::new(); + let mut a = default_audience(lookups::LOGS); + a.paused = true; + auds.insert(lookups::LOGS.to_string(), a); + let d = decide_all(&who, &auds, None); + let kinds = readable_kinds(&ad, &d); + assert!(!kinds.contains(&"alerts") && !kinds.contains(&"log_findings")); + assert!(kinds.contains(&"resources") && kinds.contains(&"runs")); + } + + #[test] + fn audience_edits_are_checked() { + let a = Audience { + roles: vec![" member ".into(), "member".into()], + people: vec!["Dev@Example.com".into(), "".into()], + ..Default::default() + } + .checked() + .unwrap(); + assert_eq!(a.roles, ["member"]); + assert_eq!(a.people, ["dev@example.com"]); + assert!(Audience { + roles: vec!["boss".into()], + ..Default::default() + } + .checked() + .is_err()); + assert!(Audience { + people: vec!["not an email".into()], + ..Default::default() + } + .checked() + .is_err()); + assert!(Audience::default().label().contains("Everyone")); + } + + #[test] + fn code_follows_the_persons_github_access() { + let repos = vec![ + RepoInfo::new("acme/web", "main"), + RepoInfo::new("acme/api", "main"), + RepoInfo::new("acme/infra", "main"), + ]; + let known = RepoAccess { + repos: [ + ("acme/web".to_string(), true), + ("acme/api".to_string(), false), + ] + .into(), + checked_at: 100, + }; + let (keep, held) = mirror(repos, &known); + assert_eq!( + keep.iter().map(|r| r.name.as_str()).collect::>(), + ["acme/web"] + ); + // Refused and not yet known: withheld, counted. + assert_eq!(held, 2); + assert!(known.fresh(100 + ACCESS_TTL_SECS - 1)); + assert!(!known.fresh(100 + ACCESS_TTL_SECS)); + for p in ["admin", "maintain", "write", "triage", "read"] { + assert!(grants_read(p), "{p}"); + } + assert!(!grants_read("none") && !grants_read("")); + } + + #[test] + fn freshness_is_the_newest_time_a_row_carries() { + let row = |t: &str, inner: &str| -> Item { + HashMap::from([ + ("updated_at".to_string(), s(t)), + ( + "json".to_string(), + s(json!({ "seen_at": inner }).to_string()), + ), + ]) + }; + let rows = [ + row("2026-11-01T00:00:00Z", "2026-11-03T00:00:00Z"), + row("2026-11-02T00:00:00Z", "not a time"), + ]; + assert_eq!(newest(&rows).as_deref(), Some("2026-11-03T00:00:00Z")); + let mut sz = Size::default(); + sz.add("rows", &rows); + assert_eq!(sz.total(), 2); + let b = base(lookups::INFRA); + let v = view(b, &sz, &default_audience(b.key), &Decision::Role); + assert_eq!(v["access"]["open"], false); + assert!(v["access"]["why"].as_str().unwrap().contains("role")); + assert_eq!(v["scope"], "infra:read"); + } +} diff --git a/services/gateway/src/lookups.rs b/services/gateway/src/lookups.rs index f202720f5..e6934bde6 100644 --- a/services/gateway/src/lookups.rs +++ b/services/gateway/src/lookups.rs @@ -11,18 +11,19 @@ //! registers what it found in the citation registry, which Chat cites and //! `/mcp` turns into structured results. //! -//! [`BASES`] is the vocabulary results are named by: the six built-in bases -//! (Code and docs, Work, Infrastructure, Logs and operations, Security, -//! Team knowledge). The bases themselves, with their own audiences, come -//! later; until then a base is the name of where a result came from and the -//! scope that reaches it on `/mcp`. +//! [`BASES`] are the six built-in bases (Code, Work, Infrastructure, Logs, +//! Security, Knowledge): the name every result carries and the scope that +//! reaches it on `/mcp`. Who may read each one is decided once, in +//! `crate::bases::decide`. use common::knowledge::answer::Registry; use common::knowledge::search::{Embedder, Found, Retriever, Store}; use common::repo_read::CodeReader; use serde_json::Value; -use crate::mcp_oauth::{CODE_SCOPE, KNOWLEDGE_SCOPE, SECURITY_SCOPE, WORK_SCOPE}; +use crate::mcp_oauth::{ + CODE_SCOPE, INFRA_SCOPE, KNOWLEDGE_SCOPE, LOGS_SCOPE, SECURITY_SCOPE, WORK_SCOPE, +}; use crate::routes::{chat_code, chat_work, plan_chat_tools}; use crate::AppState; @@ -110,10 +111,10 @@ pub async fn github_hold_now( github_hold(caller, chat_work::limited_until(state, id).await, now) } -// ── The built-in bases, as names ──────────────────────────────────────────── +// ── The built-in bases ────────────────────────────────────────────────────── /// A built-in base: what results are named by, and the `/mcp` scope that -/// reaches it. +/// reaches it. Its audience, counts and freshness live in `crate::bases`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Base { pub key: &'static str, @@ -126,18 +127,17 @@ pub struct Base { pub const CODE: &str = "code"; pub const WORK: &str = "work"; pub const INFRA: &str = "infra"; -pub const OPS: &str = "ops"; +pub const LOGS: &str = "logs"; pub const SECURITY: &str = "security"; pub const TEAM: &str = "team"; -/// The six built-in bases, in the order they are shown. Infrastructure and -/// Logs and operations are reached with `security:read` until their own -/// scopes come with those bases. +/// The six built-in bases, in the order they are shown. Every team has all +/// six with nothing to set up: each is fed from what CoderHelm already reads. pub const BASES: [Base; 6] = [ Base { key: CODE, - name: "Code and docs", - about: "The team's repositories: files, code search, the code graph and history", + name: "Code", + about: "The connected repositories: files, symbols, the code graph and history", scope: CODE_SCOPE, }, Base { @@ -149,25 +149,25 @@ pub const BASES: [Base; 6] = [ Base { key: INFRA, name: "Infrastructure", - about: "Infrastructure findings", - scope: SECURITY_SCOPE, + about: "AWS accounts and resources, where each is defined in Terraform, CDK or CloudFormation, pending updates and infrastructure findings", + scope: INFRA_SCOPE, }, Base { - key: OPS, - name: "Logs and operations", - about: "Alerts and log findings", - scope: SECURITY_SCOPE, + key: LOGS, + name: "Logs", + about: "Problems found in the logs and alerts, with the repository and service each belongs to", + scope: LOGS_SCOPE, }, Base { key: SECURITY, name: "Security", - about: "Dependency advisories and CVEs, and quarantined tests", + about: "Dependency advisories and CVEs, their fixes, and quarantined tests", scope: SECURITY_SCOPE, }, Base { key: TEAM, - name: "Team knowledge", - about: "The knowledge bases people made: uploaded and synced documents", + name: "Knowledge", + about: "The team's documents: uploaded files and connected sources such as Confluence, Notion and Drive", scope: KNOWLEDGE_SCOPE, }, ]; @@ -182,8 +182,8 @@ pub fn base_of(kind: &str) -> &'static Base { let key = match kind { "code" | "memory" => CODE, "security" | "tests" => SECURITY, - "infra" => INFRA, - "alerts" | "log_findings" => OPS, + "infra" | "resources" => INFRA, + "alerts" | "log_findings" => LOGS, "knowledge" | "upload" => TEAM, _ => WORK, }; @@ -225,14 +225,19 @@ mod tests { let b = base_of(k.key); assert!(BASES.contains(b), "{}", k.key); } - assert_eq!(base_of("code").name, "Code and docs"); + assert_eq!(base_of("code").name, "Code"); assert_eq!(base_of("runs").name, "Work"); assert_eq!(base_of("security").name, "Security"); assert_eq!(base_of("infra").name, "Infrastructure"); - assert_eq!(base_of("log_findings").name, "Logs and operations"); - assert_eq!(base_of("knowledge").name, "Team knowledge"); + assert_eq!(base_of("resources").name, "Infrastructure"); + assert_eq!(base_of("log_findings").name, "Logs"); + assert_eq!(base_of("alerts").name, "Logs"); + assert_eq!(base_of("knowledge").name, "Knowledge"); let keys: Vec<&str> = BASES.iter().map(|b| b.key).collect(); - assert_eq!(keys, [CODE, WORK, INFRA, OPS, SECURITY, TEAM]); + assert_eq!(keys, [CODE, WORK, INFRA, LOGS, SECURITY, TEAM]); + // Each base has a scope of its own. + let scopes: std::collections::BTreeSet<&str> = BASES.iter().map(|b| b.scope).collect(); + assert_eq!(scopes.len(), BASES.len()); let p = provenance("Work", "WEB-42 Checkout", "2026-11-12"); assert_eq!( p, diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 031a55666..40d4ea035 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -12,6 +12,7 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilte mod api_keys; mod auth; +mod bases; mod bedrock_setup; mod clients; mod knowledge_keys; @@ -866,6 +867,26 @@ fn build_app(state: Arc) -> Router { get(routes::knowledge::list_bases).post(routes::knowledge::create_base), ) .route("/knowledge/bedrock", get(routes::knowledge::bedrock_bases)) + // The six built-in bases and share links (routes::knowledge_builtin). + .route("/knowledge/builtin", get(routes::knowledge_builtin::list)) + .route( + "/knowledge/builtin/:key", + put(routes::knowledge_builtin::update), + ) + .route( + "/knowledge/builtin/:key/search", + get(routes::knowledge_builtin::search), + ) + .route( + "/knowledge/readers", + put(routes::knowledge_builtin::set_readers), + ) + .route("/share", post(routes::knowledge_builtin::create_share)) + .route( + "/share/:id", + get(routes::knowledge_builtin::get_share) + .delete(routes::knowledge_builtin::delete_share), + ) // Using the team's knowledge from Amazon Bedrock (routes::knowledge_bedrock). .route( "/knowledge/keys", diff --git a/services/gateway/src/mcp_lookups.rs b/services/gateway/src/mcp_lookups.rs index 61be8c636..6976bdc9e 100644 --- a/services/gateway/src/mcp_lookups.rs +++ b/services/gateway/src/mcp_lookups.rs @@ -11,9 +11,11 @@ //! //! Every read goes through the shared layer (`lookups`), as the person who //! connected the app: the connection must hold the read's scope -//! (`code:read`, `work:read`, `security:read`, `knowledge:read`) and the -//! person's role must open the dashboard route that shows it ([`decide`]), -//! the same check Chat's own lookups make. Results name the built-in base +//! (`code:read`, `work:read`, `infra:read`, `logs:read`, `security:read`, +//! `knowledge:read`), the person's role must open the dashboard route that +//! shows it ([`decide`]), the same check Chat's own lookups make, and the +//! base must be open to them (`bases::decide`: its audience). Code is read +//! only from repositories their linked GitHub account can read. Results name the built-in base //! they came from, link back to the dashboard, GitHub or Jira, carry a note //! that their text is data and not instructions, and `search` counts what //! it withheld for access without naming it. @@ -30,8 +32,11 @@ use common::repo_read::{CodeReader, GitHubHost, RepoInfo}; use serde_json::{json, Value}; use tracing::warn; +use crate::bases::{self, Decision}; use crate::lookups::{self, base_of, Base, DATA_NOTE}; -use crate::mcp_oauth::{CODE_SCOPE, KNOWLEDGE_SCOPE, SECURITY_SCOPE, WORK_SCOPE}; +use crate::mcp_oauth::{ + CODE_SCOPE, INFRA_SCOPE, KNOWLEDGE_SCOPE, LOGS_SCOPE, SECURITY_SCOPE, WORK_SCOPE, +}; use crate::mcp_server::Refusal; use crate::models::Claims; use crate::permissions::{resolve_access, Access, Holder}; @@ -49,6 +54,7 @@ pub const CODE_SEARCH: &str = "code_search"; pub const READ_FILE: &str = "read_file"; pub const CODE_SYMBOL: &str = "code_symbol"; pub const HISTORY: &str = "history"; +pub const INFRA_RESOURCES: &str = "infra_resources"; /// The knowledge search, as a lookup name (Chat's own is `search_knowledge`). pub const KNOWLEDGE: &str = "knowledge"; @@ -56,9 +62,9 @@ pub const KNOWLEDGE: &str = "knowledge"; pub const GITHUB_HISTORY: &str = "github_history"; pub const GRAPH_TOOLS: [&str; 3] = ["graph_definition", "graph_callers", "graph_impact"]; -/// The route that decides code and knowledge reads: asking in Chat, which -/// is where those reads happen in the dashboard. -pub const CHAT_ROUTE: &str = "brain::stream_token"; +/// The route that decides code and knowledge reads: reading the team's +/// knowledge, which every member does (`bases::READ_ROUTE`). +pub const CHAT_ROUTE: &str = bases::READ_ROUTE; /// Most results one `search` returns, and from each place it looks. pub const MAX_RESULTS: usize = 20; @@ -103,6 +109,14 @@ fn repo_prop() -> Value { json!({ "type": "string", "description": "One of the team's repositories, owner/name or its short name." }) } +fn base_prop() -> Value { + json!({ + "type": "string", + "enum": lookups::BASES.iter().map(|b| b.key).collect::>(), + "description": "Only this base: code, work, infra, logs, security or team (the team's documents)." + }) +} + fn search_output() -> Value { json!({ "type": "object", @@ -139,9 +153,12 @@ pub const TOOLS: &[Tool] = &[ Tool { name: SEARCH, title: "Search the team's knowledge", - description: "Searches what the team knows that you can read: knowledge bases, tickets, pull requests, CoderHelm's runs, code and security findings. Returns results with an id, title and link; read one in full with fetch. Each result names the base it came from, and results not open to you are counted, never shown.", + description: "Searches what the team knows that you can read: code, tickets, pull requests, CoderHelm's runs, AWS resources, log findings and alerts, security findings and the team's documents. Give base to search one base only. Returns results with an id, title and link; read one in full with fetch. Each result names the base it came from, and results not open to you are counted, never shown.", scopes: &[], - schema: || obj(json!({ "query": { "type": "string", "description": "What to find, in plain words." } }), &["query"]), + schema: || obj(json!({ + "query": { "type": "string", "description": "What to find, in plain words." }, + "base": base_prop() + }), &["query"]), output: Some(search_output), }, Tool { @@ -149,13 +166,16 @@ pub const TOOLS: &[Tool] = &[ title: "Read one result", description: "Reads one search result in full by its id: the text, a link to it (the lines on GitHub, the Jira ticket or the CoderHelm page) and where it came from. Access is checked again and the item is read again now.", scopes: &[], - schema: || obj(json!({ "id": { "type": "string", "description": "An id from search or another lookup." } }), &["id"]), + schema: || obj(json!({ + "id": { "type": "string", "description": "An id from search or another lookup." }, + "base": base_prop() + }), &["id"]), output: Some(fetch_output), }, Tool { name: LIST_BASES, title: "List the bases", - description: "Lists where the team's knowledge lives (Code and docs, Work, Infrastructure, Logs and operations, Security, Team knowledge), which of them this connection and your role can read, and the knowledge bases you can read.", + description: "Lists the team's six built-in bases (Code, Work, Infrastructure, Logs, Security, Knowledge): what each holds, how many items and when it last changed, and whether you can read it through this connection (and why not). Also the knowledge bases you can read.", scopes: &[], schema: || obj(json!({}), &[]), output: None, @@ -206,7 +226,7 @@ pub const TOOLS: &[Tool] = &[ name: FIND_FINDINGS, title: "Find findings and records", description: "Finds the team's findings and records by kind: security (dependency advisories and CVEs), infra (infrastructure findings), tests (quarantined tests), reviews (CoderHelm's pull request reviews), alerts, log_findings and plans. Search by an advisory id, a package, a repository or words.", - scopes: &[WORK_SCOPE, SECURITY_SCOPE], + scopes: &[WORK_SCOPE, SECURITY_SCOPE, INFRA_SCOPE, LOGS_SCOPE], schema: || obj(json!({ "kind": { "type": "string", "enum": FINDING_KINDS }, "query": { "type": "string", "description": "A CVE or advisory id, a package or words." }, @@ -216,6 +236,17 @@ pub const TOOLS: &[Tool] = &[ }), &["kind"]), output: None, }, + Tool { + name: INFRA_RESOURCES, + title: "Find AWS resources", + description: "Finds the team's AWS resources from the daily read of its connected accounts: name, kind, account and region, versions, whether the internet reaches it, what AWS has pending for it, and where it is defined (repository, file, Terraform address, CloudFormation stack or CDK construct). Search by words, a name or a repository.", + scopes: &[INFRA_SCOPE], + schema: || obj(json!({ + "query": { "type": "string", "description": "Words, a resource name, a kind like lambda or rds." }, + "repo": repo_prop() + }), &[]), + output: None, + }, Tool { name: CODE_SEARCH, title: "Search code", @@ -377,6 +408,38 @@ pub fn decide( } } +/// The base a read belongs to. +pub fn base_of_read(read: &Read) -> Option<&'static Base> { + needs(&read.lookup, &read.input).map(|(_, _, k)| base_of(k)) +} + +/// [`decide`], then the base's own decision (its audience): the one +/// permission decision every read on `/mcp` passes. +pub fn decide_open( + scopes: &BTreeSet<&'static str>, + holder: &Holder, + open: &BTreeMap<&'static str, Decision>, + read: &Read, +) -> Result<(), Fail> { + refuse(decide(scopes, holder, read))?; + let base = base_of_read(read) + .ok_or_else(|| Fail::Message("That isn't a lookup apps may make.".into()))?; + match open.get(base.key) { + Some(Decision::Open) => Ok(()), + Some(d) => Err(Fail::Message(closed_message(base, d))), + None => Err(Fail::Message(closed_message(base, &Decision::Role))), + } +} + +/// What a person is told when a base is closed to them. +pub fn closed_message(base: &Base, d: &Decision) -> String { + format!( + "{} isn't open to you: {}", + base.name, + d.why(base).unwrap_or_default() + ) +} + fn take(args: &Value, keys: &[&str]) -> Value { let mut out = serde_json::Map::new(); for k in keys { @@ -427,6 +490,11 @@ pub fn read_of(tool: &str, args: &Value) -> Result { }; Read::new(k.tool, take(args, keys)) } + INFRA_RESOURCES => { + let mut r = take(args, &["query", "repo"]); + r["kind"] = json!("resources"); + Read::new(chat_work::RECORDS, r) + } CODE_SEARCH => { if args["query"] .as_str() @@ -837,11 +905,29 @@ pub struct Answer { /// The team's connections the reads of one call use. struct Conns { work: chat_work::Ctx, + /// The team's repositories this person may read (GitHub mirroring). repos: Vec, + /// Repositories left out because the person's GitHub account can't read + /// them. + repos_withheld: usize, /// Why GitHub reads wait now, when they do. hold: Option, } +/// Every base's decision for this connection and person. +pub async fn open_bases(env: &Env) -> BTreeMap<&'static str, Decision> { + let auds = bases::audiences(&env.state, &env.claims.team_id).await; + let who = bases::Asker { + holder: &env.holder, + email: &env.claims.email, + }; + bases::decide_all(&who, &auds, Some(&env.scopes)) +} + +fn reads_repos(lookup: &str) -> bool { + uses_github(lookup) || GRAPH_TOOLS.contains(&lookup) +} + fn uses_github(lookup: &str) -> bool { matches!( lookup, @@ -849,10 +935,14 @@ fn uses_github(lookup: &str) -> bool { ) } -async fn connect(env: &Env, lookups_used: &[&str]) -> Conns { +async fn connect( + env: &Env, + lookups_used: &[&str], + open: &BTreeMap<&'static str, Decision>, +) -> Conns { let state = &env.state; let team = env.claims.team_id.as_str(); - let github = lookups_used.iter().any(|l| uses_github(l)); + let github = lookups_used.iter().any(|l| reads_repos(l)); let tickets = lookups_used.contains(&chat_work::TICKETS); let (repos, installation_id) = tokio::join!( crate::routes::brain::load_repos(state, team), @@ -882,11 +972,24 @@ async fn connect(env: &Env, lookups_used: &[&str]) -> Conns { } }, ); + let (repos, repos_withheld) = if github { + bases::visible_repos( + state, + team, + &env.holder.role, + env.claims.github_login.as_deref(), + token.as_deref(), + repos, + ) + .await + } else { + (repos, 0) + }; Conns { work: chat_work::Ctx { state: state.clone(), claims: env.claims.clone(), - readable: chat_work::readable(&env.holder), + readable: bases::readable_kinds(&env.holder, open), holder: env.holder.clone(), repos: repos.iter().map(|r| r.name.clone()).collect(), github_token: token, @@ -895,6 +998,7 @@ async fn connect(env: &Env, lookups_used: &[&str]) -> Conns { caller: common::github_budget::caller::MCP, }, repos, + repos_withheld, hold, } } @@ -1112,7 +1216,7 @@ async fn knowledge_read( let mut withheld = Withheld::default(); if !held.is_empty() { withheld.by_base.insert( - lookups::base(lookups::TEAM).map_or("Team knowledge", |b| b.name), + lookups::base(lookups::TEAM).map_or("Knowledge", |b| b.name), held.len(), ); } @@ -1145,7 +1249,9 @@ async fn knowledge_read( pub fn search_reads( scopes: &BTreeSet<&'static str>, holder: &Holder, + open: &BTreeMap<&'static str, Decision>, query: &str, + only: Option<&str>, ) -> (Vec, Withheld) { let q = json!(query); let candidates = [ @@ -1162,12 +1268,36 @@ pub fn search_reads( chat_work::FINDINGS, json!({ "kind": "infra", "query": q, "state": "any" }), ), + Read::new( + chat_work::RECORDS, + json!({ "kind": "resources", "query": q }), + ), + Read::new( + chat_work::RECORDS, + json!({ "kind": "log_findings", "query": q }), + ), + Read::new(chat_work::RECORDS, json!({ "kind": "alerts", "query": q })), ]; let mut reads = Vec::new(); let mut withheld = Withheld::default(); for r in candidates { + let base = base_of_read(&r); + if only.is_some_and(|o| base.is_none_or(|b| b.key != o)) { + continue; + } + let base_open = base + .and_then(|b| open.get(b.key)) + .is_some_and(Decision::is_open); match decide(scopes, holder, &r) { - Ok(_) => reads.push(r), + Ok(_) if base_open => reads.push(r), + Ok(_) => { + // The base's audience leaves it out: named, never read. + if let Some(b) = base { + if !withheld.kinds.contains(&b.name) { + withheld.kinds.push(b.name); + } + } + } // Not in this connection's scopes: not searched, not counted. Err(Refusal::Scope(_)) | Err(Refusal::NotForApps) => {} Err(Refusal::Role(_)) => { @@ -1189,6 +1319,24 @@ pub async fn run(env: &Env, tool: &str, args: &Value) -> Result { match tool { LIST_BASES => Box::pin(list_bases(env)).await, SEARCH => { + let only = match args["base"] + .as_str() + .map(str::trim) + .filter(|b| !b.is_empty()) + { + Some(b) => Some( + lookups::BASES + .iter() + .find(|x| x.key == b || x.name.eq_ignore_ascii_case(b)) + .ok_or_else(|| { + Fail::Message( + "base must be one of: code, work, infra, logs, security, team." + .into(), + ) + })?, + ), + None => None, + }; let query = args["query"].as_str().map(str::trim).unwrap_or(""); if query.is_empty() { return Err(Fail::Message("Give query: what to find.".into())); @@ -1198,9 +1346,24 @@ pub async fn run(env: &Env, tool: &str, args: &Value) -> Result { "Keep query under {MAX_QUERY_CHARS} characters." ))); } - let (reads, mut withheld) = search_reads(&env.scopes, &env.holder, query); + let open = open_bases(env).await; + if let Some(b) = only { + let d = open.get(b.key).cloned().unwrap_or(Decision::Role); + if let Decision::Scope(s) = d { + return Err(Fail::Scope(s)); + } + if !d.is_open() { + return Err(Fail::Message(closed_message(b, &d))); + } + } + let (reads, mut withheld) = + search_reads(&env.scopes, &env.holder, &open, query, only.map(|b| b.key)); let used: Vec<&str> = reads.iter().map(|r| r.lookup.as_str()).collect(); - let conns = connect(env, &used).await; + let conns = connect(env, &used, &open).await; + if conns.repos_withheld > 0 && used.iter().any(|l| reads_repos(l)) { + let code = lookups::base(lookups::CODE).map_or("Code", |b| b.name); + *withheld.by_base.entry(code).or_default() += conns.repos_withheld; + } let mut out: Vec = Vec::new(); let mut unread: Vec = Vec::new(); for r in &reads { @@ -1230,8 +1393,17 @@ pub async fn run(env: &Env, tool: &str, args: &Value) -> Result { FETCH => { let id = args["id"].as_str().unwrap_or(""); let Target { read, title, place } = decode_id(id).map_err(Fail::Message)?; - refuse(decide(&env.scopes, &env.holder, &read))?; - let conns = connect(env, &[read.lookup.as_str()]).await; + if let Some(b) = args["base"].as_str().filter(|b| !b.trim().is_empty()) { + if base_of_read(&read).is_none_or(|x| x.key != b.trim()) { + return Err(Fail::Message(format!( + "That id isn't from the {} base.", + b.trim() + ))); + } + } + let open = open_bases(env).await; + decide_open(&env.scopes, &env.holder, &open, &read)?; + let conns = connect(env, &[read.lookup.as_str()], &open).await; let mut reg = Registry::default(); let (text, _) = Box::pin(run_read(env, &conns, &mut reg, &read)) .await @@ -1259,8 +1431,9 @@ pub async fn run(env: &Env, tool: &str, args: &Value) -> Result { } _ => { let read = read_of(tool, args).map_err(Fail::Message)?; - refuse(decide(&env.scopes, &env.holder, &read))?; - let conns = connect(env, &[read.lookup.as_str()]).await; + let open = open_bases(env).await; + decide_open(&env.scopes, &env.holder, &open, &read)?; + let conns = connect(env, &[read.lookup.as_str()], &open).await; let mut reg = Registry::default(); let (text, _) = Box::pin(run_read(env, &conns, &mut reg, &read)) .await @@ -1301,33 +1474,23 @@ fn refuse(r: Result<&'static str, Refusal>) -> Result<(), Fail> { } } -/// Whether the role opens what a base holds today. -pub fn role_reads(holder: &Holder, base: &str) -> bool { - let route_ok = |h: &str| matches!(resolve_access(holder, Some(h)), Access::Allow { .. }); - match base { - lookups::CODE | lookups::TEAM => route_ok(CHAT_ROUTE), - b => chat_work::KINDS - .iter() - .filter(|k| base_of(k.key).key == b) - .any(|k| route_ok(k.handler)), - } -} - /// `list_bases`: the six bases (what each holds now, and whether this /// connection and role read it) and the knowledge bases the person reads. async fn list_bases(env: &Env) -> Result { use common::knowledge::search::Store; - let bases: Vec = lookups::BASES - .iter() - .map(|b| { - json!({ - "key": b.key, - "name": b.name, - "holds": b.about, - "scope": b.scope, - "this_connection_may_read": env.scopes.contains(b.scope), - "your_role_may_read": role_reads(&env.holder, b.key), - }) + let who = bases::Asker { + holder: &env.holder, + email: &env.claims.email, + }; + let bases: Vec = bases::list(&env.state, &env.claims.team_id, &who, Some(&env.scopes)) + .await + .into_iter() + .map(|mut b| { + // What an AI tool needs; the audience's names stay in CoderHelm. + if let Some(o) = b.as_object_mut() { + o.remove("audience"); + } + b }) .collect(); let mut kbs: Vec = Vec::new(); @@ -1345,9 +1508,10 @@ async fn list_bases(env: &Env) -> Result { }; let open = crate::mcp_knowledge::readable(all, &reader).unwrap_or_default(); if total > open.len() { - withheld - .by_base - .insert("Team knowledge", total - open.len()); + withheld.by_base.insert( + lookups::base(lookups::TEAM).map_or("Knowledge", |b| b.name), + total - open.len(), + ); } kbs = open .iter() @@ -1363,7 +1527,7 @@ async fn list_bases(env: &Env) -> Result { "bases": bases, "knowledge_bases": kbs, "withheld": withheld.to_json(), - "note": "These six are the names results carry today. Each reads what your CoderHelm role opens in the dashboard, through the scopes this connection holds; their own audiences and settings come later.", + "note": "Each base is open to you when your CoderHelm role opens what it holds, its audience includes you, and this connection holds its scope. Code follows your GitHub access. Closed bases say why, never what is in them.", }), items: Vec::new(), withheld: n, @@ -1485,6 +1649,13 @@ mod tests { crate::mcp_oauth::SCOPES.iter().copied().collect() } + fn all_open() -> BTreeMap<&'static str, Decision> { + lookups::BASES + .iter() + .map(|b| (b.key, Decision::Open)) + .collect() + } + fn custom(caps: &[&str]) -> Holder { let caps: Vec = caps.iter().map(|c| c.to_string()).collect(); Holder::custom("r1", Some(("Custom", &caps))) @@ -1509,6 +1680,7 @@ mod tests { (FIND_PULL_REQUESTS, json!({ "ticket": "WEB-42" })), (FIND_RUNS, json!({ "status": "active" })), (CODE_SEARCH, json!({ "query": "refund" })), + (INFRA_RESOURCES, json!({ "query": "orders" })), ( READ_FILE, json!({ "repo": "acme/web", "path": "src/pay.ts" }), @@ -1540,6 +1712,7 @@ mod tests { FIND_PULL_REQUESTS, FIND_RUNS, FIND_FINDINGS, + INFRA_RESOURCES, CODE_SEARCH, READ_FILE, CODE_SYMBOL, @@ -1672,14 +1845,14 @@ mod tests { } } } - // A viewer reads runs, not code (Chat needs asking). + // Everyone on the team reads runs and code (reading knowledge is + // every member's; asking Chat is not needed to read). let viewer = Holder::builtin("viewer"); let runs = read_of(FIND_RUNS, &json!({})).unwrap(); assert!(decide(&all_scopes(), &viewer, &runs).is_ok()); let code = read_of(CODE_SEARCH, &json!({ "query": "x" })).unwrap(); - assert!( - matches!(decide(&all_scopes(), &viewer, &code), Err(Refusal::Role(c)) if c.key == "brain_ask") - ); + assert!(decide(&all_scopes(), &viewer, &code).is_ok()); + assert!(decide(&all_scopes(), &Holder::builtin(bases::READER_ROLE), &code).is_ok()); // Nothing else: a write tool or a made-up lookup is never a read. for l in ["start_run", "write_file", "live_lookup", "db_query"] { assert_eq!( @@ -1708,11 +1881,19 @@ mod tests { ); assert_eq!( scope_needed(FIND_FINDINGS, &json!({"kind": "infra"})), - Some(SECURITY_SCOPE) + Some(INFRA_SCOPE) + ); + assert_eq!( + scope_needed(INFRA_RESOURCES, &json!({"query": "orders"})), + Some(INFRA_SCOPE) ); assert_eq!( scope_needed(FIND_FINDINGS, &json!({"kind": "alerts"})), - Some(SECURITY_SCOPE) + Some(LOGS_SCOPE) + ); + assert_eq!( + scope_needed(FIND_FINDINGS, &json!({"kind": "log_findings"})), + Some(LOGS_SCOPE) ); assert_eq!( scope_needed(FIND_FINDINGS, &json!({"kind": "reviews"})), @@ -1747,6 +1928,8 @@ mod tests { ] ); assert!(names(BTreeSet::from([SECURITY_SCOPE])).contains(&FIND_FINDINGS.to_string())); + assert!(names(BTreeSet::from([INFRA_SCOPE])).contains(&INFRA_RESOURCES.to_string())); + assert!(!names(BTreeSet::from([LOGS_SCOPE])).contains(&INFRA_RESOURCES.to_string())); // The search toolset: two tools, whatever the scopes. let two: Vec = listing(&all_scopes(), true); assert_eq!(two.len(), 2); @@ -1757,12 +1940,18 @@ mod tests { #[test] fn search_reads_what_the_connection_and_role_reach_and_counts_the_rest() { let member = Holder::builtin("member"); - let (reads, w) = search_reads(&all_scopes(), &member, "refund"); + let (reads, w) = search_reads(&all_scopes(), &member, &all_open(), "refund", None); let looks: Vec<&str> = reads.iter().map(|r| r.lookup.as_str()).collect(); assert!(looks.contains(&KNOWLEDGE) && looks.contains(&chat_code::SEARCH_CODE)); assert!(looks.contains(&chat_work::TICKETS)); // Only work scope: no code, no knowledge, no security. - let (reads, _) = search_reads(&BTreeSet::from([READ_SCOPE, WORK_SCOPE]), &member, "x"); + let (reads, _) = search_reads( + &BTreeSet::from([READ_SCOPE, WORK_SCOPE]), + &member, + &all_open(), + "x", + None, + ); for r in &reads { assert_eq!(needs(&r.lookup, &r.input).unwrap().0, WORK_SCOPE); } @@ -1772,7 +1961,7 @@ mod tests { caps: Default::default(), custom: None, }; - let (reads, w2) = search_reads(&all_scopes(), &none, "x"); + let (reads, w2) = search_reads(&all_scopes(), &none, &all_open(), "x", None); assert!(!reads.iter().any(|r| r.lookup == chat_work::RUNS)); assert!( w2.kinds.contains(&"runs") && w2.kinds.contains(&"tickets"), @@ -1782,15 +1971,55 @@ mod tests { assert!(w.kinds.is_empty() || !w.kinds.contains(&"runs")); } + /// Each base searches on its own, and a base closed to the person (its + /// audience, or paused) is never read: it is named as not open, and + /// nothing from it comes back. + #[test] + fn each_base_searches_alone_and_a_closed_one_gives_nothing() { + let admin = Holder::builtin("admin"); + for b in lookups::BASES.iter() { + let (reads, _) = + search_reads(&all_scopes(), &admin, &all_open(), "orders", Some(b.key)); + assert!(!reads.is_empty(), "{} has nothing to search", b.key); + for r in &reads { + assert_eq!(base_of_read(r).unwrap().key, b.key, "{}", r.lookup); + } + } + let mut open = all_open(); + open.insert(lookups::INFRA, Decision::Audience); + let (reads, w) = search_reads(&all_scopes(), &admin, &open, "orders", None); + assert!(reads + .iter() + .all(|r| base_of_read(r).unwrap().key != lookups::INFRA)); + assert!(w.kinds.contains(&"Infrastructure"), "{:?}", w.kinds); + let (reads, w) = search_reads(&all_scopes(), &admin, &open, "orders", Some(lookups::INFRA)); + assert!(reads.is_empty()); + assert_eq!(w.kinds, ["Infrastructure"]); + // A typed lookup and a fetch into it are refused with the reason. + let read = read_of(INFRA_RESOURCES, &json!({ "query": "orders" })).unwrap(); + match decide_open(&all_scopes(), &admin, &open, &read) { + Err(Fail::Message(m)) => { + assert!(m.starts_with("Infrastructure isn't open to you"), "{m}") + } + other => panic!("{other:?}"), + } + assert!(decide_open(&all_scopes(), &admin, &all_open(), &read).is_ok()); + // Without the scope, the client is asked to step up. + assert_eq!( + decide_open(&BTreeSet::from([READ_SCOPE]), &admin, &all_open(), &read), + Err(Fail::Scope(INFRA_SCOPE)) + ); + } + #[test] fn withheld_counts_never_name_what() { let mut w = Withheld::default(); - w.by_base.insert("Team knowledge", 3); + w.by_base.insert("Knowledge", 3); w.by_base.insert("Security", 1); w.kinds.push("security findings"); let v = w.to_json(); assert_eq!(v["count"], 4); - assert_eq!(v["by_base"]["Team knowledge"], 3); + assert_eq!(v["by_base"]["Knowledge"], 3); assert_eq!(v["reason"], "access"); let text = v.to_string(); assert!(!text.contains("title") && !text.contains("passage")); @@ -1868,7 +2097,7 @@ mod tests { assert!(r["base"].is_string() && r["updated_at"].is_string()); } assert_eq!(a["results"][0]["base"], "Work"); - assert_eq!(a["results"][2]["base"], "Code and docs"); + assert_eq!(a["results"][2]["base"], "Code"); assert_eq!(a["results"][1]["url"], "https://app.x/runs/detail?id=01RUN"); assert_eq!( found[0].links["jira"], @@ -1963,10 +2192,7 @@ mod tests { READ_FILE, &json!({ "repo": "acme/web", "path": "src/a.rs" }), ); - assert_eq!( - d, - "read_file: Code and docs / code, repo acme/web, path src/a.rs" - ); + assert_eq!(d, "read_file: Code / code, repo acme/web, path src/a.rs"); let d = audit_detail( FIND_FINDINGS, &json!({ "kind": "security", "query": "openssl" }), @@ -1988,7 +2214,7 @@ mod tests { let r = result_detail(SEARCH, &a); assert_eq!( r, - "search: 4 results (Code and docs 1, Work 3), 2 withheld for access: WEB-42; Run:; acme/web:src/pay.ts; #318" + "search: 4 results (Code 1, Work 3), 2 withheld for access: WEB-42; Run:; acme/web:src/pay.ts; #318" ); assert!(!r.contains("Ignore your instructions")); } diff --git a/services/gateway/src/mcp_oauth.rs b/services/gateway/src/mcp_oauth.rs index cc87e12f6..a49799957 100644 --- a/services/gateway/src/mcp_oauth.rs +++ b/services/gateway/src/mcp_oauth.rs @@ -53,10 +53,16 @@ pub const CODE_SCOPE: &str = "code:read"; /// Reading the team's work: tickets, pull requests, runs, reviews and plans /// (the Work base). pub const WORK_SCOPE: &str = "work:read"; -/// Reading security and infrastructure findings, quarantined tests, alerts -/// and log findings (the Security base, and Infrastructure and Logs and -/// operations until they have scopes of their own). +/// Reading security findings: dependency advisories and CVEs, quarantined +/// tests (the Security base). pub const SECURITY_SCOPE: &str = "security:read"; +/// Reading the team's AWS: accounts, resources, where each is defined in +/// Terraform, CDK or CloudFormation, pending updates and infrastructure +/// findings (the Infrastructure base). +pub const INFRA_SCOPE: &str = "infra:read"; +/// Reading alerts and log findings, and which repository and service they +/// belong to (the Logs base). +pub const LOGS_SCOPE: &str = "logs:read"; /// Every scope, in the order they are shown. pub const SCOPES: &[&str] = &[ READ_SCOPE, @@ -64,25 +70,49 @@ pub const SCOPES: &[&str] = &[ KNOWLEDGE_SCOPE, CODE_SCOPE, WORK_SCOPE, + INFRA_SCOPE, + LOGS_SCOPE, SECURITY_SCOPE, ]; /// The scopes of the team lookups (`mcp_lookups`), which only read. -pub const LOOKUP_SCOPES: &[&str] = &[CODE_SCOPE, WORK_SCOPE, SECURITY_SCOPE]; +pub const LOOKUP_SCOPES: &[&str] = &[ + CODE_SCOPE, + WORK_SCOPE, + INFRA_SCOPE, + LOGS_SCOPE, + SECURITY_SCOPE, +]; /// The lookup scopes granted when the consent page doesn't say otherwise: -/// code and work. Security findings only when asked for and allowed. +/// code and work. Infrastructure, logs and security only when asked for and +/// allowed. pub const DEFAULT_LOOKUP_SCOPES: &[&str] = &[CODE_SCOPE, WORK_SCOPE]; -/// What a scope lets an app do, as the consent page says it. +/// What a scope lets an app do, in plain words, as the consent page says it. pub fn scope_label(scope: &str) -> &'static str { match scope { READ_SCOPE => "See your team's runs and reviews", WRITE_SCOPE => "Start and retry runs, and ask for reviews", - KNOWLEDGE_SCOPE => "Search the knowledge bases you can read in Chat", - CODE_SCOPE => "Read and search your team's code, as Chat does", + KNOWLEDGE_SCOPE => "Search the team's documents and knowledge bases you can read", + CODE_SCOPE => "Read and search the code in repositories you can see", WORK_SCOPE => "Find tickets, pull requests, runs, reviews and plans you can see", - SECURITY_SCOPE => { - "Read security and infrastructure findings, alerts and log findings you can see" - } + INFRA_SCOPE => "See the team's AWS resources, where each is defined, and pending updates", + LOGS_SCOPE => "See alerts and problems found in the logs", + SECURITY_SCOPE => "See security findings: advisories, CVEs, fixes and quarantined tests", + _ => "", + } +} + +/// One word for a scope, as the consent page heads it. +pub fn scope_plain(scope: &str) -> &'static str { + match scope { + READ_SCOPE => "Runs", + WRITE_SCOPE => "Act", + KNOWLEDGE_SCOPE => "Knowledge", + CODE_SCOPE => "Code", + WORK_SCOPE => "Work", + INFRA_SCOPE => "Infrastructure", + LOGS_SCOPE => "Logs", + SECURITY_SCOPE => "Security", _ => "", } } @@ -392,6 +422,93 @@ pub fn register( }) } +// ── Client ID Metadata Documents ──────────────────────────────────── + +/// A client's metadata document is read again after a day. +pub const METADATA_DOCUMENT_TTL_SECS: i64 = 86_400; + +/// Is `id` a Client ID Metadata Document address (the MCP authorization +/// spec's preferred way for a client to say who it is)? An `https` URL with +/// a path, no fragment, no user name, no dot segments. +pub fn is_metadata_client_id(id: &str) -> bool { + if id.len() > MAX_URI_LEN || !id.starts_with("https://") { + return false; + } + let Ok(u) = url::Url::parse(id) else { + return false; + }; + let raw_path = id + .trim_start_matches("https://") + .split_once('/') + .map_or("", |(_, p)| p); + u.host().is_some() + && u.fragment().is_none() + && u.username().is_empty() + && u.password().is_none() + && u.path().len() > 1 + && !raw_path + .split(['/', '?']) + .any(|seg| seg == "." || seg == "..") +} + +/// The client a metadata document describes, checked: its `client_id` is +/// exactly the address it was read from, it names where codes may go +/// (checked as a registration's are), and it is a public client. +pub fn client_from_document( + client_id: &str, + doc: &serde_json::Value, + now: chrono::DateTime, +) -> Result { + if !is_metadata_client_id(client_id) { + return Err("The app's address isn't a client metadata document.".into()); + } + if doc["client_id"].as_str() != Some(client_id) { + return Err("The app's metadata document names a different client_id.".into()); + } + let redirect_uris: Vec = doc["redirect_uris"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + if redirect_uris.is_empty() || redirect_uris.len() > MAX_REDIRECT_URIS { + return Err("The app's metadata document needs 1 to 10 redirect_uris.".into()); + } + for uri in &redirect_uris { + check_redirect_uri(uri)?; + } + match doc["token_endpoint_auth_method"].as_str() { + None | Some("none") => {} + Some(_) => { + return Err( + "CoderHelm signs in public clients only: token_endpoint_auth_method must be none." + .into(), + ) + } + } + let client_uri = doc["client_uri"] + .as_str() + .filter(|u| u.len() <= MAX_URI_LEN && u.starts_with("https://")) + .map(str::to_string); + Ok(StoredClient { + client_id: client_id.to_string(), + client_name: clean_name(doc["client_name"].as_str()), + redirect_uris, + client_uri, + created_at: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + }) +} + +/// Whether a stored client read from a metadata document is due to be read +/// again. +pub fn document_stale(c: &StoredClient, now: chrono::DateTime) -> bool { + chrono::DateTime::parse_from_rfc3339(&c.created_at).map_or(true, |t| { + now.timestamp() - t.timestamp() >= METADATA_DOCUMENT_TTL_SECS + }) +} + /// The registration answer (RFC 7591 3.2.1). `token_endpoint_auth_method` /// is always `none`, whatever was asked: every client here is public. pub fn registration_answer(c: &StoredClient, issued_at: i64) -> serde_json::Value { @@ -1323,6 +1440,13 @@ fn epoch(at: &str) -> i64 { impl OAuthStore for DynamoOAuth<'_> { async fn put_client(&self, c: &StoredClient) -> Result<(), String> { let ttl = epoch(&c.created_at) + CLIENT_TTL_DAYS * 86_400; + // A registered client is written once; a metadata document's client + // is its document, read again when stale. + let condition = if is_metadata_client_id(&c.client_id) { + None + } else { + Some("attribute_not_exists(pk)".to_string()) + }; self.dynamo .put_item() .table_name(self.table) @@ -1334,7 +1458,7 @@ impl OAuthStore for DynamoOAuth<'_> { s(&serde_json::to_string(c).map_err(|e| e.to_string())?), ) .item("ttl", n(ttl)) - .condition_expression("attribute_not_exists(pk)") + .set_condition_expression(condition) .send() .await .map_err(err)?; @@ -1342,7 +1466,8 @@ impl OAuthStore for DynamoOAuth<'_> { } async fn get_client(&self, id: &str) -> Result, String> { - if !id.starts_with(CLIENT_PREFIX) || id.len() > 64 { + let registered = id.starts_with(CLIENT_PREFIX) && id.len() <= 64; + if !registered && !is_metadata_client_id(id) { return Ok(None); } let r = self @@ -2327,4 +2452,74 @@ pub(crate) mod tests { .await .unwrap()); } + + #[test] + fn a_metadata_document_is_its_own_client() { + let id = "https://app.example.com/oauth/client.json"; + assert!(is_metadata_client_id(id)); + for bad in [ + "mcpc_01abc", + "http://app.example.com/c.json", + "https://app.example.com", + "https://app.example.com/", + "https://app.example.com/c.json#x", + "https://user@app.example.com/c.json", + "https://app.example.com/a/../c.json", + ] { + assert!(!is_metadata_client_id(bad), "{bad}"); + } + let now = chrono::Utc::now(); + let doc = serde_json::json!({ + "client_id": id, + "client_name": "Example Tool", + "redirect_uris": ["http://localhost/callback", "https://app.example.com/cb"], + "token_endpoint_auth_method": "none", + }); + let c = client_from_document(id, &doc, now).unwrap(); + assert_eq!(c.client_id, id); + assert_eq!(c.client_name, "Example Tool"); + // A loopback redirect matches on any port (a native app picks one). + assert!(redirect_matches( + &c.redirect_uris, + "http://localhost:53682/callback" + )); + assert!(!redirect_matches( + &c.redirect_uris, + "https://evil.example.net/cb" + )); + // The document must name itself, list safe redirects, and be public. + let mut other = doc.clone(); + other["client_id"] = serde_json::json!("https://evil.example.net/c.json"); + assert!(client_from_document(id, &other, now).is_err()); + let mut unsafe_uri = doc.clone(); + unsafe_uri["redirect_uris"] = serde_json::json!(["javascript:alert(1)"]); + assert!(client_from_document(id, &unsafe_uri, now).is_err()); + let mut secret = doc.clone(); + secret["token_endpoint_auth_method"] = serde_json::json!("client_secret_basic"); + assert!(client_from_document(id, &secret, now).is_err()); + let mut none = doc; + none["redirect_uris"] = serde_json::json!([]); + assert!(client_from_document(id, &none, now).is_err()); + // Read again after a day. + assert!(!document_stale(&c, now)); + assert!(document_stale( + &c, + now + chrono::Duration::seconds(METADATA_DOCUMENT_TTL_SECS) + )); + } + + #[test] + fn every_lookup_scope_says_what_it_opens_in_plain_words() { + for s in LOOKUP_SCOPES { + assert!(!scope_label(s).is_empty(), "{s}"); + assert!(!scope_plain(s).is_empty(), "{s}"); + assert!(SCOPES.contains(s)); + } + // Infrastructure, logs and security are asked for, never given by default. + for s in [INFRA_SCOPE, LOGS_SCOPE, SECURITY_SCOPE] { + assert!(!DEFAULT_LOOKUP_SCOPES.contains(&s)); + assert!(lookup_grant(None, &[]).iter().all(|g| *g != s)); + assert!(lookup_grant(None, &[s.to_string()]).contains(s)); + } + } } diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 52ffa6dbf..dbfaeca4b 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -11,8 +11,8 @@ use serde::Serialize; use std::collections::{BTreeSet, HashMap}; use std::sync::OnceLock; -/// Numeric role level: owner=4, admin=3, billing=2, member=1, viewer=0. -/// Unknown roles get the lowest level. +/// Numeric role level: owner=4, admin=3, billing=2, member=1, viewer=0, +/// reader=0. Unknown roles get the lowest level. pub fn role_level(role: &str) -> u8 { match role { "owner" => 4, @@ -25,7 +25,9 @@ pub fn role_level(role: &str) -> u8 { /// Roles the gateway accepts on a record. `billing` is kept for older records; /// nothing requires it, so it has exactly a member's access and is not offered. -pub const VALID_ROLES: &[&str] = &["owner", "admin", "billing", "member", "viewer"]; +/// `reader` is a person who connected an AI tool without an account +/// (`bases::READER_ROLE`): a viewer's reads, never a seat. +pub const VALID_ROLES: &[&str] = &["owner", "admin", "billing", "member", "viewer", "reader"]; #[derive(Serialize, Clone, Copy)] pub struct RoleInfo { @@ -38,6 +40,13 @@ pub struct RoleInfo { } pub const ROLES: &[RoleInfo] = &[ + RoleInfo { + key: "reader", + label: "Reader", + level: 0, + summary: "Reads the team's bases from Chat and their own AI tools. Not a seat.", + assignable: true, + }, RoleInfo { key: "viewer", label: "Viewer", @@ -150,6 +159,11 @@ pub const CAPABILITIES: &[Capability] = &[ "knowledge_ask::search_base", "knowledge_ask::suggestions", "knowledge_ask::usage", + "knowledge_builtin::list", + "knowledge_builtin::search", + "knowledge_builtin::create_share", + "knowledge_builtin::get_share", + "knowledge_builtin::delete_share", "brain::list_threads", "brain::get_thread", "brain::sources", @@ -371,6 +385,7 @@ pub const CAPABILITIES: &[Capability] = &[ min_role: "admin", handlers: &[ "knowledge::create_base", + "knowledge_builtin::update", "knowledge::bedrock_bases", "knowledge_bedrock::list_keys", "knowledge_bedrock::create_key", @@ -421,6 +436,7 @@ pub const CAPABILITIES: &[Capability] = &[ "users::update_role", "users::remove_user", "users::link_github", + "knowledge_builtin::set_readers", ], }, Capability { @@ -1890,11 +1906,18 @@ mod tests { assert!(can_grant("owner", "owner")); assert!(!can_grant("owner", "superuser")); - assert_eq!(grantable_roles("admin"), vec!["viewer", "member"]); + assert_eq!(grantable_roles("admin"), vec!["reader", "viewer", "member"]); assert_eq!( grantable_roles("owner"), - vec!["viewer", "member", "admin", "owner"] + vec!["reader", "viewer", "member", "admin", "owner"] + ); + // A reader (connected from an AI tool, not a seat) reads what a + // viewer reads, and admins manage readers. + assert_eq!( + builtin_capabilities("reader"), + builtin_capabilities("viewer") ); + assert!(can_manage("admin", "reader")); assert!(grantable_roles("member").is_empty()); // Invites are not seats: an admin manages every pending invite, diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index 59ae0bded..1cfc67b4e 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -1715,7 +1715,10 @@ fn github_not_set_up(state: &AppState, step: &'static str) -> Option { /// GET /auth/github — Redirect to GitHub OAuth (sign in, or connect a GitHub /// account). Without an OAuth client of its own, a hybrid install goes /// through CoderHelm's GitHub App (routes::github_hybrid). -pub async fn github_login(State(state): State>) -> Response { +pub async fn github_login( + State(state): State>, + Query(q): Query, +) -> Response { if !own_github_client(&state) && super::github_hybrid::available() { return super::github_hybrid::start(&state).await; } @@ -1731,14 +1734,63 @@ pub async fn github_login(State(state): State>) -> Response { let url = format!( "https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&scope=read:user,read:org&state={csrf}" ); - ( + let mut resp = ( [( header::SET_COOKIE, oauth_signin::state_cookie(Provider::Github, &csrf), )], Redirect::temporary(&url), ) - .into_response() + .into_response(); + // Signing in from an AI tool's consent page: come back to it after. + if let Some(back) = q.return_to.as_deref().and_then(safe_return_to) { + if let Ok(v) = HeaderValue::from_str(&return_to_cookie(&back)) { + resp.headers_mut().append(header::SET_COOKIE, v); + } + } + resp +} + +#[derive(Deserialize, Default)] +pub struct GithubLoginQuery { + #[serde(default)] + pub return_to: Option, +} + +const RETURN_TO_COOKIE: &str = "coderhelm_return_to"; + +/// Where a sign-in may send the person back to: only the consent page of an +/// AI tool's sign-in, as a path on the dashboard, never another site. +pub fn safe_return_to(raw: &str) -> Option { + let r = raw.trim(); + let ok = r.starts_with("/authorize/?request=") + && r.len() <= 4_000 + && !r.contains("//") + && !r.contains('\\') + && r.chars().all(|c| c.is_ascii_graphic()); + ok.then(|| r.to_string()) +} + +fn return_to_cookie(path: &str) -> String { + format!( + "{RETURN_TO_COOKIE}={}; HttpOnly; Secure; SameSite=Lax; Path=/auth; Max-Age=900", + urlencoding::encode(path) + ) +} + +/// The consent page a sign-in started from, when it did. +fn return_to_of(headers: &HeaderMap) -> Option { + let raw = extract_cookie(cookie_header(headers), RETURN_TO_COOKIE)?; + let path = urlencoding::decode(raw).ok()?; + safe_return_to(&path) +} + +/// Whether a first GitHub sign-in may join `team` as a reader: the team lets +/// people connect AI tools as readers, and GitHub just showed, with the +/// person's own token, that they can reach the team's installation (they +/// are in its organization). +pub(crate) fn may_join_as_reader(readers_enabled: bool, owns_installation: bool) -> bool { + readers_enabled && owns_installation } /// GET /auth/github/callback — GitHub OAuth callback. @@ -2127,8 +2179,34 @@ pub(crate) async fn github_sign_in_with_token( let has_existing_record = existing_user.is_some(); + // A first sign-in from the organization of a team that lets people + // connect AI tools as readers: a reader of that team (no seat, no + // invite). Otherwise the rules below. + let mut reader_team: Option = None; + if !has_existing_record && from == TokenFrom::OwnClient { + for (inst_id, org) in &all_installations { + if let Some(owner) = + super::github_webhook::resolve_team_by_installation(state, *inst_id).await + { + if may_join_as_reader(crate::bases::readers_enabled(state, &owner).await, true) { + info!( + github_login, + org = org.as_str(), + team_id = %owner, + "First GitHub sign-in joins as a reader" + ); + reader_team = Some(owner); + break; + } + } + } + } + // Open beta: a first sign-in starts a team, a few times an hour per address. - if !has_existing_record && super::open_signup::allow_new_team(state, ip).await.is_err() { + if !has_existing_record + && reader_team.is_none() + && super::open_signup::allow_new_team(state, ip).await.is_err() + { let dash = common::public_urls::app_url(&state.config.stage); return Ok(Redirect::temporary(&format!("{dash}?error=signup_limit")).into_response()); } @@ -2138,7 +2216,7 @@ pub(crate) async fn github_sign_in_with_token( // installation (each such team split the org and stole its webhooks). // The person needs an invite from that team; an invited person already // has a record and never reaches this branch. - if !has_existing_record { + if !has_existing_record && reader_team.is_none() { for (inst_id, org) in &all_installations { if let Some(owner) = super::github_webhook::resolve_team_by_installation(state, *inst_id).await @@ -2174,6 +2252,12 @@ pub(crate) async fn github_sign_in_with_token( .cloned() .unwrap_or_else(|| "member".to_string()); (tid, uid, r) + } else if let Some(team) = reader_team.clone() { + ( + team, + github_user_id.clone(), + crate::bases::READER_ROLE.to_string(), + ) } else { // Brand new user — create a new team with ULID let new_team_id = format!("TEAM#{}", ulid::Ulid::new().to_string().to_lowercase()); @@ -2238,7 +2322,7 @@ pub(crate) async fn github_sign_in_with_token( .map_or(email, |e| e.as_str()); // Ensure teams table record exists (for new users without an existing record) - if !has_existing_record { + if !has_existing_record && reader_team.is_none() { let _ = state .dynamo .put_item() @@ -2257,6 +2341,8 @@ pub(crate) async fn github_sign_in_with_token( // Link GitHub installations to the team in the teams table — only when no // OTHER team owns the installation already. let link_target = match all_installations.first() { + // A reader never links an installation. + Some(_) if reader_team.is_some() => None, Some(&(inst_id, _)) => { let owner = super::github_webhook::resolve_team_by_installation(state, inst_id).await; if may_link_installation(owner.as_deref(), &team_id) { @@ -2388,7 +2474,17 @@ pub(crate) async fn github_sign_in_with_token( .map_err(|e| SignInFailure::new(P, Reason::Server, "session_token", e))?; let dashboard_url = common::public_urls::app_url(&state.config.stage); - Ok(session_redirect(P, &token, dashboard_url)) + let back = match return_to_of(headers) { + Some(path) => format!("{dashboard_url}{path}"), + None => dashboard_url.to_string(), + }; + let mut resp = session_redirect(P, &token, &back); + if let Ok(v) = HeaderValue::from_str(&format!( + "{RETURN_TO_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/auth; Max-Age=0" + )) { + resp.headers_mut().append(header::SET_COOKIE, v); + } + Ok(resp) } /// Record when a member last signed in (shown on the team page). Only that one @@ -3750,4 +3846,34 @@ mod github_link_tests { assert_eq!(link_outcome(true, 2, 0), "owned_elsewhere"); assert_eq!(link_outcome(true, 2, 1), "linked"); } + + #[test] + fn a_reader_joins_only_where_the_team_lets_readers_in() { + assert!(crate::routes::auth::may_join_as_reader(true, true)); + assert!(!crate::routes::auth::may_join_as_reader(false, true)); + assert!(!crate::routes::auth::may_join_as_reader(true, false)); + } + + #[test] + fn a_sign_in_returns_only_to_an_ai_tools_consent_page() { + let ok = "/authorize/?request=eyJhbGciOi.abc_DEF-123"; + assert_eq!(crate::routes::auth::safe_return_to(ok).as_deref(), Some(ok)); + for bad in [ + "https://evil.example.net/authorize/?request=x", + "//evil.example.net/authorize/?request=x", + "/settings/", + "/authorize/?request=a//b", + "/authorize/?request=a b", + "/authorize/?request=a\\b", + ] { + assert!(crate::routes::auth::safe_return_to(bad).is_none(), "{bad}"); + } + assert!(crate::routes::auth::safe_return_to(&format!( + "/authorize/?request={}", + "a".repeat(5_000) + )) + .is_none()); + let c = crate::routes::auth::return_to_cookie(ok); + assert!(c.contains("HttpOnly") && c.contains("Secure") && c.contains("Path=/auth")); + } } diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index c708a74ff..3c0684e45 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -2157,14 +2157,29 @@ pub async fn brain_stream( let (api_key, model_id, check_model_id) = load_provider(&state, &claims.team_id).await; let st = super::knowledge::store(&state); - let readable: Vec = super::knowledge::chat_readable( - st.bases(&claims.team_id).await.unwrap_or_default(), - &holder, - &me, - ) - .into_iter() - .map(|b| b.id) - .collect(); + // The built-in bases decide what Chat reads, as they do for AI tools: + // a base closed to this person is never read for them (crate::bases). + let open = { + let auds = crate::bases::audiences(&state, &claims.team_id).await; + let who = crate::bases::Asker { + holder: &holder, + email: &claims.email, + }; + crate::bases::decide_all(&who, &auds, None) + }; + let base_open = |k: &str| open.get(k).is_some_and(crate::bases::Decision::is_open); + let readable: Vec = if base_open(crate::lookups::TEAM) { + super::knowledge::chat_readable( + st.bases(&claims.team_id).await.unwrap_or_default(), + &holder, + &me, + ) + .into_iter() + .map(|b| b.id) + .collect() + } else { + Vec::new() + }; let all_repos = load_repos(&state, &claims.team_id).await; let repo_names: Vec = all_repos.iter().map(|r| r.name.clone()).collect(); let picks = resolve_picks( @@ -2173,7 +2188,7 @@ pub async fn brain_stream( &readable, &repo_names, ); - let code_repos: Vec = if picks.code { + let code_repos: Vec = if picks.code && base_open(crate::lookups::CODE) { all_repos .iter() .filter(|r| picks.repos.is_empty() || picks.repos.contains(&r.name)) @@ -2182,6 +2197,26 @@ pub async fn brain_stream( } else { Vec::new() }; + let github = if (picks.code && !code_repos.is_empty()) || (picks.work && !all_repos.is_empty()) + { + github_token(&state, &claims.team_id).await + } else { + None + }; + // Code only from repositories the person's GitHub account can read. + let (code_repos, _) = if code_repos.is_empty() { + (code_repos, 0) + } else { + crate::bases::visible_repos( + &state, + &claims.team_id, + &holder.role, + claims.github_login.as_deref(), + github.as_deref(), + code_repos, + ) + .await + }; // The repository skills, data sources and the code graph start from: the // one named in the question, else the one picked, else the first. let named = common::repo_read::mentioned(&code_repos, &question) @@ -2203,7 +2238,7 @@ pub async fn brain_stream( mcp: false, }; let needs_worker = picks.skills || picks.data_sources || picks.code; - let (worker, github, mcp_tools) = tokio::join!( + let (worker, mcp_tools) = tokio::join!( async { if needs_worker { super::plan_chat_tools::setup(&state, &scope).await @@ -2211,13 +2246,6 @@ pub async fn brain_stream( WorkerTools::default() } }, - async { - if (picks.code && !code_repos.is_empty()) || (picks.work && !all_repos.is_empty()) { - github_token(&state, &claims.team_id).await - } else { - None - } - }, async { if picks.connections { connection_tools(&state, &claims.team_id, &claims.email).await @@ -2241,12 +2269,23 @@ pub async fn brain_stream( super::chat_work_tickets::load(&state, &claims.team_id), super::graph::installation_id(&state, &claims.team_id), ); + // Pull requests only in repositories the person's GitHub account + // can read, as code. + let (work_repos, _) = crate::bases::visible_repos( + &state, + &claims.team_id, + &holder.role, + claims.github_login.as_deref(), + github.as_deref(), + all_repos.clone(), + ) + .await; Some(super::chat_work::Ctx { state: state.clone(), claims: claims.clone(), - readable: super::chat_work::readable(&holder), + readable: crate::bases::readable_kinds(&holder, &open), holder: holder.clone(), - repos: repo_names.clone(), + repos: work_repos.iter().map(|r| r.name.clone()).collect(), github_token: github.clone(), installation_id, jira, diff --git a/services/gateway/src/routes/chat_work.rs b/services/gateway/src/routes/chat_work.rs index 31d788e26..ac5f6d8dd 100644 --- a/services/gateway/src/routes/chat_work.rs +++ b/services/gateway/src/routes/chat_work.rs @@ -10,8 +10,8 @@ //! - [`RUNS`]: runs, current and past (`chat_work_runs`). //! - [`FINDINGS`]: security findings (dependency advisories and CVEs), //! infrastructure findings and quarantined tests. -//! - [`RECORDS`]: reviews and their verdicts, alerts, log findings and -//! plans (`chat_work_records`). +//! - [`RECORDS`]: reviews and their verdicts, alerts, log findings, plans +//! and the team's AWS resources (`chat_work_records`). //! //! Each tool is offered only when the asker could see what it reads in the //! dashboard: the route that shows it is named ([`Kind::handler`]) and @@ -140,6 +140,12 @@ pub const KINDS: &[Kind] = &[ handler: "infra_security::findings", tool: FINDINGS, }, + Kind { + key: "resources", + label: "AWS resources", + handler: "infra_security::resources", + tool: RECORDS, + }, Kind { key: "tests", label: "quarantined tests", @@ -263,14 +269,14 @@ pub fn defs(readable: &[&str], repos: &[String], can_github: bool) -> Vec }, "required": ["kind"]} })); } - let record_kinds: Vec<&str> = ["reviews", "alerts", "log_findings", "plans"] + let record_kinds: Vec<&str> = ["reviews", "alerts", "log_findings", "plans", "resources"] .into_iter() .filter(|k| may(readable, k)) .collect(); if !record_kinds.is_empty() { out.push(json!({ "name": RECORDS, - "description": "Find other records Coderhelm keeps, newest first: reviews (Coderhelm's pull request reviews and their verdicts), alerts (alerts that came in and what was done), log_findings (problems found in the logs and their fixes), plans (plans and their tickets). Search by words, a repository or a pull request number.", + "description": "Find other records Coderhelm keeps, newest first: reviews (Coderhelm's pull request reviews and their verdicts), alerts (alerts that came in and what was done), log_findings (problems found in the logs and their fixes), plans (plans and their tickets), resources (the team's AWS resources: name, kind, account, region, versions, whether the internet reaches it, what AWS has pending for it, and where it is defined: repository, file, Terraform address, CloudFormation stack or CDK construct). Search by words, a repository or a pull request number. Use resources for \"what runs where\", \"which stack or file defines X\", \"what updates are pending\".", "input_schema": {"type": "object", "properties": { "kind": {"type": "string", "enum": record_kinds}, "query": {"type": "string"}, diff --git a/services/gateway/src/routes/chat_work_records.rs b/services/gateway/src/routes/chat_work_records.rs index 63ef2420d..6bd9845b0 100644 --- a/services/gateway/src/routes/chat_work_records.rs +++ b/services/gateway/src/routes/chat_work_records.rs @@ -150,6 +150,10 @@ pub async fn fetch( .await .map(of) .map_err(read_failed(kind.key, "log findings"))?, + "resources" => Box::pin(super::infra_security::resources(st, ext)) + .await + .map(of) + .map_err(read_failed(kind.key, "AWS resources"))?, "plans" => Box::pin(super::plans::list_plans( st, ext, @@ -181,6 +185,7 @@ pub fn rows(kind: &str, v: &Value) -> Vec { "reviews" => "reviews", "alerts" => "alerts", "plans" => "plans", + "resources" => "resources", _ => "findings", }; v[key].as_array().cloned().unwrap_or_default() @@ -301,6 +306,7 @@ fn date_of(v: &Value) -> String { "received_at", "created_at", "first_seen_at", + "seen_at", ] .iter() .find_map(|k| v[*k].as_str().filter(|t| !t.is_empty())) @@ -313,6 +319,7 @@ fn repo_of(v: &Value) -> String { ["repo", "fix_repo"] .iter() .find_map(|k| v[*k].as_str().filter(|t| !t.is_empty())) + .or_else(|| v["defined_in"]["repo"].as_str().filter(|t| !t.is_empty())) .unwrap_or("") .to_string() } @@ -366,6 +373,27 @@ pub fn found(kind: &str, v: &Value) -> Found { Some("/logs".to_string()), None, ), + "resources" => { + let kind_word = s(v, "kind").replace('_', " "); + let name = if s(v, "name").is_empty() { + s(v, "id") + } else { + s(v, "name") + }; + ( + format!( + "Resource: {} ({kind_word}, {} {})", + clip(name, 100), + s(v, "account"), + s(v, "region") + ), + Some(format!( + "/security/infrastructure?resource={}", + enc(s(v, "id")) + )), + None, + ) + } "plans" => ( format!("Plan: {}", clip(s(v, "title"), 100)), Some(format!("/plans/detail?id={}", enc(s(v, "plan_id")))), diff --git a/services/gateway/src/routes/knowledge_builtin.rs b/services/gateway/src/routes/knowledge_builtin.rs new file mode 100644 index 000000000..ac792d105 --- /dev/null +++ b/services/gateway/src/routes/knowledge_builtin.rs @@ -0,0 +1,501 @@ +//! The built-in bases on the Knowledge page, and share links (`crate::bases` +//! decides who reads what): +//! +//! - `GET /api/knowledge/builtin` — the six bases: what each holds, counts, +//! when it last changed, its audience and whether it is open to the asker. +//! Any member; a closed base shows its name and why, never its contents. +//! - `PUT /api/knowledge/builtin/{key}` — a base's audience: roles, people, +//! readers from AI tools, paused. Admins. +//! - `PUT /api/knowledge/readers` — whether people may connect AI tools as +//! readers without an account (never a seat). Admins. +//! - `GET /api/knowledge/builtin/{key}/search?q=` — searches one base as the +//! asker, exactly as an AI tool's `search` does. +//! - `POST /api/share`, `GET`/`DELETE /api/share/{id}` — share links. A link +//! holds the search (base and words), never what it found: every open +//! searches again as the person opening it, so a link never carries the +//! sharer's access. Links end after 1, 7 or 30 days, and the sharer or an +//! admin can end one sooner. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::extract::{Path, Query, State}; +use axum::{http::StatusCode, Extension, Json}; +use serde::Deserialize; +use serde_json::{json, Value}; +use tracing::error; + +use crate::bases::{self, Asker, Audience}; +use crate::lookups; +use crate::models::Claims; +use crate::routes::roles::{self, AuditEntry}; +use crate::AppState; + +type Reply = Result, (StatusCode, Json)>; + +fn fail(status: StatusCode, message: &str) -> (StatusCode, Json) { + (status, Json(json!({ "error": message }))) +} + +fn internal(context: &str, e: impl std::fmt::Display) -> (StatusCode, Json) { + error!(error = %e, "{context}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong. Try again.", + ) +} + +/// The scopes a dashboard read holds: every base, as Chat reads them. The +/// role and the audiences still decide. +pub fn dashboard_scopes() -> BTreeSet<&'static str> { + crate::mcp_oauth::SCOPES.iter().copied().collect() +} + +/// GET /api/knowledge/builtin +pub async fn list( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + let holder = roles::holder_for(&state, &claims).await; + let who = Asker { + holder: &holder, + email: &claims.email, + }; + let bases = bases::list(&state, &claims.team_id, &who, None).await; + Ok(Json(json!({ + "bases": bases, + "readers": { "enabled": bases::readers_enabled(&state, &claims.team_id).await }, + "can_manage": claims.support_view.is_none() && holder.holds("knowledge_manage"), + }))) +} + +#[derive(Deserialize, Default)] +pub struct AudienceInput { + pub roles: Option>, + pub people: Option>, + pub readers: Option, + pub paused: Option, +} + +/// The audience after an edit: only what the edit names changes. +pub fn edited(mut a: Audience, input: &AudienceInput) -> Result { + if let Some(r) = &input.roles { + a.roles = r.clone(); + } + if let Some(p) = &input.people { + a.people = p.clone(); + } + if let Some(r) = input.readers { + a.readers = r; + } + if let Some(p) = input.paused { + a.paused = p; + } + a.checked() +} + +/// PUT /api/knowledge/builtin/{key} +pub async fn update( + State(state): State>, + Extension(claims): Extension, + Path(key): Path, + Json(input): Json, +) -> Reply { + claims.require_role(3).map_err(|_| { + fail( + StatusCode::FORBIDDEN, + "Only admins choose who reads a base.", + ) + })?; + let base = lookups::base(&key).ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such base."))?; + let mut all = bases::audiences(&state, &claims.team_id).await; + let current = all + .remove(base.key) + .unwrap_or_else(|| bases::default_audience(base.key)); + let next = edited(current, &input).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + roles::record( + &state, + &claims, + AuditEntry { + action: "base_audience", + role_id: base.key, + role_name: base.name, + detail: format!("Set who reads {}: {}.", base.name, next.label()), + }, + ) + .await?; + bases::save_audience(&state, &claims.team_id, base.key, &next, &claims.email) + .await + .map_err(|e| internal("base audience not saved", e))?; + let holder = roles::holder_for(&state, &claims).await; + let who = Asker { + holder: &holder, + email: &claims.email, + }; + let d = bases::decide(base, &who, &next, None); + let size = if d.is_open() { + bases::size(&state, &claims.team_id, base.key).await + } else { + bases::Size::default() + }; + Ok(Json(bases::view(base, &size, &next, &d))) +} + +#[derive(Deserialize)] +pub struct ReadersInput { + pub enabled: bool, +} + +/// PUT /api/knowledge/readers +pub async fn set_readers( + State(state): State>, + Extension(claims): Extension, + Json(input): Json, +) -> Reply { + claims.require_role(3).map_err(|_| { + fail( + StatusCode::FORBIDDEN, + "Only admins choose whether people connect as readers.", + ) + })?; + roles::record( + &state, + &claims, + AuditEntry { + action: "readers", + role_id: bases::READER_ROLE, + role_name: "Readers", + detail: if input.enabled { + "Let people in the team's GitHub organization connect AI tools as readers, without an account or a seat.".into() + } else { + "Stopped new readers from connecting AI tools.".into() + }, + }, + ) + .await?; + bases::set_readers(&state, &claims.team_id, input.enabled, &claims.email) + .await + .map_err(|e| internal("readers setting not saved", e))?; + Ok(Json(json!({ "enabled": input.enabled }))) +} + +#[derive(Deserialize)] +pub struct SearchQuery { + #[serde(default)] + pub q: String, +} + +/// Searches one base as this person, through the same lookups AI tools use. +pub async fn search_as( + state: &Arc, + claims: &Claims, + key: &str, + query: &str, +) -> Result)> { + let base = lookups::base(key).ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such base."))?; + let holder = roles::holder_for(state, claims).await; + let env = crate::mcp_lookups::Env { + state: state.clone(), + claims: claims.clone(), + holder, + scopes: dashboard_scopes(), + grant_id: "dashboard".into(), + }; + match Box::pin(crate::mcp_lookups::run( + &env, + crate::mcp_lookups::SEARCH, + &json!({ "query": query, "base": base.key }), + )) + .await + { + Ok(a) => Ok(a.value), + Err(crate::mcp_lookups::Fail::Scope(_)) => Err(fail( + StatusCode::FORBIDDEN, + &format!("{} isn't open to you.", base.name), + )), + Err(crate::mcp_lookups::Fail::Message(m)) => { + let status = if m.contains("isn't open to you") || m.contains("paused") { + StatusCode::FORBIDDEN + } else { + StatusCode::BAD_REQUEST + }; + Err(fail(status, &m)) + } + } +} + +/// GET /api/knowledge/builtin/{key}/search?q= +pub async fn search( + State(state): State>, + Extension(claims): Extension, + Path(key): Path, + Query(q): Query, +) -> Reply { + search_as(&state, &claims, &key, &q.q).await.map(Json) +} + +// ── Share links ───────────────────────────────────────────────────────────── + +pub const SHARE_PREFIX: &str = "SHARE#"; +/// How long a link may live, in days. +pub const SHARE_DAYS: [i64; 3] = [1, 7, 30]; + +#[derive(Deserialize)] +pub struct ShareInput { + pub base: String, + pub query: String, + #[serde(default)] + pub days: Option, +} + +/// A link's days, checked: 1, 7 (the default) or 30. +pub fn share_days(asked: Option) -> Result { + match asked { + None => Ok(7), + Some(d) if SHARE_DAYS.contains(&d) => Ok(d), + Some(_) => Err("A link lasts 1, 7 or 30 days.".into()), + } +} + +fn share_id() -> String { + use rand::RngCore; + let mut b = [0u8; 16]; + rand::rng().fill_bytes(&mut b); + hex::encode(b) +} + +fn s(v: impl Into) -> AttributeValue { + AttributeValue::S(v.into()) +} + +/// POST /api/share +pub async fn create_share( + State(state): State>, + Extension(claims): Extension, + Json(input): Json, +) -> Reply { + let base = + lookups::base(&input.base).ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such base."))?; + let query = input.query.trim(); + if query.is_empty() || query.chars().count() > 1_000 { + return Err(fail( + StatusCode::BAD_REQUEST, + "Share a search of 1 to 1,000 characters.", + )); + } + let days = share_days(input.days).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + // Only what the sharer can read may be shared. + let holder = roles::holder_for(&state, &claims).await; + let auds = bases::audiences(&state, &claims.team_id).await; + let a = auds + .get(base.key) + .cloned() + .unwrap_or_else(|| bases::default_audience(base.key)); + let who = Asker { + holder: &holder, + email: &claims.email, + }; + if let Some(why) = bases::decide(base, &who, &a, None).why(base) { + return Err(fail(StatusCode::FORBIDDEN, &why)); + } + let id = share_id(); + let now = chrono::Utc::now(); + let expires = now + chrono::Duration::days(days); + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(&claims.team_id)) + .item("sk", s(format!("{SHARE_PREFIX}{id}"))) + .item("base", s(base.key)) + .item("query", s(query)) + .item("created_by", s(&claims.email)) + .item("created_by_sub", s(&claims.sub)) + .item("created_at", s(now.to_rfc3339())) + .item("expires_at", s(expires.to_rfc3339())) + .item("ttl", AttributeValue::N(expires.timestamp().to_string())) + .send() + .await + .map_err(|e| internal("share link not saved", e))?; + roles::record( + &state, + &claims, + AuditEntry { + action: "share_created", + role_id: &id, + role_name: base.name, + detail: format!("Shared a search of {} for {days} days.", base.name), + }, + ) + .await?; + Ok(Json(json!({ + "id": id, + "path": format!("/s/?id={id}"), + "expires_at": expires.to_rfc3339(), + }))) +} + +async fn load_share( + state: &AppState, + team_id: &str, + id: &str, +) -> Result, (StatusCode, Json)> { + let gone = || { + fail( + StatusCode::NOT_FOUND, + "This link doesn't exist or has ended.", + ) + }; + if id.is_empty() || id.len() > 64 || !id.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(gone()); + } + // Only the asker's own team: another team's link is not found. + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(team_id)) + .key("sk", s(format!("{SHARE_PREFIX}{id}"))) + .send() + .await + .map_err(|e| internal("share link not read", e))? + .item + .ok_or_else(gone)?; + let expires = item + .get("expires_at") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + if share_expired(&expires, chrono::Utc::now()) { + return Err(gone()); + } + Ok(item) +} + +/// Whether a link has ended (an unreadable time has). +pub fn share_expired(expires_at: &str, now: chrono::DateTime) -> bool { + chrono::DateTime::parse_from_rfc3339(expires_at).map_or(true, |t| t <= now) +} + +/// GET /api/share/{id} — searches again as the person opening it. +pub async fn get_share( + State(state): State>, + Extension(claims): Extension, + Path(id): Path, +) -> Reply { + let item = load_share(&state, &claims.team_id, &id).await?; + let get = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let key = get("base"); + let base = lookups::base(&key).ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such base."))?; + let query = get("query"); + let mut out = json!({ + "id": id, + "base": base.key, + "base_name": base.name, + "query": query, + "created_by": get("created_by"), + "expires_at": get("expires_at"), + }); + match search_as(&state, &claims, base.key, &query).await { + Ok(v) => { + out["open"] = json!(true); + out["why"] = Value::Null; + out["results"] = v["results"].clone(); + out["withheld"] = v["withheld"].clone(); + } + Err((StatusCode::FORBIDDEN, _)) => { + out["open"] = json!(false); + out["why"] = json!(format!( + "This was shared with you, but {} isn't open to you. Ask an admin for access.", + base.name + )); + out["results"] = json!([]); + } + Err(e) => return Err(e), + } + Ok(Json(out)) +} + +/// DELETE /api/share/{id} — the sharer, or an admin. +pub async fn delete_share( + State(state): State>, + Extension(claims): Extension, + Path(id): Path, +) -> Reply { + let item = load_share(&state, &claims.team_id, &id).await?; + let by = item + .get("created_by_sub") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + if by != claims.sub && claims.role_level() < 3 { + return Err(fail( + StatusCode::FORBIDDEN, + "Only the person who shared it or an admin can end a link.", + )); + } + state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(&claims.team_id)) + .key("sk", s(format!("{SHARE_PREFIX}{id}"))) + .send() + .await + .map_err(|e| internal("share link not ended", e))?; + Ok(Json(json!({ "ok": true }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_edit_changes_only_what_it_names() { + let a = bases::default_audience(lookups::INFRA); + let e = edited( + a.clone(), + &AudienceInput { + roles: Some(vec!["member".into()]), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(e.roles, ["member"]); + assert_eq!((e.readers, e.paused), (a.readers, a.paused)); + assert!(edited( + a, + &AudienceInput { + roles: Some(vec!["nobody".into()]), + ..Default::default() + } + ) + .is_err()); + } + + #[test] + fn links_last_one_seven_or_thirty_days() { + assert_eq!(share_days(None), Ok(7)); + for d in SHARE_DAYS { + assert_eq!(share_days(Some(d)), Ok(d)); + } + assert!(share_days(Some(365)).is_err()); + let now = chrono::Utc::now(); + assert!(share_expired("not a time", now)); + assert!(share_expired( + &(now - chrono::Duration::seconds(1)).to_rfc3339(), + now + )); + assert!(!share_expired( + &(now + chrono::Duration::days(1)).to_rfc3339(), + now + )); + assert_eq!(share_id().len(), 32); + } +} diff --git a/services/gateway/src/routes/mcp_oauth.rs b/services/gateway/src/routes/mcp_oauth.rs index 199427522..7642e6cab 100644 --- a/services/gateway/src/routes/mcp_oauth.rs +++ b/services/gateway/src/routes/mcp_oauth.rs @@ -23,7 +23,7 @@ use axum::{ use serde::Deserialize; use serde_json::{json, Value}; use std::sync::Arc; -use tracing::{error, info}; +use tracing::{error, info, warn}; use crate::auth::jwt::SignInProof; use crate::mcp_oauth::{self as oauth, OAuthStore, StoredGrant, READ_SCOPE, SCOPES}; @@ -105,6 +105,10 @@ pub fn server_metadata(issuer: &str) -> Value { "revocation_endpoint_auth_methods_supported": ["none"], "scopes_supported": SCOPES, "authorization_response_iss_parameter_supported": true, + // An https client_id is read as the client's metadata document + // (the MCP spec's preferred registration); dynamic registration + // stays for clients that don't publish one. + "client_id_metadata_document_supported": true, "service_documentation": "https://docs.coderhelm.com/mcp", }) } @@ -193,6 +197,10 @@ pub async fn authorize( ); } let client = match p.client_id.as_deref() { + Some(id) if oauth::is_metadata_client_id(id) => match metadata_client(&state, id).await { + Ok(c) => Some(c), + Err(m) => return refusal_page(&m), + }, Some(id) => match oauth::store(&state).get_client(id).await { Ok(c) => c, Err(e) => { @@ -227,6 +235,42 @@ pub async fn authorize( .into_response() } +/// The client a Client ID Metadata Document describes: the stored copy +/// while it is fresh, else the document read again now, through the same +/// guard every outside address passes (HTTPS only, never a private, +/// loopback or link-local address). +async fn metadata_client(state: &AppState, id: &str) -> Result { + use common::mcp_remote::http::{GuardedHttps, Http, HttpRequest}; + let store = oauth::store(state); + let now = chrono::Utc::now(); + if let Ok(Some(c)) = store.get_client(id).await { + if !oauth::document_stale(&c, now) { + return Ok(c); + } + } + let unreadable = || { + "CoderHelm couldn't read this app's metadata document. Try again, or remove CoderHelm from the app and add it again.".to_string() + }; + let r = GuardedHttps + .send(HttpRequest::get(id).header("Accept", "application/json")) + .await + .map_err(|e| { + warn!(error = %e, "MCP client metadata document not read"); + unreadable() + })?; + if r.status != 200 { + return Err(unreadable()); + } + let doc = r.json().ok_or_else(unreadable)?; + let c = oauth::client_from_document(id, &doc, now)?; + if let Err(e) = store.put_client(&c).await { + error!(error = %e, "MCP metadata client not saved"); + return Err("CoderHelm couldn't answer just now. Try again shortly.".into()); + } + info!(client_name = %c.client_name, "MCP client read from its metadata document"); + Ok(c) +} + // ── Tokens ────────────────────────────────────────────────────────── /// POST /oauth/token (form-encoded, RFC 6749 3.2). @@ -393,6 +437,15 @@ fn own_session(claims: &Claims) -> Result<(), ApiError> { Ok(()) } +/// The built-in bases a scope opens, by name, for the consent page. +pub fn scope_opens(scope: &str) -> Vec<&'static str> { + crate::lookups::BASES + .iter() + .filter(|b| b.scope == scope) + .map(|b| b.name) + .collect() +} + /// POST /api/mcp/authorize/describe — what the consent page shows. pub async fn describe_request( State(state): State>, @@ -408,6 +461,8 @@ pub async fn describe_request( json!({ "key": s, "label": oauth::scope_label(s), + "plain": oauth::scope_plain(s), + "opens": scope_opens(s), "requested": req.scopes.iter().any(|r| r == s), "always": *s == READ_SCOPE, }) @@ -428,9 +483,12 @@ pub async fn describe_request( "mcp_url": oauth::resource(), // The team lookups the page may offer as choices (`allow_scopes`), // ticked by default when `default` is true. + "reader": claims.role == crate::bases::READER_ROLE, "lookup_scopes": oauth::LOOKUP_SCOPES.iter().map(|s| json!({ "key": s, "label": oauth::scope_label(s), + "plain": oauth::scope_plain(s), + "opens": scope_opens(s), "requested": req.scopes.iter().any(|r| r == s), "default": oauth::DEFAULT_LOOKUP_SCOPES.contains(s), })).collect::>(), @@ -649,6 +707,8 @@ mod tests { "knowledge:read", "code:read", "work:read", + "infra:read", + "logs:read", "security:read" ]) ); diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 58cd51e95..eb5fa873e 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -51,6 +51,7 @@ pub mod jira_webhook; pub mod knowledge; pub mod knowledge_ask; pub mod knowledge_bedrock; +pub mod knowledge_builtin; pub mod knowledge_sources; pub mod knowledge_tokens; pub mod learning;