From b44388366ed2ab35d56f0b79ec245a64dbfe0bb6 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 8 Nov 2026 23:03:24 -0500 Subject: [PATCH 1/2] Knowledge: import an existing knowledge base and connect any MCP search tool, with per-person access - Connect a search tool through MCP in place: a Connected apps server's search tool (and fetch for results without text) is searched live and its ranked list joins the rank fusion; one test search on save, failures in plain words. A server that signs each person in is searched with the asker's own sign-in. - Import from an S3 bucket (Bedrock metadata sidecars read), from a Bedrock knowledge base (its S3 data sources become S3 imports) and from an export archive (Notion, Confluence HTML, a zipped docs folder). Imports are sources: progress, re-sync, deletes and re-embedding only what changed. - Buckets are read only with the team's CoderHelmLogReader role, on the buckets named in its new ImportBuckets parameter; the install's own role gets no bucket reads. The boundary already allows what is used, so no admin step. - Bases can be limited to named people and roles; agent runs search only what their person may read; the page says what attaching means. - Imports keep up to 2,500 documents per source; indexes load 16 at a time into a byte-budgeted least recently used cache. --- services/common/src/knowledge/remote_mcp.rs | 1240 +++++++++++++++++ .../common/src/knowledge/sources/archive.rs | 515 +++++++ .../src/knowledge/sources/bedrock_import.rs | 379 +++++ services/common/src/knowledge/sources/s3.rs | 1033 ++++++++++++++ 4 files changed, 3167 insertions(+) create mode 100644 services/common/src/knowledge/remote_mcp.rs create mode 100644 services/common/src/knowledge/sources/archive.rs create mode 100644 services/common/src/knowledge/sources/bedrock_import.rs create mode 100644 services/common/src/knowledge/sources/s3.rs diff --git a/services/common/src/knowledge/remote_mcp.rs b/services/common/src/knowledge/remote_mcp.rs new file mode 100644 index 000000000..12faa5d29 --- /dev/null +++ b/services/common/src/knowledge/remote_mcp.rs @@ -0,0 +1,1240 @@ +//! Knowledge bases connected in place through a search tool the team +//! already runs behind an MCP server: Azure AI Search or Foundry IQ, +//! Pinecone Assistant, Glean, Atlassian Rovo, Dropbox Dash, a Bedrock +//! knowledge base behind an AgentCore gateway, or the team's own retrieval +//! server. The server is an entry on the team's Connected apps +//! (`mcp_remote`), so its sign-in, its sealed tokens and its address checks +//! are the ones agents already use. +//! +//! The contract is the one most search servers speak: a `search` tool that +//! takes a query and returns results (`id`, `title`, `url`, and often the +//! passage text), and an optional `fetch` tool that takes an id and returns +//! the document (`id`, `title`, `text`, `url`, `metadata`). Answers are read +//! as data wherever the server puts them ([`results`]): the first list of +//! results in its JSON (`results`, `retrievalResults`, `documents`, `hits`, +//! `snippets`, ...), each result's text from its usual field names. A result +//! without text is fetched, best first, up to [`FETCH_DEPTH`]. +//! +//! Who it searches as: a server the team shares is searched with the +//! team's connection. A server that signs each person in is searched with +//! the asking person's own sign-in ([`super::Remote::per_person`]), so a +//! person only ever gets what the tool lets them see; a search with no +//! person (an agent run nobody started) skips it. +//! +//! Only the two tools picked when the base was connected are ever called, +//! and only through the read path that never needs the agents' allow list +//! (`Runtime::read_tool`). A tool the server marks as destructive is never +//! picked. + +use std::sync::Arc; + +use serde::Serialize; +use serde_json::{json, Value}; + +use super::search::{Hit, Retriever}; +use super::sources::connector::ConnectorError; +use super::sources::mcp::{result_json, McpTools, RuntimeTools}; +use super::{Access, Backend, Base, Provider, Remote}; +use crate::mcp_remote::client::RemoteTool; +use crate::mcp_remote::runtime::Runtime; +use crate::mcp_remote::store::{Owner, Sharing}; + +/// Results whose text is missing are fetched, best first, up to this many. +pub const FETCH_DEPTH: usize = 5; +/// The longest passage kept from one result. +const MAX_TEXT: usize = 6_000; +/// The query the connection check sends. +const PROBE: &str = "Coderhelm connection check"; + +/// Why a search tool couldn't be searched, and what to do. +pub type Refusal = super::remote::Refusal; + +fn refusal(code: &'static str, message: impl Into, fix: impl Into) -> Refusal { + Refusal { + code, + message: message.into(), + fix: fix.into(), + } +} + +// ── Picking the tools ──────────────────────────────────────────────────────── + +/// Tool names that search, best first (OpenAI's contract, Azure Foundry IQ, +/// AgentCore gateways, Pinecone Assistant and other common ones). +const SEARCH_NAMES: &[&str] = &[ + "search", + "knowledge_base_retrieve", + "retrieve", + "search_documents", + "search_knowledge", + "semantic_search", + "get_context", + "query", +]; +/// Tool names that read one result in full. +const FETCH_NAMES: &[&str] = &["fetch", "fetch_document", "get_document", "read_document"]; + +fn safe(t: &RemoteTool) -> bool { + t.destructive != Some(true) && t.read_only != Some(false) +} + +/// The tool most likely to be the server's search, if any. +pub fn guess_search(tools: &[RemoteTool]) -> Option<&RemoteTool> { + let usable: Vec<&RemoteTool> = tools.iter().filter(|t| safe(t)).collect(); + SEARCH_NAMES + .iter() + .find_map(|n| usable.iter().copied().find(|t| t.name == *n)) + .or_else(|| { + usable.iter().copied().find(|t| { + let n = t.name.to_ascii_lowercase(); + n.ends_with("___retrieve") || n.ends_with("__retrieve") + }) + }) + .or_else(|| { + usable.iter().copied().find(|t| { + let n = t.name.to_ascii_lowercase(); + n.contains("search") || n.contains("retrieve") + }) + }) +} + +/// The tool most likely to be the server's fetch, if any. +pub fn guess_fetch(tools: &[RemoteTool]) -> Option<&RemoteTool> { + let usable: Vec<&RemoteTool> = tools.iter().filter(|t| safe(t)).collect(); + FETCH_NAMES + .iter() + .find_map(|n| usable.iter().copied().find(|t| t.name == *n)) + .or_else(|| { + usable + .iter() + .copied() + .find(|t| t.name.to_ascii_lowercase().contains("fetch")) + }) +} + +/// The tool's properties. +fn props(t: &RemoteTool) -> serde_json::Map { + t.input_schema["properties"] + .as_object() + .cloned() + .unwrap_or_default() +} + +/// The argument a tool takes its main text in: a usual name, else its only +/// required string, else its first string. +fn text_arg(t: &RemoteTool, usual: &[&str]) -> String { + let p = props(t); + if let Some(n) = usual.iter().find(|n| p.contains_key(**n)) { + return n.to_string(); + } + let required: Vec<&str> = t.input_schema["required"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|n| p.get(*n).is_some_and(|v| v["type"] == "string")) + .collect(); + if let [one] = required.as_slice() { + return one.to_string(); + } + p.iter() + .find(|(_, v)| v["type"] == "string") + .map(|(k, _)| k.clone()) + .unwrap_or_else(|| usual[0].to_string()) +} + +/// The arguments of one search for `query`, asking for `k` results where +/// the tool takes a count. +pub fn search_args(t: &RemoteTool, query: &str, k: usize) -> Value { + let mut args = serde_json::Map::new(); + args.insert( + text_arg( + t, + &[ + "query", + "q", + "queryString", + "search", + "text", + "question", + "input", + "prompt", + ], + ), + json!(crate::truncate_str(query, 1_000)), + ); + let p = props(t); + for n in [ + "limit", + "top_k", + "topK", + "k", + "max_results", + "maxResults", + "num_results", + "count", + "top", + "numberOfResults", + ] { + if p.contains_key(n) { + args.insert(n.to_string(), json!(k)); + break; + } + } + Value::Object(args) +} + +/// The arguments of one fetch of result `id`. +pub fn fetch_args(t: &RemoteTool, id: &str) -> Value { + json!({ text_arg(t, &["id", "document_id", "documentId", "doc_id", "uri", "url"]): id }) +} + +// ── Reading answers ────────────────────────────────────────────────────────── + +/// One result, as read from a server's answer. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Found { + pub id: String, + pub title: String, + pub url: String, + pub text: String, + pub date: String, +} + +/// List keys that hold results, best first. +const LIST_KEYS: &[&str] = &[ + "results", + "retrievalResults", + "documents", + "hits", + "items", + "matches", + "snippets", + "chunks", + "passages", + "references", + "data", + "value", +]; + +fn str_at<'a>(v: &'a Value, path: &[&str]) -> Option<&'a str> { + let mut at = v; + for p in path { + at = at.get(*p)?; + } + at.as_str().map(str::trim).filter(|s| !s.is_empty()) +} + +fn first_str(v: &Value, paths: &[&[&str]]) -> String { + paths + .iter() + .find_map(|p| str_at(v, p)) + .unwrap_or("") + .to_string() +} + +/// A value's text: a string, `{text}`, or a list of either, joined. +fn text_of(v: &Value) -> String { + match v { + Value::String(s) => s.trim().to_string(), + Value::Object(m) => ["text", "content", "snippet", "value"] + .iter() + .find_map(|k| m.get(*k).map(text_of).filter(|t| !t.is_empty())) + .unwrap_or_default(), + Value::Array(a) => a + .iter() + .map(text_of) + .filter(|t| !t.is_empty()) + .collect::>() + .join("\n"), + _ => String::new(), + } +} + +/// One result object read. +pub fn read_one(v: &Value) -> Found { + let text = [ + "text", + "content", + "chunk", + "passage", + "snippet", + "snippets", + "excerpt", + "highlights", + "body", + "page_content", + "summary", + ] + .iter() + .find_map(|k| v.get(*k).map(text_of).filter(|t| !t.is_empty())) + .unwrap_or_default(); + let url = [ + &["url"][..], + &["link"], + &["href"], + &["source_url"], + &["sourceUrl"], + &["uri"], + &["metadata", "url"], + &["metadata", "source"], + &["location", "webLocation", "url"], + &["location", "confluenceLocation", "url"], + &["location", "sharePointLocation", "url"], + &["document", "url"], + &["reference", "url"], + ] + .iter() + .find_map(|p| str_at(v, p).filter(|u| u.starts_with("https://"))) + .unwrap_or("") + .to_string(); + let id = first_str( + v, + &[ + &["id"], + &["document_id"], + &["documentId"], + &["doc_id"], + &["key"], + &["metadata", "x-amz-bedrock-kb-source-uri"], + &["location", "s3Location", "uri"], + &["uri"], + &["reference", "file", "id"], + &["file", "id"], + ], + ); + let title = first_str( + v, + &[ + &["title"], + &["name"], + &["document_title"], + &["file_name"], + &["fileName"], + &["metadata", "title"], + &["metadata", "x-amz-bedrock-kb-title"], + &["document", "title"], + &["reference", "file", "name"], + &["file", "name"], + ], + ); + let date = first_str( + v, + &[ + &["updated_at"], + &["updatedAt"], + &["last_modified"], + &["lastModified"], + &["modified"], + &["date"], + &["metadata", "updated_at"], + &["metadata", "last_modified"], + &["metadata", "lastModified"], + ], + ); + Found { + id, + title, + url, + text, + date, + } +} + +/// The first list of result objects in `v`, depth first, a usual key +/// before any other. +fn result_list(v: &Value, depth: usize) -> Option<&Vec> { + if depth > 8 { + return None; + } + let objects = |a: &Vec| !a.is_empty() && a.iter().all(Value::is_object); + match v { + Value::Array(a) if objects(a) => Some(a), + Value::Object(m) => { + for k in LIST_KEYS { + if let Some(Value::Array(a)) = m.get(*k) { + if objects(a) { + return Some(a); + } + } + } + m.values().find_map(|x| result_list(x, depth + 1)) + } + _ => None, + } +} + +/// Every result in a tool's answer, best first. An answer that is only +/// prose (no data in it) is one result: the prose. +pub fn results(provider: &str, answer: &Value) -> Result, Refusal> { + let data = match result_json(provider, answer) { + Ok(d) => d, + Err(ConnectorError::Temporary(m)) if answer["isError"].as_bool() == Some(true) => { + return Err(refusal( + "refused", + m, + "Check the search tool's own settings, then try again.", + )) + } + Err(_) => { + let prose = text_of(&answer["content"]); + if prose.is_empty() { + return Ok(Vec::new()); + } + return Ok(vec![Found { + text: prose, + ..Default::default() + }]); + } + }; + let list: Vec = match result_list(&data, 0) { + Some(a) => a.clone(), + None if data.is_object() => vec![data.clone()], + None => Vec::new(), + }; + Ok(list + .iter() + .map(read_one) + .filter(|f| !f.text.is_empty() || !f.id.is_empty() || !f.url.is_empty()) + .collect()) +} + +/// Results as hits of `base`, best first: each result is its own document +/// (its id, else its link, else its title), with its title as the place. +pub fn to_hits(base: &Base, found: &[Found]) -> Vec { + let mut out = Vec::new(); + for (i, f) in found.iter().enumerate() { + let text = f.text.trim(); + if text.is_empty() { + continue; + } + let document = [&f.id, &f.url, &f.title] + .iter() + .find(|s| !s.is_empty()) + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("result-{i}")); + let name = if f.title.is_empty() { + document.clone() + } else { + f.title.clone() + }; + out.push(Hit { + kb_id: base.id.clone(), + kb_name: base.name.clone(), + file_id: crate::truncate_str(&document, 512).to_string(), + file_name: crate::truncate_str(&name, 200).to_string(), + loc: crate::truncate_str(&f.title, 300).to_string(), + as_of: super::remote::date_of(&f.date), + text: crate::truncate_str(text, MAX_TEXT).to_string(), + score: 1.0 / (i as f32 + 1.0), + authoritative: base.authoritative, + ord: i as u32, + url: super::answer::original_url(&f.url).unwrap_or_default(), + source_kind: super::SourceKind::McpSearch.key().into(), + }); + } + out +} + +// ── Opening the server ─────────────────────────────────────────────────────── + +/// A search tool's server, opened as one owner. +pub struct Opened { + pub name: String, + /// It signs each person in. + pub personal: bool, + pub tools: Arc, +} + +/// Opens a team's Connected apps server as an owner. The seam tests fake. +#[async_trait::async_trait] +pub trait Servers: Send + Sync { + /// The team the servers belong to. + fn team(&self) -> &str; + /// Opens server `id` of [`Self::team`], as `person` when it signs each + /// person in (`None`: nobody), else with the team's connection. + async fn open(&self, id: &str, person: Option<&str>) -> Result; +} + +/// The production [`Servers`]: the team's MCP runtime. +pub struct RuntimeServers { + pub rt: Runtime, +} + +#[async_trait::async_trait] +impl Servers for RuntimeServers { + fn team(&self) -> &str { + &self.rt.team + } + + async fn open(&self, id: &str, person: Option<&str>) -> Result { + let server = self + .rt + .store + .get_server(&self.rt.team, id) + .await + .map_err(|e| { + tracing::warn!(error = %e, "Connected apps server unreadable"); + refusal( + "reach", + "Coderhelm couldn't read the team's Connected apps.", + "Try again in a minute.", + ) + })? + .ok_or_else(|| { + refusal( + "not_found", + "The search tool's server isn't on Connected apps any more.", + "Add it again on Settings, Connected apps, then connect this knowledge base again.", + ) + })?; + let personal = server.sharing == Sharing::Personal + && server.auth == crate::mcp_remote::store::AuthKind::OAuth; + let owner = server.owner_for(person).ok_or_else(|| { + refusal( + "not_signed_in", + format!( + "{} answers each person with their own sign-in, and this search has no person.", + server.name + ), + "It is searched when a person asks, or in runs a person started.", + ) + })?; + let name = server.name.clone(); + let label: &'static str = "The search tool"; + Ok(Opened { + name, + personal, + tools: Arc::new(RuntimeTools::new(self.rt.clone(), server, owner, label)), + }) + } +} + +/// A connection failure in plain words. +fn conn_refusal(name: &str, e: ConnectorError) -> Refusal { + match e { + ConnectorError::Reconnect(m) => refusal( + "not_signed_in", + format!("{name} needs a sign-in ({}).", crate::truncate_str(&m, 200)), + format!("Sign in to {name} on Settings, Connected apps, then try again."), + ), + ConnectorError::Forbidden(m) | ConnectorError::Config(m) => refusal( + "refused", + format!( + "{name} refused the search ({}).", + crate::truncate_str(&m, 200) + ), + "Check the search tool's own settings and who it lets search, then try again.", + ), + ConnectorError::NotFound(_) => refusal( + "not_found", + format!("{name} no longer answers at its address."), + "Check the server's address on Settings, Connected apps.", + ), + ConnectorError::RateLimited(_) => refusal( + "busy", + format!("{name} is limiting searches right now."), + "Try again in a minute.", + ), + ConnectorError::Temporary(m) => refusal( + "reach", + format!( + "Coderhelm couldn't reach {name} ({}).", + crate::truncate_str(&m, 200) + ), + "Try again. If it keeps failing, check the server on Settings, Connected apps.", + ), + } +} + +/// The tool named `name` on the server (from its cached list, else asked). +async fn named(o: &Opened, name: &str) -> Result { + let tools = o + .tools + .tools() + .await + .map_err(|e| conn_refusal(&o.name, e))?; + tools + .into_iter() + .find(|t| t.name == name && safe(t)) + .ok_or_else(|| { + refusal( + "no_search_tool", + format!("{} no longer offers the tool {name}.", o.name), + "Check the knowledge base again to pick its search tool.", + ) + }) +} + +/// One search: up to `k` results, the text of the best ones without text +/// fetched. +pub async fn search_with( + o: &Opened, + search: &RemoteTool, + fetch: Option<&RemoteTool>, + query: &str, + k: usize, +) -> Result, Refusal> { + let answer = o + .tools + .call(search, &search_args(search, query, k)) + .await + .map_err(|e| conn_refusal(&o.name, e))?; + let mut found = results(&o.name, &answer)?; + found.truncate(k); + if let Some(fetch) = fetch { + let missing: Vec = found + .iter() + .enumerate() + .filter(|(_, f)| f.text.is_empty() && !f.id.is_empty()) + .map(|(i, _)| i) + .take(FETCH_DEPTH) + .collect(); + let fetched = futures::future::join_all(missing.iter().map(|i| { + let id = found[*i].id.clone(); + async move { + let a = o.tools.call(fetch, &fetch_args(fetch, &id)).await.ok()?; + results(&o.name, &a).ok()?.into_iter().next() + } + })) + .await; + for (i, f) in missing.into_iter().zip(fetched) { + if let Some(f) = f { + let r = &mut found[i]; + r.text = f.text; + if r.title.is_empty() { + r.title = f.title; + } + if r.url.is_empty() { + r.url = f.url; + } + if r.date.is_empty() { + r.date = f.date; + } + } + } + } + Ok(found) +} + +/// What the connection check settled. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Checked { + pub server_name: String, + pub search_tool: String, + pub fetch_tool: String, + pub per_person: bool, +} + +/// Checks a search tool before its base is saved: the server answers, a +/// search tool is there (the one asked for, or the likeliest), and one test +/// search reads. Run as the admin connecting it (their own sign-in when the +/// server signs each person in). +pub async fn check( + servers: &dyn Servers, + server_id: &str, + person: &str, + search_tool: &str, + fetch_tool: &str, +) -> Result { + let o = servers.open(server_id, Some(person)).await?; + let tools = o + .tools + .tools() + .await + .map_err(|e| conn_refusal(&o.name, e))?; + let names = || { + let mut n: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect(); + n.truncate(12); + n.join(", ") + }; + let search = if search_tool.trim().is_empty() { + guess_search(&tools).cloned().ok_or_else(|| { + refusal( + "no_search_tool", + format!( + "{} has no tool that searches (its tools: {}).", + o.name, + names() + ), + "Pick the tool that searches, or connect a server that offers search.", + ) + })? + } else { + tools + .iter() + .find(|t| t.name == search_tool.trim()) + .cloned() + .ok_or_else(|| { + refusal( + "no_search_tool", + format!("{} has no tool named {}.", o.name, search_tool.trim()), + format!("Pick one of its tools: {}.", names()), + ) + })? + }; + if !safe(&search) { + return Err(refusal( + "invalid", + format!( + "{} says {} changes things, so Coderhelm won't call it to search.", + o.name, search.name + ), + "Pick a read-only tool that searches.", + )); + } + let fetch = if fetch_tool.trim().is_empty() { + guess_fetch(&tools) + .filter(|t| t.name != search.name) + .cloned() + } else { + let f = tools + .iter() + .find(|t| t.name == fetch_tool.trim() && safe(t)) + .cloned(); + if f.is_none() { + return Err(refusal( + "no_search_tool", + format!( + "{} has no read-only tool named {}.", + o.name, + fetch_tool.trim() + ), + format!("Pick one of its tools, or none: {}.", names()), + )); + } + f + }; + search_with(&o, &search, fetch.as_ref(), PROBE, 1) + .await + .map_err(|r| { + if r.code == "refused" { + refusal( + "unreadable", + format!("{}'s test search failed: {}", o.name, r.message), + r.fix, + ) + } else { + r + } + })?; + Ok(Checked { + server_name: o.name, + search_tool: search.name, + fetch_tool: fetch.map(|t| t.name).unwrap_or_default(), + per_person: o.personal, + }) +} + +/// A connected search tool on server `server_id`, as checked. +pub fn mcp_remote(server_id: &str, c: &Checked) -> Remote { + Remote { + provider: Provider::Mcp, + target: server_id.to_string(), + region: String::new(), + access: Access::Connection { + server_id: server_id.to_string(), + }, + hybrid: false, + per_person: c.per_person, + search_tool: c.search_tool.clone(), + fetch_tool: c.fetch_tool.clone(), + name: c.server_name.clone(), + } +} + +// ── The retriever ──────────────────────────────────────────────────────────── + +/// Searches connected search tools, as the team, for `person` (the asker's +/// email, when a person asked). +pub struct McpSearch<'a> { + pub servers: &'a dyn Servers, + pub person: Option, +} + +#[async_trait::async_trait] +impl Retriever for McpSearch<'_> { + async fn retrieve( + &self, + team_id: &str, + base: &Base, + query: &str, + k: usize, + ) -> Result, String> { + let Backend::Remote(remote) = &base.backend else { + return Ok(Vec::new()); + }; + let Access::Connection { server_id } = &remote.access else { + return Err("This knowledge base isn't reached through a search tool.".into()); + }; + // A team only ever opens its own Connected apps. + if self.servers.team() != team_id { + return Err("That search tool isn't this team's.".into()); + } + let person = self.person.as_deref().filter(|p| !p.trim().is_empty()); + if remote.per_person && person.is_none() { + return Err( + "it answers each person with their own sign-in, and this search has no person" + .into(), + ); + } + let o = self + .servers + .open(server_id, person) + .await + .map_err(|r| r.message)?; + let search = named(&o, &remote.search_tool) + .await + .map_err(|r| r.message)?; + let fetch = if remote.fetch_tool.is_empty() { + None + } else { + named(&o, &remote.fetch_tool).await.ok() + }; + let found = search_with(&o, &search, fetch.as_ref(), query, k.min(20)) + .await + .map_err(|r| r.message)?; + Ok(to_hits(base, &found)) + } +} + +/// A Connected apps server as the "Connect a search tool" list shows it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Listed { + pub id: String, + pub name: String, + pub url: String, + pub sharing: &'static str, + pub search_tool: Option, + pub fetch_tool: Option, + pub tools: Vec, +} + +/// A server and its last listed tools, for the picker. +pub fn listed(s: &crate::mcp_remote::store::ServerRecord) -> Listed { + Listed { + id: s.id.clone(), + name: s.name.clone(), + url: s.url.clone(), + sharing: s.sharing.as_str(), + search_tool: guess_search(&s.tools).map(|t| t.name.clone()), + fetch_tool: guess_fetch(&s.tools).map(|t| t.name.clone()), + tools: s + .tools + .iter() + .filter(|t| safe(t)) + .map(|t| json!({ "name": t.name, "description": crate::truncate_str(&t.description, 200) })) + .collect(), + } +} + +/// Is `owner` the owner whose connection a person's search would use? +pub fn owner_for(personal: bool, person: Option<&str>) -> Option { + if personal { + person.filter(|p| !p.trim().is_empty()).map(Owner::user) + } else { + Some(Owner::Team) + } +} + +#[cfg(test)] +mod tests { + use super::super::sources::mcp::fake::{text_result, tool_with, FakeMcp}; + use super::*; + use std::collections::HashMap; + use std::sync::Mutex; + + type Answer = Arc Result + Send + Sync>; + + /// Servers of one team: each server's tools, answering per owner. + struct FakeServers { + team: String, + personal: bool, + made: Mutex>>, + /// Who each open was for. + opened: Mutex>>, + tools: Vec, + answer: Answer, + } + + impl FakeServers { + fn new( + personal: bool, + tools: Vec, + answer: impl Fn(&str, &Value) -> Result + Send + Sync + 'static, + ) -> Self { + FakeServers { + team: "TEAM#a".into(), + personal, + made: Mutex::new(HashMap::new()), + opened: Mutex::new(Vec::new()), + tools, + answer: Arc::new(answer), + } + } + fn calls(&self, id: &str) -> Vec<(String, Value)> { + self.made.lock().unwrap()[id].calls() + } + } + + #[async_trait::async_trait] + impl Servers for FakeServers { + fn team(&self) -> &str { + &self.team + } + async fn open(&self, id: &str, person: Option<&str>) -> Result { + if id != "search-1" { + return Err(refusal("not_found", "gone", "add it")); + } + self.opened.lock().unwrap().push(person.map(str::to_string)); + if self.personal && person.is_none() { + return Err(refusal("not_signed_in", "no person", "")); + } + let answer = self.answer.clone(); + let who = person.unwrap_or("team").to_string(); + let m = Arc::new(FakeMcp::new(self.tools.clone(), move |t, a| { + let mut a = a.clone(); + a["_as"] = json!(who.clone()); + answer(t, &a) + })); + self.made.lock().unwrap().insert(id.into(), m.clone()); + Ok(Opened { + name: "Docs search".into(), + personal: self.personal, + tools: m, + }) + } + } + + fn base(per_person: bool) -> Base { + let c = Checked { + server_name: "Docs search".into(), + search_tool: "search".into(), + fetch_tool: "fetch".into(), + per_person, + }; + Base { + id: "kb".into(), + name: "Product docs".into(), + backend: Backend::Remote(mcp_remote("search-1", &c)), + ..Default::default() + } + } + + fn openai_tools() -> Vec { + vec![tool_with("search", &["query"]), tool_with("fetch", &["id"])] + } + + #[test] + fn the_search_and_fetch_tools_are_found_by_their_usual_names() { + let t = openai_tools(); + assert_eq!(guess_search(&t).unwrap().name, "search"); + assert_eq!(guess_fetch(&t).unwrap().name, "fetch"); + let azure = vec![tool_with("knowledge_base_retrieve", &["queries"])]; + assert_eq!( + guess_search(&azure).unwrap().name, + "knowledge_base_retrieve" + ); + let agentcore = vec![tool_with("managed-kb___Retrieve", &["retrievalQuery"])]; + assert_eq!( + guess_search(&agentcore).unwrap().name, + "managed-kb___Retrieve" + ); + let mut dangerous = tool_with("search_and_delete", &["query"]); + dangerous.destructive = Some(true); + assert!( + guess_search(&[dangerous]).is_none(), + "a destructive tool is never picked" + ); + assert!(guess_search(&[tool_with("create_issue", &["title"])]).is_none()); + } + + #[test] + fn arguments_follow_the_tool_schema() { + let a = search_args(&tool_with("search", &["query", "limit"]), "leave policy", 5); + assert_eq!(a, json!({"query": "leave policy", "limit": 5})); + let a = search_args(&tool_with("get_context", &["question", "top_k"]), "x", 3); + assert_eq!(a, json!({"question": "x", "top_k": 3})); + let mut odd = tool_with("lookup", &["needle"]); + odd.input_schema["required"] = json!(["needle"]); + assert_eq!(search_args(&odd, "x", 3), json!({"needle": "x"})); + assert_eq!( + fetch_args(&tool_with("fetch", &["id"]), "doc-1"), + json!({"id": "doc-1"}) + ); + assert_eq!( + fetch_args(&tool_with("get_document", &["document_id"]), "d"), + json!({"document_id": "d"}) + ); + } + + #[test] + fn answers_in_the_usual_shapes_are_read() { + // OpenAI's search contract, as structured content. + let a = json!({"content": [], "structuredContent": {"results": [ + {"id": "d1", "title": "Leave policy", "url": "https://docs.example.com/leave", "text": "Sixteen weeks."}, + {"id": "d2", "title": "Holidays", "url": "https://docs.example.com/holidays"} + ]}}); + let f = results("Docs", &a).unwrap(); + assert_eq!(f.len(), 2); + assert_eq!(f[0].text, "Sixteen weeks."); + assert_eq!(f[1].text, "", "fetched later"); + // A Bedrock answer through an AgentCore gateway, as text JSON. + let bedrock = json!({"retrievalResults": [{ + "content": {"text": "Drain the queue first."}, + "location": {"type": "S3", "s3Location": {"uri": "s3://ops/runbook.md"}}, + "metadata": {"x-amz-bedrock-kb-title": "Runbook"}, + "score": 0.8 + }]}); + let f = results("Gateway", &text_result(&bedrock)).unwrap(); + assert_eq!(f[0].text, "Drain the queue first."); + assert_eq!(f[0].id, "s3://ops/runbook.md"); + assert_eq!(f[0].title, "Runbook"); + // Pinecone Assistant's context snippets. + let pine = json!({"snippets": [{"content": "Use the v2 API.", "reference": {"file": {"name": "api.pdf", "id": "f9"}}}]}); + let f = results("Pinecone", &text_result(&pine)).unwrap(); + assert_eq!( + (f[0].text.as_str(), f[0].title.as_str(), f[0].id.as_str()), + ("Use the v2 API.", "api.pdf", "f9") + ); + // Glean-style results with snippet lists. + let glean = json!({"results": [{"title": "On-call", "url": "https://wiki.example.com/oncall", "snippets": [{"text": "Rotates Monday."}, "Pager first."]}]}); + let f = results("Glean", &text_result(&glean)).unwrap(); + assert_eq!(f[0].text, "Rotates Monday.\nPager first."); + // Prose only: one result, the prose. + let prose = + json!({"content": [{"type": "text", "text": "The deploy freeze starts Friday."}]}); + let f = results("Docs", &prose).unwrap(); + assert_eq!(f.len(), 1); + assert_eq!(f[0].text, "The deploy freeze starts Friday."); + // The server's own error is said plainly. + let err = + json!({"isError": true, "content": [{"type": "text", "text": "index not found"}]}); + let r = results("Docs", &err).unwrap_err(); + assert_eq!(r.code, "refused"); + assert!(r.message.contains("index not found")); + // Nothing found is no results, not an error. + assert!( + results("Docs", &json!({"structuredContent": {"results": []}})) + .unwrap() + .is_empty() + ); + } + + #[test] + fn results_become_hits_with_document_title_date_and_link() { + let b = base(false); + let hits = to_hits( + &b, + &[ + Found { + id: "d1".into(), + title: "Leave policy".into(), + url: "https://docs.example.com/leave".into(), + text: "Sixteen weeks.".into(), + date: "2026-09-30T00:00:00Z".into(), + }, + Found { + url: "http://insecure.example.com/x".into(), + text: "Plain link.".into(), + ..Default::default() + }, + Found { + id: "empty".into(), + ..Default::default() + }, + ], + ); + assert_eq!(hits.len(), 2, "a result without text is dropped"); + assert_eq!(hits[0].file_id, "d1"); + assert_eq!(hits[0].file_name, "Leave policy"); + assert_eq!(hits[0].as_of, "2026-09-30"); + assert_eq!(hits[0].url, "https://docs.example.com/leave"); + assert_eq!(hits[0].source_kind, "mcp"); + assert!(hits[0].score > hits[1].score, "best first"); + assert_eq!(hits[1].url, "", "only an https link is a link"); + assert_eq!(hits[1].file_id, "http://insecure.example.com/x"); + } + + #[tokio::test] + async fn a_search_fetches_results_without_text_best_first() { + let s = FakeServers::new(false, openai_tools(), |tool, args| { + Ok(match tool { + "search" => text_result(&json!({"results": [ + {"id": "d1", "title": "Leave policy", "url": "https://docs.example.com/leave"}, + {"id": "d2", "title": "Holidays", "text": "Twelve days."} + ]})), + "fetch" => { + assert_eq!(args["id"], "d1"); + text_result( + &json!({"id": "d1", "title": "Leave policy", "text": "Sixteen weeks of leave."}), + ) + } + _ => unreachable!(), + }) + }); + let r = McpSearch { + servers: &s, + person: None, + }; + let hits = r + .retrieve("TEAM#a", &base(false), "leave", 10) + .await + .unwrap(); + assert_eq!(hits.len(), 2); + assert_eq!(hits[0].text, "Sixteen weeks of leave."); + assert_eq!(hits[1].text, "Twelve days."); + let calls = s.calls("search-1"); + assert_eq!(calls[0].0, "search"); + assert_eq!(calls[0].1["query"], "leave"); + assert_eq!( + calls.iter().filter(|c| c.0 == "fetch").count(), + 1, + "only the result without text" + ); + } + + #[tokio::test] + async fn a_per_person_search_uses_the_askers_own_sign_in_and_never_runs_without_one() { + let s = FakeServers::new(true, openai_tools(), |tool, args| { + assert_eq!(tool, "search"); + // Each person sees only their own documents. + let who = args["_as"].as_str().unwrap_or(""); + Ok(text_result( + &json!({"results": [{"id": who, "text": format!("for {who}")}]}), + )) + }); + let ada = McpSearch { + servers: &s, + person: Some("ada@example.com".into()), + }; + let hits = ada.retrieve("TEAM#a", &base(true), "x", 5).await.unwrap(); + assert_eq!(hits[0].text, "for ada@example.com"); + assert_eq!( + s.opened.lock().unwrap().last().unwrap().as_deref(), + Some("ada@example.com") + ); + let nobody = McpSearch { + servers: &s, + person: None, + }; + let e = nobody + .retrieve("TEAM#a", &base(true), "x", 5) + .await + .unwrap_err(); + assert!(e.contains("own sign-in"), "{e}"); + assert_eq!( + s.opened.lock().unwrap().len(), + 1, + "nothing was opened for nobody" + ); + } + + #[tokio::test] + async fn a_team_never_reaches_another_teams_search_tool() { + let s = FakeServers::new(false, openai_tools(), |_, _| { + Ok(text_result(&json!({"results": []}))) + }); + let r = McpSearch { + servers: &s, + person: None, + }; + let e = r + .retrieve("TEAM#b", &base(false), "x", 5) + .await + .unwrap_err(); + assert!(e.contains("isn't this team's")); + assert!(s.opened.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn connecting_checks_the_tools_and_one_search_in_plain_words() { + let s = FakeServers::new(false, openai_tools(), |_, _| { + Ok(text_result(&json!({"results": []}))) + }); + let c = check(&s, "search-1", "admin@example.com", "", "") + .await + .unwrap(); + assert_eq!( + (c.search_tool.as_str(), c.fetch_tool.as_str()), + ("search", "fetch") + ); + assert!(!c.per_person); + assert_eq!(s.calls("search-1")[0].1["query"], PROBE); + // A server without a search tool names its tools. + let none = FakeServers::new( + false, + vec![tool_with("create_issue", &["title"])], + |_, _| unreachable!(), + ); + let r = check(&none, "search-1", "a@example.com", "", "") + .await + .unwrap_err(); + assert_eq!(r.code, "no_search_tool"); + assert!(r.message.contains("create_issue"), "{}", r.message); + // A tool asked for by name that isn't there. + let r = check(&s, "search-1", "a@example.com", "lookup", "") + .await + .unwrap_err(); + assert_eq!(r.code, "no_search_tool"); + // A server that isn't on Connected apps. + assert_eq!( + check(&s, "gone", "a@example.com", "", "") + .await + .unwrap_err() + .code, + "not_found" + ); + // A sign-in that stopped working. + let expired = FakeServers::new(false, openai_tools(), |_, _| { + Err(ConnectorError::Reconnect("expired".into())) + }); + let r = check(&expired, "search-1", "a@example.com", "", "") + .await + .unwrap_err(); + assert_eq!(r.code, "not_signed_in"); + assert!(r.fix.contains("Connected apps")); + // The server's own error on the test search. + let broken = FakeServers::new(false, openai_tools(), |_, _| { + Ok(json!({"isError": true, "content": [{"type": "text", "text": "index missing"}]})) + }); + let r = check(&broken, "search-1", "a@example.com", "", "") + .await + .unwrap_err(); + assert_eq!(r.code, "unreadable"); + assert!(r.message.contains("index missing")); + // A destructive tool is refused even when named. + let mut d = tool_with("search", &["query"]); + d.destructive = Some(true); + let bad = FakeServers::new(false, vec![d], |_, _| unreachable!()); + assert_eq!( + check(&bad, "search-1", "a@example.com", "search", "") + .await + .unwrap_err() + .code, + "invalid" + ); + let r = refusal("x", "a", "b"); + assert!(!format!("{}{}", r.message, r.fix).contains('\u{2192}')); + } + + #[test] + fn a_connected_search_tool_round_trips_without_any_token() { + let b = base(true); + let v = serde_json::to_value(&b).unwrap(); + assert_eq!(v["backend"]["provider"], "mcp"); + assert_eq!(v["backend"]["access"]["kind"], "connection"); + assert_eq!(v["backend"]["access"]["server_id"], "search-1"); + assert_eq!(v["backend"]["per_person"], true); + assert_eq!(v["backend"]["search_tool"], "search"); + let back: Base = serde_json::from_value(v.clone()).unwrap(); + assert_eq!(back, b); + assert!(!v.to_string().contains("token")); + assert_eq!(owner_for(true, None), None); + assert_eq!( + owner_for(true, Some("A@x.com")), + Some(Owner::user("a@x.com")) + ); + assert_eq!(owner_for(false, None), Some(Owner::Team)); + } +} diff --git a/services/common/src/knowledge/sources/archive.rs b/services/common/src/knowledge/sources/archive.rs new file mode 100644 index 000000000..d8990fa2c --- /dev/null +++ b/services/common/src/knowledge/sources/archive.rs @@ -0,0 +1,515 @@ +//! Importing an archive: a `.zip` of a Notion export (Markdown and CSV), a +//! Confluence HTML export, or a zipped docs folder, uploaded once and +//! unpacked on the server (Notion's paths are often too long to unpack on +//! Windows). +//! +//! An archive is a source like any other ([`Kind::Archive`]), so the sync +//! engine does the rest: every supported entry becomes an item of the base +//! (its path in the archive is its id), and uploading a newer export to the +//! same source re-reads only the entries whose content changed (by their +//! CRC-32 and size), keeps the vectors of passages whose text didn't change, +//! and removes the entries the newer export no longer has. +//! +//! The archive stays in the team's own folder of the data bucket +//! ([`archive_key`]), KMS encrypted, and goes with its source or its base. +//! Every entry becomes readable by everyone who can read the base, which the +//! page says before the upload ([`NOTE`]). + +use std::io::Read; +use std::sync::Arc; + +use tokio::sync::OnceCell; + +use super::super::extract::{extract, Kind as FileKind}; +use super::connector::{Connector, ConnectorError, Document, Listed, Listing, Node}; +use super::{Kind, Source}; + +/// The largest archive taken. +pub const MAX_ARCHIVE_BYTES: u64 = 200 * 1024 * 1024; +/// Entries read from one archive at most (supported or not). +const MAX_ENTRIES: usize = 50_000; +/// An entry that unpacks to more than this many times its packed size is +/// not read (a zip bomb). +const MAX_RATIO: u64 = 200; + +/// Shown before an archive is uploaded. +pub const NOTE: &str = "Every page in the archive becomes readable by everyone who can read this knowledge base. A Confluence Full Export also includes pages that are restricted in Confluence."; + +/// Where an archive's upload is kept: the team's folder, by base, source +/// and upload. +pub fn archive_key(team_id: &str, kb_id: &str, source_id: &str, version: u32) -> String { + format!("{team_id}/knowledge/{kb_id}/archives/{source_id}/v{version}/archive.zip") +} + +/// An archive's file name, checked. +pub fn check_archive(name: &str, size: u64) -> Result { + let name = super::super::clean_file_name(name); + if !name.to_ascii_lowercase().ends_with(".zip") { + return Err( + "Upload a .zip file: a Notion or Confluence export, or a zipped docs folder.".into(), + ); + } + if size == 0 { + return Err("The archive is empty.".into()); + } + if size > MAX_ARCHIVE_BYTES { + return Err(format!( + "The archive is larger than {} MB. Split it, or connect the source in place instead.", + MAX_ARCHIVE_BYTES / (1024 * 1024) + )); + } + Ok(name) +} + +/// An exported name made readable: Notion's ` <32 hex id>` and +/// Confluence's `_` endings dropped, dashes in Confluence's names +/// read as spaces. +pub fn clean_title(segment: &str) -> String { + let (stem, ext) = match segment.rsplit_once('.') { + Some((s, e)) if FileKind::of(segment).is_some() => (s, Some(e)), + _ => (segment, None), + }; + let mut t = stem.to_string(); + if let Some((head, id)) = t.rsplit_once(' ') { + if id.len() == 32 && id.chars().all(|c| c.is_ascii_hexdigit()) { + t = head.to_string(); + } + } + if ext.is_some_and(|e| e.eq_ignore_ascii_case("html") || e.eq_ignore_ascii_case("htm")) { + if let Some((head, id)) = t.rsplit_once('_') { + if !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()) { + t = head.replace('-', " "); + } + } + } + let t = t.trim(); + if t.is_empty() { + segment.to_string() + } else { + t.to_string() + } +} + +/// Is this entry a document (not a folder, a hidden file or a Mac resource +/// fork)? +fn readable(path: &str) -> bool { + let name = path.rsplit('/').next().unwrap_or(path); + !path.ends_with('/') + && !path.starts_with("__MACOSX/") + && !path.split('/').any(|p| p.starts_with('.')) + && FileKind::of(name).is_some() +} + +/// The archive's bytes, as the connector reads them. The seam tests fake. +#[async_trait::async_trait] +pub trait ArchiveBytes: Send + Sync { + async fn bytes(&self) -> Result, ConnectorError>; +} + +/// The archive connector, reading one uploaded archive. +pub struct Archive<'a> { + pub bytes: Box, + /// Items one source keeps. + pub max_items: usize, + loaded: OnceCell>>, +} + +impl<'a> Archive<'a> { + pub fn new(bytes: Box, max_items: usize) -> Self { + Archive { + bytes, + max_items, + loaded: OnceCell::new(), + } + } + + /// The archive, read once per sync. + async fn data(&self) -> Result>, ConnectorError> { + self.loaded + .get_or_try_init(|| async { self.bytes.bytes().await.map(Arc::new) }) + .await + .cloned() + } +} + +fn open(bytes: &[u8]) -> Result>, ConnectorError> { + zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|_| { + ConnectorError::Config( + "The upload isn't a zip archive Coderhelm can read. Export again and upload the .zip as it was downloaded.".into(), + ) + }) +} + +/// A zip entry's time as `YYYY-MM-DD`. +fn entry_date(f: &zip::read::ZipFile<'_, std::io::Cursor<&[u8]>>) -> String { + f.last_modified() + .filter(|d| d.year() >= 1990) + .map(|d| format!("{:04}-{:02}-{:02}", d.year(), d.month(), d.day())) + .unwrap_or_default() +} + +/// Every document entry of the archive, with its version marker. +pub fn entries(bytes: &[u8], max_items: usize) -> Result { + let mut zip = open(bytes)?; + let mut items: Vec = Vec::new(); + for i in 0..zip.len().min(MAX_ENTRIES) { + let Ok(f) = zip.by_index_raw(i) else { continue }; + let path = f.name().replace('\\', "/"); + if !readable(&path) { + continue; + } + let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + let Some((last, folders)) = segments.split_last() else { + continue; + }; + items.push(Listed { + external_id: path.clone(), + title: clean_title(last), + updated_at: entry_date(&f), + version: format!("{:08x}-{}", f.crc32(), f.size()), + path: folders + .iter() + .map(|s| clean_title(s)) + .collect::>() + .join(" / "), + hint: serde_json::json!({ "size": f.size(), "packed": f.compressed_size() }), + ..Default::default() + }); + } + let truncated = items.len() > max_items; + items.truncate(max_items); + Ok(Listing { + items, + complete: true, + truncated, + ..Default::default() + }) +} + +/// One entry's content, bounded. +pub fn entry(bytes: &[u8], path: &str) -> Result, ConnectorError> { + let mut zip = open(bytes)?; + let max = super::super::MAX_FILE_BYTES; + let f = zip.by_name(path).map_err(|_| { + ConnectorError::NotFound("The newer upload no longer has this page.".into()) + })?; + if f.size() > max { + return Err(ConnectorError::Config(format!( + "The file is larger than {} MB.", + max / (1024 * 1024) + ))); + } + if f.compressed_size() > 0 && f.size() / f.compressed_size().max(1) > MAX_RATIO { + return Err(ConnectorError::Config( + "This file unpacks to far more than its size in the archive, so it isn't read.".into(), + )); + } + let mut out = Vec::with_capacity(f.size() as usize); + f.take(max + 1) + .read_to_end(&mut out) + .map_err(|_| ConnectorError::Config("This file in the archive is damaged.".into()))?; + if out.len() as u64 > max { + return Err(ConnectorError::Config("The file is too large.".into())); + } + Ok(out) +} + +#[async_trait::async_trait] +impl Connector for Archive<'_> { + fn kind(&self) -> Kind { + Kind::Archive + } + + async fn browse( + &self, + _parent: Option<&str>, + _query: &str, + ) -> Result, ConnectorError> { + Ok(Vec::new()) + } + + async fn list(&self, _source: &Source) -> Result { + let data = self.data().await?; + let max = self.max_items; + tokio::task::spawn_blocking(move || entries(&data, max)) + .await + .map_err(|_| ConnectorError::Temporary("The archive couldn't be read.".into()))? + } + + async fn fetch(&self, _source: &Source, item: &Listed) -> Result { + let name = item.external_id.rsplit('/').next().unwrap_or(""); + let kind = FileKind::of(name) + .ok_or_else(|| ConnectorError::Config("This kind of file isn't read.".into()))?; + let data = self.data().await?; + let path = item.external_id.clone(); + let extracted = tokio::task::spawn_blocking(move || { + entry(&data, &path).and_then(|b| extract(kind, &b).map_err(ConnectorError::Config)) + }) + .await + .map_err(|_| ConnectorError::Temporary("The archive couldn't be read.".into()))??; + let mut sections = extracted.sections; + for s in sections.iter_mut() { + if s.loc.is_empty() { + s.loc = item.title.clone(); + } + } + Ok(Document { + title: item.title.clone(), + url: String::new(), + updated_at: extracted.as_of.unwrap_or_else(|| item.updated_at.clone()), + sections, + }) + } +} + +/// The archive in the data bucket. +pub struct StoredArchive { + pub s3: aws_sdk_s3::Client, + pub bucket: String, + pub key: String, +} + +#[async_trait::async_trait] +impl ArchiveBytes for StoredArchive { + async fn bytes(&self) -> Result, ConnectorError> { + let out = self + .s3 + .get_object() + .bucket(&self.bucket) + .key(&self.key) + .send() + .await + .map_err(|_| { + ConnectorError::Config("The uploaded archive wasn't found. Upload it again.".into()) + })?; + if out.content_length().unwrap_or(0).max(0) as u64 > MAX_ARCHIVE_BYTES { + return Err(ConnectorError::Config("The archive is too large.".into())); + } + Ok(out + .body + .collect() + .await + .map_err(|_| ConnectorError::Temporary("The archive couldn't be read.".into()))? + .into_bytes() + .to_vec()) + } +} + +/// The key of a source's current upload, from its options. +pub fn current_key(team_id: &str, src: &Source) -> Option { + let v = src.options["version"].as_u64().filter(|v| *v > 0)? as u32; + Some(archive_key(team_id, &src.kb_id, &src.id, v)) +} + +#[cfg(test)] +pub mod testing { + use std::io::Write; + + use super::*; + + /// A zip of `(path, content)` entries. + pub fn zip_of(entries: &[(&str, &[u8])]) -> Vec { + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut w = zip::ZipWriter::new(&mut buf); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + for (p, c) in entries { + if p.ends_with('/') { + w.add_directory(*p, opts).unwrap(); + } else { + w.start_file(*p, opts).unwrap(); + w.write_all(c).unwrap(); + } + } + w.finish().unwrap(); + } + buf.into_inner() + } + + /// An archive held in memory, swappable for a newer upload. + pub struct InMemory(pub Arc>>); + + #[async_trait::async_trait] + impl ArchiveBytes for InMemory { + async fn bytes(&self) -> Result, ConnectorError> { + Ok(self.0.lock().unwrap().clone()) + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::testing::{zip_of, InMemory}; + use super::*; + use crate::knowledge::search::testing::WordEmbedder; + use crate::knowledge::sources::store::memory::MemSyncStore; + use crate::knowledge::sources::store::SyncStore; + use crate::knowledge::sources::{sync, Selected, Status}; + + const NOTION_ID: &str = "0123456789abcdef0123456789abcdef"; + + fn notion_export() -> Vec { + let page = format!("Engineering {NOTION_ID}/Runbooks {NOTION_ID}/Deploy {NOTION_ID}.md"); + let table = format!("Engineering {NOTION_ID}/Services {NOTION_ID}.csv"); + zip_of(&[ + (&format!("Engineering {NOTION_ID}/"), b""), + (&page, b"# Deploy\nRoll out region by region." as &[u8]), + (&table, b"Service,Owner\nbilling,payments\n"), + ("__MACOSX/._x.md", b"junk"), + (".DS_Store", b"junk"), + ("images/logo.png", b"png"), + ]) + } + + #[test] + fn exported_names_read_as_their_titles() { + assert_eq!(clean_title(&format!("Deploy {NOTION_ID}.md")), "Deploy"); + assert_eq!( + clean_title(&format!("Engineering {NOTION_ID}")), + "Engineering" + ); + assert_eq!( + clean_title("Release-Checklist_123456789.html"), + "Release Checklist" + ); + assert_eq!(clean_title("guide.md"), "guide"); + assert_eq!( + clean_title("v2_2026.md"), + "v2_2026", + "only Confluence's HTML names lose their ids" + ); + } + + #[test] + fn archives_are_checked_before_upload() { + assert_eq!(check_archive("Export.zip", 10).unwrap(), "Export.zip"); + assert!(check_archive("export.tar.gz", 10) + .unwrap_err() + .contains(".zip")); + assert!(check_archive("a.zip", 0).unwrap_err().contains("empty")); + assert!(check_archive("a.zip", MAX_ARCHIVE_BYTES + 1) + .unwrap_err() + .contains("200 MB")); + assert_eq!( + archive_key("TEAM#a", "kb", "s", 2), + "TEAM#a/knowledge/kb/archives/s/v2/archive.zip" + ); + assert!(crate::knowledge::owns_key( + "TEAM#a", + &archive_key("TEAM#a", "kb", "s", 2) + )); + assert!(NOTE.contains("Full Export")); + } + + #[test] + fn a_notion_export_lists_its_pages_and_tables_only() { + let l = entries(¬ion_export(), 100).unwrap(); + let titles: Vec<&str> = l.items.iter().map(|i| i.title.as_str()).collect(); + assert_eq!(titles, ["Deploy", "Services"]); + assert_eq!(l.items[0].path, "Engineering / Runbooks"); + assert!(l.items[0].version.contains('-')); + assert!(l.complete && !l.truncated); + let few = entries(¬ion_export(), 1).unwrap(); + assert!(few.truncated); + assert!(matches!( + entries(b"not a zip", 10), + Err(ConnectorError::Config(_)) + )); + } + + #[test] + fn an_entry_is_read_bounded_and_a_zip_bomb_is_refused() { + let big = vec![b'a'; 1_000_000]; + let z = zip_of(&[("bomb.txt", &big), ("ok.txt", b"fine")]); + assert_eq!(entry(&z, "ok.txt").unwrap(), b"fine"); + assert!(entry(&z, "bomb.txt") + .unwrap_err() + .to_string() + .contains("far more")); + assert!(matches!( + entry(&z, "missing.txt"), + Err(ConnectorError::NotFound(_)) + )); + } + + fn source() -> Source { + Source { + id: "arch".into(), + kb_id: "kb".into(), + kind: Some(Kind::Archive), + name: "Notion export".into(), + selection: vec![Selected { + id: "archive".into(), + title: "Export.zip".into(), + kind: "file".into(), + ..Default::default() + }], + options: serde_json::json!({ "file_name": "Export.zip", "version": 1 }), + ..Default::default() + } + } + + #[tokio::test] + async fn a_newer_export_keeps_what_is_unchanged_rereads_changes_and_removes_the_rest() { + let held = Arc::new(Mutex::new(notion_export())); + let c = Archive::new(Box::new(InMemory(held.clone())), 100); + let store = MemSyncStore::default(); + store.put_source("t", &source()).await.unwrap(); + let ctx = sync::Ctx { + store: &store, + connector: &c, + embedder: &WordEmbedder, + team: "t", + now: &|| 1_000, + }; + let first = sync::run(&ctx, "kb", "arch").await; + assert_eq!((first.fetched, first.indexed, first.failed), (2, 2, 0)); + let items = store.items("t", "kb", "arch").await.unwrap(); + assert!(items + .iter() + .any(|f| f.name == "Deploy" && f.path == "Engineering / Runbooks")); + // A newer export: Deploy edited, Services gone, a new page, and a + // copy of a page with the same text under another name. + let page = format!("Engineering {NOTION_ID}/Runbooks {NOTION_ID}/Deploy {NOTION_ID}.md"); + *held.lock().unwrap() = zip_of(&[ + (&page, b"# Deploy\nRoll out one region at a time." as &[u8]), + ("Onboarding.md", b"# Onboarding\nRead the handbook."), + ]); + // The next sync reads the new upload (a new connector per sync). + let c = Archive::new(Box::new(InMemory(held.clone())), 100); + let ctx = sync::Ctx { + connector: &c, + ..ctx + }; + let second = sync::run(&ctx, "kb", "arch").await; + assert_eq!(second.fetched, 2, "the edited page and the new one"); + assert_eq!(second.removed, 1, "the page the newer export no longer has"); + let items = store.items("t", "kb", "arch").await.unwrap(); + let names: std::collections::BTreeSet<&str> = + items.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["Deploy", "Onboarding"].into_iter().collect()); + // The same export again: nothing fetched. + let third = sync::run(&ctx, "kb", "arch").await; + assert_eq!(third.fetched, 0); + let s = store.source("t", "kb", "arch").await.unwrap().unwrap(); + assert_eq!(s.status, Status::Ready); + assert_eq!(s.items, 2); + } + + #[test] + fn the_current_upload_is_found_from_the_source() { + let s = source(); + assert_eq!( + current_key("t", &s).unwrap(), + "t/knowledge/kb/archives/arch/v1/archive.zip" + ); + let none = Source { + options: serde_json::json!({}), + ..s + }; + assert!(current_key("t", &none).is_none()); + } +} diff --git a/services/common/src/knowledge/sources/bedrock_import.rs b/services/common/src/knowledge/sources/bedrock_import.rs new file mode 100644 index 000000000..f3da2066c --- /dev/null +++ b/services/common/src/knowledge/sources/bedrock_import.rs @@ -0,0 +1,379 @@ +//! Importing a Bedrock knowledge base: finding where its documents are, so +//! Coderhelm can read the originals and index them itself. +//! +//! Bedrock has no export of its passages or vectors (and a MANAGED base's +//! store can't be reached at all), so the faithful copy is the knowledge +//! base's own data source. An S3 data source becomes an S3 source here +//! ([`super::s3`]) on its bucket and inclusion prefixes; a Confluence or web +//! data source points at Coderhelm's own connector, which reads the +//! originals rather than Bedrock's passages; the rest are said plainly. +//! +//! The knowledge base's settings are read with `bedrock:GetKnowledgeBase`, +//! `bedrock:ListDataSources` and `bedrock:GetDataSource`, by the same role +//! that searches it ([`super::super::remote::session`]): on hosted, the +//! team's `CoderHelmLogReader` role (its `ReadKnowledgeBases` statement); +//! on a self-hosted install, its own role (the boundary's `bedrock:Get*` +//! and `bedrock:List*`). Nothing in Bedrock changes. + +use serde::Serialize; + +use super::super::remote::{refusal, KbArn, Refusal}; +use super::s3; +use crate::live::aws::Session; + +/// One data source of a knowledge base, and how it is imported. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct DataSource { + pub id: String, + pub name: String, + /// Bedrock's type: `S3`, `CONFLUENCE`, `SHAREPOINT`, `SALESFORCE`, + /// `WEB`, `CUSTOM`, `REDSHIFT_METADATA`. + #[serde(rename = "type")] + pub kind: String, + pub status: String, + /// An S3 data source's bucket. + pub bucket: String, + /// The account that owns the bucket (the knowledge base's, unless the + /// data source names another). + pub bucket_account: String, + pub prefixes: Vec, + /// It can be imported as an S3 source. + pub importable: bool, + /// The Coderhelm connector to use instead (`confluence`, `web`). + pub use_instead: String, + /// What to do, in plain words. + pub note: String, +} + +/// A knowledge base's import plan. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Plan { + pub name: String, + pub account: String, + pub region: String, + pub data_sources: Vec, +} + +/// A data source as Bedrock describes it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Described { + pub id: String, + pub name: String, + pub kind: String, + pub status: String, + pub bucket_arn: String, + pub bucket_owner: String, + pub prefixes: Vec, +} + +/// What Bedrock answers about a knowledge base. The seam tests fake. +#[async_trait::async_trait] +pub trait Catalog: Send + Sync { + /// The knowledge base's name. + async fn name(&self, arn: &KbArn) -> Result; + /// Every data source, described. + async fn data_sources(&self, arn: &KbArn) -> Result, Refusal>; +} + +/// How one data source is imported. +pub fn plan_one(d: &Described, kb_account: &str) -> DataSource { + let mut out = DataSource { + id: d.id.clone(), + name: d.name.clone(), + kind: d.kind.clone(), + status: d.status.clone(), + ..Default::default() + }; + match d.kind.as_str() { + "S3" => match s3::bucket_of(&d.bucket_arn) { + Some(b) => { + out.bucket = b; + out.bucket_account = if d.bucket_owner.len() == 12 { + d.bucket_owner.clone() + } else { + kb_account.to_string() + }; + out.prefixes = d + .prefixes + .iter() + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .collect(); + out.importable = true; + out.note = format!( + "Coderhelm reads the documents in bucket {} itself and indexes them; nothing in Bedrock changes.", + out.bucket + ); + } + None => { + out.note = "Bedrock didn't say which bucket this data source reads.".into(); + } + }, + "CONFLUENCE" => { + out.use_instead = "confluence".into(); + out.note = "Connect Confluence in Coderhelm instead: it reads the original pages and keeps them in sync.".into(); + } + "WEB" => { + out.use_instead = "web".into(); + out.note = + "Add these pages as a Website source instead: Coderhelm reads them itself.".into(); + } + "SHAREPOINT" | "SALESFORCE" => { + out.note = format!( + "Coderhelm has no {} connector yet. Connect the knowledge base in place to search it live instead.", + if d.kind == "SHAREPOINT" { "SharePoint" } else { "Salesforce" } + ); + } + _ => { + out.note = "This kind of data source can't be imported. Connect the knowledge base in place to search it live instead.".into(); + } + } + out +} + +/// Where a knowledge base's documents are, and how each data source is +/// imported. +pub async fn plan(catalog: &dyn Catalog, arn: &KbArn) -> Result { + let name = catalog.name(arn).await?; + let mut data_sources: Vec = catalog + .data_sources(arn) + .await? + .iter() + .map(|d| plan_one(d, &arn.account)) + .collect(); + data_sources.sort_by(|a, b| b.importable.cmp(&a.importable).then(a.name.cmp(&b.name))); + Ok(Plan { + name, + account: arn.account.clone(), + region: arn.region.clone(), + data_sources, + }) +} + +/// A Bedrock refusal for reading a knowledge base's settings. +fn settings_refusal(code: &str, message: &str) -> Refusal { + let r = refusal(code, message); + if r.code == "access" { + Refusal { + code: "access", + message: "The role in your account can't read this knowledge base's settings.".into(), + fix: "Give the role bedrock:GetKnowledgeBase, bedrock:ListDataSources and bedrock:GetDataSource on this knowledge base (the CoderHelmLogReader update does it), then try again.".into(), + } + } else { + r + } +} + +/// The production [`Catalog`]: `bedrock-agent` with a session. +pub struct Bedrock { + pub client: aws_sdk_bedrockagent::Client, +} + +impl Bedrock { + pub fn new(s: &Session, region: &str) -> Bedrock { + use aws_sdk_bedrockagent::config::{BehaviorVersion, Credentials, Region}; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + Bedrock { + client: aws_sdk_bedrockagent::Client::from_conf( + aws_sdk_bedrockagent::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(region.to_string())) + .credentials_provider(creds) + .build(), + ), + } + } +} + +fn sdk_refusal(e: &aws_sdk_bedrockagent::error::SdkError) -> Refusal +where + E: aws_sdk_bedrockagent::error::ProvideErrorMetadata + std::error::Error + 'static, + R: std::fmt::Debug, +{ + match e.as_service_error() { + Some(se) => settings_refusal(se.code().unwrap_or("Unknown"), se.message().unwrap_or("")), + None => settings_refusal( + "", + &aws_sdk_bedrockagent::error::DisplayErrorContext(e).to_string(), + ), + } +} + +#[async_trait::async_trait] +impl Catalog for Bedrock { + async fn name(&self, arn: &KbArn) -> Result { + let out = self + .client + .get_knowledge_base() + .knowledge_base_id(&arn.id) + .send() + .await + .map_err(|e| sdk_refusal(&e))?; + Ok(out + .knowledge_base() + .map(|k| k.name().to_string()) + .unwrap_or_default()) + } + + async fn data_sources(&self, arn: &KbArn) -> Result, Refusal> { + let mut ids: Vec = Vec::new(); + let mut next: Option = None; + for _ in 0..10 { + let page = self + .client + .list_data_sources() + .knowledge_base_id(&arn.id) + .max_results(100) + .set_next_token(next.take()) + .send() + .await + .map_err(|e| sdk_refusal(&e))?; + ids.extend( + page.data_source_summaries() + .iter() + .map(|d| d.data_source_id().to_string()), + ); + match page.next_token() { + Some(t) if !t.is_empty() => next = Some(t.to_string()), + _ => break, + } + } + let mut out = Vec::new(); + for id in ids.iter().take(50) { + let d = self + .client + .get_data_source() + .knowledge_base_id(&arn.id) + .data_source_id(id) + .send() + .await + .map_err(|e| sdk_refusal(&e))?; + let Some(ds) = d.data_source() else { continue }; + let conf = ds.data_source_configuration(); + let s3c = conf.and_then(|c| c.s3_configuration()); + out.push(Described { + id: ds.data_source_id().to_string(), + name: ds.name().to_string(), + kind: conf + .map(|c| c.r#type().as_str().to_string()) + .unwrap_or_default(), + status: ds.status().as_str().to_string(), + bucket_arn: s3c.map(|c| c.bucket_arn().to_string()).unwrap_or_default(), + bucket_owner: s3c + .and_then(|c| c.bucket_owner_account_id()) + .unwrap_or("") + .to_string(), + prefixes: s3c + .map(|c| c.inclusion_prefixes().to_vec()) + .unwrap_or_default(), + }); + } + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::knowledge::remote::parse_kb_arn; + + struct Fake(Result, Refusal>); + + #[async_trait::async_trait] + impl Catalog for Fake { + async fn name(&self, _arn: &KbArn) -> Result { + self.0 + .as_ref() + .map(|_| "Runbooks".to_string()) + .map_err(Clone::clone) + } + async fn data_sources(&self, _arn: &KbArn) -> Result, Refusal> { + self.0.clone() + } + } + + fn arn() -> KbArn { + parse_kb_arn("arn:aws:bedrock:eu-west-1:111122223333:knowledge-base/ABCDE12345").unwrap() + } + + #[tokio::test] + async fn an_s3_data_source_becomes_an_s3_import_and_the_rest_are_said_plainly() { + let c = Fake(Ok(vec![ + Described { + id: "W1".into(), + name: "Wiki".into(), + kind: "CONFLUENCE".into(), + ..Default::default() + }, + Described { + id: "D1".into(), + name: "Docs bucket".into(), + kind: "S3".into(), + status: "AVAILABLE".into(), + bucket_arn: "arn:aws:s3:::ops-docs".into(), + prefixes: vec!["runbooks/".into(), " ".into()], + ..Default::default() + }, + Described { + id: "D2".into(), + name: "Shared bucket".into(), + kind: "S3".into(), + bucket_arn: "arn:aws:s3:::shared-docs".into(), + bucket_owner: "444455556666".into(), + ..Default::default() + }, + Described { + id: "S1".into(), + name: "Intranet".into(), + kind: "SHAREPOINT".into(), + ..Default::default() + }, + ])); + let p = plan(&c, &arn()).await.unwrap(); + assert_eq!(p.name, "Runbooks"); + assert_eq!( + (p.account.as_str(), p.region.as_str()), + ("111122223333", "eu-west-1") + ); + let names: Vec<&str> = p.data_sources.iter().map(|d| d.name.as_str()).collect(); + assert_eq!( + names, + ["Docs bucket", "Shared bucket", "Intranet", "Wiki"], + "importable first" + ); + let docs = &p.data_sources[0]; + assert!(docs.importable); + assert_eq!(docs.bucket, "ops-docs"); + assert_eq!(docs.bucket_account, "111122223333"); + assert_eq!(docs.prefixes, ["runbooks/"]); + assert_eq!( + p.data_sources[1].bucket_account, "444455556666", + "a bucket in another account" + ); + assert!(!p.data_sources[2].importable); + assert!(p.data_sources[2].note.contains("SharePoint")); + assert_eq!(p.data_sources[3].use_instead, "confluence"); + for d in &p.data_sources { + assert!(!d.note.contains('\u{2192}')); + } + } + + #[tokio::test] + async fn a_role_that_cant_read_the_settings_is_told_what_to_add() { + let denied = settings_refusal("AccessDeniedException", "not authorized to perform: bedrock:GetKnowledgeBase because no identity-based policy allows it"); + assert_eq!(denied.code, "access"); + assert!(denied.fix.contains("bedrock:ListDataSources")); + let e = plan(&Fake(Err(denied)), &arn()).await.unwrap_err(); + assert!(e.message.contains("settings")); + assert_eq!( + settings_refusal("ResourceNotFoundException", "").code, + "not_found" + ); + } +} diff --git a/services/common/src/knowledge/sources/s3.rs b/services/common/src/knowledge/sources/s3.rs new file mode 100644 index 000000000..db927e9d8 --- /dev/null +++ b/services/common/src/knowledge/sources/s3.rs @@ -0,0 +1,1033 @@ +//! Importing documents from an Amazon S3 bucket (a folder of docs, or the +//! S3 data source behind a Bedrock knowledge base) into a knowledge base. +//! +//! The bucket is read with the team's `CoderHelmLogReader` role in the +//! bucket's account, taken on with the team's private ID, on hosted and +//! self-hosted alike: the role's `ReadImportBuckets` statement (both log +//! reader templates) names the buckets it may read, so an admin chooses +//! every bucket in AWS itself, and the install's own role never gains read +//! access to the account's buckets. +//! +//! - [`Connector::browse`] lists one level of the bucket (its folders and +//! supported files); `/` is the whole bucket. +//! - [`Connector::list`] lists every supported object under the picked +//! folders, with its ETag (and its sidecar's) as the version marker, so a +//! sync fetches only what changed and removes what was deleted. +//! - [`Connector::fetch`] reads one object as text, and its +//! `.metadata.json` sidecar (the Bedrock data source format) for its +//! title, original link and date. + +use std::collections::HashMap; + +use serde_json::{json, Value}; + +use super::super::extract::{extract, Kind as FileKind}; +use super::connector::{Connector, ConnectorError, Document, Listed, Listing, Node}; +use super::{Kind, Source}; + +/// A Bedrock data source's metadata file for ``. +pub const SIDECAR: &str = ".metadata.json"; +/// The selection id of the whole bucket. +pub const WHOLE: &str = "/"; +/// The largest sidecar read (Bedrock allows about 10 KB). +const MAX_SIDECAR_BYTES: u64 = 64 * 1024; +/// Listing pages one sync reads at most (1,000 objects each). +const MAX_PAGES: usize = 50; + +/// One object in a listing. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Object { + pub key: String, + pub size: u64, + pub etag: String, + pub last_modified: String, +} + +/// One page of a listing. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Page { + pub objects: Vec, + /// Folders directly under the prefix (a listing by `/`). + pub prefixes: Vec, + pub next: Option, +} + +/// The bucket, as the connector reads it. The seam tests fake. +#[async_trait::async_trait] +pub trait Objects: Send + Sync { + /// One page of the objects under `prefix`; `by_folder` lists one level. + async fn list( + &self, + prefix: &str, + by_folder: bool, + token: Option, + ) -> Result; + /// One object, refused when it is larger than `max` bytes. + async fn get(&self, key: &str, max: u64) -> Result, ConnectorError>; +} + +/// A bucket name as S3 allows it. +pub fn valid_bucket(b: &str) -> bool { + (3..=63).contains(&b.len()) + && b.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '.') + && b.starts_with(|c: char| c.is_ascii_alphanumeric()) + && b.ends_with(|c: char| c.is_ascii_alphanumeric()) + && !b.contains("..") +} + +/// `bucket` from an `arn:aws:s3:::bucket` ARN or a plain name. +pub fn bucket_of(raw: &str) -> Option { + let b = raw + .trim() + .strip_prefix("arn:aws:s3:::") + .unwrap_or(raw.trim()); + let b = b.trim_end_matches('/'); + valid_bucket(b).then(|| b.to_string()) +} + +/// What a source reads: its account, bucket and region. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Where { + pub account: String, + pub bucket: String, + pub region: String, +} + +/// A source's options, checked. +pub fn where_of(options: &Value) -> Result { + let account = options["account"].as_str().unwrap_or("").trim().to_string(); + if account.len() != 12 || !account.chars().all(|c| c.is_ascii_digit()) { + return Err("Pick the AWS account the bucket is in.".into()); + } + let bucket = bucket_of(options["bucket"].as_str().unwrap_or("")) + .ok_or("That isn't an S3 bucket name. It looks like my-team-docs.")?; + let region = options["region"].as_str().unwrap_or("").trim().to_string(); + if !region.is_empty() + && !region + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + { + return Err("That isn't an AWS region.".into()); + } + Ok(Where { + account, + bucket, + region, + }) +} + +/// The S3 console page of an object, which opens only for people who have +/// access there. +pub fn console_url(bucket: &str, region: &str, key: &str) -> String { + format!( + "https://s3.console.aws.amazon.com/s3/object/{bucket}?region={region}&prefix={}", + urlencoding::encode(key) + ) +} + +/// The file name of a key. +fn name_of(key: &str) -> &str { + key.rsplit('/').next().unwrap_or(key) +} + +/// Is `key` a document the knowledge base reads (not a sidecar, a folder +/// marker or a hidden file)? +pub fn readable(key: &str) -> bool { + let name = name_of(key); + !key.ends_with('/') + && !key.ends_with(SIDECAR) + && !name.starts_with('.') + && FileKind::of(name).is_some() +} + +/// A sidecar's values: `metadataAttributes` with plain values or Bedrock's +/// typed `{value: {type, stringValue}}` ones. +pub fn sidecar_values(bytes: &[u8]) -> HashMap { + let v: Value = serde_json::from_slice(bytes).unwrap_or_default(); + let attrs = v + .get("metadataAttributes") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + attrs + .into_iter() + .filter_map(|(k, x)| { + let val = match &x { + Value::String(s) => s.clone(), + Value::Number(n) => n.to_string(), + Value::Object(_) => { + let inner = x.get("value").unwrap_or(&x); + inner["stringValue"] + .as_str() + .map(str::to_string) + .or_else(|| inner["numberValue"].as_f64().map(|n| n.to_string()))? + } + _ => return None, + }; + (!val.trim().is_empty()).then(|| (k, val.trim().to_string())) + }) + .collect() +} + +fn first<'a>(m: &'a HashMap, keys: &[&str]) -> Option<&'a str> { + keys.iter().find_map(|k| m.get(*k).map(String::as_str)) +} + +/// The S3 connector. +pub struct S3<'a> { + pub objects: Box, + pub bucket: String, + pub region: String, + /// Items one source keeps. + pub max_items: usize, +} + +impl S3<'_> { + /// Every object under `prefix`, by page, at most `limit` plus one (so a + /// bigger folder is known to be bigger). + async fn all_under(&self, prefix: &str, limit: usize) -> Result, ConnectorError> { + let mut out = Vec::new(); + let mut token = None; + for _ in 0..MAX_PAGES { + let page = self.objects.list(prefix, false, token.take()).await?; + out.extend(page.objects); + match page.next { + Some(t) if out.len() <= limit => token = Some(t), + _ => break, + } + } + Ok(out) + } +} + +#[async_trait::async_trait] +impl Connector for S3<'_> { + fn kind(&self) -> Kind { + Kind::S3 + } + + async fn browse(&self, parent: Option<&str>, query: &str) -> Result, ConnectorError> { + let prefix = parent.filter(|p| *p != WHOLE).unwrap_or(""); + let mut nodes = Vec::new(); + if prefix.is_empty() { + nodes.push(Node { + id: WHOLE.into(), + title: format!("Everything in {}", self.bucket), + kind: "prefix".into(), + selectable: true, + ..Default::default() + }); + } + let mut token = None; + for _ in 0..5 { + let page = self.objects.list(prefix, true, token.take()).await?; + for p in &page.prefixes { + let title = p.trim_end_matches('/').rsplit('/').next().unwrap_or(p); + if super::connector::matches(query, title) { + nodes.push(Node { + id: p.clone(), + title: title.to_string(), + kind: "prefix".into(), + has_children: true, + selectable: true, + detail: "Folder".into(), + ..Default::default() + }); + } + } + for o in page.objects.iter().filter(|o| readable(&o.key)) { + let title = name_of(&o.key); + if super::connector::matches(query, title) { + nodes.push(Node { + id: o.key.clone(), + title: title.to_string(), + kind: "file".into(), + selectable: true, + updated_at: o.last_modified.clone(), + bytes: Some(o.size), + url: console_url(&self.bucket, &self.region, &o.key), + ..Default::default() + }); + } + } + match page.next { + Some(t) if nodes.len() < 500 => token = Some(t), + _ => break, + } + } + Ok(nodes) + } + + async fn list(&self, source: &Source) -> Result { + let limit = self.max_items; + let mut objects: Vec = Vec::new(); + for sel in &source.selection { + let prefix = if sel.id == WHOLE { "" } else { sel.id.as_str() }; + let under = self.all_under(prefix, limit).await?; + if sel.kind == "file" { + objects.extend(under.into_iter().filter(|o| o.key == sel.id)); + } else { + objects.extend(under); + } + } + // Sidecars, by the document they describe. + let sidecars: HashMap = objects + .iter() + .filter_map(|o| { + o.key + .strip_suffix(SIDECAR) + .map(|doc| (doc.to_string(), o.etag.clone())) + }) + .collect(); + let mut items: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for o in objects.iter().filter(|o| readable(&o.key)) { + if !seen.insert(o.key.clone()) { + continue; + } + let sidecar = sidecars.get(&o.key); + let folder: Vec<&str> = o.key.split('/').collect(); + items.push(Listed { + external_id: o.key.clone(), + title: name_of(&o.key).to_string(), + url: console_url(&self.bucket, &self.region, &o.key), + updated_at: o.last_modified.clone(), + version: match sidecar { + Some(s) => format!("{}+{s}", o.etag), + None => o.etag.clone(), + }, + path: folder[..folder.len().saturating_sub(1)].join(" / "), + hint: json!({ "sidecar": sidecar.is_some(), "size": o.size }), + }); + } + let truncated = items.len() > limit; + items.truncate(limit); + Ok(Listing { + items, + complete: true, + truncated, + ..Default::default() + }) + } + + async fn fetch(&self, _source: &Source, item: &Listed) -> Result { + let key = &item.external_id; + let kind = FileKind::of(name_of(key)) + .ok_or_else(|| ConnectorError::Config("This kind of file isn't read.".into()))?; + let max = super::super::MAX_FILE_BYTES; + if item.hint["size"].as_u64().is_some_and(|s| s > max) { + return Err(ConnectorError::Config(format!( + "The file is larger than {} MB.", + max / (1024 * 1024) + ))); + } + let bytes = self.objects.get(key, max).await?; + let extracted = tokio::task::spawn_blocking(move || extract(kind, &bytes)) + .await + .map_err(|_| ConnectorError::Temporary("The file couldn't be read.".into()))? + .map_err(ConnectorError::Config)?; + let meta = if item.hint["sidecar"].as_bool() == Some(true) { + match self + .objects + .get(&format!("{key}{SIDECAR}"), MAX_SIDECAR_BYTES) + .await + { + Ok(b) => sidecar_values(&b), + Err(_) => HashMap::new(), + } + } else { + HashMap::new() + }; + let title = first( + &meta, + &["title", "Title", "document_title", "x-amz-bedrock-kb-title"], + ) + .map(str::to_string) + .unwrap_or_else(|| item.title.clone()); + let url = first( + &meta, + &[ + "url", + "source_url", + "sourceUrl", + "source", + "link", + "x-amz-bedrock-kb-source-uri", + ], + ) + .and_then(super::super::answer::original_url) + .unwrap_or_else(|| item.url.clone()); + let updated_at = first( + &meta, + &[ + "updated_at", + "updatedAt", + "last_modified", + "lastModified", + "modified", + "date", + ], + ) + .map(str::to_string) + .or(extracted.as_of) + .unwrap_or_else(|| item.updated_at.clone()); + let mut sections = extracted.sections; + for s in sections.iter_mut() { + if s.loc.is_empty() { + s.loc = title.clone(); + } + } + Ok(Document { + title, + url, + updated_at, + sections, + }) + } +} + +// ── The bucket in AWS ──────────────────────────────────────────────────────── + +/// A bucket read with a session on the team's role. +pub struct AwsObjects { + pub client: aws_sdk_s3::Client, + pub bucket: String, + /// Says which role and account in errors. + pub account: String, +} + +impl AwsObjects { + pub fn new(s: &crate::live::aws::Session, w: &Where) -> AwsObjects { + use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region}; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + let region = if w.region.is_empty() { + s.region.clone() + } else { + w.region.clone() + }; + AwsObjects { + client: aws_sdk_s3::Client::from_conf( + aws_sdk_s3::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new(region)) + .credentials_provider(creds) + .build(), + ), + bucket: w.bucket.clone(), + account: w.account.clone(), + } + } +} + +/// S3's error `code` for bucket `bucket`, in plain words. +pub fn s3_error(code: &str, message: &str, bucket: &str, account: &str) -> ConnectorError { + match code { + "AccessDenied" | "AccessDeniedException" | "AllAccessDisabled" => { + if message.to_ascii_lowercase().contains("kms") { + ConnectorError::Forbidden(format!( + "The CoderHelmLogReader role in account {account} can read bucket {bucket} but not decrypt it: its KMS key doesn't let the role use it through S3." + )) + } else { + ConnectorError::Forbidden(format!( + "The CoderHelmLogReader role in account {account} can't read bucket {bucket}. Name the bucket in the role's update stack (ImportBuckets)." + )) + } + } + "NoSuchBucket" => ConnectorError::NotFound(format!("There is no bucket named {bucket}.")), + "NoSuchKey" | "NotFound" => { + ConnectorError::NotFound(format!("The file is no longer in bucket {bucket}.")) + } + "PermanentRedirect" | "AuthorizationHeaderMalformed" | "IllegalLocationConstraintException" => { + ConnectorError::Config(format!( + "Bucket {bucket} is in another region. Edit the source and pick the bucket's region." + )) + } + "SlowDown" | "ThrottlingException" | "RequestLimitExceeded" => { + ConnectorError::RateLimited("S3 asked us to slow down.".into()) + } + "" => ConnectorError::Temporary(format!( + "Coderhelm couldn't reach S3 ({}). An install in a private network needs a VPC endpoint for S3.", + crate::truncate_str(message, 160) + )), + other => ConnectorError::Temporary(format!( + "S3 couldn't read bucket {bucket} ({other})." + )), + } +} + +#[async_trait::async_trait] +impl Objects for AwsObjects { + async fn list( + &self, + prefix: &str, + by_folder: bool, + token: Option, + ) -> Result { + use aws_sdk_s3::error::ProvideErrorMetadata; + let mut req = self + .client + .list_objects_v2() + .bucket(&self.bucket) + .prefix(prefix) + .set_continuation_token(token); + if by_folder { + req = req.delimiter("/"); + } + let out = req.send().await.map_err(|e| match e.as_service_error() { + Some(se) => s3_error( + se.code().unwrap_or("Unknown"), + se.message().unwrap_or(""), + &self.bucket, + &self.account, + ), + None => s3_error( + "", + &aws_sdk_s3::error::DisplayErrorContext(&e).to_string(), + &self.bucket, + &self.account, + ), + })?; + Ok(Page { + objects: out + .contents() + .iter() + .filter_map(|o| { + Some(Object { + key: o.key()?.to_string(), + size: o.size().unwrap_or(0).max(0) as u64, + etag: o.e_tag().unwrap_or("").trim_matches('"').to_string(), + last_modified: o + .last_modified() + .and_then(|d| { + d.fmt(aws_sdk_s3::primitives::DateTimeFormat::DateTime).ok() + }) + .unwrap_or_default(), + }) + }) + .collect(), + prefixes: out + .common_prefixes() + .iter() + .filter_map(|p| p.prefix().map(str::to_string)) + .collect(), + next: out + .next_continuation_token() + .filter(|_| out.is_truncated().unwrap_or(false)) + .map(str::to_string), + }) + } + + async fn get(&self, key: &str, max: u64) -> Result, ConnectorError> { + use aws_sdk_s3::error::ProvideErrorMetadata; + let out = self + .client + .get_object() + .bucket(&self.bucket) + .key(key) + .send() + .await + .map_err(|e| match e.as_service_error() { + Some(se) => s3_error( + se.code().unwrap_or("Unknown"), + se.message().unwrap_or(""), + &self.bucket, + &self.account, + ), + None => s3_error( + "", + &aws_sdk_s3::error::DisplayErrorContext(&e).to_string(), + &self.bucket, + &self.account, + ), + })?; + if out.content_length().unwrap_or(0).max(0) as u64 > max { + return Err(ConnectorError::Config(format!( + "The file is larger than {} MB.", + max / (1024 * 1024) + ))); + } + let bytes = out + .body + .collect() + .await + .map_err(|_| ConnectorError::Temporary("The file couldn't be read from S3.".into()))? + .into_bytes(); + if bytes.len() as u64 > max { + return Err(ConnectorError::Config("The file is too large.".into())); + } + Ok(bytes.to_vec()) + } +} + +/// The region a bucket is in (`GetBucketLocation`), with a session in any +/// region. +pub async fn bucket_region(objects: &AwsObjects) -> Result { + use aws_sdk_s3::error::ProvideErrorMetadata; + let out = objects + .client + .get_bucket_location() + .bucket(&objects.bucket) + .send() + .await + .map_err(|e| match e.as_service_error() { + Some(se) => s3_error( + se.code().unwrap_or("Unknown"), + se.message().unwrap_or(""), + &objects.bucket, + &objects.account, + ), + None => s3_error( + "", + &aws_sdk_s3::error::DisplayErrorContext(&e).to_string(), + &objects.bucket, + &objects.account, + ), + })?; + // No constraint means us-east-1; "EU" is the old name of eu-west-1. + Ok(match out.location_constraint().map(|c| c.as_str()) { + None | Some("") => "us-east-1".into(), + Some("EU") => "eu-west-1".into(), + Some(r) => r.to_string(), + }) +} + +/// The buckets of a team's S3 sources in `account`, for the log reader +/// update that lets the role read them. +pub fn buckets_in(sources: &[Source], account: &str) -> Vec { + let mut out: Vec = sources + .iter() + .filter(|s| s.kind == Some(Kind::S3)) + .filter_map(|s| where_of(&s.options).ok()) + .filter(|w| w.account == account) + .map(|w| w.bucket) + .collect(); + out.sort(); + out.dedup(); + out +} + +#[cfg(test)] +pub mod fake { + //! An in-memory bucket. + + use std::sync::Mutex; + + use super::*; + + #[derive(Default)] + pub struct FakeBucket { + pub objects: Mutex)>>, + /// Objects per listing page. + pub page: usize, + pub refuse: Mutex>, + pub gets: Mutex>, + } + + impl FakeBucket { + pub fn put(&self, key: &str, etag: &str, body: &[u8]) { + let mut o = self.objects.lock().unwrap(); + o.retain(|(x, _)| x.key != key); + o.push(( + Object { + key: key.into(), + size: body.len() as u64, + etag: etag.into(), + last_modified: "2026-10-01T00:00:00Z".into(), + }, + body.to_vec(), + )); + o.sort_by(|a, b| a.0.key.cmp(&b.0.key)); + } + pub fn remove(&self, key: &str) { + self.objects.lock().unwrap().retain(|(x, _)| x.key != key); + } + } + + #[async_trait::async_trait] + impl Objects for FakeBucket { + async fn list( + &self, + prefix: &str, + by_folder: bool, + token: Option, + ) -> Result { + if let Some(e) = self.refuse.lock().unwrap().clone() { + return Err(e); + } + let all: Vec = self + .objects + .lock() + .unwrap() + .iter() + .map(|(o, _)| o.clone()) + .filter(|o| o.key.starts_with(prefix)) + .collect(); + let (objects, prefixes): (Vec, Vec) = if by_folder { + let mut folders = std::collections::BTreeSet::new(); + let mut here = Vec::new(); + for o in all { + match o.key[prefix.len()..].split_once('/') { + Some((f, _)) => { + folders.insert(format!("{prefix}{f}/")); + } + None => here.push(o), + } + } + (here, folders.into_iter().collect()) + } else { + (all, Vec::new()) + }; + let size = if self.page == 0 { 1000 } else { self.page }; + let start: usize = token.and_then(|t| t.parse().ok()).unwrap_or(0); + let end = (start + size).min(objects.len()); + Ok(Page { + objects: objects[start..end].to_vec(), + prefixes: if start == 0 { prefixes } else { Vec::new() }, + next: (end < objects.len()).then(|| end.to_string()), + }) + } + + async fn get(&self, key: &str, max: u64) -> Result, ConnectorError> { + self.gets.lock().unwrap().push(key.into()); + let o = self.objects.lock().unwrap(); + let (obj, body) = o + .iter() + .find(|(x, _)| x.key == key) + .ok_or_else(|| ConnectorError::NotFound("gone".into()))?; + if obj.size > max { + return Err(ConnectorError::Config("too large".into())); + } + Ok(body.clone()) + } + } + + /// The bucket shared between a test and the connector reading it. + pub struct Shared(pub std::sync::Arc); + + #[async_trait::async_trait] + impl Objects for Shared { + async fn list( + &self, + prefix: &str, + by_folder: bool, + token: Option, + ) -> Result { + self.0.list(prefix, by_folder, token).await + } + async fn get(&self, key: &str, max: u64) -> Result, ConnectorError> { + self.0.get(key, max).await + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::fake::{FakeBucket, Shared}; + use super::*; + use crate::knowledge::search::testing::WordEmbedder; + use crate::knowledge::sources::store::memory::MemSyncStore; + use crate::knowledge::sources::store::SyncStore; + use crate::knowledge::sources::{sync, Selected, Status}; + + fn bucket() -> Arc { + let b = Arc::new(FakeBucket::default()); + b.put( + "runbooks/deploy.md", + "e1", + b"# Deploy\nRoll out region by region.", + ); + b.put( + "runbooks/queues/drain.md", + "e2", + b"# Drain\nDrain the queue before a restart.", + ); + b.put( + "runbooks/queues/drain.md.metadata.json", + "m2", + br#"{"metadataAttributes": {"title": "Draining queues", "source_url": "https://wiki.example.com/drain", "updated_at": {"value": {"type": "STRING", "stringValue": "2026-09-30"}}}}"#, + ); + b.put("runbooks/diagram.png", "e3", b"\x89PNG"); + b.put("runbooks/.hidden.md", "e4", b"secret"); + b.put("hr/leave.txt", "e5", b"Sixteen weeks of leave."); + b + } + + fn connector(b: &Arc, max: usize) -> S3<'static> { + S3 { + objects: Box::new(Shared(b.clone())), + bucket: "team-docs".into(), + region: "eu-west-1".into(), + max_items: max, + } + } + + fn source(sel: &[(&str, &str)]) -> Source { + Source { + id: "src".into(), + kb_id: "kb".into(), + kind: Some(Kind::S3), + selection: sel + .iter() + .map(|(id, kind)| Selected { + id: id.to_string(), + title: id.to_string(), + kind: kind.to_string(), + include_children: true, + ..Default::default() + }) + .collect(), + options: json!({"account": "111122223333", "bucket": "team-docs", "region": "eu-west-1"}), + ..Default::default() + } + } + + #[test] + fn bucket_names_and_options_are_checked() { + assert!(valid_bucket("team-docs")); + assert!(valid_bucket("a.b-c1")); + for bad in ["", "ab", "Team", "-x-", "a..b", "x_y", &"a".repeat(64)] { + assert!(!valid_bucket(bad), "{bad}"); + } + assert_eq!( + bucket_of("arn:aws:s3:::team-docs").as_deref(), + Some("team-docs") + ); + assert_eq!(bucket_of("team-docs/").as_deref(), Some("team-docs")); + let w = where_of(&json!({"account": "111122223333", "bucket": "team-docs"})).unwrap(); + assert_eq!(w.bucket, "team-docs"); + assert!(where_of(&json!({"account": "1", "bucket": "team-docs"})) + .unwrap_err() + .contains("account")); + assert!( + where_of(&json!({"account": "111122223333", "bucket": "No"})) + .unwrap_err() + .contains("bucket") + ); + assert!(where_of( + &json!({"account": "111122223333", "bucket": "abc", "region": "US EAST"}) + ) + .is_err()); + } + + #[tokio::test] + async fn browsing_shows_one_level_of_folders_and_readable_files() { + let b = bucket(); + let c = connector(&b, 100); + let top = c.browse(None, "").await.unwrap(); + let ids: Vec<&str> = top.iter().map(|n| n.id.as_str()).collect(); + assert_eq!(ids, [WHOLE, "hr/", "runbooks/"]); + assert!(top[0].title.contains("team-docs")); + let inside = c.browse(Some("runbooks/"), "").await.unwrap(); + let ids: Vec<&str> = inside.iter().map(|n| n.id.as_str()).collect(); + assert_eq!( + ids, + ["runbooks/queues/", "runbooks/deploy.md"], + "no images, sidecars or hidden files" + ); + assert_eq!(inside[1].kind, "file"); + let found = c.browse(Some("runbooks/"), "dep").await.unwrap(); + assert_eq!(found.len(), 1); + } + + #[tokio::test] + async fn a_listing_covers_the_folders_picked_with_etags_and_sidecars() { + let b = bucket(); + let c = connector(&b, 100); + let l = c.list(&source(&[("runbooks/", "prefix")])).await.unwrap(); + let keys: Vec<&str> = l.items.iter().map(|i| i.external_id.as_str()).collect(); + assert_eq!(keys, ["runbooks/deploy.md", "runbooks/queues/drain.md"]); + assert_eq!(l.items[0].version, "e1"); + assert_eq!( + l.items[1].version, "e2+m2", + "a sidecar change re-reads the document" + ); + assert_eq!(l.items[1].path, "runbooks / queues"); + assert!(l.complete && !l.truncated); + // The whole bucket, and one file. + assert_eq!( + c.list(&source(&[(WHOLE, "prefix")])) + .await + .unwrap() + .items + .len(), + 3 + ); + let one = c.list(&source(&[("hr/leave.txt", "file")])).await.unwrap(); + assert_eq!(one.items.len(), 1); + // Overlapping picks list a document once. + let both = c + .list(&source(&[(WHOLE, "prefix"), ("runbooks/", "prefix")])) + .await + .unwrap(); + assert_eq!(both.items.len(), 3); + } + + #[tokio::test] + async fn a_big_bucket_is_listed_by_page_up_to_the_import_limit() { + let b = Arc::new(FakeBucket { + page: 7, + ..Default::default() + }); + for i in 0..40 { + b.put(&format!("docs/{i:03}.md"), "e", b"x"); + } + let c = connector(&b, 25); + let l = c.list(&source(&[(WHOLE, "prefix")])).await.unwrap(); + assert_eq!(l.items.len(), 25); + assert!(l.truncated); + let c = connector(&b, 100); + let l = c.list(&source(&[(WHOLE, "prefix")])).await.unwrap(); + assert_eq!(l.items.len(), 40, "every page read"); + assert!(!l.truncated); + } + + #[tokio::test] + async fn a_document_reads_its_sidecar_for_title_link_and_date() { + let b = bucket(); + let c = connector(&b, 100); + let src = source(&[("runbooks/", "prefix")]); + let l = c.list(&src).await.unwrap(); + let d = c.fetch(&src, &l.items[1]).await.unwrap(); + assert_eq!(d.title, "Draining queues"); + assert_eq!(d.url, "https://wiki.example.com/drain"); + assert_eq!(d.updated_at, "2026-09-30"); + assert!(d + .sections + .iter() + .any(|s| s.text.contains("Drain the queue"))); + let d = c.fetch(&src, &l.items[0]).await.unwrap(); + assert_eq!(d.title, "deploy.md"); + assert!(d.url.starts_with("https://s3.console.aws.amazon.com/s3/object/team-docs?region=eu-west-1&prefix=runbooks%2Fdeploy.md")); + } + + #[test] + fn sidecars_in_both_shapes_are_read() { + let m = sidecar_values(br#"{"metadataAttributes": {"title": "A", "year": 2026, "kind": {"value": {"type": "STRING", "stringValue": "policy"}}, "n": {"value": {"type": "NUMBER", "numberValue": 3}}, "empty": ""}}"#); + assert_eq!(m["title"], "A"); + assert_eq!(m["year"], "2026"); + assert_eq!(m["kind"], "policy"); + assert_eq!(m["n"], "3"); + assert!(!m.contains_key("empty")); + assert!(sidecar_values(b"not json").is_empty()); + } + + #[test] + fn s3_errors_are_said_in_plain_words() { + let e = s3_error("AccessDenied", "Access Denied", "team-docs", "111122223333"); + assert!(matches!(e, ConnectorError::Forbidden(_))); + assert!(e.to_string().contains("ImportBuckets")); + let e = s3_error( + "AccessDenied", + "User is not authorized to perform kms:Decrypt", + "b1x", + "111122223333", + ); + assert!(e.to_string().contains("decrypt")); + assert!(matches!( + s3_error("NoSuchBucket", "", "b1x", "1"), + ConnectorError::NotFound(_) + )); + assert!(matches!( + s3_error("PermanentRedirect", "", "b1x", "1"), + ConnectorError::Config(_) + )); + assert!(matches!( + s3_error("SlowDown", "", "b1x", "1"), + ConnectorError::RateLimited(_) + )); + assert!(s3_error("", "dispatch failure", "b1x", "1") + .to_string() + .contains("VPC endpoint")); + } + + #[test] + fn the_update_names_only_this_accounts_buckets() { + let mut a = source(&[(WHOLE, "prefix")]); + let mut b = a.clone(); + b.options["bucket"] = json!("other-docs"); + let mut c = a.clone(); + c.options["account"] = json!("444455556666"); + a.id = "a".into(); + let notion = Source { + kind: Some(Kind::Notion), + ..Default::default() + }; + assert_eq!( + buckets_in(&[a.clone(), a, b, c, notion], "111122223333"), + ["other-docs", "team-docs"] + ); + } + + #[tokio::test] + async fn a_resync_fetches_only_changes_and_removes_deleted_objects() { + let b = bucket(); + let c = connector(&b, 100); + let store = MemSyncStore::default(); + let src = source(&[(WHOLE, "prefix")]); + store.put_source("t", &src).await.unwrap(); + let ctx = sync::Ctx { + store: &store, + connector: &c, + embedder: &WordEmbedder, + team: "t", + now: &|| 1_000, + }; + let first = sync::run(&ctx, "kb", "src").await; + assert_eq!((first.fetched, first.indexed), (3, 3)); + let gets_before = b.gets.lock().unwrap().len(); + // Nothing changed: nothing fetched. + let again = sync::run(&ctx, "kb", "src").await; + assert_eq!(again.fetched, 0); + assert_eq!(b.gets.lock().unwrap().len(), gets_before); + // One edited, one deleted, one sidecar changed. + b.put("hr/leave.txt", "e5b", b"Eighteen weeks of leave."); + b.remove("runbooks/deploy.md"); + b.put( + "runbooks/queues/drain.md.metadata.json", + "m3", + br#"{"metadataAttributes": {"title": "Queues"}}"#, + ); + let third = sync::run(&ctx, "kb", "src").await; + assert_eq!(third.fetched, 2); + assert_eq!(third.removed, 1); + let items = store.items("t", "kb", "src").await.unwrap(); + assert_eq!(items.len(), 2); + assert!(items.iter().any(|f| f.name == "Queues")); + let s = store.source("t", "kb", "src").await.unwrap().unwrap(); + assert_eq!(s.status, Status::Ready); + assert_eq!(s.items, 2); + } + + #[tokio::test] + async fn a_bucket_the_role_cant_read_stops_the_sync_with_the_fix() { + let b = bucket(); + *b.refuse.lock().unwrap() = Some(s3_error("AccessDenied", "", "team-docs", "111122223333")); + let c = connector(&b, 100); + let store = MemSyncStore::default(); + store + .put_source("t", &source(&[(WHOLE, "prefix")])) + .await + .unwrap(); + let ctx = sync::Ctx { + store: &store, + connector: &c, + embedder: &WordEmbedder, + team: "t", + now: &|| 1_000, + }; + let out = sync::run(&ctx, "kb", "src").await; + assert!(matches!(out.error, Some(ConnectorError::Forbidden(_)))); + let s = store.source("t", "kb", "src").await.unwrap().unwrap(); + assert_eq!(s.status, Status::Error); + assert!(s.error.unwrap().message.contains("ImportBuckets")); + } +} From 099a3a4e94af4ce5bb3deac7061d31da324972c2 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 8 Nov 2026 23:04:54 -0500 Subject: [PATCH 2/2] Knowledge: wire the imports, MCP search and per-person readers into the existing modules, routes, passes and role templates --- docs/self-host/knowledge-sources.md | 37 +- infra/cfn/coderhelm-log-reader-update.yaml | 60 +- infra/cfn/coderhelm-log-reader.yaml | 53 ++ infra/lib/own-account-read.ts | 10 +- infra/test/synth.test.ts | 10 +- services/common/src/knowledge/mod.rs | 228 ++++++- services/common/src/knowledge/remote.rs | 42 +- services/common/src/knowledge/search.rs | 158 ++++- .../common/src/knowledge/sources/connect.rs | 128 +++- services/common/src/knowledge/sources/mod.rs | 46 +- .../common/src/knowledge/sources/store.rs | 33 + services/common/src/live/aws_account.rs | 14 +- services/common/src/live/permissions.rs | 13 +- services/common/src/log_reader.rs | 150 +++- services/gateway/src/main.rs | 16 + services/gateway/src/permissions.rs | 4 + services/gateway/src/routes/brain.rs | 17 +- services/gateway/src/routes/connectors.rs | 14 +- services/gateway/src/routes/integrations.rs | 30 +- services/gateway/src/routes/knowledge.rs | 646 ++++++++++++++++-- .../gateway/src/routes/knowledge_sources.rs | 124 +++- services/worker/src/passes/implement.rs | 8 +- services/worker/src/passes/knowledge.rs | 167 ++++- services/worker/src/passes/knowledge_sync.rs | 7 + services/worker/src/passes/plan.rs | 8 +- services/worker/src/passes/plan_chat.rs | 2 +- services/worker/src/passes/review_pr.rs | 5 +- 27 files changed, 1866 insertions(+), 164 deletions(-) diff --git a/docs/self-host/knowledge-sources.md b/docs/self-host/knowledge-sources.md index 8eec105e5..b20c73414 100644 --- a/docs/self-host/knowledge-sources.md +++ b/docs/self-host/knowledge-sources.md @@ -1,6 +1,6 @@ --- title: Knowledge sources -description: Sanity connects by signing in on every install with nothing to set up; the OAuth apps and webhook settings here give Notion, Confluence and Google Drive one-click sign-in and instant updates. +description: Sanity connects by signing in on every install with nothing to set up; the OAuth apps and webhook settings here give Notion, Confluence and Google Drive one-click sign-in and instant updates. Bedrock knowledge bases and MCP search tools connect in place; S3 buckets, Bedrock knowledge bases and export archives import. order: 14 --- @@ -165,9 +165,40 @@ Until an admin applies it, connecting a knowledge base in the install's own acco An install whose functions have no internet route needs interface VPC endpoints for `bedrock-agent-runtime` (search) and `bedrock-agent` (the list), in each region a connected knowledge base lives in. Without them the dialog says CoderHelm couldn't reach Bedrock. -### Who sees what +## Connecting a search tool through MCP -Everyone who can read the CoderHelm knowledge base sees what the search returns, whatever their rights in the systems the Bedrock knowledge base was built from. Agents search the bases attached to them, so anyone who can start a run reaches everything the role can search in those bases. Connect only knowledge bases that everyone with that access may read. +Any search tool your team already runs behind an MCP server can be connected in place too: Azure AI Search or Foundry IQ, Pinecone Assistant, Glean, Atlassian Rovo, Dropbox Dash, a Bedrock knowledge base behind an AgentCore gateway, or your own retrieval server. Add the server on **Settings**, **Connected apps** first, then open **Knowledge**, **New knowledge base**, **Search tool (MCP)** and pick it. + +- **The tools.** CoderHelm calls the server's search tool (`search`, `knowledge_base_retrieve`, `retrieve`, `get_context` and similar names are found by themselves, or pick one) and, for results without text, its fetch tool (`fetch` or similar). Nothing else is called, and a tool the server marks as destructive is never picked. +- **Check on save.** One test search runs before anything is saved. When it fails, the dialog says why in one sentence (not signed in, no search tool, an answer it couldn't read, the server's own error, unreachable) and what to do. +- **Who it searches as.** A server the team shares is searched with the team's connection. A server that signs each person in is searched with the asking person's own sign-in, so they only get what the tool lets them see; agent runs search it as the person who started them, and runs nobody started skip it. +- **Nothing new in AWS.** It uses the Connected apps sign-in and tokens (sealed with your KMS key) and needs no permission change. If you restrict outbound traffic, allow the server's address. + +## Importing an existing knowledge base + +### From Amazon S3 + +A bucket of documents (or a folder in one) becomes a source of a knowledge base: **Add source**, **Amazon S3**, pick the AWS account, type the bucket name, and pick folders or files. CoderHelm reads supported files (PDF, Word, Markdown, text, CSV, Excel, HTML), embeds them with Titan and keeps them in sync like any other source: an object whose ETag didn't change isn't read again, a changed one re-embeds only its changed passages, and a deleted one is removed. A `.metadata.json` sidecar next to a document (the Bedrock data source format) gives it its title, original link and date. + +The bucket is always read with that account's `CoderHelmLogReader` role (connect the account on **Settings**, **Integrations**, **AWS**, including the install's own account), never with the install's own role. The role may read only the buckets named in its stack's `ImportBuckets` parameter: `s3:ListBucket`, `s3:GetBucketLocation` and `s3:GetObject` on them, and `kms:Decrypt` only through S3 for a bucket with its own KMS key. When the role can't read a bucket, the dialog offers the one-click update stack with the bucket named. The install's permissions boundary already allows S3 and KMS, so there is no admin step on the install itself. + +### From a Bedrock knowledge base + +**Import from a Bedrock knowledge base** reads the knowledge base's settings (`bedrock:GetKnowledgeBase`, `bedrock:ListDataSources`, `bedrock:GetDataSource`) and turns each S3 data source into an S3 source on its bucket and prefixes. Bedrock can't export its passages, so CoderHelm reads the original documents and indexes them itself; nothing in Bedrock changes. A Confluence or web data source points you at CoderHelm's own connector instead; SharePoint and Salesforce data sources can't be imported, so connect the knowledge base in place to search them. On a self-hosted install, a knowledge base in its own account is read with the install's own role (the boundary's `bedrock:Get*` and `bedrock:List*`, which arrive with the version update); one in another account with that account's role, whose `ReadKnowledgeBases` statement now includes these three actions. + +### From an export archive + +**Upload an archive** takes a `.zip` (up to 200 MB) of a Notion export (Markdown and CSV), a Confluence HTML export or a zipped docs folder, and unpacks it on the server. Every supported entry becomes a page of the base, titled without the export's ids. Uploading a newer export to the same archive keeps unchanged pages, re-reads changed ones and removes pages it no longer has. The archive is kept in the team's folder of the data bucket and goes with its source. Before the upload the dialog warns that every page becomes readable by everyone who can read the base, and that a Confluence Full Export includes restricted pages. + +### Limits + +An import keeps up to 2,500 documents per source (other sources keep 1,000). CoderHelm ranks its own bases in memory, so a bigger corpus is better connected in place; the page says so when an import is cut short. Each search reads up to 16 indexes at once and keeps recently used indexes in memory (up to 160 MB per process). + +## Who sees what + +Every knowledge base has a lowest read role, and can also be limited to named people and roles (**Only these people or roles**). A person only gets passages from bases they may read, in the brain chat and on the Knowledge page. + +Agents search the bases attached to them. A base limited to named people is searched only in runs one of them started; a search tool that signs each person in is searched as the person who started the run. Every other attached base is searched by every run, whatever the starter's rights in the systems the content came from, and the page says so when a base is attached. Connect and attach only content that everyone with that access may read. ## What runs diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index 6df4b6e2b..1b0bda8d6 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -1,8 +1,9 @@ AWSTemplateFormatVersion: "2010-09-09" Description: > Brings the existing CoderHelmLogReader role up to date with the read-only - permissions the current CoderHelm release uses, and lets it search the - Bedrock knowledge bases named in KnowledgeBases. Every permission here is + permissions the current CoderHelm release uses, lets it search the + Bedrock knowledge bases named in KnowledgeBases, and lets it read the + documents in the S3 buckets named in ImportBuckets. Every permission here is read-only: CoderHelm can list, describe and query, never change anything. It only adds: to drop a permission an older release granted, update the CoderHelmLogReader stack itself with the current role template. @@ -26,9 +27,20 @@ Parameters: AllowedPattern: "^(|all|arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10}(,arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10})*)$" ConstraintDescription: Knowledge base ARNs separated by commas, "all", or empty. + ImportBuckets: + Type: String + Default: "" + Description: > + S3 buckets CoderHelm may import knowledge base documents from, + read-only: their names separated by commas. Empty: none (the role reads + no object in any bucket). + AllowedPattern: "^(|[a-z0-9][a-z0-9.-]{1,61}[a-z0-9](,[a-z0-9][a-z0-9.-]{1,61}[a-z0-9])*)$" + ConstraintDescription: Bucket names separated by commas, or empty. + Conditions: ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] + ReadsImportBuckets: !Not [!Equals [!Ref ImportBuckets, ""]] Resources: CoderHelmReadOnlyUpdate: @@ -130,6 +142,9 @@ Resources: Action: - "bedrock:Retrieve" - "bedrock:GetDocumentContent" + - "bedrock:GetKnowledgeBase" + - "bedrock:ListDataSources" + - "bedrock:GetDataSource" Resource: !If - ReadsEveryKnowledgeBase - !Sub "arn:aws:bedrock:*:${AWS::AccountId}:knowledge-base/*" @@ -143,3 +158,44 @@ Resources: - "bedrock:ListKnowledgeBases" Resource: "*" - !Ref AWS::NoValue + # Imports: the documents in the buckets named in ImportBuckets, + # read so a knowledge base can index them; never a write, never + # another bucket. + - !If + - ReadsImportBuckets + - Sid: ReadImportBuckets + Effect: Allow + Action: + - "s3:ListBucket" + - "s3:GetBucketLocation" + Resource: !Split + - "," + - !Sub + - "arn:aws:s3:::${Names}" + - Names: !Join [",arn:aws:s3:::", !Split [",", !Ref ImportBuckets]] + - !Ref AWS::NoValue + - !If + - ReadsImportBuckets + - Sid: ReadImportObjects + Effect: Allow + Action: + - "s3:GetObject" + Resource: !Split + - "," + - !Sub + - "arn:aws:s3:::${Names}/*" + - Names: !Join ["/*,arn:aws:s3:::", !Split [",", !Ref ImportBuckets]] + - !Ref AWS::NoValue + # A bucket encrypted with its own KMS key: decrypt only through S3, + # so only objects the role may read anyway. + - !If + - ReadsImportBuckets + - Sid: DecryptImportsThroughS3 + Effect: Allow + Action: + - "kms:Decrypt" + Resource: "*" + Condition: + StringLike: + kms:ViaService: "s3.*.amazonaws.com" + - !Ref AWS::NoValue diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 17636dda2..5556e9eee 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -37,9 +37,20 @@ Parameters: AllowedPattern: "^(|all|arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10}(,arn:aws:bedrock:[a-z0-9-]+:[0-9]{12}:knowledge-base/[A-Z0-9]{10})*)$" ConstraintDescription: Knowledge base ARNs separated by commas, "all", or empty. + ImportBuckets: + Type: String + Default: "" + Description: > + S3 buckets CoderHelm may import knowledge base documents from, + read-only: their names separated by commas. Empty: none (the role reads + no object in any bucket). + AllowedPattern: "^(|[a-z0-9][a-z0-9.-]{1,61}[a-z0-9](,[a-z0-9][a-z0-9.-]{1,61}[a-z0-9])*)$" + ConstraintDescription: Bucket names separated by commas, or empty. + Conditions: ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] + ReadsImportBuckets: !Not [!Equals [!Ref ImportBuckets, ""]] Resources: CoderHelmLogReaderRole: @@ -201,6 +212,9 @@ Resources: Action: - "bedrock:Retrieve" - "bedrock:GetDocumentContent" + - "bedrock:GetKnowledgeBase" + - "bedrock:ListDataSources" + - "bedrock:GetDataSource" Resource: !If - ReadsEveryKnowledgeBase - !Sub "arn:aws:bedrock:*:${AWS::AccountId}:knowledge-base/*" @@ -214,6 +228,45 @@ Resources: Resource: "*" - !Ref AWS::NoValue - !Ref AWS::NoValue + # Imports: the documents in the buckets named in ImportBuckets, read + # so a knowledge base can index them; never a write, never another + # bucket. + - !If + - ReadsImportBuckets + - PolicyName: KnowledgeImportsReadOnly + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: ReadImportBuckets + Effect: Allow + Action: + - "s3:ListBucket" + - "s3:GetBucketLocation" + Resource: !Split + - "," + - !Sub + - "arn:aws:s3:::${Names}" + - Names: !Join [",arn:aws:s3:::", !Split [",", !Ref ImportBuckets]] + - Sid: ReadImportObjects + Effect: Allow + Action: + - "s3:GetObject" + Resource: !Split + - "," + - !Sub + - "arn:aws:s3:::${Names}/*" + - Names: !Join ["/*,arn:aws:s3:::", !Split [",", !Ref ImportBuckets]] + # A bucket encrypted with its own KMS key: decrypt only through S3, + # so only objects the role may read anyway. + - Sid: DecryptImportsThroughS3 + Effect: Allow + Action: + - "kms:Decrypt" + Resource: "*" + Condition: + StringLike: + kms:ViaService: "s3.*.amazonaws.com" + - !Ref AWS::NoValue Outputs: RoleArn: diff --git a/infra/lib/own-account-read.ts b/infra/lib/own-account-read.ts index 005eec5e9..dbc1cdb91 100644 --- a/infra/lib/own-account-read.ts +++ b/infra/lib/own-account-read.ts @@ -19,6 +19,12 @@ * for the picker. Admins still choose which ones a team connects. Retrieve also * needs the permissions boundary to allow bedrock:Retrieve, which reaches an * install only through the access stack an AWS admin applies (native/access-stack.ts). + * + * Knowledge imports from S3 (services/common/src/knowledge/sources/s3.rs) never + * use the install's own role: the template's ImportBuckets is empty here, so + * the role gains no read on the account's buckets. An import reads a bucket + * with the team's CoderHelmLogReader role in that account, whose stack names + * every bucket an admin chose. */ import * as cdk from "aws-cdk-lib"; import * as iam from "aws-cdk-lib/aws-iam"; @@ -34,7 +40,7 @@ const ROLE_NAME_MARK = "__CODERHELM_ROLE__"; /** The install's own role searches every knowledge base in its own account. */ const OWN_KNOWLEDGE_BASES = "all"; /** The template's conditions for that value. A condition not listed here fails the build. */ -const OWN_CONDITIONS: Record = { ReadsKnowledgeBases: true, ReadsEveryKnowledgeBase: true }; +const OWN_CONDITIONS: Record = { ReadsKnowledgeBases: true, ReadsEveryKnowledgeBase: true, ReadsImportBuckets: false }; type Statement = { Sid?: string; Effect: string; Action: string | string[]; Resource: unknown }; @@ -61,7 +67,7 @@ export function decideConditions(v: unknown, conditions: Record /** The update template's statements for the install's own role: its knowledge bases are every one in its account. */ export function updateTemplateStatements(): Statement[] { const scratch = new cdk.Stack(new cdk.App(), "Scratch"); - const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK, KnowledgeBases: OWN_KNOWLEDGE_BASES } }); + const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK, KnowledgeBases: OWN_KNOWLEDGE_BASES, ImportBuckets: "" } }); const p = inc.getResource(UPDATE_POLICY_ID) as iam.CfnPolicy; return decideConditions(scratch.resolve(p.policyDocument).Statement, OWN_CONDITIONS) as Statement[]; } diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 7e1944129..eee454e68 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -180,7 +180,14 @@ test("self-host: the gateway and worker read the install's own account with this const t = synth(selfHost()); // Every permission the services check a role against (services/common/src/log_reader.rs ABILITIES). const rs = fs.readFileSync(path.join(INFRA, "..", "services", "common", "src", "log_reader.rs"), "utf8"); - const abilities = rs.slice(rs.indexOf("pub const ABILITIES"), rs.indexOf("];", rs.indexOf("pub const ABILITIES"))); + const all = rs.slice(rs.indexOf("pub const ABILITIES"), rs.indexOf("];", rs.indexOf("pub const ABILITIES"))); + // Knowledge imports from S3 read a bucket only with the team's CoderHelmLogReader role, whose stack + // names each bucket (services/common/src/knowledge/sources/s3.rs): the install's own role never gains + // read on the account's buckets. + const importsAt = all.indexOf('key: "imports"'); + assert.ok(importsAt > 0, "the imports ability"); + const nextAt = all.indexOf("Ability {", importsAt); + const abilities = all.slice(0, importsAt) + (nextAt > 0 ? all.slice(nextAt) : ""); const needed = [...new Set([...abilities.matchAll(/"([a-z0-9-]+:[A-Za-z]+)"/g)].map((m) => m[1]))]; assert.ok(needed.length > 20, `${needed.length} actions`); for (const [stack, fn] of [ @@ -193,6 +200,7 @@ test("self-host: the gateway and worker read the install's own account with this assert.equal(policies.length, 1, `${fn}: one read policy`); const doc = JSON.stringify(policies[0].Properties.PolicyDocument); for (const a of needed) assert.ok(doc.includes(`"${a}"`), `${fn} lacks ${a}`); + for (const a of ["s3:GetObject", "s3:ListBucket", "kms:Decrypt"]) assert.ok(!doc.includes(`"${a}"`), `${fn} must not read buckets with ${a}`); // Only reads: list, describe, get, query, never a write. const actions: string[] = policies[0].Properties.PolicyDocument.Statement.flatMap((s: any) => ([] as string[]).concat(s.Action)); for (const a of actions) assert.match(a, /^[a-z0-9-]+:(List|Describe|Get|Filter|Start(Query)?$|Stop(Query)?$|BatchGet|Simulate|InvokeRestApi|Retrieve$)/, a); diff --git a/services/common/src/knowledge/mod.rs b/services/common/src/knowledge/mod.rs index b118a75c1..a15c81f6a 100644 --- a/services/common/src/knowledge/mod.rs +++ b/services/common/src/knowledge/mod.rs @@ -18,15 +18,22 @@ //! comfortably fast at the limits below. //! //! A base can instead be **connected in place** ([`Backend::Remote`]): an -//! Amazon Bedrock knowledge base in the team's own AWS account, searched -//! live where it is ([`remote`]). Nothing of it is copied: it has no files, -//! no passages and no vectors here, and search merges the list Bedrock -//! ranked with the local ones. +//! Amazon Bedrock knowledge base in the team's own AWS account ([`remote`]), +//! or a search tool the team already runs behind an MCP server +//! ([`remote_mcp`]), searched live where it is. Nothing of it is copied: it +//! has no files, no passages and no vectors here, and search merges the list +//! the provider ranked with the local ones. +//! +//! Who reads a base: its lowest read role, and optionally only named people +//! or roles ([`Base::readers`], checked with [`Base::open_to`]). A base read +//! through each person's own sign-in ([`Remote::per_person`]) answers every +//! search with that person's access in the tool itself. pub mod answer; pub mod chunk; pub mod extract; pub mod remote; +pub mod remote_mcp; pub mod search; pub mod sources; @@ -38,6 +45,8 @@ pub const MAX_FILE_BYTES: u64 = 25 * 1024 * 1024; pub const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024; /// Files per knowledge base. pub const MAX_FILES_PER_BASE: usize = 500; +/// Named readers one base keeps ([`Base::readers`]). +pub const MAX_READERS: usize = 50; /// Knowledge bases per team. pub const MAX_BASES: usize = 50; /// Passages kept from one file; the rest of a very long file is dropped @@ -99,6 +108,74 @@ pub struct Base { /// before connecting in place existed), or searched live elsewhere. #[serde(default, skip_serializing_if = "Backend::is_local")] pub backend: Backend, + /// Only these people and roles read it (on top of [`Self::read_role`]): + /// `user:` or `role:`. Empty: everyone the read role + /// allows. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub readers: Vec, +} + +/// A person asking: who they are and which role they hold on the team. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Person { + /// Lowercased email. + pub email: String, + /// Their role's key (`member`, `admin`, a custom role's id). + pub role: String, +} + +impl Person { + pub fn new(email: &str, role: &str) -> Person { + Person { + email: email.trim().to_ascii_lowercase(), + role: role.trim().to_string(), + } + } +} + +/// A reader entry as stored (`user:`, `role:`), or why it isn't +/// one. +pub fn clean_reader(raw: &str) -> Result { + let raw = raw.trim(); + let bad = || { + format!("\"{raw}\" isn't a person or a role. Use an email, or role: and the role's name.") + }; + let (kind, value) = match raw.split_once(':') { + Some((k, v)) if k.eq_ignore_ascii_case("user") || k.eq_ignore_ascii_case("role") => { + (k.to_ascii_lowercase(), v.trim()) + } + _ if raw.contains('@') => ("user".to_string(), raw), + _ => return Err(bad()), + }; + if value.is_empty() + || value.len() > 200 + || value.chars().any(|c| c.is_control() || c.is_whitespace()) + { + return Err(bad()); + } + if kind == "user" { + let (local, domain) = value.split_once('@').ok_or_else(bad)?; + if local.is_empty() || !domain.contains('.') { + return Err(bad()); + } + return Ok(format!("user:{}", value.to_ascii_lowercase())); + } + Ok(format!("role:{value}")) +} + +/// Reader entries checked, duplicates dropped, at most [`MAX_READERS`]. +pub fn clean_readers(raw: &[String]) -> Result, String> { + let mut out: Vec = Vec::new(); + for r in raw.iter().filter(|r| !r.trim().is_empty()) { + let r = clean_reader(r)?; + if !out.contains(&r) { + out.push(r); + } + } + if out.len() > MAX_READERS { + return Err(format!("Name up to {MAX_READERS} people and roles.")); + } + Ok(out) } /// Where a base's passages live and are ranked. @@ -132,6 +209,22 @@ pub struct Remote { /// the knowledge base's vector store refused it when it was connected. #[serde(default = "yes")] pub hybrid: bool, + /// Searched with each person's own sign-in (a search tool whose MCP + /// server signs every person in): a person only gets what the tool lets + /// them see, and a search nobody asked for (an agent run without a + /// person) skips it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub per_person: bool, + /// The search tool's tool that searches (`search`), for an MCP base. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub search_tool: String, + /// Its tool that reads one result in full (`fetch`), when it has one. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub fetch_tool: String, + /// What the provider calls it, when connected (a search tool's server + /// name), for the page. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub name: String, } fn yes() -> bool { @@ -144,12 +237,25 @@ fn yes() -> bool { pub enum Provider { /// Amazon Bedrock Knowledge Bases (`bedrock-agent-runtime` Retrieve). BedrockKb, + /// A search tool behind an MCP server on the team's Connected apps + /// (Azure AI Search, Pinecone Assistant, Glean, Rovo, Dropbox Dash, an + /// AgentCore gateway, the team's own): its `search` and `fetch` tools. + Mcp, } impl Provider { pub fn label(self) -> &'static str { match self { Provider::BedrockKb => "Bedrock knowledge base", + Provider::Mcp => "Search tool (MCP)", + } + } + + /// What a passage from it is cited as. + pub fn source_kind(self) -> SourceKind { + match self { + Provider::BedrockKb => SourceKind::BedrockKb, + Provider::Mcp => SourceKind::McpSearch, } } } @@ -167,6 +273,10 @@ pub enum Access { /// (`live::aws::assume`). The private ID is read from Coderhelm's own /// record of the account, never stored here. Account { account: String }, + /// A server on the team's Connected apps (`mcp_remote`): its shared + /// connection, or each person's own sign-in ([`Remote::per_person`]). + /// Tokens stay sealed with the server's record, never here. + Connection { server_id: String }, } /// Where a passage came from, as a [`search::Hit`] and a citation name it @@ -179,6 +289,8 @@ pub enum SourceKind { Synced(sources::Kind), /// A passage a connected Bedrock knowledge base returned, live. BedrockKb, + /// A passage a connected search tool (MCP) returned, live. + McpSearch, } impl SourceKind { @@ -188,6 +300,7 @@ impl SourceKind { SourceKind::Upload => "", SourceKind::Synced(k) => k.key(), SourceKind::BedrockKb => "bedrock_kb", + SourceKind::McpSearch => "mcp", } } @@ -196,6 +309,7 @@ impl SourceKind { SourceKind::Upload => "Uploaded file", SourceKind::Synced(k) => k.label(), SourceKind::BedrockKb => Provider::BedrockKb.label(), + SourceKind::McpSearch => Provider::Mcp.label(), } } @@ -203,6 +317,7 @@ impl SourceKind { match key { "" => Some(SourceKind::Upload), "bedrock_kb" => Some(SourceKind::BedrockKb), + "mcp" => Some(SourceKind::McpSearch), k => sources::Kind::parse(k).map(SourceKind::Synced), } } @@ -226,6 +341,56 @@ impl Base { role_level(role) >= role_level(&self.read_role) } + /// Is the base open to `who` by name? Always, unless it names its + /// readers ([`Self::readers`]); then only a named person or someone + /// holding a named role. On top of [`Self::readable_by`], never instead. + pub fn open_to(&self, who: &Person) -> bool { + self.readers.is_empty() + || self.readers.iter().any(|r| match r.split_once(':') { + Some(("user", e)) => !who.email.is_empty() && e.eq_ignore_ascii_case(&who.email), + Some(("role", k)) => !who.role.is_empty() && k == who.role, + _ => false, + }) + } + + /// Read only by named people or roles. + pub fn named_readers(&self) -> bool { + !self.readers.is_empty() + } + + /// Searched with each person's own sign-in. + pub fn per_person(&self) -> bool { + self.remote().is_some_and(|r| r.per_person) + } + + /// May an agent run started by `who` (`None`: nobody, such as a + /// scheduled run) search this attached base? A base for named readers + /// only in runs one of them started; a base read with each person's own + /// sign-in only when a person started the run. Every other attached base + /// is searched by every run, which the page says when it is attached + /// ([`Self::agent_access_note`]). + pub fn searchable_in_run(&self, who: Option<&Person>) -> bool { + match who { + Some(p) => self.open_to(p), + None => !self.named_readers() && !self.per_person(), + } + } + + /// What attaching it to agents means for who sees its results, for the + /// page (empty when it isn't attached to any agent). + pub fn agent_access_note(&self) -> &'static str { + if !self.attach_team && self.agents.is_empty() { + return ""; + } + if self.per_person() { + "Agent runs search it as the person who started them, with their own sign-in. Runs nobody started skip it." + } else if self.named_readers() { + "Agents search it only in runs started by the people and roles named here. Runs anyone else started skip it." + } else { + "Everyone who can start an agent run gets results from this knowledge base when the agent searches it, whatever their own access in the app the content comes from." + } + } + /// Does `agent` (a key of [`AGENTS`]) search this base? pub fn attached_to(&self, agent: &str) -> bool { self.attach_team || self.agents.iter().any(|a| a == agent) @@ -584,6 +749,10 @@ mod tests { account: "111122223333".into(), }, hybrid: true, + per_person: false, + search_tool: String::new(), + fetch_tool: String::new(), + name: String::new(), }), ..Default::default() }; @@ -611,6 +780,57 @@ mod tests { assert_eq!(SourceKind::parse("nope"), None); } + #[test] + fn named_readers_open_a_base_to_those_people_and_roles_only() { + assert_eq!( + clean_reader("Ada@Example.com").unwrap(), + "user:ada@example.com" + ); + assert_eq!(clean_reader("role:custom:r1").unwrap(), "role:custom:r1"); + assert_eq!(clean_reader("USER:bo@x.io").unwrap(), "user:bo@x.io"); + for bad in [ + "ada", + "user:", + "user:no-at", + "role:", + "role:two words", + "x:y", + ] { + assert!(clean_reader(bad).is_err(), "{bad}"); + } + let many: Vec = (0..=MAX_READERS).map(|i| format!("u{i}@x.io")).collect(); + assert!(clean_readers(&many).is_err()); + assert_eq!( + clean_readers(&["a@x.io".into(), "A@x.io".into(), " ".into()]).unwrap(), + ["user:a@x.io"] + ); + + let open = Base::default(); + let ada = Person::new("Ada@Example.com", "member"); + let bo = Person::new("bo@example.com", "member"); + let admin = Person::new("cy@example.com", "admin"); + assert!(open.open_to(&ada) && open.open_to(&Person::default())); + let named = Base { + readers: vec!["user:ada@example.com".into(), "role:admin".into()], + ..Default::default() + }; + assert!(named.open_to(&ada)); + assert!(!named.open_to(&bo)); + assert!(named.open_to(&admin)); + assert!(!named.open_to(&Person::default())); + // Runs: a named base only for its readers, never for nobody. + assert!(named.searchable_in_run(Some(&ada))); + assert!(!named.searchable_in_run(Some(&bo))); + assert!(!named.searchable_in_run(None)); + assert!(open.searchable_in_run(None)); + // An old record has no readers and saves none. + let old: Base = serde_json::from_str(r#"{"id":"k","name":"n"}"#).unwrap(); + assert!(old.readers.is_empty()); + assert!(serde_json::to_value(&old).unwrap().get("readers").is_none()); + assert_eq!(SourceKind::parse("mcp"), Some(SourceKind::McpSearch)); + assert_eq!(Provider::Mcp.source_kind().label(), "Search tool (MCP)"); + } + #[test] fn only_a_ready_version_is_searched() { let mut f = FileMeta { diff --git a/services/common/src/knowledge/remote.rs b/services/common/src/knowledge/remote.rs index 67c60f679..da293d74b 100644 --- a/services/common/src/knowledge/remote.rs +++ b/services/common/src/knowledge/remote.rs @@ -229,6 +229,10 @@ pub fn bedrock_remote(arn: &KbArn, access: Access, hybrid: bool) -> Remote { region: arn.region.clone(), access, hybrid, + per_person: false, + search_tool: String::new(), + fetch_tool: String::new(), + name: String::new(), } } @@ -259,6 +263,11 @@ pub async fn session( ) }) } + Access::Connection { .. } => Err(Refusal::new( + "invalid", + "This knowledge base is reached through a search tool, not AWS.", + "Check it from its own page.", + )), Access::Account { account } => { let accounts = if accounts_table.is_empty() { Vec::new() @@ -477,6 +486,11 @@ const DATE_KEYS: &[&str] = &[ "date", ]; +/// A metadata date as `YYYY-MM-DD` ([`as_of`]), for the other retrievers. +pub fn date_of(raw: &str) -> String { + as_of(raw) +} + /// A metadata date as `YYYY-MM-DD`: RFC 3339, a plain date, or epoch /// seconds or milliseconds. Empty when there is none (no recency nudge). fn as_of(raw: &str) -> String { @@ -590,8 +604,8 @@ impl Retriever for Bedrock<'_> { let Backend::Remote(remote) = &base.backend else { return Ok(Vec::new()); }; - match remote.provider { - Provider::BedrockKb => {} + if remote.provider != Provider::BedrockKb { + return Err("This knowledge base isn't a Bedrock knowledge base.".into()); } let s = session( self.sts, @@ -610,6 +624,30 @@ impl Retriever for Bedrock<'_> { } } +/// Every kind of connected base, each answered by its own retriever: what +/// [`super::search::search`] is given in production. +pub struct Connected<'a> { + pub bedrock: Bedrock<'a>, + pub mcp: super::remote_mcp::McpSearch<'a>, +} + +#[async_trait::async_trait] +impl Retriever for Connected<'_> { + async fn retrieve( + &self, + team_id: &str, + base: &Base, + query: &str, + k: usize, + ) -> Result, String> { + match base.remote().map(|r| r.provider) { + Some(Provider::BedrockKb) => self.bedrock.retrieve(team_id, base, query, k).await, + Some(Provider::Mcp) => self.mcp.retrieve(team_id, base, query, k).await, + None => Ok(Vec::new()), + } + } +} + // ── Listing (self-hosted) ──────────────────────────────────────────────────── /// A knowledge base found in the install's own account. diff --git a/services/common/src/knowledge/search.rs b/services/common/src/knowledge/search.rs index cec489093..4c903ede1 100644 --- a/services/common/src/knowledge/search.rs +++ b/services/common/src/knowledge/search.rs @@ -269,12 +269,84 @@ async fn query_data Deserialize<'de>>( } /// Indexes kept in memory, by key (a key names one version, so a cached -/// index is never stale). -fn cache() -> &'static Mutex>> { - static C: OnceLock>>> = OnceLock::new(); - C.get_or_init(|| Mutex::new(HashMap::new())) +/// index is never stale), least recently used first out once they pass +/// [`CACHE_BYTES`] or [`CACHE_ENTRIES`]. +#[derive(Default)] +pub struct IndexCache { + map: HashMap, usize, u64)>, + bytes: usize, + tick: u64, +} + +/// Memory the cached indexes may take in one process. +pub const CACHE_BYTES: usize = 160 * 1024 * 1024; +/// Indexes one process keeps at most. +pub const CACHE_ENTRIES: usize = 4_096; +/// Indexes read at once for one search. +pub const LOAD_CONCURRENCY: usize = 16; + +/// About how much memory an index takes. +pub fn index_bytes(i: &Index) -> usize { + i.chunks + .iter() + .map(|c| c.vector.len() * 4 + c.text.len() + c.loc.len() + 64) + .sum::() + + 64 +} + +impl IndexCache { + pub fn get(&mut self, key: &str) -> Option> { + self.tick += 1; + let tick = self.tick; + self.map.get_mut(key).map(|e| { + e.2 = tick; + e.0.clone() + }) + } + + /// Keeps `index`, letting the least recently used go until it fits. + /// An index bigger than the whole budget isn't kept. + pub fn put(&mut self, key: &str, index: Arc, budget: usize, entries: usize) { + let size = index_bytes(&index); + if size > budget { + return; + } + if let Some((_, old, _)) = self.map.remove(key) { + self.bytes -= old; + } + while !self.map.is_empty() && (self.bytes + size > budget || self.map.len() >= entries) { + let oldest = self + .map + .iter() + .min_by_key(|(_, e)| e.2) + .map(|(k, _)| k.clone()) + .unwrap_or_default(); + if let Some((_, b, _)) = self.map.remove(&oldest) { + self.bytes -= b; + } + } + self.tick += 1; + self.bytes += size; + self.map.insert(key.to_string(), (index, size, self.tick)); + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + pub fn bytes(&self) -> usize { + self.bytes + } +} + +fn cache() -> &'static Mutex { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| Mutex::new(IndexCache::default())) } -const CACHE_ENTRIES: usize = 64; #[async_trait::async_trait] impl Store for AwsStore { @@ -315,7 +387,7 @@ impl Store for AwsStore { if !super::owns_key(team_id, key) { return Err("that index isn't this team's".into()); } - if let Some(hit) = cache().lock().ok().and_then(|c| c.get(key).cloned()) { + if let Some(hit) = cache().lock().ok().and_then(|mut c| c.get(key)) { return Ok(hit); } let obj = self @@ -334,10 +406,7 @@ impl Store for AwsStore { .into_bytes(); let index = Arc::new(decode_index(&bytes)?); if let Ok(mut c) = cache().lock() { - if c.len() >= CACHE_ENTRIES { - c.clear(); - } - c.insert(key.to_string(), index.clone()); + c.put(key, index.clone(), CACHE_BYTES, CACHE_ENTRIES); } Ok(index) } @@ -673,8 +742,17 @@ pub async fn search( let qv = embedder.embed(crate::truncate_str(query, 8_000)).await?; let mut loaded: Vec<(Base, FileMeta, Arc)> = Vec::new(); let mut stale = Vec::new(); - for (base, file, key) in &files { - match store.index(team_id, key).await { + // Many files at once (an import holds thousands), in a steady order. + let mut read = Vec::with_capacity(files.len()); + for group in files.chunks(LOAD_CONCURRENCY) { + let got = + futures::future::join_all(group.iter().map(|f| store.index(team_id, &f.2))).await; + for (f, index) in group.iter().zip(got) { + read.push((&f.0, &f.1, index)); + } + } + for (base, file, index) in read { + match index { Ok(i) if i.model != embedder.model() || i.dims != qv.len() => { tracing::warn!(kb = %base.id, file = %file.id, model = %i.model, dims = i.dims, "Knowledge index from another embedding model; needs re-embedding"); @@ -791,7 +869,12 @@ pub async fn search( kb_name: base.name.clone(), score, authoritative: base.authoritative, - source_kind: super::SourceKind::BedrockKb.key().into(), + source_kind: base + .remote() + .map(|r| r.provider.source_kind()) + .unwrap_or(super::SourceKind::BedrockKb) + .key() + .into(), ..h.clone() }, }; @@ -981,6 +1064,10 @@ pub mod testing { account: account.into(), }, hybrid: true, + per_person: false, + search_tool: String::new(), + fetch_tool: String::new(), + name: String::new(), }), ..Default::default() } @@ -1084,6 +1171,51 @@ mod tests { use super::testing::*; use super::*; + #[test] + fn the_index_cache_keeps_the_most_recently_used_within_its_budget() { + let idx = |n: usize| { + Arc::new(Index { + model: "m".into(), + dims: 4, + chunks: (0..n) + .map(|i| IndexedChunk { + ord: i as u32, + loc: String::new(), + text: "x".repeat(36), + vector: vec![0.0; 4], + }) + .collect(), + }) + }; + let one = index_bytes(&idx(1)); + let mut c = IndexCache::default(); + let budget = one * 3; + c.put("a", idx(1), budget, 100); + c.put("b", idx(1), budget, 100); + c.put("c", idx(1), budget, 100); + assert_eq!(c.len(), 3); + // "a" is used, so "b" is the oldest when "d" needs room. + assert!(c.get("a").is_some()); + c.put("d", idx(1), budget, 100); + assert!(c.get("b").is_none()); + assert!(c.get("a").is_some() && c.get("c").is_some() && c.get("d").is_some()); + assert!(c.bytes() <= budget); + // Too big for the whole budget: not kept, nothing else lost. + c.put("huge", idx(10), budget, 100); + assert!(c.get("huge").is_none()); + assert_eq!(c.len(), 3); + // The entry cap holds too. + let mut small = IndexCache::default(); + for k in ["p", "q", "r"] { + small.put(k, idx(1), usize::MAX, 2); + } + assert_eq!(small.len(), 2); + assert!(small.get("p").is_none()); + // Putting the same key again replaces it without counting it twice. + small.put("r", idx(2), usize::MAX, 2); + assert_eq!(small.bytes(), index_bytes(&idx(1)) + index_bytes(&idx(2))); + } + fn base(id: &str, name: &str) -> Base { Base { id: id.into(), diff --git a/services/common/src/knowledge/sources/connect.rs b/services/common/src/knowledge/sources/connect.rs index b2829856c..f0e002964 100644 --- a/services/common/src/knowledge/sources/connect.rs +++ b/services/common/src/knowledge/sources/connect.rs @@ -12,6 +12,8 @@ //! | Google Drive | Google sign-in (OAuth) | | //! | GitHub | the Coderhelm GitHub App | | //! | Website | none needed | | +//! | Amazon S3 | the team's `CoderHelmLogReader` role in the bucket's account | | +//! | Archive upload | none needed (the upload is in the team's own folder) | | //! //! A token is opened for the one call that needs it and never leaves the //! server. @@ -36,7 +38,7 @@ use super::connector::{Connector, ConnectorError}; use super::mcp::RuntimeTools; use super::oauth::{catalog_id, connection_id}; use super::sanity_mcp::{self, SanityMcp}; -use super::{confluence, gdrive, github, notion, sanity, web, Kind, SignIn, Source}; +use super::{archive, confluence, gdrive, github, notion, s3, sanity, web, Kind, SignIn, Source}; use crate::live::connectors::{self as conns, ConnKind}; use crate::mcp_remote::http::Http; use crate::mcp_remote::runtime::{ConnError, Detected, KmsCipher, Runtime}; @@ -54,6 +56,64 @@ pub struct Env { pub http: Arc, /// An installation token of the team's GitHub App, when it has one. pub github_token: Option, + /// AWS, for imports: the team's connected accounts and the data bucket. + pub aws: Option, +} + +/// What an import from AWS (an S3 bucket) or an uploaded archive needs. +#[derive(Clone)] +pub struct AwsEnv { + pub sts: aws_sdk_sts::Client, + /// The table of connected AWS accounts (`AWS_CONN#`). + pub accounts_table: String, + /// The data bucket uploads are kept in, and its client. + pub s3: aws_sdk_s3::Client, + pub bucket: String, + /// Names the session in the team's AWS records. + pub actor: String, +} + +impl Env { + /// The team's connected AWS accounts. + pub async fn aws_accounts(&self) -> Vec { + let Some(a) = self.aws.as_ref().filter(|a| !a.accounts_table.is_empty()) else { + return Vec::new(); + }; + crate::live::aws_account::list(&self.dynamo, &a.accounts_table, &self.team) + .await + .unwrap_or_default() + } + + /// A session on the team's role in the account that holds bucket `w`. + pub async fn s3_session( + &self, + w: &s3::Where, + ) -> Result { + let a = self + .aws + .as_ref() + .ok_or_else(|| ConnectorError::Config("This Coderhelm can't reach AWS here.".into()))?; + let accounts = self.aws_accounts().await; + let acct = accounts.iter().find(|x| x.account == w.account).ok_or_else(|| { + ConnectorError::Reconnect(format!( + "AWS account {} isn't connected to Coderhelm. Connect it on Settings, Integrations, AWS.", + w.account + )) + })?; + let target = crate::live::aws::AwsTarget { + region: if w.region.is_empty() { + acct.region.clone() + } else { + w.region.clone() + }, + ..acct.target() + }; + // Always the team's role, never the install's own: an admin names + // every bucket the role may read. + crate::live::aws::assume_exact(&a.sts, &target, &a.actor) + .await + .map_err(|e| ConnectorError::Reconnect(format!("{} {}", e.message, e.fix))) + } } /// How a connector reaches its provider. @@ -66,6 +126,10 @@ pub enum Via { SavedKey, GithubApp, Public, + /// The team's role in its AWS account. + AwsRole, + /// An archive uploaded to the team's own folder. + Upload, } /// A connector ready to call, and the settings it worked out on the way @@ -330,6 +394,56 @@ pub async fn open<'a>( ) } Kind::Web => (Box::new(web::Web { http }), Via::Public), + Kind::S3 => { + let w = s3::where_of(&opts).map_err(ConnectorError::Config)?; + let session = env.s3_session(&w).await?; + let mut objects = s3::AwsObjects::new(&session, &w); + let region = if w.region.is_empty() { + let r = s3::bucket_region(&objects).await?; + opts["region"] = json!(r); + objects = s3::AwsObjects::new( + &session, + &s3::Where { + region: r.clone(), + ..w.clone() + }, + ); + r + } else { + w.region.clone() + }; + ( + Box::new(s3::S3 { + objects: Box::new(objects), + bucket: w.bucket, + region, + max_items: Kind::S3.max_items(), + }), + Via::AwsRole, + ) + } + Kind::Archive => { + let a = env.aws.as_ref().ok_or_else(|| { + ConnectorError::Config("This Coderhelm can't read uploads here.".into()) + })?; + let key = opts["key"].as_str().unwrap_or("").to_string(); + if key.is_empty() || !crate::knowledge::owns_key(&env.team, &key) { + return Err(ConnectorError::Config( + "Upload the archive again: its upload wasn't found.".into(), + )); + } + ( + Box::new(archive::Archive::new( + Box::new(archive::StoredArchive { + s3: a.s3.clone(), + bucket: a.bucket.clone(), + key, + }), + Kind::Archive.max_items(), + )), + Via::Upload, + ) + } }; Ok(Opened { connector, @@ -582,6 +696,18 @@ pub async fn status(env: &Env, kind: Kind, app_configured: bool, member: &str) - st.connected = true; st.via = "public".into(); } + Kind::Archive => { + st.connected = true; + st.via = "upload".into(); + } + Kind::S3 => { + st.connected = !env.aws_accounts().await.is_empty(); + if st.connected { + st.via = "aws_role".into(); + } else { + st.hint = "Connect the AWS account the bucket is in first (Settings, then Integrations, then AWS).".into(); + } + } Kind::Github => { st.connected = env.github_token.is_some(); st.via = if st.connected { diff --git a/services/common/src/knowledge/sources/mod.rs b/services/common/src/knowledge/sources/mod.rs index c8bcde6a7..b20bd99ac 100644 --- a/services/common/src/knowledge/sources/mod.rs +++ b/services/common/src/knowledge/sources/mod.rs @@ -1,6 +1,10 @@ //! Connected sources: a knowledge base kept in sync with pages that live //! somewhere else (Notion, Confluence, Sanity, Google Drive, GitHub, public -//! web pages), next to the files people upload. +//! web pages), next to the files people upload; and imports of an existing +//! knowledge base: an S3 bucket of documents (or the S3 data source behind +//! a Bedrock knowledge base) and an uploaded export archive. An import is a +//! source like the others, so re-syncing, removing what was deleted and +//! re-embedding only what changed work the same way. //! //! A source is one connector plus a selection ("these Notion pages and //! everything under them"). Syncing it works the same for every connector @@ -35,6 +39,8 @@ //! the GitHub App) and the worker opens it for each sync. pub mod alert; +pub mod archive; +pub mod bedrock_import; pub mod confluence; pub mod connect; pub mod connector; @@ -43,6 +49,7 @@ pub mod github; pub mod mcp; pub mod notion; pub mod oauth; +pub mod s3; pub mod sanity; pub mod sanity_mcp; pub mod sanity_repos; @@ -77,6 +84,10 @@ pub const MAX_SOURCES_PER_BASE: usize = 10; /// Items one source keeps; a bigger selection syncs its first ones and says /// so. pub const MAX_ITEMS_PER_SOURCE: usize = 1_000; +/// Items one import keeps (an S3 bucket, an archive). Higher than a synced +/// app's, still bounded: every local base is ranked in memory, so a bigger +/// corpus is connected in place instead (the page says so). +pub const MAX_ITEMS_PER_IMPORT: usize = 2_500; /// Entries one selection holds (each may cover a whole tree). pub const MAX_SELECTED: usize = 100; /// How often a source is synced on schedule without webhooks. @@ -103,16 +114,22 @@ pub enum Kind { GoogleDrive, Github, Web, + /// Documents in an S3 bucket, read with the team's role in its account. + S3, + /// An uploaded export archive (`.zip`), unpacked on the server. + Archive, } impl Kind { - pub const ALL: [Kind; 6] = [ + pub const ALL: [Kind; 8] = [ Kind::Notion, Kind::Confluence, Kind::Sanity, Kind::GoogleDrive, Kind::Github, Kind::Web, + Kind::S3, + Kind::Archive, ]; pub fn key(self) -> &'static str { @@ -123,6 +140,8 @@ impl Kind { Kind::GoogleDrive => "google_drive", Kind::Github => "github", Kind::Web => "web", + Kind::S3 => "s3", + Kind::Archive => "archive", } } @@ -138,6 +157,8 @@ impl Kind { Kind::GoogleDrive => "Google Drive", Kind::Github => "GitHub", Kind::Web => "Website", + Kind::S3 => "Amazon S3", + Kind::Archive => "Archive upload", } } @@ -150,6 +171,22 @@ impl Kind { Kind::GoogleDrive => "Folders, Docs, Sheets, Slides and PDFs", Kind::Github => "Docs folders and Markdown in your repositories", Kind::Web => "Public pages or a whole sitemap", + Kind::S3 => "Documents in a bucket, or a Bedrock knowledge base's data source", + Kind::Archive => "A Notion or Confluence export, or a zipped docs folder", + } + } + + /// An import of an existing knowledge base (higher limits). + pub fn is_import(self) -> bool { + matches!(self, Kind::S3 | Kind::Archive) + } + + /// Items one source of this kind keeps. + pub fn max_items(self) -> usize { + if self.is_import() { + MAX_ITEMS_PER_IMPORT + } else { + MAX_ITEMS_PER_SOURCE } } @@ -800,5 +837,10 @@ mod tests { assert_eq!(serde_json::to_value(k).unwrap(), serde_json::json!(k.key())); } assert_eq!(Kind::parse("dropbox"), None); + assert_eq!(Kind::parse("s3"), Some(Kind::S3)); + assert_eq!(Kind::parse("archive"), Some(Kind::Archive)); + assert!(!Kind::S3.has_webhooks() && !Kind::Archive.has_webhooks()); + assert!(Kind::S3.max_items() > Kind::Notion.max_items()); + assert_eq!(Kind::Archive.max_items(), MAX_ITEMS_PER_IMPORT); } } diff --git a/services/common/src/knowledge/sources/store.rs b/services/common/src/knowledge/sources/store.rs index 8637d9f1b..ebef352af 100644 --- a/services/common/src/knowledge/sources/store.rs +++ b/services/common/src/knowledge/sources/store.rs @@ -379,6 +379,39 @@ impl SyncStore for AwsSyncStore { } } +/// Every source of a team, across its bases (for the log reader update that +/// names the buckets the team imports from). +pub async fn team_sources( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team: &str, +) -> Result, String> { + let mut out = Vec::new(); + let mut start: Option> = None; + loop { + let resp = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team.to_string())) + .expression_attribute_values(":p", AttributeValue::S("KBSRC#".into())) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| format!("query sources: {e}"))?; + out.extend( + resp.items() + .iter() + .filter_map(super::super::read_data::), + ); + match resp.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + Ok(out) +} + /// An in-memory store for tests here and in the services. pub mod memory { use std::sync::Mutex; diff --git a/services/common/src/live/aws_account.rs b/services/common/src/live/aws_account.rs index a2e98338d..f519781a3 100644 --- a/services/common/src/live/aws_account.rs +++ b/services/common/src/live/aws_account.rs @@ -71,6 +71,17 @@ pub struct AwsAccount { /// (filled by the caller, never stored here): an update keeps the role /// able to search them. pub knowledge_bases: Vec, + /// The buckets the team imports knowledge from in this account (filled + /// by the caller, never stored here): an update keeps the role able to + /// read them. + pub import_buckets: Vec, +} + +impl AwsAccount { + /// What the team chose for the role here. + pub fn chosen(&self) -> crate::log_reader::Chosen<'_> { + crate::log_reader::Chosen::new(&self.knowledge_bases, &self.import_buckets) + } } fn s(item: &Item, k: &str) -> String { @@ -120,6 +131,7 @@ impl AwsAccount { }, status: s(item, "status"), knowledge_bases: Vec::new(), + import_buckets: Vec::new(), permissions: item .get("permissions_check") .and_then(|v| v.as_s().ok()) @@ -308,7 +320,7 @@ impl AwsAccount { "skipped": a.airflow_skip, "environments": self.airflow_environments(), }, - "permissions": self.permissions.as_ref().map(|p| p.view_with(false, &crate::public_urls::log_reader_template_url(), &self.knowledge_bases)), + "permissions": self.permissions.as_ref().map(|p| p.view_with(false, &crate::public_urls::log_reader_template_url(), &self.chosen())), }) } diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index cb615b6c1..9e92ccceb 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -221,16 +221,17 @@ impl PermissionCheck { /// missing), the one-click update and any problem. `template_url` is /// the install's role template ([`crate::public_urls::log_reader_template_url`]). pub fn view(&self, pressed: bool, template_url: &str) -> Value { - self.view_with(pressed, template_url, &[]) + self.view_with(pressed, template_url, &log_reader::Chosen::default()) } - /// [`Self::view`], with the ARNs of the team's knowledge bases connected - /// in this account: the update keeps the role able to search them. + /// [`Self::view`], with what the team chose in this account (its + /// connected knowledge bases and its import buckets): the update keeps + /// the role able to search and read them. pub fn view_with( &self, pressed: bool, template_url: &str, - knowledge_bases: &[String], + chosen: &log_reader::Chosen, ) -> Value { let missing: Vec = self .missing @@ -267,8 +268,8 @@ impl PermissionCheck { .flatten() .map(|t| { json!({ - "url": log_reader::update_url(&t, &self.region, knowledge_bases), - "stack_name": log_reader::update_stack_name_for(knowledge_bases), + "url": log_reader::update_url(&t, &self.region, chosen), + "stack_name": log_reader::update_stack_name_for(chosen), "template_url": t, "sign_in_account": self.account, "stacks_url": log_reader::stack_list_url(&self.region), diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index e2b824d53..c0859d75f 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -138,11 +138,48 @@ pub const ABILITIES: &[Ability] = &[ "bedrock:Retrieve", "bedrock:GetDocumentContent", "bedrock:ListKnowledgeBases", + "bedrock:GetKnowledgeBase", + "bedrock:ListDataSources", + "bedrock:GetDataSource", + ], + chosen: true, + }, + Ability { + key: "imports", + name: "Knowledge imports from S3", + why: "Reads the documents in the S3 buckets a team imports into a knowledge base (a docs folder, or the data source behind a Bedrock knowledge base), and decrypts them through S3 when a bucket uses its own KMS key. Only the buckets named in the stack's ImportBuckets parameter. Nothing is changed.", + actions: &[ + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:GetObject", + "kms:Decrypt", ], chosen: true, }, ]; +/// What a team chose for the role in one account: the knowledge bases it +/// connects and the buckets it imports. The update stack grants exactly +/// these. +#[derive(Debug, Clone, Copy, Default)] +pub struct Chosen<'a> { + pub knowledge_bases: &'a [String], + pub buckets: &'a [String], +} + +impl<'a> Chosen<'a> { + pub fn new(knowledge_bases: &'a [String], buckets: &'a [String]) -> Chosen<'a> { + Chosen { + knowledge_bases, + buckets, + } + } + + pub fn is_empty(&self) -> bool { + self.knowledge_bases.is_empty() && self.buckets.is_empty() + } +} + /// Every action of [`ABILITIES`], once each, in order. pub fn all_actions() -> Vec<&'static str> { let mut out: Vec<&'static str> = Vec::new(); @@ -307,39 +344,56 @@ pub fn quick_create_url( /// The one-click update: a Launch Stack link that adds this release's /// update stack to the role, in `region` (IAM is global; the region only -/// decides where the stack is listed). `knowledge_bases` are the ARNs of -/// the team's knowledge bases connected in this account: the stack lets the -/// role search them, and its name says which (a new set is a new stack, so -/// it never collides with the one before it). -pub fn update_url(update_template_url: &str, region: &str, knowledge_bases: &[String]) -> String { +/// decides where the stack is listed). `chosen` are the team's knowledge +/// bases connected in this account and the buckets it imports from: the +/// stack lets the role search and read exactly those, and its name says +/// which (a new set is a new stack, so it never collides with the one +/// before it). +pub fn update_url(update_template_url: &str, region: &str, chosen: &Chosen) -> String { let mut u = format!( "https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/quickcreate?stackName={}&templateURL={}¶m_RoleName={ROLE_NAME}", - update_stack_name_for(knowledge_bases), + update_stack_name_for(chosen), urlencoding::encode(update_template_url) ); - if !knowledge_bases.is_empty() { + if !chosen.knowledge_bases.is_empty() { u.push_str(&format!( "¶m_KnowledgeBases={}", - urlencoding::encode(&knowledge_bases.join(",")) + urlencoding::encode(&chosen.knowledge_bases.join(",")) + )); + } + if !chosen.buckets.is_empty() { + u.push_str(&format!( + "¶m_ImportBuckets={}", + urlencoding::encode(&chosen.buckets.join(",")) )); } u } -/// This release's update stack name for a set of knowledge bases: the -/// release's own name when there are none. -pub fn update_stack_name_for(knowledge_bases: &[String]) -> String { - if knowledge_bases.is_empty() { +fn sorted(v: &[String]) -> Vec<&str> { + let mut out: Vec<&str> = v.iter().map(String::as_str).collect(); + out.sort_unstable(); + out.dedup(); + out +} + +/// This release's update stack name for what a team chose: the release's +/// own name when it chose nothing. +pub fn update_stack_name_for(chosen: &Chosen) -> String { + if chosen.is_empty() { return update_stack_name(); } use sha2::{Digest, Sha256}; - let mut kbs: Vec<&str> = knowledge_bases.iter().map(String::as_str).collect(); - kbs.sort_unstable(); - kbs.dedup(); + let mut seed = sorted(chosen.knowledge_bases).join(","); + // Knowledge bases alone keep the name they had before imports existed. + if !chosen.buckets.is_empty() { + seed.push('|'); + seed.push_str(&sorted(chosen.buckets).join(",")); + } format!( "{}-kb{}", update_stack_name(), - hex::encode(&Sha256::digest(kbs.join(",").as_bytes())[..3]) + hex::encode(&Sha256::digest(seed.as_bytes())[..3]) ) } @@ -410,6 +464,12 @@ mod tests { !template_actions(t).iter().any(|x| x.starts_with("bedrock:") && !ability("knowledge").unwrap().actions.contains(&x.as_str())) ); + // Imports: read objects only in the buckets named, decrypt only + // through S3. + assert!(t.contains("- Sid: ReadImportBuckets")); + assert!(t.contains("!Split [\",\", !Ref ImportBuckets]")); + assert!(t.contains("kms:ViaService")); + assert!(!t.contains("\"s3:*\"")); } // Airflow's REST API only as the Viewer role. assert!(UPDATE_TEMPLATE.contains("arn:aws:airflow:*:*:role/*/Viewer")); @@ -427,7 +487,7 @@ mod tests { let u = update_url( "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml", "eu-west-1", - &[], + &Chosen::default(), ); assert!(u.starts_with("https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/quickcreate?")); assert!(u.contains(&format!("stackName=CoderHelmLogReaderUpdate-{id}"))); @@ -482,15 +542,26 @@ mod tests { /// The reviewer's bucket and key lookups use exactly the settings /// ability's actions, all reads of settings: no object reads, no - /// encrypt or decrypt. + /// encrypt or decrypt. Object reads and decrypts exist only in the + /// knowledge import statements, on the buckets a team names. #[test] fn the_settings_ability_is_what_the_lookups_use() { let a = ability("settings").unwrap(); assert_eq!(a.actions, crate::live::aws_settings::ACTIONS); + for x in ["s3:GetObject", "s3:ListBucket", "kms:Decrypt"] { + assert!(!a.actions.contains(&x), "{x}"); + assert!(ability("imports").unwrap().actions.contains(&x), "{x}"); + } for t in [ROLE_TEMPLATE, UPDATE_TEMPLATE] { - let all = template_actions(t); + // Everything but the import statements. + let start = t + .find("Sid: ReadImportBuckets") + .expect("the import statements"); + let end = t.find("kms:ViaService").expect("decrypt only through S3"); + let rest = format!("{}{}", &t[..start], &t[end..]); + let all = template_actions(&rest); for x in a.actions { - assert!(all.iter().any(|y| y == x), "{x}"); + assert!(template_actions(t).iter().any(|y| y == x), "{x}"); } for no in [ "s3:GetObject", @@ -506,13 +577,15 @@ mod tests { #[test] fn knowledge_bases_ride_on_the_update_and_are_never_counted_missing() { let kb = "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ABCDE12345".to_string(); + let kbs = std::slice::from_ref(&kb); let u = update_url( "https://b/x/coderhelm-log-reader-update.yaml", "us-east-1", - std::slice::from_ref(&kb), + &Chosen::new(kbs, &[]), ); assert!(u.contains("¶m_KnowledgeBases=arn%3Aaws%3Abedrock%3Aus-east-1%3A111122223333%3Aknowledge-base%2FABCDE12345"), "{u}"); - let name = update_stack_name_for(std::slice::from_ref(&kb)); + assert!(!u.contains("ImportBuckets")); + let name = update_stack_name_for(&Chosen::new(kbs, &[])); assert!( name.starts_with(&format!("{}-kb", update_stack_name())), "{name}" @@ -521,18 +594,37 @@ mod tests { assert!(u.contains(&format!("stackName={name}"))); // The same set in another order is the same stack; another set is another. let other = "arn:aws:bedrock:us-east-1:111122223333:knowledge-base/ZZZZZ00000".to_string(); + let both = [kb.clone(), other.clone()]; + let reversed = [other.clone(), kb.clone()]; assert_eq!( - update_stack_name_for(&[kb.clone(), other.clone()]), - update_stack_name_for(&[other.clone(), kb.clone()]) + update_stack_name_for(&Chosen::new(&both, &[])), + update_stack_name_for(&Chosen::new(&reversed, &[])) + ); + assert_ne!(update_stack_name_for(&Chosen::new(&both, &[])), name); + assert_eq!( + update_stack_name_for(&Chosen::default()), + update_stack_name() + ); + assert!( + !update_url("https://b/x/y.yaml", "us-east-1", &Chosen::default()) + .contains("KnowledgeBases") + ); + // Buckets ride along too, and make it another stack. + let buckets = ["team-docs".to_string()]; + let u = update_url( + "https://b/x/y.yaml", + "us-east-1", + &Chosen::new(kbs, &buckets), ); - assert_ne!(update_stack_name_for(&[kb.clone(), other]), name); - assert_eq!(update_stack_name_for(&[]), update_stack_name()); - assert!(!update_url("https://b/x/y.yaml", "us-east-1", &[]).contains("KnowledgeBases")); - // The live check asks about everything but the chosen knowledge bases. + assert!(u.contains("¶m_ImportBuckets=team-docs"), "{u}"); + assert_ne!(update_stack_name_for(&Chosen::new(kbs, &buckets)), name); + assert!(update_stack_name_for(&Chosen::new(&[], &buckets)).len() <= 128); + // The live check asks about everything but what a team chose. let checked = checked_actions(); assert!(!checked.contains(&"bedrock:Retrieve")); + assert!(!checked.contains(&"s3:GetObject")); assert!(checked.contains(&"logs:StartQuery")); - assert_eq!(checked.len() + 3, all_actions().len()); + assert_eq!(checked.len() + 10, all_actions().len()); } #[test] diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 5814fdc98..ec4df9482 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -709,6 +709,22 @@ async fn main() -> Result<(), Error> { get(routes::knowledge::list_bases).post(routes::knowledge::create_base), ) .route("/knowledge/bedrock", get(routes::knowledge::bedrock_bases)) + .route( + "/knowledge/bedrock/import", + get(routes::knowledge::bedrock_import), + ) + .route( + "/knowledge/search-tools", + get(routes::knowledge::search_tools), + ) + .route( + "/knowledge/:kb_id/archives", + post(routes::knowledge::start_archive), + ) + .route( + "/knowledge/:kb_id/archives/:source_id/uploaded", + post(routes::knowledge::finish_archive), + ) .route( "/knowledge/:kb_id", get(routes::knowledge::get_base) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 8d9fcb3d0..30da6cf9e 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -354,6 +354,10 @@ pub const CAPABILITIES: &[Capability] = &[ handlers: &[ "knowledge::create_base", "knowledge::bedrock_bases", + "knowledge::bedrock_import", + "knowledge::search_tools", + "knowledge::start_archive", + "knowledge::finish_archive", "knowledge::check_connection", "knowledge::update_base", "knowledge::delete_base", diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index b6fa0297d..b95926db2 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -648,7 +648,10 @@ pub async fn sources( for b in bases .map_err(|e| internal("knowledge bases", e))? .into_iter() - .filter(|b| b.readable_by(super::knowledge::reader_role(&claims.holder()))) + .filter(|b| { + b.readable_by(super::knowledge::reader_role(&claims.holder())) + && b.open_to(&super::knowledge::person(&claims)) + }) { let files = st.files(&claims.team_id, &b.id).await.unwrap_or_default(); let ready = files.iter().filter(|f| f.ready_version > 0).count(); @@ -908,10 +911,11 @@ pub async fn starters( recent_runs(&state, &claims.team_id), ); let role = super::knowledge::reader_role(&claims.holder()); + let me = super::knowledge::person(&claims); let mut readable: Vec<_> = bases .map_err(|e| internal("knowledge bases", e))? .into_iter() - .filter(|b| b.readable_by(role)) + .filter(|b| b.readable_by(role) && b.open_to(&me)) .collect(); readable.sort_by(|a, b| a.name.cmp(&b.name)); // Bases with something to read come first; at most a few are checked. @@ -1483,10 +1487,11 @@ async fn run_tool( meter: &meter, }; let st = super::knowledge::store(state); + let servers = super::knowledge::servers(state, &run.team_id); match search( &st, &titan, - &super::knowledge::retriever(state, "brain"), + &super::knowledge::retriever(state, "brain", &servers, Some(&run.user_email)), &run.team_id, &run.kb_ids, q, @@ -1940,6 +1945,7 @@ pub async fn brain_stream( )); } let reader = super::knowledge::reader_role(&holder); + let me = super::knowledge::person(&claims); claims.role = holder.floor().to_string(); let question = body.question.trim().to_string(); if question.is_empty() || question.chars().count() > MAX_QUESTION_CHARS { @@ -1989,7 +1995,7 @@ pub async fn brain_stream( .await .unwrap_or_default() .into_iter() - .filter(|b| b.readable_by(reader)) + .filter(|b| b.readable_by(reader) && b.open_to(&me)) .map(|b| b.id) .collect(); let all_repos = load_repos(&state, &claims.team_id).await; @@ -2259,10 +2265,11 @@ async fn answer( meter: &meter, }; let st = super::knowledge::store(state); + let servers = super::knowledge::servers(state, &run.team_id); match search( &st, &titan, - &super::knowledge::retriever(state, "brain"), + &super::knowledge::retriever(state, "brain", &servers, Some(&run.user_email)), &run.team_id, &run.kb_ids, &retrieval_query(question, history), diff --git a/services/gateway/src/routes/connectors.rs b/services/gateway/src/routes/connectors.rs index 102f01ef3..2825ef657 100644 --- a/services/gateway/src/routes/connectors.rs +++ b/services/gateway/src/routes/connectors.rs @@ -172,12 +172,12 @@ async fn log_reader( /// role up to this release's permissions (metrics, Airflow, ECS and the /// rest), as a stack in its own account, from the install's own template /// copy. None when the install's template has no update template next to -/// it (a template URL an operator chose). `knowledge_bases` are the ARNs -/// of the team's knowledge bases connected in that account, which the -/// update lets the role search. -pub fn update_stack_url(region: &str, knowledge_bases: &[String]) -> Option { +/// it (a template URL an operator chose). `chosen` are the team's knowledge +/// bases connected in that account and the buckets it imports from, which +/// the update lets the role search and read. +pub fn update_stack_url(region: &str, chosen: &common::log_reader::Chosen) -> Option { common::log_reader::update_template_url(&common::public_urls::log_reader_template_url()) - .map(|t| common::log_reader::update_url(&t, region, knowledge_bases)) + .map(|t| common::log_reader::update_url(&t, region, chosen)) } async fn record( @@ -860,7 +860,7 @@ pub async fn aws_check( { None } else { - update_stack_url(&t.region, &[]) + update_stack_url(&t.region, &common::log_reader::Chosen::default()) }, "stack_name": common::log_reader::update_stack_name(), "template_url": common::log_reader::update_template_url(&template), @@ -911,7 +911,7 @@ mod tests { #[test] fn the_update_link_opens_the_update_stack_for_the_existing_role() { - let u = update_stack_url("us-west-2", &[]).unwrap(); + let u = update_stack_url("us-west-2", &common::log_reader::Chosen::default()).unwrap(); assert!(u.starts_with("https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/quickcreate?")); assert!(u.contains("stackName=CoderHelmLogReaderUpdate-")); assert!(u.contains("coderhelm-log-reader-update.yaml")); diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index ee08512c1..1ca79417c 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -294,7 +294,7 @@ pub fn install_account(a: &AwsAccount) -> bool { /// person can add it (never in the install's own account). fn update_stack_link(a: &AwsAccount) -> Option { (!install_account(a) && (!aws_missing(a).is_empty() || needs_update(a))) - .then(|| super::connectors::update_stack_url(&a.region, &a.knowledge_bases)) + .then(|| super::connectors::update_stack_url(&a.region, &a.chosen())) .flatten() } @@ -577,9 +577,7 @@ pub async fn list( detail["missing"] = json!(aws_missing(a)); detail["update_url"] = json!(update_stack_link(a)); detail["install_account"] = json!(install_account(a)); - detail["stack_name"] = json!(common::log_reader::update_stack_name_for( - &a.knowledge_bases - )); + detail["stack_name"] = json!(common::log_reader::update_stack_name_for(&a.chosen())); items.push(card( &format!("aws-{}", a.account), &format!("AWS account {}", a.account), @@ -791,6 +789,8 @@ async fn load_account( account: &str, ) -> Result)> { let kbs = common::knowledge::remote::arns_in(&team_bases(state, team_id).await, account); + let buckets = + common::knowledge::sources::s3::buckets_in(&team_sources(state, team_id).await, account); aws_account::list( &state.dynamo, &state.config.aws_insights_table_name, @@ -803,19 +803,33 @@ async fn load_account( .ok_or_else(|| fail(StatusCode::NOT_FOUND, "That AWS account isn't connected.")) .map(|mut a| { a.knowledge_bases = kbs; + a.import_buckets = buckets; a }) } -/// Each account's connected knowledge bases, so its update link keeps the -/// role able to search them. +/// Each account's connected knowledge bases and import buckets, so its +/// update link keeps the role able to search and read them. async fn with_knowledge_bases(state: &AppState, team_id: &str, accounts: &mut [AwsAccount]) { let bases = team_bases(state, team_id).await; + let sources = team_sources(state, team_id).await; for a in accounts { a.knowledge_bases = common::knowledge::remote::arns_in(&bases, &a.account); + a.import_buckets = common::knowledge::sources::s3::buckets_in(&sources, &a.account); } } +/// Every knowledge source of the team (the buckets it imports from). +async fn team_sources(state: &AppState, team_id: &str) -> Vec { + common::knowledge::sources::store::team_sources( + &state.dynamo, + &state.config.settings_table_name, + team_id, + ) + .await + .unwrap_or_default() +} + async fn team_bases(state: &AppState, team_id: &str) -> Vec { use common::knowledge::search::Store; super::knowledge::store(state) @@ -829,9 +843,7 @@ fn account_reply(a: &AwsAccount) -> Value { detail["missing"] = json!(aws_missing(a)); detail["update_url"] = json!(update_stack_link(a)); detail["install_account"] = json!(install_account(a)); - detail["stack_name"] = json!(common::log_reader::update_stack_name_for( - &a.knowledge_bases - )); + detail["stack_name"] = json!(common::log_reader::update_stack_name_for(&a.chosen())); let st = aws_state(a); json!({ "account": detail, "status": st.status, "reason": st.reason, "last_check": a.abilities.checked_at }) } diff --git a/services/gateway/src/routes/knowledge.rs b/services/gateway/src/routes/knowledge.rs index c59a91dbe..1f2936a07 100644 --- a/services/gateway/src/routes/knowledge.rs +++ b/services/gateway/src/routes/knowledge.rs @@ -48,17 +48,42 @@ fn forbidden(_: StatusCode) -> (StatusCode, Json) { fail(StatusCode::FORBIDDEN, "Only admins manage knowledge bases.") } -/// Searches the team's connected Bedrock knowledge bases, as `actor` in the -/// team's AWS records. -pub(crate) fn retriever<'a>(state: &'a AppState, actor: &'a str) -> kb::remote::Bedrock<'a> { - kb::remote::Bedrock { - sts: &state.sts, - dynamo: &state.dynamo, - accounts_table: &state.config.aws_insights_table_name, - actor, +/// The team's Connected apps servers, which connected search tools are +/// searched through. +pub(crate) fn servers(state: &AppState, team: &str) -> kb::remote_mcp::RuntimeServers { + kb::remote_mcp::RuntimeServers { + rt: super::mcp_servers::runtime(state, team), } } +/// Searches the team's connected bases: Bedrock knowledge bases as `actor` +/// in the team's AWS records, search tools through `servers` as `person` +/// (the asker's email) where each person signs in. +pub(crate) fn retriever<'a>( + state: &'a AppState, + actor: &'a str, + servers: &'a kb::remote_mcp::RuntimeServers, + person: Option<&str>, +) -> kb::remote::Connected<'a> { + kb::remote::Connected { + bedrock: kb::remote::Bedrock { + sts: &state.sts, + dynamo: &state.dynamo, + accounts_table: &state.config.aws_insights_table_name, + actor, + }, + mcp: kb::remote_mcp::McpSearch { + servers, + person: person.map(str::to_string), + }, + } +} + +/// The person asking, for named readers ([`kb::Base::open_to`]). +pub(crate) fn person(claims: &Claims) -> kb::Person { + kb::Person::new(&claims.email, claims.session_role()) +} + pub(crate) fn store(state: &AppState) -> kb::search::AwsStore { kb::search::AwsStore { dynamo: state.dynamo.clone(), @@ -102,6 +127,10 @@ pub struct BaseInput { pub agents: Vec, #[serde(default)] pub authoritative: bool, + /// Only these people and roles read it (`user:`, `role:`); + /// left out, the readers stay as they are. + #[serde(default)] + pub readers: Option>, /// On create only: the base's first connected source, so a base is made /// with what it holds in one step. #[serde(default)] @@ -115,12 +144,18 @@ pub struct BaseInput { /// A knowledge base to connect in place. #[derive(Debug, Clone, Default, Deserialize)] pub struct ConnectInput { - /// `bedrock_kb`. + /// `bedrock_kb` (the default) or `mcp`. #[serde(default)] pub provider: String, - /// The Bedrock knowledge base's ARN. + /// The Bedrock knowledge base's ARN, or the Connected apps server's id. #[serde(default)] pub target: String, + /// A search tool's tool that searches (picked when empty). + #[serde(default)] + pub search_tool: String, + /// Its tool that reads a result in full (picked when empty). + #[serde(default)] + pub fetch_tool: String, } /// `input` applied to `base`, or why it can't be. @@ -161,6 +196,9 @@ pub fn apply_input(base: &mut Base, input: &BaseInput) -> Result<(), String> { base.name = name.to_string(); base.description = input.description.trim().to_string(); base.read_role = role; + if let Some(r) = &input.readers { + base.readers = kb::clean_readers(r)?; + } base.attach_team = input.attach_team; base.agents = agents; base.authoritative = input.authoritative; @@ -285,6 +323,8 @@ fn base_json( "created_at": b.created_at, "updated_at": b.updated_at, "backend": backend_json(b), + "readers": b.readers, + "agent_access_note": b.agent_access_note(), "files": files.len(), "ready": count(FileStatus::Ready), "processing": count(FileStatus::Processing) + count(FileStatus::Uploading), @@ -297,6 +337,17 @@ fn base_json( fn backend_json(b: &Base) -> Value { match b.remote() { None => json!({ "kind": "local" }), + Some(r) if r.provider == kb::Provider::Mcp => json!({ + "kind": "remote", + "provider": r.provider, + "label": r.provider.label(), + "target": r.target, + "server_name": r.name, + "access": if r.per_person { "per_person" } else { "team" }, + "per_person": r.per_person, + "search_tool": r.search_tool, + "fetch_tool": r.fetch_tool, + }), Some(r) => json!({ "kind": "remote", "provider": r.provider, @@ -307,6 +358,7 @@ fn backend_json(b: &Base) -> Value { "access": match &r.access { kb::Access::Install => "install", kb::Access::Account { .. } => "account", + kb::Access::Connection { .. } => "team", }, "hybrid": r.hybrid, }), @@ -317,6 +369,10 @@ fn backend_json(b: &Base) -> Value { /// place has none. fn refuse_connected(base: &Base) -> Result<(), (StatusCode, Json)> { match base.remote() { + Some(r) if r.provider == kb::Provider::Mcp => Err(fail( + StatusCode::BAD_REQUEST, + "This knowledge base is connected in place: it is searched live through its search tool, so nothing can be added to it here. Add documents to the search tool itself.", + )), Some(r) => Err(fail( StatusCode::BAD_REQUEST, &format!( @@ -384,11 +440,15 @@ async fn check_connect( existing: &[Base], input: &ConnectInput, ) -> Result)> { - if !input.provider.is_empty() && input.provider != "bedrock_kb" { - return Err(fail( - StatusCode::BAD_REQUEST, - "Only a Bedrock knowledge base can be connected in place.", - )); + match input.provider.as_str() { + "" | "bedrock_kb" => {} + "mcp" => return check_mcp(state, claims, existing, input).await, + _ => { + return Err(fail( + StatusCode::BAD_REQUEST, + "Connect a Bedrock knowledge base or a search tool (MCP) in place.", + )) + } } let arn = kb::remote::parse_kb_arn(&input.target).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; @@ -410,6 +470,48 @@ async fn check_connect( Ok(remote) } +/// Checks a search tool to connect: its server is on the team's Connected +/// apps, a search tool is there, and one test search reads (as the admin +/// connecting it, with their own sign-in where the server signs each person +/// in). Nothing is saved. +async fn check_mcp( + state: &AppState, + claims: &Claims, + existing: &[Base], + input: &ConnectInput, +) -> Result)> { + let id = input.target.trim(); + if !kb::valid_id(id) { + return Err(fail( + StatusCode::BAD_REQUEST, + "Pick the search tool's server from Connected apps.", + )); + } + if let Some(same) = existing.iter().find(|b| { + b.remote() + .is_some_and(|r| r.provider == kb::Provider::Mcp && r.target == id) + }) { + return Err(fail( + StatusCode::BAD_REQUEST, + &format!("That search tool is already connected as {}.", same.name), + )); + } + let servers = servers(state, &claims.team_id); + let checked = kb::remote_mcp::check( + &servers, + id, + &claims.email, + &input.search_tool, + &input.fetch_tool, + ) + .await + .map_err(|r| { + info!(team_id = %claims.team_id, code = r.code, "A search tool's test search failed"); + connect_fail(&r, None) + })?; + Ok(kb::remote_mcp::mcp_remote(id, &checked)) +} + /// One test search of `remote` as the team: `Ok(hybrid)`, or what went /// wrong in plain words (with the one-click grant when the team's role only /// lacks the permission). @@ -431,33 +533,68 @@ async fn test_remote( ) .await .map_err(|r| connect_fail(&r, None))?; - kb::remote::test_retrieve(&session, remote).await.map_err(|r| { - // The team's role only lacks the permission: the update that lets - // it search this knowledge base (and the ones already connected in - // that account), in one click. - let grant = match (&remote.access, r.code) { - (kb::Access::Account { account }, "access") => { - let mut kbs = kb::remote::arns_in(existing, account); - kbs.push(remote.target.clone()); - kbs.sort(); - kbs.dedup(); - let region = accounts - .iter() - .find(|a| &a.account == account) - .map(|a| a.region.clone()) - .unwrap_or_else(|| remote.region.clone()); - super::connectors::update_stack_url(®ion, &kbs).map(|url| { - json!({ - "url": url, - "stack_name": common::log_reader::update_stack_name_for(&kbs), - "account": account, - }) - }) - } - _ => None, - }; - info!(team_id = %claims.team_id, code = r.code, "A connected knowledge base's test search failed"); - connect_fail(&r, grant) + let r = match kb::remote::test_retrieve(&session, remote).await { + Ok(hybrid) => return Ok(hybrid), + Err(r) => r, + }; + // The team's role only lacks the permission: the update that lets it + // search this knowledge base (and keeps what the team already chose in + // that account), in one click. + let grant = match (&remote.access, r.code) { + (kb::Access::Account { account }, "access") => { + let region = accounts + .iter() + .find(|a| &a.account == account) + .map(|a| a.region.clone()) + .unwrap_or_else(|| remote.region.clone()); + grant_for( + state, + &claims.team_id, + existing, + account, + ®ion, + Some(&remote.target), + None, + ) + .await + } + _ => None, + }; + info!(team_id = %claims.team_id, code = r.code, "A connected knowledge base's test search failed"); + Err(connect_fail(&r, grant)) +} + +/// The one-click update that lets the team's role in `account` search the +/// knowledge bases the team connected there and read the buckets it imports +/// from, plus `add_kb` and `add_bucket` (what is being added now). +pub(crate) async fn grant_for( + state: &AppState, + team: &str, + bases: &[Base], + account: &str, + region: &str, + add_kb: Option<&str>, + add_bucket: Option<&str>, +) -> Option { + let mut kbs = kb::remote::arns_in(bases, account); + kbs.extend(add_kb.map(str::to_string)); + kbs.sort(); + kbs.dedup(); + let sources = + kb::sources::store::team_sources(&state.dynamo, &state.config.settings_table_name, team) + .await + .unwrap_or_default(); + let mut buckets = kb::sources::s3::buckets_in(&sources, account); + buckets.extend(add_bucket.map(str::to_string)); + buckets.sort(); + buckets.dedup(); + let chosen = common::log_reader::Chosen::new(&kbs, &buckets); + super::connectors::update_stack_url(region, &chosen).map(|url| { + json!({ + "url": url, + "stack_name": common::log_reader::update_stack_name_for(&chosen), + "account": account, + }) }) } @@ -465,6 +602,10 @@ fn limits() -> Value { json!({ "max_file_bytes": MAX_FILE_BYTES, "max_files": MAX_FILES_PER_BASE, + "max_items_per_import": kb::sources::MAX_ITEMS_PER_IMPORT, + "max_items_per_source": kb::sources::MAX_ITEMS_PER_SOURCE, + "max_archive_bytes": kb::sources::archive::MAX_ARCHIVE_BYTES, + "max_readers": kb::MAX_READERS, "extensions": EXTENSIONS, "agents": AGENTS.iter().map(|(k, l)| json!({"key": k, "label": l})).collect::>(), "read_roles": READ_ROLES, @@ -483,7 +624,12 @@ pub async fn list_bases( .map_err(|e| internal("knowledge bases", e))?; let mut out = Vec::new(); let reader = reader_role(&claims.holder()); - for b in bases.iter().filter(|b| b.readable_by(reader)) { + let manages = claims.holder().holds("knowledge_manage"); + let me = person(&claims); + for b in bases + .iter() + .filter(|b| b.readable_by(reader) && (manages || b.open_to(&me))) + { let files = st.files(&claims.team_id, &b.id).await.unwrap_or_default(); let sources = super::knowledge_sources::sources_of(&state, &claims.team_id, &b.id).await; out.push(base_json(b, &files, &sources)); @@ -505,7 +651,10 @@ pub async fn get_base( let base = get_base_record(&state, &claims.team_id, &kb_id) .await .map_err(|e| internal("knowledge base", e))? - .filter(|b| b.readable_by(reader_role(&claims.holder()))) + .filter(|b| { + b.readable_by(reader_role(&claims.holder())) + && (claims.holder().holds("knowledge_manage") || b.open_to(&person(&claims))) + }) .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such knowledge base."))?; let mut files = store(&state) .files(&claims.team_id, &base.id) @@ -593,6 +742,19 @@ pub async fn check_connection( "This knowledge base is kept here: there is no connection to check.", ) })?; + if remote.provider == kb::Provider::Mcp { + let servers = servers(&state, &claims.team_id); + kb::remote_mcp::check( + &servers, + &remote.target, + &claims.email, + &remote.search_tool, + &remote.fetch_tool, + ) + .await + .map_err(|r| connect_fail(&r, None))?; + return Ok(Json(json!({ "ok": true, "checked_at": now() }))); + } let accounts = aws_accounts(&state, &claims.team_id).await; let hybrid = test_remote(&state, &claims, &existing, &accounts, remote).await?; Ok(Json( @@ -600,6 +762,297 @@ pub async fn check_connection( )) } +/// GET /api/knowledge/search-tools — the servers on the team's Connected +/// apps a knowledge base can be connected to, each with the tools that look +/// like its search and fetch (from its last tool listing), and which are +/// connected already. +pub async fn search_tools( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + claims.require_role(3).map_err(forbidden)?; + let rt = super::mcp_servers::runtime(&state, &claims.team_id); + let list = rt + .store + .list_servers(&claims.team_id) + .await + .map_err(|e| internal("mcp servers", e))?; + let mut servers = Vec::new(); + for s in &list { + let owner = kb::remote_mcp::owner_for( + s.sharing == common::mcp_remote::store::Sharing::Personal + && s.auth == common::mcp_remote::store::AuthKind::OAuth, + Some(&claims.email), + ); + let connected = match (s.auth, owner) { + (common::mcp_remote::store::AuthKind::OAuth, Some(o)) => matches!( + rt.store.get_token(&claims.team_id, &s.id, &o).await, + Ok(Some(t)) if t.status == common::mcp_remote::store::Status::Connected + ), + _ => s.status == common::mcp_remote::store::Status::Connected, + }; + let mut v = serde_json::to_value(kb::remote_mcp::listed(s)).unwrap_or_default(); + v["connected"] = json!(connected); + servers.push(v); + } + let connected: Vec = store(&state) + .bases(&claims.team_id) + .await + .unwrap_or_default() + .iter() + .filter_map(|b| b.remote()) + .filter(|r| r.provider == kb::Provider::Mcp) + .map(|r| r.target.clone()) + .collect(); + Ok(Json(json!({ "servers": servers, "connected": connected }))) +} + +#[derive(Debug, Deserialize)] +pub struct ImportQuery { + #[serde(default)] + pub arn: String, +} + +/// GET /api/knowledge/bedrock/import?arn= — where a Bedrock knowledge +/// base's documents are and how each of its data sources is imported (an +/// S3 data source becomes an S3 source here). Read with the same role that +/// would search it; nothing in Bedrock changes. +pub async fn bedrock_import( + State(state): State>, + Extension(claims): Extension, + axum::extract::Query(q): axum::extract::Query, +) -> Reply { + claims.require_role(3).map_err(forbidden)?; + let arn = kb::remote::parse_kb_arn(&q.arn).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let accounts = aws_accounts(&state, &claims.team_id).await; + let own = common::live::aws::install_read_role(); + let access = kb::remote::access_for(&arn, own.as_deref(), &accounts) + .map_err(|r| connect_fail(&r, None))?; + let remote = kb::remote::bedrock_remote(&arn, access, true); + let actor = format!("knowledge-{}", claims.email); + let session = kb::remote::session( + &state.sts, + &state.dynamo, + &state.config.aws_insights_table_name, + &claims.team_id, + &remote, + &actor, + ) + .await + .map_err(|r| connect_fail(&r, None))?; + let catalog = kb::sources::bedrock_import::Bedrock::new(&session, &arn.region); + match kb::sources::bedrock_import::plan(&catalog, &arn).await { + Ok(p) => Ok(Json(serde_json::to_value(p).unwrap_or_default())), + Err(r) => { + let grant = match (&remote.access, r.code) { + (kb::Access::Account { account }, "access") => { + let bases = store(&state) + .bases(&claims.team_id) + .await + .unwrap_or_default(); + let region = accounts + .iter() + .find(|a| &a.account == account) + .map(|a| a.region.clone()) + .unwrap_or_else(|| arn.region.clone()); + grant_for( + &state, + &claims.team_id, + &bases, + account, + ®ion, + Some(&arn.arn()), + None, + ) + .await + } + _ => None, + }; + Err(connect_fail(&r, grant)) + } + } +} + +/// What starting an archive upload takes. +#[derive(Debug, Deserialize)] +pub struct ArchiveBody { + pub name: String, + pub size: u64, + /// Upload a newer export to this archive source. + #[serde(default)] + pub replace: Option, +} + +/// POST /api/knowledge/:kb_id/archives — start uploading an export archive +/// (a new archive source, or a newer export for one): the source and a +/// signed upload URL. Nothing is read until the upload is in. +pub async fn start_archive( + State(state): State>, + Extension(claims): Extension, + Path(kb_id): Path, + Json(body): Json, +) -> Reply { + use kb::sources::store::SyncStore; + claims.require_role(3).map_err(forbidden)?; + let base = get_base_record(&state, &claims.team_id, &kb_id) + .await + .map_err(|e| internal("knowledge base", e))? + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such knowledge base."))?; + refuse_connected(&base)?; + let name = kb::sources::archive::check_archive(&body.name, body.size) + .map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let st = super::knowledge_sources::sync_store(&state); + let mut src = match body.replace.as_deref() { + Some(id) => { + let s = st + .source(&claims.team_id, &base.id, id) + .await + .map_err(|e| internal("knowledge source", e))? + .filter(|s| s.kind == Some(kb::sources::Kind::Archive)) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such archive."))?; + s + } + None => { + let existing = + super::knowledge_sources::sources_of(&state, &claims.team_id, &base.id).await; + if existing.len() >= kb::sources::MAX_SOURCES_PER_BASE { + return Err(fail( + StatusCode::BAD_REQUEST, + &format!( + "A knowledge base can have up to {} sources.", + kb::sources::MAX_SOURCES_PER_BASE + ), + )); + } + kb::sources::Source { + id: kb::new_id(), + kb_id: base.id.clone(), + kind: Some(kb::sources::Kind::Archive), + name: common::truncate_str(name.trim_end_matches(".zip"), 80).to_string(), + selection: vec![kb::sources::Selected { + id: "archive".into(), + title: name.clone(), + kind: "file".into(), + ..Default::default() + }], + options: json!({}), + created_at: now(), + created_by: claims.email.clone(), + // Paused until the upload is in: the sweep never reads a + // missing archive. + paused: true, + ..Default::default() + } + } + }; + let version = src.options["version"].as_u64().unwrap_or(0) as u32 + 1; + src.options["pending"] = json!({ "version": version, "file_name": name, "size": body.size }); + st.put_source(&claims.team_id, &src) + .await + .map_err(|e| internal("archive source", e))?; + let key = kb::sources::archive::archive_key(&claims.team_id, &base.id, &src.id, version); + let upload = presign_put(&state, &key, "application/zip", body.size) + .await + .map_err(|e| internal("archive upload url", e))?; + info!(team_id = %claims.team_id, kb = %base.id, source = %src.id, version, "Archive upload started"); + Ok(Json(json!({ + "source": super::knowledge_sources::source_json(&src, chrono::Utc::now().timestamp()), + "upload": upload, + "note": kb::sources::archive::NOTE, + }))) +} + +/// POST /api/knowledge/:kb_id/archives/:source_id/uploaded — the archive is +/// in: point the source at it and import it (a newer export re-reads only +/// what changed and removes what it no longer has). +pub async fn finish_archive( + State(state): State>, + Extension(claims): Extension, + Path((kb_id, source_id)): Path<(String, String)>, +) -> Reply { + use kb::sources::store::SyncStore; + claims.require_role(3).map_err(forbidden)?; + let st = super::knowledge_sources::sync_store(&state); + let mut src = st + .source(&claims.team_id, &kb_id, &source_id) + .await + .map_err(|e| internal("knowledge source", e))? + .filter(|s| s.kind == Some(kb::sources::Kind::Archive)) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "No such archive."))?; + let pending = src.options["pending"].clone(); + let version = pending["version"].as_u64().unwrap_or(0) as u32; + if version == 0 { + return Err(fail(StatusCode::BAD_REQUEST, "Start the upload first.")); + } + let key = kb::sources::archive::archive_key(&claims.team_id, &kb_id, &source_id, version); + let size = match state + .s3 + .head_object() + .bucket(&state.config.bucket_name) + .key(&key) + .send() + .await + { + Ok(h) => h.content_length().unwrap_or(0).max(0) as u64, + Err(_) => { + return Err(fail( + StatusCode::BAD_REQUEST, + "The upload didn't arrive. Try uploading the archive again.", + )) + } + }; + if size == 0 || size > kb::sources::archive::MAX_ARCHIVE_BYTES { + return Err(fail( + StatusCode::BAD_REQUEST, + "The uploaded archive is empty or too large.", + )); + } + let old = kb::sources::archive::current_key(&claims.team_id, &src); + let file_name = pending["file_name"] + .as_str() + .unwrap_or("archive.zip") + .to_string(); + src.options = json!({ + "version": version, + "key": key, + "file_name": file_name, + "size": size, + "uploaded_at": now(), + "uploaded_by": claims.email, + }); + src.selection = vec![kb::sources::Selected { + id: "archive".into(), + title: file_name, + kind: "file".into(), + ..Default::default() + }]; + src.paused = false; + src.next_sync_at = chrono::Utc::now().timestamp(); + if src.status == kb::sources::Status::Error { + src.status = kb::sources::Status::Queued; + src.error = None; + } + st.put_source(&claims.team_id, &src) + .await + .map_err(|e| internal("archive source", e))?; + st.put_registry(&claims.team_id, &src) + .await + .map_err(|e| internal("register archive source", e))?; + // The export it replaces is no longer needed. + if let Some(old) = old.filter(|o| *o != key) { + st.delete_object(&claims.team_id, &old).await; + } + if let Err(e) = + super::knowledge_sources::start_sync(&state, &claims.team_id, &kb_id, &source_id).await + { + warn!(error = %e, "Archive import not started; the sweep starts it"); + } + info!(team_id = %claims.team_id, kb = %kb_id, source = %source_id, version, "Archive uploaded"); + Ok(Json(json!({ + "source": super::knowledge_sources::source_json(&src, chrono::Utc::now().timestamp()), + }))) +} + /// POST /api/knowledge — create a base. pub async fn create_base( State(state): State>, @@ -1174,6 +1627,111 @@ mod tests { assert!(refuse_connected(&local).is_ok()); } + #[test] + fn a_connected_search_tool_shows_its_server_and_who_it_searches_as() { + let remote = kb::remote_mcp::mcp_remote( + "search-1", + &kb::remote_mcp::Checked { + server_name: "Docs search".into(), + search_tool: "search".into(), + fetch_tool: "fetch".into(), + per_person: true, + }, + ); + let b = Base { + id: "kb".into(), + name: "Product docs".into(), + agents: vec!["coder".into()], + backend: kb::Backend::Remote(remote), + ..Default::default() + }; + let v = base_json(&b, &[], &[]); + assert_eq!(v["backend"]["provider"], "mcp"); + assert_eq!(v["backend"]["label"], "Search tool (MCP)"); + assert_eq!(v["backend"]["server_name"], "Docs search"); + assert_eq!(v["backend"]["access"], "per_person"); + assert_eq!(v["backend"]["search_tool"], "search"); + assert!(v["agent_access_note"] + .as_str() + .unwrap() + .contains("own sign-in")); + let (_, body) = refuse_connected(&b).unwrap_err(); + assert!(body["error"].as_str().unwrap().contains("search tool")); + let input: BaseInput = serde_json::from_value(json!({ + "name": "Docs", "connect": { "provider": "mcp", "target": "search-1", "search_tool": "search" } + })) + .unwrap(); + let c = input.connect.unwrap(); + assert_eq!( + (c.provider.as_str(), c.search_tool.as_str()), + ("mcp", "search") + ); + } + + #[test] + fn readers_are_checked_and_the_attach_note_says_who_sees_results() { + let mut b = Base { + read_role: "member".into(), + ..Default::default() + }; + let input = BaseInput { + name: "HR".into(), + readers: Some(vec![ + " Ada@Example.com ".into(), + "role:admin".into(), + "user:ada@example.com".into(), + ]), + attach_team: true, + ..Default::default() + }; + apply_input(&mut b, &input).unwrap(); + assert_eq!(b.readers, ["user:ada@example.com", "role:admin"]); + assert!(b.agent_access_note().contains("only in runs started by")); + let v = base_json(&b, &[], &[]); + assert_eq!(v["readers"][1], "role:admin"); + // Left out: unchanged. Empty: everyone the role allows. + apply_input( + &mut b, + &BaseInput { + name: "HR".into(), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(b.readers.len(), 2); + apply_input( + &mut b, + &BaseInput { + name: "HR".into(), + readers: Some(vec![]), + attach_team: true, + ..Default::default() + }, + ) + .unwrap(); + assert!(b.readers.is_empty()); + assert!(b + .agent_access_note() + .starts_with("Everyone who can start an agent run")); + let bad = BaseInput { + name: "HR".into(), + readers: Some(vec!["not a person".into()]), + ..Default::default() + }; + assert!(apply_input(&mut b, &bad) + .unwrap_err() + .contains("isn't a person or a role")); + // Not attached: no note. + assert_eq!(Base::default().agent_access_note(), ""); + // Limits say what imports take. + let l = limits(); + assert_eq!(l["max_items_per_import"], kb::sources::MAX_ITEMS_PER_IMPORT); + assert_eq!( + l["max_archive_bytes"], + kb::sources::archive::MAX_ARCHIVE_BYTES + ); + } + #[test] fn a_failed_connection_says_what_happened_what_to_do_and_offers_the_grant() { let r = kb::remote::refusal("AccessDeniedException", "not authorized to perform: bedrock:Retrieve because no identity-based policy allows the bedrock:Retrieve action"); diff --git a/services/gateway/src/routes/knowledge_sources.rs b/services/gateway/src/routes/knowledge_sources.rs index c2edf2f62..7a7434d2d 100644 --- a/services/gateway/src/routes/knowledge_sources.rs +++ b/services/gateway/src/routes/knowledge_sources.rs @@ -119,6 +119,13 @@ pub(crate) async fn env(state: &AppState, team: &str, kind: Option) -> con team: team.to_string(), http: Arc::new(common::mcp_remote::http::GuardedHttps), github_token: github, + aws: Some(connect::AwsEnv { + sts: state.sts.clone(), + accounts_table: state.config.aws_insights_table_name.clone(), + s3: state.s3.clone(), + bucket: state.config.bucket_name.clone(), + actor: "knowledge".into(), + }), } } @@ -490,6 +497,13 @@ pub struct BrowseQuery { /// `sign_in`: browse with your own sign-in (Sanity), not the team's key. #[serde(default)] pub via: String, + /// Amazon S3: the account, bucket and region to browse. + #[serde(default)] + pub account: String, + #[serde(default)] + pub bucket: String, + #[serde(default)] + pub region: String, } /// GET /api/knowledge/connectors/:kind/browse?parent=&q= — one level of the @@ -527,20 +541,73 @@ pub async fn browse( }))); } let env = env(&state, &claims.team_id, Some(kind)).await; - let opened = connect::open(&env, kind, &json!({})) - .await - .map_err(|e| connector_fail(kind, &e))?; - let nodes = opened - .connector - .browse(parent, query) - .await - .map_err(|e| connector_fail(kind, &e))?; + let options = if kind == Kind::S3 { + json!({ "account": q.account.trim(), "bucket": q.bucket.trim(), "region": q.region.trim() }) + } else { + json!({}) + }; + if kind == Kind::Archive { + return Err(fail( + StatusCode::BAD_REQUEST, + "An archive is uploaded, not browsed.", + )); + } + let opened = match connect::open(&env, kind, &options).await { + Ok(o) => o, + Err(e) if kind == Kind::S3 => return Err(s3_fail(&state, &claims, &options, &e).await), + Err(e) => return Err(connector_fail(kind, &e)), + }; + let nodes = match opened.connector.browse(parent, query).await { + Ok(n) => n, + Err(e) if kind == Kind::S3 => return Err(s3_fail(&state, &claims, &options, &e).await), + Err(e) => return Err(connector_fail(kind, &e)), + }; Ok(Json(json!({ "nodes": nodes.into_iter().take(500).collect::>(), "options": public_options(&opened.options), }))) } +/// An S3 bucket that couldn't be read, in plain words, with the one-click +/// update that names the bucket for the team's role when that is all it +/// lacks. +async fn s3_fail( + state: &AppState, + claims: &Claims, + options: &Value, + e: &ks::ConnectorError, +) -> (StatusCode, Json) { + let (status, Json(mut body)) = connector_fail(Kind::S3, e); + if let (ks::ConnectorError::Forbidden(_), Ok(w)) = (e, ks::s3::where_of(options)) { + use common::knowledge::search::Store; + let bases = super::knowledge::store(state) + .bases(&claims.team_id) + .await + .unwrap_or_default(); + let env = env(state, &claims.team_id, Some(Kind::S3)).await; + let region = env + .aws_accounts() + .await + .into_iter() + .find(|a| a.account == w.account) + .map(|a| a.region) + .unwrap_or_else(|| w.region.clone()); + body["fix"] = json!("Update the CoderHelmLogReader role in that account so it may read this bucket (the link below names it in the role's update stack), then try again."); + body["grant"] = super::knowledge::grant_for( + state, + &claims.team_id, + &bases, + &w.account, + ®ion, + None, + Some(&w.bucket), + ) + .await + .unwrap_or(Value::Null); + } + (status, Json(body)) +} + /// Where the team's scan for Sanity projects named in its repositories is /// kept, and for how long it is reused. const SANITY_REPO_PROJECTS_SK: &str = "KNOWLEDGE#SANITY_REPO_PROJECTS"; @@ -666,6 +733,7 @@ pub fn clean_options(kind: Kind, raw: &Value) -> Result { let allowed: &[&str] = match kind { Kind::Sanity => &["project_id", "studio_url", "types"], Kind::Confluence => &["cloud_id", "site"], + Kind::S3 => &["account", "bucket", "region"], _ => &[], }; let mut out = serde_json::Map::new(); @@ -715,6 +783,12 @@ pub(crate) async fn add_source( ) -> Result)> { super::knowledge::refuse_if_connected(state, &claims.team_id, kb_id).await?; let kind = kind_of(&input.kind)?; + if kind == Kind::Archive { + return Err(fail( + StatusCode::BAD_REQUEST, + "Upload an archive from the knowledge base's page instead.", + )); + } let selection = clean_selection(input.selection.as_deref().unwrap_or_default()) .map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; let existing = sources_of(state, &claims.team_id, kb_id).await; @@ -726,15 +800,29 @@ pub(crate) async fn add_source( } let mut options = clean_options(kind, input.options.as_ref().unwrap_or(&Value::Null)) .map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + if kind == Kind::S3 { + let w = ks::s3::where_of(&options).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + options["bucket"] = json!(w.bucket); + } if input.via.as_deref() == Some("sign_in") { return add_signin_source(state, claims, kb_id, kind, selection, options, input).await; } // Opening it checks the connection works before anything is saved, and // settles which site or project it reads. let env = env(state, &claims.team_id, Some(kind)).await; - let opened = connect::open(&env, kind, &options) - .await - .map_err(|e| connector_fail(kind, &e))?; + let opened = match connect::open(&env, kind, &options).await { + Ok(o) => o, + Err(e) if kind == Kind::S3 => return Err(s3_fail(state, claims, &options, &e).await), + Err(e) => return Err(connector_fail(kind, &e)), + }; + // An import from S3 reads the bucket once first: nothing is saved + // unless the team's role can list what was picked. + if kind == Kind::S3 { + let first = selection.first().map(|s| s.id.as_str()); + if let Err(e) = opened.connector.browse(first, "").await { + return Err(s3_fail(state, claims, &opened.options, &e).await); + } + } if let (Some(o), Some(resolved)) = (options.as_object_mut(), opened.options.as_object()) { for (k, v) in resolved { o.entry(k.clone()).or_insert(v.clone()); @@ -1138,6 +1226,20 @@ pub(crate) async fn remove_source( for f in &items { st.delete_item(team, f).await?; } + if src.kind == Some(Kind::Archive) { + // Every upload of the archive goes too. + let v = src.options["version"] + .as_u64() + .unwrap_or(0) + .max(src.options["pending"]["version"].as_u64().unwrap_or(0)) as u32; + for n in 1..=v { + st.delete_object( + team, + &ks::archive::archive_key(team, &src.kb_id, &src.id, n), + ) + .await; + } + } if !src.hook.is_empty() { let _ = state .dynamo diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 7eb789fe8..5904745da 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -699,7 +699,13 @@ pub async fn run( &plan.tasks, ); // Knowledge bases the team attached to the coder. - let knowledge = super::knowledge::KnowledgeTools::load(state, &msg.team_id, "coder").await; + let knowledge = super::knowledge::KnowledgeTools::load( + state, + &msg.team_id, + "coder", + super::requester_email(msg), + ) + .await; if let Some(k) = &knowledge { tools.extend(k.tools()); full_system.push_str(&k.prompt_section()); diff --git a/services/worker/src/passes/knowledge.rs b/services/worker/src/passes/knowledge.rs index 1bad9396c..86a003140 100644 --- a/services/worker/src/passes/knowledge.rs +++ b/services/worker/src/passes/knowledge.rs @@ -276,19 +276,64 @@ async fn remove_old_versions(state: &WorkerState, req: &IngestRequest, keep: u32 // ── The agents' tool ──────────────────────────────────────────────────────── -/// The knowledge bases attached to one agent of a team. +/// The knowledge bases attached to one agent of a team, for one run. pub struct KnowledgeTools { team_id: String, bases: Vec, + /// The team member who started the run, when known: bases read with + /// each person's own sign-in search as them. + person: Option, +} + +/// The team member with `email`, with their role (an invited person who +/// hasn't joined isn't one). +async fn member(state: &WorkerState, team: &str, email: &str) -> Option { + let mut start = None; + for _ in 0..20 { + let resp = state + .dynamo + .query() + .table_name(&state.config.users_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team.to_string())) + .expression_attribute_values(":p", AttributeValue::S("USER#".into())) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| warn!(error = %e, "Team members unreadable for knowledge access")) + .ok()?; + for i in resp.items() { + let s = |k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or("") + }; + if s("email").eq_ignore_ascii_case(email) && s("status") != "invited" { + return Some(kb::Person::new(email, s("role"))); + } + } + match resp.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => return None, + } + } + None } /// The tool's name. pub const TOOL: &str = "search_knowledge"; impl KnowledgeTools { - /// The bases attached to `agent` (a key of `knowledge::AGENTS`), or None - /// when there are none. - pub async fn load(state: &WorkerState, team_id: &str, agent: &str) -> Option { + /// The bases attached to `agent` (a key of `knowledge::AGENTS`) that a + /// run started by `requester` (their email, when the run names one) may + /// search, or None when there are none. + pub async fn load( + state: &WorkerState, + team_id: &str, + agent: &str, + requester: Option<&str>, + ) -> Option { let bases = match common::knowledge::search::Store::bases(&store(state), team_id).await { Ok(b) => b, Err(e) => { @@ -296,14 +341,32 @@ impl KnowledgeTools { return None; } }; - Self::from_bases(team_id, bases, agent) + let person = match requester.filter(|e| e.contains('@')) { + Some(e) if bases.iter().any(|b| b.attached_to(agent)) => { + member(state, team_id, e).await + } + _ => None, + }; + Self::from_bases(team_id, bases, agent, person) } - pub fn from_bases(team_id: &str, bases: Vec, agent: &str) -> Option { - let bases: Vec = bases.into_iter().filter(|b| b.attached_to(agent)).collect(); + /// The attached bases this run may search: a base for named readers only + /// in runs one of them started, a base read with each person's own + /// sign-in only when a person started the run (`kb::Base::searchable_in_run`). + pub fn from_bases( + team_id: &str, + bases: Vec, + agent: &str, + person: Option, + ) -> Option { + let bases: Vec = bases + .into_iter() + .filter(|b| b.attached_to(agent) && b.searchable_in_run(person.as_ref())) + .collect(); (!bases.is_empty()).then(|| Self { team_id: team_id.to_string(), bases, + person, }) } @@ -367,11 +430,30 @@ impl KnowledgeTools { client: &state.bedrock, meter: &meter, }; - let retriever = common::knowledge::remote::Bedrock { - sts: &state.sts, - dynamo: &state.dynamo, - accounts_table: &state.config.aws_insights_table_name, - actor: "knowledge", + let servers = common::knowledge::remote_mcp::RuntimeServers { + rt: common::mcp_remote::runtime::Runtime::aws( + state.dynamo.clone(), + if state.config.mcp_configs_table_name.is_empty() { + &state.config.settings_table_name + } else { + &state.config.mcp_configs_table_name + }, + state.kms.clone(), + &state.config.secrets_key_id, + &self.team_id, + ), + }; + let retriever = common::knowledge::remote::Connected { + bedrock: common::knowledge::remote::Bedrock { + sts: &state.sts, + dynamo: &state.dynamo, + accounts_table: &state.config.aws_insights_table_name, + actor: "knowledge", + }, + mcp: common::knowledge::remote_mcp::McpSearch { + servers: &servers, + person: self.person.as_ref().map(|p| p.email.clone()), + }, }; let hits = search( &store(state), @@ -462,18 +544,69 @@ mod tests { base("b", &[], true), base("c", &["coder"], false), ]; - let r = KnowledgeTools::from_bases("t", bases.clone(), "reviewer").unwrap(); + let r = KnowledgeTools::from_bases("t", bases.clone(), "reviewer", None).unwrap(); let ids: Vec<&str> = r.bases.iter().map(|b| b.id.as_str()).collect(); assert_eq!(ids, ["a", "b"]); - assert!( - KnowledgeTools::from_bases("t", vec![base("c", &["coder"], false)], "planner") - .is_none() - ); + assert!(KnowledgeTools::from_bases( + "t", + vec![base("c", &["coder"], false)], + "planner", + None + ) + .is_none()); let p = r.prompt_section(); assert!(p.contains("Base a") && p.contains("search_knowledge")); assert_eq!(r.tools()[0].name, TOOL); } + #[test] + fn a_run_only_searches_the_bases_its_person_may_read() { + let mut named = base("hr", &[], true); + named.readers = vec!["user:ada@example.com".into(), "role:admin".into()]; + let mut per_person = base("glean", &[], true); + per_person.backend = kb::Backend::Remote(kb::remote_mcp::mcp_remote( + "search-1", + &kb::remote_mcp::Checked { + server_name: "Glean".into(), + search_tool: "search".into(), + fetch_tool: String::new(), + per_person: true, + }, + )); + let open = base("docs", &[], true); + let all = vec![named, per_person, open]; + let ids = |p: Option| { + KnowledgeTools::from_bases("t", all.clone(), "coder", p) + .map(|k| k.bases.iter().map(|b| b.id.clone()).collect::>()) + .unwrap_or_default() + }; + // Nobody started it (a scheduled run): only the base open to every run. + assert_eq!(ids(None), ["docs"]); + // A named reader gets all three; another member doesn't get the named base. + assert_eq!( + ids(Some(kb::Person::new("ada@example.com", "member"))), + ["hr", "glean", "docs"] + ); + assert_eq!( + ids(Some(kb::Person::new("bo@example.com", "member"))), + ["glean", "docs"] + ); + // A named role counts. + assert_eq!( + ids(Some(kb::Person::new("cy@example.com", "admin"))), + ["hr", "glean", "docs"] + ); + // The person searches the per-person base as themselves. + let k = KnowledgeTools::from_bases( + "t", + all.clone(), + "coder", + Some(kb::Person::new("Bo@Example.com", "member")), + ) + .unwrap(); + assert_eq!(k.person.unwrap().email, "bo@example.com"); + } + #[test] fn hits_render_with_their_citation() { assert!(render_hits(&[]).contains("Nothing")); diff --git a/services/worker/src/passes/knowledge_sync.rs b/services/worker/src/passes/knowledge_sync.rs index f59dd1430..cabe044d7 100644 --- a/services/worker/src/passes/knowledge_sync.rs +++ b/services/worker/src/passes/knowledge_sync.rs @@ -74,6 +74,13 @@ pub async fn sync(state: &WorkerState, msg: &SyncMessage) -> Value { team: msg.team_id.clone(), http: Arc::new(common::mcp_remote::http::GuardedHttps), github_token, + aws: Some(connect::AwsEnv { + sts: state.sts.clone(), + accounts_table: state.config.aws_insights_table_name.clone(), + s3: state.s3.clone(), + bucket: state.config.bucket_name.clone(), + actor: "knowledge-sync".into(), + }), }; let now = || chrono::Utc::now().timestamp(); if let Some(si) = &src.signin { diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 683ae5021..098d6e26c 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -684,7 +684,13 @@ Then the ```fix_location.json block described above."#, } // Knowledge bases the team attached to the planner. - let knowledge = super::knowledge::KnowledgeTools::load(state, &msg.team_id, "planner").await; + let knowledge = super::knowledge::KnowledgeTools::load( + state, + &msg.team_id, + "planner", + super::requester_email(msg), + ) + .await; if let Some(k) = &knowledge { tools.extend(k.tools()); full_system.push_str(&k.prompt_section()); diff --git a/services/worker/src/passes/plan_chat.rs b/services/worker/src/passes/plan_chat.rs index fd6132a99..c5a3b8011 100644 --- a/services/worker/src/passes/plan_chat.rs +++ b/services/worker/src/passes/plan_chat.rs @@ -108,7 +108,7 @@ async fn load(state: &WorkerState, req: &Request) -> Loaded { let knowledge = if req.feature == "brain" { None } else { - super::knowledge::KnowledgeTools::load(state, &req.team_id, "plan_chat").await + super::knowledge::KnowledgeTools::load(state, &req.team_id, "plan_chat", None).await }; Loaded { skills, diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index a8e5f5042..11c3f8a78 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -1945,7 +1945,7 @@ async fn run_once( ) }; let knowledge = - super::knowledge::KnowledgeTools::load(state, &msg.team_id, "reviewer").await; + super::knowledge::KnowledgeTools::load(state, &msg.team_id, "reviewer", None).await; let system = match &knowledge { Some(k) => format!("{system}{}", k.prompt_section()), None => system, @@ -2801,7 +2801,8 @@ async fn run_once( let extra_context = format!("{extra_context}{agent_notes}"); // Knowledge bases the team attached to the reviewer. - let knowledge = super::knowledge::KnowledgeTools::load(state, &msg.team_id, "reviewer").await; + let knowledge = + super::knowledge::KnowledgeTools::load(state, &msg.team_id, "reviewer", None).await; // 1) High-recall generation with repo-walking tools. live_job .step(