diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index 228a658cb..fb9012446 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -87,7 +87,7 @@ Two ways. A team picks one in **Settings, Integrations, Jira**. ## Monitoring and data sources -New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics and Airflow connect from **Settings, Integrations** or **Data sources** with keys or the AWS role. None needs an app of its own or a URL of CoderHelm's. +New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics and Airflow connect from **Settings, Integrations** or **Data sources** with keys or the AWS role. None needs an app of its own or a URL of CoderHelm's. A team signed in to Confluence for Knowledge needs no token for runs: its Confluence card on Settings, Integrations reads Connected, and Use in runs too lets agents read pages with the same sign-in (reading only). - **New Relic**\ A user API key, and the US or EU region. @@ -103,7 +103,7 @@ New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics - **Figma**\ Figma's MCP server signs in only apps Figma approved, so CoderHelm runs Figma's tools against Figma's API with a sign-in (or a personal access token). Three ways, in Settings, Integrations, Figma: - **Sign in with Figma** (CoderHelm's app): on a hybrid install that uses Coderhelm's apps (the default, in Settings, System, Hybrid, Other apps), sign in. Nothing to create. CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within ten minutes; agents call Figma from your install. - - **Use my own Figma app**: create the app at https://www.figma.com/developers/apps under your Figma team or organization, add the redirect URI above, give it the `current_user:read` and `file_content:read` scopes, and publish it as a private app (no review from Figma; people in that team or organization can sign in). Paste its client id and secret there, then select Connect. + - **Use your own Figma app** (under Other ways to connect): create the app at https://www.figma.com/developers/apps under your Figma team or organization, add the redirect URI above, give it the `current_user:read` and `file_content:read` scopes, and publish it as a private app (no review from Figma; people in that team or organization can sign in). Paste its client id and secret there, then select Save and sign in with Figma. - **For every team on the install**: put a Figma app's `figma_client_id` and `figma_client_secret` in the install's secret. The card's Sign in with Figma then uses it, with no hybrid. - **With hybrid**\ MCP sign-ins go to your install directly, except Figma when the install uses Coderhelm's apps and has no Figma app of its own (above). diff --git a/services/common/src/live/atlassian.rs b/services/common/src/live/atlassian.rs new file mode 100644 index 000000000..80c956ed6 --- /dev/null +++ b/services/common/src/live/atlassian.rs @@ -0,0 +1,237 @@ +//! Confluence with the Atlassian sign-in the team made for Knowledge. +//! +//! A team that signed in to Atlassian so Knowledge can sync its pages has +//! already granted everything agents need to read those pages during runs +//! and reviews (pages, spaces, search: `knowledge::sources::oauth::provider`). +//! An admin turns that on with one switch, with no second sign-in and no API +//! token: the team's `CONNECTOR#confluence` record then says +//! [`VIA_SIGN_IN`](super::connectors::VIA_SIGN_IN), and every read opens the +//! same sealed sign-in (renewed when it is about to expire) for that one +//! call. It never writes: the sign-in has no write scope. + +use crate::knowledge::sources::confluence::{accessible_sites, oauth_base}; +use crate::knowledge::sources::connector::ConnectorError; +use crate::knowledge::sources::oauth::connection_id; +use crate::knowledge::sources::Kind; +use crate::mcp_remote::runtime::{ConnError, Runtime}; +use crate::mcp_remote::store::Owner; + +use super::StepError; + +/// The team's Atlassian sign-in, opened for Confluence. +#[derive(Clone, PartialEq, Eq)] +pub struct SignedIn { + /// Where the REST API is: `https://api.atlassian.com/ex/confluence/`. + pub base: String, + /// The site people open pages on: `https://x.atlassian.net`. + pub site: String, + /// The `Authorization` value (`Bearer ...`). + pub bearer: String, +} + +// Written by hand so the token never reaches a log. +impl std::fmt::Debug for SignedIn { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SignedIn") + .field("site", &self.site) + .finish_non_exhaustive() + } +} + +const WHERE: &str = "Sign in to Confluence again in Settings, Integrations, Confluence."; + +fn gone(message: impl Into) -> StepError { + StepError::new("sign_in", message, WHERE) +} + +/// Opens the team's Atlassian sign-in for the Confluence site `want` (the +/// connection's saved site; empty takes the first site the sign-in +/// reaches). An error says what to do: sign in again, or try later. +pub async fn confluence(rt: &Runtime, want: &str) -> Result { + let rec = rt + .store + .get_server(&rt.team, &connection_id(Kind::Confluence)) + .await + .map_err(|e| StepError::new("reach", e, "Try again in a minute."))? + .ok_or_else(|| gone("The team isn't signed in to Confluence any more."))?; + let bearer = match rt.auth_header(&rec, &Owner::Team, false).await { + Ok(Some(h)) => h.1, + Ok(None) | Err(ConnError::NotConnected) => { + return Err(gone("The team isn't signed in to Confluence any more.")) + } + Err(ConnError::NeedsReconnect(why)) | Err(ConnError::Failed(why)) => { + return Err(gone(if why.is_empty() { + "The team's Atlassian sign-in has to be renewed.".to_string() + } else { + why + })) + } + Err(e) => { + return Err(StepError::new( + "reach", + format!("The Atlassian sign-in couldn't be opened: {e:?}"), + "Try again in a minute.", + )) + } + }; + let sites = accessible_sites(rt.http.as_ref(), &bearer) + .await + .map_err(|e| match e { + ConnectorError::Reconnect(m) | ConnectorError::Forbidden(m) => gone(m), + other => StepError::new( + "reach", + format!("Atlassian didn't say which sites the sign-in reaches: {other:?}"), + "Try again in a minute.", + ), + })?; + pick_site(sites, want) + .map(|(cloud, site)| SignedIn { + base: oauth_base(&cloud), + site, + bearer, + }) + .ok_or_else(|| { + StepError::new( + "read", + if want.trim().is_empty() { + "The Atlassian sign-in can't reach any Confluence site.".to_string() + } else { + format!("The Atlassian sign-in can't reach {want} any more.") + }, + WHERE, + ) + }) +} + +/// The (cloud id, site address) to use: the wanted site when the sign-in +/// still reaches it, the first one when none is wanted. A wanted site the +/// sign-in doesn't reach is never swapped for another. +pub fn pick_site(sites: Vec<(String, String, String)>, want: &str) -> Option<(String, String)> { + let want = want.trim().trim_end_matches('/'); + let ok = |id: &str| !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'); + sites + .into_iter() + .filter(|(id, _, _)| ok(id)) + .find(|(_, url, _)| want.is_empty() || url.eq_ignore_ascii_case(want)) + .map(|(id, url, _)| (id, url)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::knowledge::sources::oauth::{connection_record, provider}; + use crate::mcp_remote::http::fake::{json as fjson, Fake}; + use crate::mcp_remote::runtime::testing::{sign_in, FakeKms}; + use crate::mcp_remote::store::fake::MemStore; + use crate::mcp_remote::store::Status; + use serde_json::json; + use std::sync::Arc; + + fn rt(http: Arc) -> Runtime { + Runtime { + store: Arc::new(MemStore::default()), + cipher: Arc::new(FakeKms), + http, + team: "TEAM#a".into(), + clock: Arc::new(|| 1_000_000), + } + } + + fn sites() -> Vec<(String, String, String)> { + vec![ + ( + "cloud-1".into(), + "https://one.atlassian.net".into(), + "One".into(), + ), + ( + "cloud-2".into(), + "https://two.atlassian.net".into(), + "Two".into(), + ), + ] + } + + #[test] + fn the_saved_site_is_used_and_never_swapped() { + assert_eq!( + pick_site(sites(), ""), + Some(("cloud-1".into(), "https://one.atlassian.net".into())) + ); + assert_eq!( + pick_site(sites(), "https://TWO.atlassian.net/"), + Some(("cloud-2".into(), "https://two.atlassian.net".into())) + ); + assert_eq!(pick_site(sites(), "https://three.atlassian.net"), None); + // An id that isn't one is never put in an address. + let bad = vec![( + "a/b".to_string(), + "https://x.atlassian.net".to_string(), + String::new(), + )]; + assert_eq!(pick_site(bad, ""), None); + } + + #[tokio::test] + async fn the_knowledge_sign_in_opens_confluence_for_runs() { + let http = Arc::new(Fake::default()); + http.with(|r| { + r.url + .ends_with("/oauth/token/accessible-resources") + .then(|| { + fjson( + 200, + json!([{ "id": "cloud-1", "url": "https://one.atlassian.net", "name": "One", + "scopes": ["read:page:confluence"] }]), + ) + }) + }); + let rt = rt(http); + // Nobody signed in: it says where to sign in. + let e = confluence(&rt, "").await.unwrap_err(); + assert_eq!(e.step, "sign_in"); + assert!( + e.fix.contains("Settings, Integrations, Confluence"), + "{e:?}" + ); + + let p = provider(Kind::Confluence).unwrap(); + let rec = connection_record(Kind::Confluence, &p, "cid", "sealed"); + rt.store.put_server("TEAM#a", &rec).await.unwrap(); + sign_in( + &rt, + &rec.id, + &Owner::Team, + "at-1", + None, + None, + "ada@example.com", + ) + .await; + let s = confluence(&rt, "").await.unwrap(); + assert_eq!(s.base, "https://api.atlassian.com/ex/confluence/cloud-1"); + assert_eq!(s.site, "https://one.atlassian.net"); + assert_eq!(s.bearer, "Bearer at-1"); + assert!(!format!("{s:?}").contains("at-1")); + // A site the sign-in no longer reaches is an error, not another site. + let e = confluence(&rt, "https://two.atlassian.net") + .await + .unwrap_err(); + assert!(e.message.contains("two.atlassian.net"), "{e:?}"); + + // A grant that was revoked says to sign in again. + rt.store + .set_token_status( + "TEAM#a", + &rec.id, + &Owner::Team, + Status::NeedsReconnect, + "Atlassian ended the sign-in.", + &[], + ) + .await + .unwrap(); + let e = confluence(&rt, "").await.unwrap_err(); + assert_eq!(e.step, "sign_in"); + } +} diff --git a/services/common/src/live/confluence.rs b/services/common/src/live/confluence.rs index 1c25bab5a..ad2f546bd 100644 --- a/services/common/src/live/confluence.rs +++ b/services/common/src/live/confluence.rs @@ -1,4 +1,5 @@ -//! Confluence Cloud through its REST API, with an Atlassian API token or +//! Confluence Cloud through its REST API, with an Atlassian API token, with +//! the Atlassian sign-in the team made for Knowledge (reading only), or //! through the Coderhelm app the team installed in its Jira ([`Access`]). //! //! Reads are GETs to the team's own `*.atlassian.net` site (or the same calls @@ -200,6 +201,12 @@ pub enum Access<'a> { /// shared secret it checks. The app makes the same calls with its own /// Confluence access (see `coderhelm-jira/src/confluence.js`). JiraApp { url: &'a str, secret: &'a str }, + /// The team's Atlassian sign-in (the one Knowledge syncs with), through + /// `api.atlassian.com/ex/confluence/` (`base`) with its + /// `Bearer` header. Its scopes read pages, spaces and search and + /// nothing else, so it never writes + /// (`knowledge::sources::oauth::provider`). + SignIn { base: &'a str, bearer: &'a str }, } /// A Confluence connection for one call. @@ -239,9 +246,33 @@ enum Op<'b> { impl Confluence<'_> { fn request(&self, op: &Op) -> Result { match self.access { - Access::Token(token) => { - let site = check_site(&self.conn.site)?; + Access::Token(_) | Access::SignIn { .. } => { + let (root, auth) = match self.access { + Access::Token(token) => ( + check_site(&self.conn.site)?, + format!( + "Basic {}", + STANDARD.encode(format!("{}:{token}", self.conn.email)) + ), + ), + Access::SignIn { base, bearer } => { + if matches!(op, Op::Append { .. }) { + return Err(refused( + "The Atlassian sign-in only reads Confluence.", + "To add text to pages, connect Confluence with an API token or the Jira app.", + )); + } + (base.trim_end_matches('/').to_string(), bearer.to_string()) + } + Access::JiraApp { .. } => unreachable!("matched above"), + }; + let signed_in = matches!(self.access, Access::SignIn { .. }); let (method, path, body) = match op { + // The sign-in has no scope for "who am I": one space + // listed shows it reads. + Op::WhoAmI if signed_in => { + (Method::Get, "/wiki/api/v2/spaces?limit=1".to_string(), None) + } Op::WhoAmI => (Method::Get, "/wiki/rest/api/user/current".to_string(), None), Op::Page(id) => ( Method::Get, @@ -283,15 +314,9 @@ impl Confluence<'_> { }; Ok(Request { method, - url: format!("{site}{path}"), + url: format!("{root}{path}"), headers: vec![ - ( - "Authorization".to_string(), - format!( - "Basic {}", - STANDARD.encode(format!("{}:{token}", self.conn.email)) - ), - ), + ("Authorization".to_string(), auth), ("Accept".to_string(), "application/json".to_string()), ], body, @@ -328,6 +353,7 @@ impl Confluence<'_> { async fn call(&self, op: Op<'_>) -> Result { let app = matches!(self.access, Access::JiraApp { .. }); + let signed_in = matches!(self.access, Access::SignIn { .. }); let reply = self.http.send(self.request(&op)?).await?; match reply.status { 200..=299 => reply.json().ok_or_else(|| { @@ -342,6 +368,16 @@ impl Confluence<'_> { "The Coderhelm app in Jira didn't accept Coderhelm's secret.", "Open Coderhelm Settings in Jira and save them again.", )), + 401 if signed_in => Err(StepError::new( + "sign_in", + "Confluence didn't accept the team's Atlassian sign-in.", + "Sign in to Confluence again in Settings, Integrations, Confluence.", + )), + 403 if signed_in => Err(StepError::new( + "read", + "The Atlassian account that signed in can't see this in Confluence.", + "Give that account access to the space, or use a page it can see.", + )), 401 => Err(StepError::new( "sign_in", "Confluence didn't accept the email and token.", @@ -498,6 +534,12 @@ impl Confluence<'_> { /// writes on and listed this page. Returns the new version number. pub async fn append(&self, id: &str, text: &str) -> Result { let id = check_page_id(id)?; + if matches!(self.access, Access::SignIn { .. }) { + return Err(refused( + "The Atlassian sign-in only reads Confluence.", + "To add text to pages, connect Confluence with an API token or the Jira app. Put the text in your reply for a person to add.", + )); + } if !self.conn.may_write_page(id) { return Err(refused( format!("Coderhelm may not write to page {id}."), @@ -530,9 +572,13 @@ impl Confluence<'_> { }) } - /// Checks the email and token: who they sign in as. + /// Checks the email and token: who they sign in as. With the team's + /// Atlassian sign-in, that it reads the site. pub async fn whoami(&self) -> Result { let v = self.call(Op::WhoAmI).await?; + if matches!(self.access, Access::SignIn { .. }) { + return Ok("the team's Atlassian sign-in".to_string()); + } Ok(v["displayName"] .as_str() .or(v["publicName"].as_str()) @@ -850,6 +896,53 @@ mod tests { assert!(e.fix.contains("Coderhelm Settings in Jira"), "{}", e.fix); } + #[tokio::test] + async fn with_the_atlassian_sign_in_reads_go_to_its_site_and_nothing_is_written() { + let c = Connector { + via: crate::live::connectors::VIA_SIGN_IN.into(), + email: String::new(), + ..conn() + }; + let http = Fake::answering(vec![ + (200, r#"{"results":[{"id":"7"}]}"#), + (200, PAGE), + (401, "{}"), + ]); + let cf = Confluence { + conn: &c, + access: Access::SignIn { + base: "https://api.atlassian.com/ex/confluence/cloud-1/", + bearer: "Bearer at-1", + }, + http: &http, + }; + assert_eq!(cf.whoami().await.unwrap(), "the team's Atlassian sign-in"); + cf.page("42").await.unwrap(); + // An append is refused before anything is sent: the sign-in only reads. + let e = cf.append("42", "note").await.unwrap_err(); + assert!(e.is_refusal(), "{e:?}"); + assert!(e.fix.contains("API token or the Jira app"), "{e:?}"); + // A sign-in Confluence refuses says where to sign in again. + let e = cf.page("42").await.unwrap_err(); + assert!(e.message.contains("Atlassian sign-in"), "{e:?}"); + let sent = http.sent(); + assert_eq!(sent.len(), 3, "the append sent nothing"); + assert_eq!( + sent[0].url, + "https://api.atlassian.com/ex/confluence/cloud-1/wiki/api/v2/spaces?limit=1" + ); + assert!(sent[1] + .url + .starts_with("https://api.atlassian.com/ex/confluence/cloud-1/wiki/api/v2/pages/42")); + for r in &sent { + assert_eq!(r.method, Method::Get); + assert!(r + .headers + .iter() + .any(|(k, v)| k == "Authorization" && v == "Bearer at-1")); + } + } + #[tokio::test] async fn children_are_listed_after_the_parent_passes_the_space_check() { let http = Fake::answering(vec![ diff --git a/services/common/src/live/connectors.rs b/services/common/src/live/connectors.rs index 54df671ea..2365e1624 100644 --- a/services/common/src/live/connectors.rs +++ b/services/common/src/live/connectors.rs @@ -21,6 +21,10 @@ const PREFIX: &str = "CONNECTOR#"; /// A Confluence connection reached through the team's installed Coderhelm /// Jira app instead of an API token. pub const VIA_JIRA_APP: &str = "jira_app"; +/// A Confluence connection reached with the Atlassian sign-in the team made +/// for Knowledge (`knowledge::sources::oauth`): no key of its own, reading +/// only. +pub const VIA_SIGN_IN: &str = "sign_in"; /// Pages a Confluence write list may hold. pub const MAX_WRITE_PAGES: usize = 20; /// Lookups one agent pass may make across every connection here. @@ -348,6 +352,11 @@ impl Connector { self.via == VIA_JIRA_APP } + /// Reached with the team's Atlassian sign-in, not a key of its own. + pub fn via_sign_in(&self) -> bool { + self.via == VIA_SIGN_IN + } + /// Whether work on `repo` (`owner/name`) may use it. pub fn usable_for(&self, repo: &str) -> bool { self.enabled diff --git a/services/common/src/live/mod.rs b/services/common/src/live/mod.rs index 9bd9f0b03..a7478e14c 100644 --- a/services/common/src/live/mod.rs +++ b/services/common/src/live/mod.rs @@ -24,6 +24,7 @@ pub mod airflow; pub mod api; +pub mod atlassian; pub mod aws; pub mod aws_account; pub mod aws_settings; diff --git a/services/common/src/mcp_catalog.rs b/services/common/src/mcp_catalog.rs index 88b36af2a..caba2f03e 100644 --- a/services/common/src/mcp_catalog.rs +++ b/services/common/src/mcp_catalog.rs @@ -560,7 +560,7 @@ pub fn key_help(id: &str) -> Option { } }; Some(format!( - "Create one in {place}, then paste it under Use a key instead." + "Create one in {place}, then paste it under Other ways to connect, Use a key." )) } @@ -579,6 +579,9 @@ pub struct OwnApp { pub refresh: &'static str, /// Exactly what the package (and the connection check) calls. pub scopes: &'static [&'static str], + /// What those scopes let Coderhelm do, in plain words, for the card + /// (the scope names themselves go behind its "Details"). + pub reads: &'static str, /// The environment variable the package reads the token from. #[serde(skip)] pub env_var: &'static str, @@ -615,6 +618,7 @@ pub fn own_app(id: &str) -> Option { token: "https://api.figma.com/v1/oauth/token", refresh: "https://api.figma.com/v1/oauth/refresh", scopes: &["current_user:read", "file_content:read"], + reads: "Coderhelm reads your Figma files and the name of the account that signs in. It can't change anything in Figma.", env_var: "FIGMA_OAUTH_TOKEN", check: "https://api.figma.com/v1/me", console: "https://www.figma.com/developers/apps", diff --git a/services/common/src/mcp_remote/runtime.rs b/services/common/src/mcp_remote/runtime.rs index 9946b2fbd..c70700cc1 100644 --- a/services/common/src/mcp_remote/runtime.rs +++ b/services/common/src/mcp_remote/runtime.rs @@ -915,6 +915,11 @@ impl Runtime { } } } + // A new sign-in ends the ones it replaces: an earlier attempt by this + // person for this connection can't finish any more, so its record + // doesn't wait out its ten minutes (or longer, where the table + // doesn't expire records on its own). + self.end_pending(&s.id, Some(owner), Some(user_sub)).await; let pkce = oauth::Pkce::new(); let state = oauth::new_state_for(flow); self.store @@ -947,6 +952,39 @@ impl Runtime { oauth::with_extra_params(&url, &o.extra_authorize) } + /// Ends the team's sign-ins in progress for `server_id` (for one owner + /// and one person when given, else all of them), and every one of the + /// team's that has expired. Returns how many were removed. Never fails: + /// a record that stays is refused by [`Self::finish`] once it expires. + pub async fn end_pending( + &self, + server_id: &str, + owner: Option<&Owner>, + user_sub: Option<&str>, + ) -> usize { + let now = self.now(); + let Ok(all) = self.store.list_pending(&self.team).await else { + return 0; + }; + let mut ended = 0; + for p in all { + let replaced = p.server_id == server_id + && owner.is_none_or(|o| *o == p.owner) + && user_sub.is_none_or(|u| u == p.user_sub); + if (replaced || now > p.expires_at) + && self.store.delete_pending(&self.team, &p.key).await.is_ok() + { + ended += 1; + } + } + ended + } + + /// Removes the team's expired sign-ins in progress (see [`Self::end_pending`]). + pub async fn sweep_pending(&self) -> usize { + self.end_pending("", None, None).await + } + /// Finishes a sign-in from the callback. The `state` is consumed first /// (it works once), must belong to this person and this team, and the /// answer's `iss` must match the issuer recorded at the start. Only then @@ -1250,6 +1288,7 @@ impl Runtime { for t in self.store.list_tokens(&self.team, &s.id).await? { self.disconnect(s, &t.owner).await?; } + self.end_pending(&s.id, None, None).await; self.store.delete_server(&self.team, &s.id).await } } @@ -1760,6 +1799,66 @@ mod tests { assert_eq!(q["scope"], "read write"); } + /// A sign-in in progress never outlives its use: starting again ends + /// the earlier attempt, cancelling ends it, and expired ones are swept + /// (the table's own expiry isn't relied on). + #[tokio::test] + async fn a_new_sign_in_ends_the_one_it_replaces_and_expired_ones_are_swept() { + let r = rig("TEAM#a"); + let mut s = server(); + r.store.put_server("TEAM#a", &s).await.unwrap(); + let state_of = |url: String| -> String { + reqwest::Url::parse(&url) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "state") + .map(|(_, v)| v.into_owned()) + .unwrap() + }; + let cb = "https://app.example.com/cb/"; + let first = state_of( + r.rt.start_sign_in(&mut s, &Owner::Team, "USER#1", "a@x.com", cb, None) + .await + .unwrap(), + ); + // Another admin's attempt for the same server is theirs to finish. + r.rt.start_sign_in(&mut s, &Owner::Team, "USER#2", "b@x.com", cb, None) + .await + .unwrap(); + assert_eq!(r.store.list_pending("TEAM#a").await.unwrap().len(), 2); + // The same person starts again: their first attempt is gone. + r.rt.start_sign_in(&mut s, &Owner::Team, "USER#1", "a@x.com", cb, None) + .await + .unwrap(); + let left = r.store.list_pending("TEAM#a").await.unwrap(); + assert_eq!(left.len(), 2); + assert!(left.iter().all(|p| p.key != oauth::state_key(&first))); + assert!(r + .rt + .finish_sign_in(&first, Some("code"), None, None, "USER#1", "a@x.com") + .await + .unwrap_err() + .contains("already used or has expired")); + // Cancelling ends only that person's attempt. + assert_eq!( + r.rt.end_pending("docs", Some(&Owner::Team), Some("USER#1")) + .await, + 1 + ); + assert_eq!(r.store.list_pending("TEAM#a").await.unwrap().len(), 1); + // Nothing expired yet, so a sweep leaves the other one alone. + assert_eq!(r.rt.sweep_pending().await, 0); + r.now.fetch_add(PENDING_TTL_SECS + 1, Ordering::SeqCst); + assert_eq!(r.rt.sweep_pending().await, 1); + assert!(r.store.list_pending("TEAM#a").await.unwrap().is_empty()); + // Removing a server takes its sign-ins in progress with it. + r.rt.start_sign_in(&mut s, &Owner::Team, "USER#1", "a@x.com", cb, None) + .await + .unwrap(); + r.rt.remove(&s).await.unwrap(); + assert!(r.store.list_pending("TEAM#a").await.unwrap().is_empty()); + } + #[tokio::test] async fn sign_in_end_to_end_binds_state_iss_and_person() { let r = rig("TEAM#a"); @@ -1835,23 +1934,6 @@ mod tests { .unwrap_err() .contains("already used")); - // A fresh one, finished by its starter with the right issuer. - let url = - r.rt.start_sign_in( - &mut s, - &Owner::Team, - "USER#1", - "a@x.com", - "https://app.example.com/cb/", - None, - ) - .await - .unwrap(); - let q: HashMap = reqwest::Url::parse(&url) - .unwrap() - .query_pairs() - .into_owned() - .collect(); r.http.on(Method::Post, TOKEN, fjson(200, json!({"access_token": "at-1", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "rt-1"}))); // Wrong issuer: refused before any token request. let url2 = @@ -1883,6 +1965,25 @@ mod tests { .await .is_err()); assert!(r.http.sent_to(TOKEN).is_empty()); + // A fresh one, finished by its starter with the right issuer. + // (Started after the refused one: a person's new sign-in ends + // their earlier attempt for the same connection.) + let url = + r.rt.start_sign_in( + &mut s, + &Owner::Team, + "USER#1", + "a@x.com", + "https://app.example.com/cb/", + None, + ) + .await + .unwrap(); + let q: HashMap = reqwest::Url::parse(&url) + .unwrap() + .query_pairs() + .into_owned() + .collect(); let (back, owner) = r.rt.finish_sign_in( &q["state"], diff --git a/services/common/src/mcp_remote/store.rs b/services/common/src/mcp_remote/store.rs index a0676fd47..bc0ac0588 100644 --- a/services/common/src/mcp_remote/store.rs +++ b/services/common/src/mcp_remote/store.rs @@ -798,6 +798,11 @@ pub trait Store: Send + Sync { async fn put_pending(&self, team: &str, p: &PendingAuth) -> Result<(), String>; /// Reads and deletes a pending sign-in in one step: a `state` works once. async fn take_pending(&self, team: &str, key: &str) -> Result, String>; + /// Every sign-in in progress for the team (a handful at most: each + /// lives ten minutes), so a new one can end the ones it replaces and + /// expired ones are removed without waiting for the table to do it. + async fn list_pending(&self, team: &str) -> Result, String>; + async fn delete_pending(&self, team: &str, key: &str) -> Result<(), String>; async fn put_log(&self, team: &str, e: &LogEntry, now: i64) -> Result<(), String>; async fn list_logs(&self, team: &str, id: &str, limit: i32) -> Result, String>; } @@ -1071,6 +1076,19 @@ impl Store for DynamoStore { } } + async fn list_pending(&self, team: &str) -> Result, String> { + Ok(self + .query_prefix(team, PENDING_PREFIX, None, false) + .await? + .iter() + .filter_map(PendingAuth::from_item) + .collect()) + } + + async fn delete_pending(&self, team: &str, key: &str) -> Result<(), String> { + self.delete(team, &format!("{PENDING_PREFIX}{key}")).await + } + async fn put_log(&self, team: &str, e: &LogEntry, now: i64) -> Result<(), String> { self.dynamo .put_item() @@ -1287,6 +1305,20 @@ pub mod fake { .as_ref() .and_then(PendingAuth::from_item)) } + async fn list_pending(&self, team: &str) -> Result, String> { + Ok(self + .prefix(team, PENDING_PREFIX) + .iter() + .filter_map(PendingAuth::from_item) + .collect()) + } + async fn delete_pending(&self, team: &str, key: &str) -> Result<(), String> { + self.items + .lock() + .unwrap() + .remove(&(team.to_string(), format!("{PENDING_PREFIX}{key}"))); + Ok(()) + } async fn put_log(&self, team: &str, e: &LogEntry, now: i64) -> Result<(), String> { self.put(team, e.to_item(team, now)); Ok(()) diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index d8fc64943..1bf4ff342 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1295,6 +1295,10 @@ fn build_app(state: Arc) -> Router { "/mcp-servers/:id/connect", post(routes::mcp_servers::connect), ) + .route( + "/mcp-servers/:id/sign-in", + delete(routes::mcp_servers::cancel_sign_in), + ) .route( "/mcp-servers/:id/connection", delete(routes::mcp_servers::disconnect), diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index c30cac5fc..3a610137b 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -251,6 +251,7 @@ pub const CAPABILITIES: &[Capability] = &[ handlers: &[ "mcp_servers::connect", "mcp_servers::oauth_callback", + "mcp_servers::cancel_sign_in", "mcp_servers::disconnect", "agent_policy::decline_sign_in", ], diff --git a/services/gateway/src/routes/connectors.rs b/services/gateway/src/routes/connectors.rs index 2825ef657..0da82cc3a 100644 --- a/services/gateway/src/routes/connectors.rs +++ b/services/gateway/src/routes/connectors.rs @@ -17,9 +17,12 @@ use axum::{ http::StatusCode, Extension, Json, }; +use common::live::atlassian::{self, SignedIn}; use common::live::aws::AwsTarget; use common::live::confluence::{check_site, Access, Confluence}; -use common::live::connectors::{self, check_page_ids, ConnKind, Connector, VIA_JIRA_APP}; +use common::live::connectors::{ + self, check_page_ids, ConnKind, Connector, VIA_JIRA_APP, VIA_SIGN_IN, +}; use common::live::http::Https; use common::live::jira_app::{self, JiraApp}; use common::live::newrelic::NewRelic; @@ -217,12 +220,41 @@ async fn jira_app_of(state: &AppState, team_id: &str) -> Option { jira_app::load(&state.dynamo, &state.config.jira_config_table_name, team_id).await } -/// How to reach `c`'s Confluence: through the Jira app, or with `key`. +/// The team's Atlassian sign-in, opened, when `c` reads Confluence with it. +async fn signed_in_of( + state: &AppState, + team_id: &str, + c: &Connector, +) -> Option> { + if !c.via_sign_in() { + return None; + } + let rt = super::mcp_servers::runtime(state, team_id); + Some(atlassian::confluence(&rt, &c.site).await) +} + +/// How to reach `c`'s Confluence: with the team's Atlassian sign-in, +/// through the Jira app, or with `key`. fn confluence_access<'a>( c: &Connector, key: &'a str, app: Option<&'a JiraApp>, + signed: Option<&'a Result>, ) -> Result, StepError> { + if c.via_sign_in() { + return match signed { + Some(Ok(s)) => Ok(Access::SignIn { + base: &s.base, + bearer: &s.bearer, + }), + Some(Err(e)) => Err(e.clone()), + None => Err(StepError::new( + "sign_in", + "The team isn't signed in to Confluence.", + "Sign in to Confluence in Settings, Integrations, Confluence.", + )), + }; + } if !c.via_jira_app() { return Ok(Access::Token(key)); } @@ -246,6 +278,7 @@ async fn try_connection( c: &Connector, key: &str, app: Option<&JiraApp>, + signed: Option<&Result>, ) -> Result { match c.kind() { ConnKind::NewRelic => { @@ -270,12 +303,14 @@ async fn try_connection( ConnKind::Confluence => { let who = Confluence { conn: c, - access: confluence_access(c, key, app)?, + access: confluence_access(c, key, app, signed)?, http: &Https, } .whoami() .await?; - if c.via_jira_app() { + if c.via_sign_in() { + Ok("Reads Confluence with the team's Atlassian sign-in".to_string()) + } else if c.via_jira_app() { Ok(format!("Connected through the Jira app (as {who})")) } else { Ok(format!("Signed in as {who}")) @@ -365,10 +400,22 @@ fn via_jira_app(asked: Option<&str>, saved: &Connector, key_sent: bool, app: boo Some(v) => v == VIA_JIRA_APP, None if key_sent => false, None if saved.via_jira_app() => true, + None if saved.via_sign_in() => false, None => app && saved.key_sealed.is_empty() && saved.site.is_empty(), } } +/// Whether a Confluence save reads with the team's Atlassian sign-in (the +/// one made for Knowledge): when the page says so (`via`), or, when it +/// doesn't, when the saved connection already does and no key is sent. +/// Never on its own: an admin switches it on. +fn via_sign_in(asked: Option<&str>, saved: &Connector, key_sent: bool) -> bool { + match asked { + Some(v) => v == VIA_SIGN_IN, + None => saved.via_sign_in() && !key_sent, + } +} + /// The Confluence settings both ways of connecting share: spaces agents may /// read, the write switch and the pages writes may touch. fn confluence_settings(body: &Value, c: &mut Connector) -> Result<(), (StatusCode, Json)> { @@ -499,12 +546,30 @@ pub async fn save( None }; let key_sent = text("key").is_some_and(|k| !k.is_empty()); + let via_signin = + kind == ConnKind::Confluence && via_sign_in(body["via"].as_str(), &c, key_sent); let via_app = kind == ConnKind::Confluence + && !via_signin && via_jira_app(body["via"].as_str(), &c, key_sent, app.is_some()); // Key: replaced only when one is sent. let mut key = String::new(); - if via_app { + let mut signed: Option> = None; + if via_signin { + // The site stays the one already read with this sign-in; a first + // switch takes the site the sign-in reaches. + let want = if c.via_sign_in() { + c.site.clone() + } else { + String::new() + }; + c.via = VIA_SIGN_IN.into(); + c.key_sealed.clear(); + c.key_hint.clear(); + c.email.clear(); + c.site = want; + signed = signed_in_of(&state, &claims.team_id, &c).await; + } else if via_app { c.via = VIA_JIRA_APP.into(); c.key_sealed.clear(); c.key_hint.clear(); @@ -576,6 +641,20 @@ pub async fn save( )); } } + ConnKind::Confluence if via_signin => { + match &signed { + Some(Ok(s)) => c.site = s.site.clone(), + Some(Err(e)) => return Err(step(e.clone())), + None => {} + } + confluence_settings(&body, &mut c)?; + if c.write_enabled { + return Err(fail( + StatusCode::BAD_REQUEST, + "The Atlassian sign-in only reads Confluence. To add text to pages, connect Confluence with an API token or the Jira app.", + )); + } + } ConnKind::Confluence if via_app => { let Some(a) = &app else { return Err(fail( @@ -717,7 +796,7 @@ pub async fn save( } } let started = std::time::Instant::now(); - let tested = try_connection(&state, &claims, &c, &key, app.as_ref()).await; + let tested = try_connection(&state, &claims, &c, &key, app.as_ref(), signed.as_ref()).await; record( &state, &claims, @@ -776,8 +855,9 @@ pub async fn test( .await .map_err(|e| internal("open connector key", e))? }; + let signed = signed_in_of(&state, &claims.team_id, &c).await; let started = std::time::Instant::now(); - let tested = try_connection(&state, &claims, &c, &key, app.as_ref()).await; + let tested = try_connection(&state, &claims, &c, &key, app.as_ref(), signed.as_ref()).await; record( &state, &claims, @@ -893,6 +973,18 @@ mod tests { assert!(!via_jira_app(None, &token_saved, false, true)); assert!(via_jira_app(None, &empty, false, true)); assert!(!via_jira_app(None, &empty, false, false)); + // Reading with the team's Atlassian sign-in is switched on by an + // admin, never taken over by the Jira app, and a token replaces it. + let signed = Connector { + via: VIA_SIGN_IN.into(), + ..Connector::new(ConnKind::Confluence) + }; + assert!(via_sign_in(Some(VIA_SIGN_IN), &empty, false)); + assert!(!via_sign_in(None, &empty, false)); + assert!(via_sign_in(None, &signed, false)); + assert!(!via_sign_in(None, &signed, true)); + assert!(!via_sign_in(Some(""), &signed, false)); + assert!(!via_jira_app(None, &signed, false, true)); } #[test] diff --git a/services/gateway/src/routes/integration_status.rs b/services/gateway/src/routes/integration_status.rs new file mode 100644 index 000000000..070e41160 --- /dev/null +++ b/services/gateway/src/routes/integration_status.rs @@ -0,0 +1,794 @@ +//! One status per product on the Integrations page. +//! +//! A team can reach the same product in several ways, each kept in its own +//! record: a connection with a key (`CONNECTOR#`), the team's Jira app, +//! a sign-in made for Knowledge (`MCPSERVER#ks-`), the vendor's remote +//! server (`MCPSERVER#`), a sign-in with an app (`MCPSERVER#app-`) +//! and a key for the vendor's package (`PLUGIN#`). The page used to +//! read one of them per card, so a team signed in to Confluence for +//! Knowledge saw "Not connected" on Confluence's card. +//! +//! Here every way the team has is a [`Path`], and [`product_state`] works +//! out the card from all of them: +//! +//! - **What it is used for.** Each use the product has ([`Use`]: runs and +//! reviews, Knowledge) is decided by the first path, in the order given, +//! that isn't "not connected": working, or needing attention. +//! - **A use nothing serves yet** is `ready` when a working path can serve +//! it with no second sign-in ([`Extend`]: a switch, or nothing at all), +//! and `needs` when a different grant really is required ([`Need`] says +//! exactly what, with one action). +//! - **The card** is "Connected" when any use works, and says which. It +//! needs attention when a use that was set up is broken. It is "Not +//! connected" only when no path works at all, so a product the team has +//! a working sign-in to never reads "Not connected". + +use serde_json::{json, Value}; + +use super::integrations::CardState; + +/// What a team uses a product for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Use { + /// Agents read it (or use its tools) during runs, reviews and chat. + Runs, + /// Its content is synced into Knowledge. + Knowledge, +} + +impl Use { + pub fn key(self) -> &'static str { + match self { + Use::Runs => "runs", + Use::Knowledge => "knowledge", + } + } + + /// The name a card shows. + pub fn label(self) -> &'static str { + match self { + Use::Runs => "Runs and reviews", + Use::Knowledge => "Knowledge", + } + } + + /// The name inside a sentence. + fn words(self) -> &'static str { + match self { + Use::Runs => "runs and reviews", + Use::Knowledge => "Knowledge", + } + } +} + +/// The one thing a person does next: `kind` is what the page does +/// (`use_in_runs`, `connect`, `reconnect`, `check_again`, `add_credentials`, +/// `link`), `label` the words on the control, `href` where a `link` goes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Action { + pub kind: &'static str, + pub label: String, + pub href: String, +} + +impl Action { + pub fn new(kind: &'static str, label: &str) -> Self { + Action { + kind, + label: label.to_string(), + href: String::new(), + } + } + + pub fn link(label: &str, href: &str) -> Self { + Action { + kind: "link", + label: label.to_string(), + href: href.to_string(), + } + } + + fn json(&self) -> Value { + json!({ "kind": self.kind, "label": self.label, "href": self.href }) + } +} + +/// A use a working path can also serve, with no second sign-in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Extend { + pub to: Use, + /// What it takes, in a sentence ("The same sign-in can read pages + /// during runs and reviews. Turn it on: no second sign-in."). + pub detail: String, + pub action: Option, +} + +/// One way the team reaches a product. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Path { + /// What it is, in a card's words: "an API token", "the Jira app", + /// "the team's Atlassian sign-in", "Coderhelm's app". + pub how: String, + /// The path's own state, from its own record. + pub state: CardState, + /// What it is used for now. + pub serves: Vec, + pub extends: Vec, + /// Who connected it and when, when the record says. + pub by: String, + pub at: String, +} + +impl Path { + pub fn new(how: &str, state: CardState, serves: &[Use]) -> Self { + Path { + how: how.to_string(), + state, + serves: serves.to_vec(), + extends: Vec::new(), + by: String::new(), + at: String::new(), + } + } + + pub fn by(mut self, by: &str, at: &str) -> Self { + self.by = by.to_string(); + self.at = at.to_string(); + self + } + + pub fn extend(mut self, to: Use, detail: &str, action: Option) -> Self { + self.extends.push(Extend { + to, + detail: detail.to_string(), + action, + }); + self + } + + fn works(&self) -> bool { + self.state.status == "connected" + } + + fn set_up(&self) -> bool { + self.state.status != "not_connected" + } +} + +/// What a use needs when no working path can serve it: a different grant. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Need { + pub for_use: Use, + /// "Reading pages during runs needs an API token or the Jira app." + pub detail: String, + pub action: Option, +} + +/// How one use stands. `state` is `on` (works), `attention` (set up, but +/// broken), `ready` (a working sign-in can serve it), `needs` (a different +/// grant is required) or `off`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UseState { + pub of: Use, + pub state: &'static str, + pub how: String, + pub detail: String, + pub action: Option, +} + +impl UseState { + fn json(&self) -> Value { + json!({ + "id": self.of.key(), + "label": self.of.label(), + "state": self.state, + "how": self.how, + "detail": self.detail, + "action": self.action.as_ref().map(Action::json), + }) + } +} + +/// A product's card, worked out from every way the team reaches it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProductState { + pub card: CardState, + pub uses: Vec, + /// The way that works (the first one), who made it and when. + pub how: String, + pub connected_by: String, + pub connected_at: String, +} + +impl ProductState { + /// The fields a card carries besides its status, reason and action. + pub fn fields(&self) -> Value { + json!({ + "uses": self.uses.iter().map(UseState::json).collect::>(), + "how": self.how, + "connected_by": self.connected_by, + "connected_at": self.connected_at, + }) + } +} + +fn action_of(st: &CardState) -> Option { + let label = match st.action { + "reconnect" => "Reconnect", + "check_again" => "Check again", + "add_credentials" => "Add credentials", + _ => return None, + }; + Some(Action::new(st.action, label)) +} + +fn sentence(s: &str) -> String { + let s = s.trim(); + if s.is_empty() || s.ends_with(['.', '!', '?']) { + s.to_string() + } else { + format!("{s}.") + } +} + +fn upper_first(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => String::new(), + } +} + +fn join(parts: &[String]) -> String { + parts + .iter() + .map(|p| p.trim()) + .filter(|p| !p.is_empty()) + .collect::>() + .join(" ") +} + +/// The card for a product with `uses`, reached by `paths` (most preferred +/// first: the one agents or a sync take when several work). +pub fn product_state(uses: &[Use], paths: &[Path], needs: &[Need]) -> ProductState { + let any_works = paths.iter().any(Path::works); + // Each use is decided by the first path serving it that is set up. + let decided: Vec<(UseState, Option<&Path>)> = uses + .iter() + .map(|&u| { + let decider = paths.iter().find(|p| p.set_up() && p.serves.contains(&u)); + match decider { + Some(p) if p.works() => ( + UseState { + of: u, + state: "on", + how: p.how.clone(), + detail: p.state.reason.clone(), + action: None, + }, + Some(p), + ), + Some(p) => ( + UseState { + of: u, + state: "attention", + how: p.how.clone(), + detail: p.state.reason.clone(), + action: action_of(&p.state), + }, + Some(p), + ), + None => { + let ready = paths.iter().filter(|p| p.works()).find_map(|p| { + p.extends.iter().find(|e| e.to == u).map(|e| UseState { + of: u, + state: "ready", + how: p.how.clone(), + detail: e.detail.clone(), + action: e.action.clone(), + }) + }); + let need = || { + needs + .iter() + .find(|n| n.for_use == u) + .filter(|_| any_works) + .map(|n| UseState { + of: u, + state: "needs", + how: String::new(), + detail: n.detail.clone(), + action: n.action.clone(), + }) + }; + ( + ready.or_else(need).unwrap_or(UseState { + of: u, + state: "off", + how: String::new(), + detail: String::new(), + action: None, + }), + None, + ) + } + } + }) + .collect(); + + let on: Vec<&(UseState, Option<&Path>)> = + decided.iter().filter(|(s, _)| s.state == "on").collect(); + let broken = decided.iter().find(|(s, _)| s.state == "attention"); + let first = on.first().and_then(|(_, p)| *p); + let (how, connected_by, connected_at) = match first { + Some(p) => (p.how.clone(), p.by.clone(), p.at.clone()), + None => Default::default(), + }; + + let card = match (on.is_empty(), broken) { + // Nothing works and something set up is broken: that path's state. + (true, Some((_, Some(p)))) => p.state.clone(), + // Nothing is set up: the first path's own words, if it has any + // ("Each person connects their own account. You haven't yet."). + (true, _) => CardState { + status: "not_connected", + reason: paths + .iter() + .map(|p| p.state.reason.as_str()) + .find(|r| !r.is_empty()) + .unwrap_or("") + .to_string(), + action: "connect", + }, + // One use works and another that was set up is broken: the card + // needs attention and says which part still works. + (false, Some((b, Some(p)))) => CardState { + status: p.state.status, + reason: join(&[ + sentence(&format!( + "{} still work{}", + upper_first(&list( + &on.iter().map(|(s, _)| s.of.words()).collect::>() + )), + if on.len() == 1 && on[0].0.of == Use::Knowledge { + "s" + } else { + "" + }, + )), + format!( + "{}: {}", + b.of.label(), + sentence(&nonempty(&b.detail, "it has to be connected again")) + ), + ]), + action: p.state.action, + }, + (false, _) => CardState { + status: "connected", + reason: connected_reason(uses, &decided), + action: "manage", + }, + }; + + ProductState { + card, + uses: decided.into_iter().map(|(s, _)| s).collect(), + how, + connected_by, + connected_at, + } +} + +fn nonempty(s: &str, fallback: &str) -> String { + if s.trim().is_empty() { + fallback.to_string() + } else { + s.trim().to_string() + } +} + +fn list(words: &[&str]) -> String { + match words { + [] => String::new(), + [one] => one.to_string(), + [a, b] => format!("{a} and {b}"), + many => format!( + "{}, and {}", + many[..many.len() - 1].join(", "), + many[many.len() - 1] + ), + } +} + +/// What a connected card says. A product with one use keeps its path's own +/// words ("Signed in with Coderhelm's app."). One with several says what it +/// is used for, then what each other use takes. +fn connected_reason(uses: &[Use], decided: &[(UseState, Option<&Path>)]) -> String { + let on: Vec<&UseState> = decided + .iter() + .map(|(s, _)| s) + .filter(|s| s.state == "on") + .collect(); + let notes: Vec = { + let mut seen: Vec = Vec::new(); + for s in &on { + let d = sentence(&s.detail); + if !d.is_empty() && !seen.contains(&d) { + seen.push(d); + } + } + seen + }; + if uses.len() < 2 { + return join(¬es); + } + let lead = if on.len() == uses.len() { + // Every use works: "Used in runs and reviews, and in Knowledge." + let parts: Vec = on.iter().map(|s| format!("in {}", s.of.words())).collect(); + format!("Used {}.", parts.join(", and ")) + } else { + format!( + "Connected for {}.", + list(&on.iter().map(|s| s.of.words()).collect::>()) + ) + }; + let rest: Vec = decided + .iter() + .map(|(s, _)| s) + .filter(|s| matches!(s.state, "ready" | "needs")) + .map(|s| sentence(&s.detail)) + .collect(); + join(&[vec![lead], notes, rest].concat()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn st(status: &'static str, reason: &str, action: &'static str) -> CardState { + CardState { + status, + reason: reason.to_string(), + action, + } + } + + fn ok(reason: &str) -> CardState { + st("connected", reason, "manage") + } + + fn off() -> CardState { + st("not_connected", "", "connect") + } + + const BOTH: &[Use] = &[Use::Runs, Use::Knowledge]; + const RUNS: &[Use] = &[Use::Runs]; + + /// The knowledge sign-in of a product whose runs it can also serve + /// with a switch (Confluence). + fn knowledge_sign_in(state: CardState) -> Path { + Path::new("the team's Atlassian sign-in", state, &[Use::Knowledge]) + .by("ada@example.com", "2026-11-11T10:00:00Z") + .extend( + Use::Runs, + "The same sign-in can read pages during runs and reviews. Turn it on: no second sign-in.", + Some(Action::new("use_in_runs", "Use in runs too")), + ) + } + + fn token(state: CardState) -> Path { + Path::new("an API token", state, &[Use::Runs]).extend( + Use::Knowledge, + "Knowledge can sync with the same token: add a source there.", + Some(Action::link("Add a source in Knowledge", "/knowledge/")), + ) + } + + fn knowledge_needs() -> Vec { + vec![Need { + for_use: Use::Knowledge, + detail: "Syncing pages into Knowledge needs an Atlassian sign-in or an API token: the Jira app only serves runs.".into(), + action: Some(Action::link("Connect in Knowledge", "/knowledge/")), + }] + } + + fn use_of(p: &ProductState, u: Use) -> &UseState { + p.uses.iter().find(|s| s.of == u).unwrap() + } + + #[test] + fn nothing_connected_is_not_connected() { + let p = product_state(BOTH, &[], &knowledge_needs()); + assert_eq!(p.card, off()); + assert!(p.uses.iter().all(|u| u.state == "off")); + // Records that exist but were never connected change nothing. + let p = product_state(BOTH, &[token(off()), knowledge_sign_in(off())], &[]); + assert_eq!(p.card.status, "not_connected"); + assert_eq!(p.card.action, "connect"); + assert_eq!((p.how.as_str(), p.connected_by.as_str()), ("", "")); + } + + /// The reported case: signed in for Knowledge, no connection saved for + /// runs. The card is Connected, says for what, and offers the switch. + #[test] + fn a_knowledge_sign_in_alone_is_connected_and_offers_runs_without_a_second_sign_in() { + let p = product_state(BOTH, &[knowledge_sign_in(ok(""))], &knowledge_needs()); + assert_eq!(p.card.status, "connected"); + assert_eq!(p.card.action, "manage"); + assert_eq!( + p.card.reason, + "Connected for Knowledge. The same sign-in can read pages during runs and reviews. Turn it on: no second sign-in." + ); + assert_eq!(use_of(&p, Use::Knowledge).state, "on"); + let runs = use_of(&p, Use::Runs); + assert_eq!(runs.state, "ready"); + assert_eq!(runs.action.as_ref().unwrap().kind, "use_in_runs"); + assert_eq!(p.connected_by, "ada@example.com"); + assert_eq!(p.connected_at, "2026-11-11T10:00:00Z"); + assert_eq!(p.how, "the team's Atlassian sign-in"); + } + + #[test] + fn a_token_alone_is_connected_for_runs_and_ready_for_knowledge() { + let p = product_state(BOTH, &[token(ok(""))], &knowledge_needs()); + assert_eq!(p.card.status, "connected"); + assert_eq!( + p.card.reason, + "Connected for runs and reviews. Knowledge can sync with the same token: add a source there." + ); + let k = use_of(&p, Use::Knowledge); + assert_eq!( + (k.state, k.action.as_ref().unwrap().kind), + ("ready", "link") + ); + } + + /// The Jira app can't sync into Knowledge: a different grant is needed, + /// and the card says exactly which, with one action. + #[test] + fn a_path_that_cannot_serve_another_use_says_what_is_missing() { + let app = Path::new( + "the Jira app", + ok("Connected through the Jira app."), + &[Use::Runs], + ); + let p = product_state(BOTH, &[app], &knowledge_needs()); + assert_eq!(p.card.status, "connected"); + assert_eq!( + p.card.reason, + "Connected for runs and reviews. Connected through the Jira app. Syncing pages into Knowledge needs an Atlassian sign-in or an API token: the Jira app only serves runs." + ); + let k = use_of(&p, Use::Knowledge); + assert_eq!(k.state, "needs"); + assert_eq!(k.action.as_ref().unwrap().href, "/knowledge/"); + // With nothing connected there is nothing "missing" to say yet. + let p = product_state(BOTH, &[], &knowledge_needs()); + assert_eq!(use_of(&p, Use::Knowledge).state, "off"); + } + + #[test] + fn both_uses_working_says_so() { + let p = product_state( + BOTH, + &[token(ok("")), knowledge_sign_in(ok(""))], + &knowledge_needs(), + ); + assert_eq!(p.card.status, "connected"); + assert_eq!(p.card.reason, "Used in runs and reviews, and in Knowledge."); + assert!(p.uses.iter().all(|u| u.state == "on")); + // Who connected it is the first working path's record. + assert_eq!(p.how, "an API token"); + } + + /// A use switched on with the knowledge sign-in is served by the same + /// path as Knowledge. + #[test] + fn one_sign_in_serving_both_uses() { + let both = Path::new( + "the team's Atlassian sign-in", + ok(""), + &[Use::Runs, Use::Knowledge], + ); + let p = product_state(BOTH, &[both], &[]); + assert_eq!(p.card.reason, "Used in runs and reviews, and in Knowledge."); + } + + #[test] + fn a_broken_use_beside_a_working_one_needs_attention_but_is_never_not_connected() { + let p = product_state( + BOTH, + &[ + token(ok("")), + knowledge_sign_in(st( + "needs_reconnect", + "Atlassian ended the sign-in.", + "reconnect", + )), + ], + &[], + ); + assert_eq!(p.card.status, "needs_reconnect"); + assert_eq!(p.card.action, "reconnect"); + assert_eq!( + p.card.reason, + "Runs and reviews still work. Knowledge: Atlassian ended the sign-in." + ); + assert_eq!(use_of(&p, Use::Runs).state, "on"); + let k = use_of(&p, Use::Knowledge); + assert_eq!( + (k.state, k.action.as_ref().unwrap().kind), + ("attention", "reconnect") + ); + // The other way round reads the same way. + let p = product_state( + BOTH, + &[ + token(st( + "error", + "Confluence didn't accept the email and token.", + "check_again", + )), + knowledge_sign_in(ok("")), + ], + &[], + ); + assert_eq!(p.card.status, "error"); + assert!(p + .card + .reason + .starts_with("Knowledge still works. Runs and reviews: ")); + } + + #[test] + fn everything_broken_is_the_broken_paths_own_state() { + let broken = st( + "needs_reconnect", + "Atlassian ended the sign-in.", + "reconnect", + ); + let p = product_state( + BOTH, + &[knowledge_sign_in(broken.clone())], + &knowledge_needs(), + ); + assert_eq!(p.card, broken); + // The other use can't be offered from a sign-in that doesn't work. + assert_eq!(use_of(&p, Use::Runs).state, "off"); + } + + /// Several records for one use (Figma: an app sign-in, an older remote + /// record, a key): one card, decided by the first that is set up. + #[test] + fn the_preferred_path_decides_a_use() { + let app = |s| Path::new("Coderhelm's app", s, RUNS); + let remote = |s| Path::new("Figma's own server", s, RUNS); + let key = |s| Path::new("a key", s, RUNS); + // An app sign-in that works wins over everything else. + let p = product_state( + RUNS, + &[ + app(ok("Signed in with Coderhelm's app.")), + remote(off()), + key(ok("")), + ], + &[], + ); + assert_eq!(p.card, ok("Signed in with Coderhelm's app.")); + assert_eq!(p.how, "Coderhelm's app"); + // A sign-in never finished doesn't hide a key that works. + let p = product_state(RUNS, &[app(off()), remote(off()), key(ok(""))], &[]); + assert_eq!(p.card, ok("")); + assert_eq!(p.how, "a key"); + // A sign-in that needs renewing is what agents would use: it shows, + // even with a key saved. + let renew = st("needs_reconnect", "Figma refused it.", "reconnect"); + let p = product_state(RUNS, &[app(renew.clone()), key(ok(""))], &[]); + assert_eq!(p.card, renew); + // Switched on with no credentials, and a sign-in that works. + let p = product_state( + RUNS, + &[ + remote(ok("")), + key(st( + "needs_credentials", + "No key is saved.", + "add_credentials", + )), + ], + &[], + ); + assert_eq!(p.card.status, "connected"); + // Only records nobody finished: not connected, with the first words. + let p = product_state( + RUNS, + &[ + app(st( + "not_connected", + "Your own app is saved. Connect it to sign in.", + "connect", + )), + remote(off()), + ], + &[], + ); + assert_eq!(p.card.status, "not_connected"); + assert_eq!( + p.card.reason, + "Your own app is saved. Connect it to sign in." + ); + } + + /// Every combination of the ways a two-use product is reached: the card + /// is "not connected" exactly when nothing is set up, so never when a + /// path works. + #[test] + fn a_working_sign_in_is_never_shown_as_not_connected() { + let states = [ + off(), + ok(""), + st("needs_reconnect", "It has to be renewed.", "reconnect"), + st("error", "The last test failed.", "check_again"), + st("needs_credentials", "No key is saved.", "add_credentials"), + ]; + let mut seen = 0; + for a in &states { + for b in &states { + for c in &states { + let paths = [ + token(a.clone()), + Path::new("the vendor's own server", b.clone(), RUNS), + knowledge_sign_in(c.clone()), + ]; + let p = product_state(BOTH, &paths, &knowledge_needs()); + let works = paths.iter().any(|x| x.state.status == "connected"); + let set_up = paths.iter().any(|x| x.state.status != "not_connected"); + assert_eq!( + p.card.status == "not_connected", + !set_up, + "{a:?} {b:?} {c:?} gave {:?}", + p.card + ); + if works { + assert_ne!(p.card.status, "not_connected", "{a:?} {b:?} {c:?}"); + } + if p.card.status == "connected" { + assert!(p.uses.iter().any(|u| u.state == "on")); + assert!(!p.card.reason.is_empty(), "says what it is used for"); + } + // A use works exactly when the first path set up for it does. + let runs_first = [a, b].into_iter().find(|s| s.status != "not_connected"); + assert_eq!( + use_of(&p, Use::Runs).state == "on", + runs_first.is_some_and(|s| s.status == "connected"), + "{a:?} {b:?} {c:?}" + ); + assert_eq!( + use_of(&p, Use::Knowledge).state == "on", + c.status == "connected", + "{a:?} {b:?} {c:?}" + ); + // A use is "ready" or "needs" only beside a working path. + if !works { + assert!(p.uses.iter().all(|u| !matches!(u.state, "ready" | "needs"))); + } + seen += 1; + } + } + } + assert_eq!(seen, 125); + } + + #[test] + fn the_cards_extra_fields() { + let p = product_state(BOTH, &[knowledge_sign_in(ok(""))], &[]); + let v = p.fields(); + assert_eq!(v["connected_by"], "ada@example.com"); + assert_eq!(v["uses"][0]["id"], "runs"); + assert_eq!(v["uses"][0]["label"], "Runs and reviews"); + assert_eq!(v["uses"][0]["state"], "ready"); + assert_eq!(v["uses"][0]["action"]["kind"], "use_in_runs"); + assert_eq!(v["uses"][1]["state"], "on"); + assert!(v["uses"][1]["action"].is_null()); + } +} diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 088c16de7..711fe1494 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -21,13 +21,16 @@ use axum::{ http::StatusCode, Extension, Json, }; +use common::knowledge::sources::Kind as SourceKind; use common::live::aws_account::{self, AwsAccount}; use common::live::connectors::{self, ConnKind, Connector}; use common::live::identity; +use common::mcp_remote::store::{Owner, ServerRecord, Sharing, Status, TokenRecord}; use common::problems::{Check, Kind, Outcome}; use serde_json::{json, Value}; use tracing::{error, info, warn}; +use super::integration_status::{product_state, Action, Need, Path as Way, ProductState, Use}; use crate::models::Claims; use crate::AppState; @@ -69,7 +72,7 @@ pub fn section_of(id: &str) -> &'static str { "github" | "jira" | "atlassian" => "code", "aws" | "opensearch" | "rest" => "cloud", "newrelic" | "sentry" => "monitoring", - "confluence" | "notion" | "figma" | "sanity" => "docs", + "confluence" | "notion" | "figma" | "sanity" | "google_drive" => "docs", "teams" | "slack" => "chat", // Remote MCP servers an admin added by address (`mcp:`). "mcp" => "mcp", @@ -210,7 +213,7 @@ pub fn remote_state( pub fn connector_state(c: Option<&Connector>) -> CardState { match c { None => cs("not_connected", "", "connect"), - Some(c) if c.key_sealed.is_empty() && !c.via_jira_app() => { + Some(c) if c.key_sealed.is_empty() && !c.via_jira_app() && !c.via_sign_in() => { cs("needs_credentials", "No key is saved.", "add_credentials") } Some(c) if c.status != "ready" => cs( @@ -226,12 +229,19 @@ pub fn connector_state(c: Option<&Connector>) -> CardState { "connected", if c.via_jira_app() { "Connected through the Jira app but paused: agents don't use it." + } else if c.via_sign_in() { + "Reads with the team's Atlassian sign-in but paused: agents don't use it." } else { "Connected but paused: agents don't use it." }, "manage", ), Some(c) if c.via_jira_app() => cs("connected", "Connected through the Jira app.", "manage"), + Some(c) if c.via_sign_in() => cs( + "connected", + "Agents read pages with the team's Atlassian sign-in.", + "manage", + ), Some(_) => cs("connected", "", "manage"), } } @@ -349,9 +359,323 @@ fn card( "last_check": last_check, "manage_href": manage, "detail": detail, + // What it is used for, how it is connected and by whom: filled in + // for a product reached in more than one way ([`product_card`]). + "uses": [], + "how": "", + "connected_by": "", + "connected_at": "", }) } +/// A card whose state comes from every way the team reaches the product +/// (`integration_status`). +fn product_card( + id: &str, + name: &str, + does: &str, + p: &ProductState, + last_check: &str, + manage: &str, + detail: Value, +) -> Value { + let mut v = card(id, name, does, p.card.clone(), last_check, manage, detail); + if let Some(fields) = p.fields().as_object() { + for (k, val) in fields { + v[k.as_str()] = val.clone(); + } + } + v +} + +/// The sign-in a team (or, for Sanity, this person) made so Knowledge can +/// sync a product: its record and its connection, when someone signed in. +#[derive(Debug, Clone)] +pub struct KnowledgeSignIn { + pub kind: SourceKind, + pub server: ServerRecord, + pub token: TokenRecord, + /// How many of the team's Knowledge sources are of this kind. + pub sources: usize, +} + +impl KnowledgeSignIn { + fn personal(&self) -> bool { + self.server.sharing == Sharing::Personal + } + + fn works(&self) -> bool { + self.token.status == Status::Connected + } + + /// Whose sign-in it is, in a card's words. + pub fn how(&self) -> String { + match (self.kind, self.personal()) { + (_, true) => format!("your {} sign-in", self.kind.label()), + (SourceKind::Confluence, _) => "the team's Atlassian sign-in".into(), + (SourceKind::GoogleDrive, _) => "the team's Google sign-in".into(), + (k, _) => format!("the team's {} sign-in", k.label()), + } + } + + /// The sign-in's own state. A sign-in that stopped working is renewed + /// by signing in again, whatever stopped it. + pub fn state(&self) -> CardState { + let why = self.token.status_reason.clone(); + match self.token.status { + Status::Connected => cs("connected", "", "manage"), + Status::Failed => cs("error", why, "reconnect"), + Status::NotConnected => cs("not_connected", why, "connect"), + Status::NeedsReconnect => cs( + "needs_reconnect", + if why.is_empty() { + "The sign-in has to be renewed.".to_string() + } else { + why + }, + "reconnect", + ), + } + } + + /// The way Knowledge reaches the product. + pub fn way(&self) -> Way { + Way::new(&self.how(), self.state(), &[Use::Knowledge]) + .by(&self.token.connected_by, &self.token.connected_at) + } + + fn json(&self) -> Value { + let st = self.state(); + json!({ + "kind": self.kind.key(), + "label": self.kind.label(), + "server_id": self.server.id, + "personal": self.personal(), + "status": st.status, + "reason": st.reason, + "connected_by": self.token.connected_by, + "connected_at": self.token.connected_at, + "sources": self.sources, + }) + } +} + +/// The Knowledge source kind a card's product is also synced as. +pub fn knowledge_kind(card_id: &str) -> Option { + match card_id { + "confluence" => Some(SourceKind::Confluence), + "notion" => Some(SourceKind::Notion), + "sanity" => Some(SourceKind::Sanity), + "google_drive" => Some(SourceKind::GoogleDrive), + _ => None, + } +} + +const KNOWLEDGE_HREF: &str = "/knowledge/"; + +/// Confluence's card, from the connection agents read with (an API token, +/// the Jira app, or the team's Atlassian sign-in switched on for runs) and +/// the sign-in made for Knowledge. +pub fn confluence_product( + conn: Option<&Connector>, + knowledge: Option<&KnowledgeSignIn>, + sources: usize, +) -> ProductState { + let mut ways = Vec::new(); + if let Some(k) = knowledge { + // The same sign-in reads pages during runs once an admin turns + // that on: its scopes cover it, so nobody signs in twice. + ways.push(k.way().extend( + Use::Runs, + "The same sign-in can read pages during runs and reviews. Turn it on: no second sign-in.", + Some(Action::new("use_in_runs", "Use in runs too")), + )); + } + if let Some(c) = conn { + let mut st = connector_state(Some(c)); + let how = if c.via_jira_app() { + "the Jira app" + } else if c.via_sign_in() { + "the team's Atlassian sign-in" + } else { + "an API token" + }; + // Reading with the sign-in stops when the sign-in does. + if c.via_sign_in() && st.status == "connected" && !knowledge.is_some_and(|k| k.works()) { + st = match knowledge { + Some(k) => k.state(), + None => cs( + "needs_reconnect", + "The team isn't signed in to Confluence any more.", + "reconnect", + ), + }; + } + let token = !c.via_jira_app() && !c.via_sign_in(); + // A saved token also syncs Knowledge's sources when nobody signed in. + let serves: &[Use] = if token && knowledge.is_none() && sources > 0 { + &[Use::Runs, Use::Knowledge] + } else { + &[Use::Runs] + }; + let mut way = Way::new(how, st, serves).by(&c.updated_by, &c.updated_at); + if token { + way = way.extend( + Use::Knowledge, + "Knowledge can sync with the same token: add a source there.", + Some(Action::link("Add a source in Knowledge", KNOWLEDGE_HREF)), + ); + } + ways.push(way); + } + let needs = [Need { + for_use: Use::Knowledge, + detail: "Syncing pages into Knowledge needs an Atlassian sign-in or an API token: the Jira app only reads pages during runs.".into(), + action: Some(Action::link("Connect in Knowledge", KNOWLEDGE_HREF)), + }]; + product_state(&[Use::Runs, Use::Knowledge], &ways, &needs) +} + +/// The ways a team reaches a catalog product, as found in its records. +#[derive(Debug, Default)] +pub struct CatalogWays<'a> { + /// The app sign-in's card JSON (`mcp_servers::own_app_json`). + pub own_app: Option<&'a Value>, + /// The vendor's remote server and this person's (or the team's) + /// connection to it. + pub remote: Option<(&'a ServerRecord, Option<&'a TokenRecord>)>, + /// The key for the vendor's package, when the switch was ever set. + pub key: Option, + pub key_at: &'a str, + pub knowledge: Option<&'a KnowledgeSignIn>, + pub sources: usize, +} + +/// A catalog product's card (Notion, Sanity, Figma, Sentry and the rest): +/// one status from its app sign-in, the vendor's remote server, its key and +/// its Knowledge sign-in. +pub fn catalog_product(id: &str, name: &str, w: &CatalogWays) -> ProductState { + let kind = knowledge_kind(id); + let mut ways = Vec::new(); + if let Some(k) = w.knowledge { + ways.push(k.way()); + } + if let Some(o) = w.own_app { + let how = if o["source"] == "coderhelm" { + format!("Coderhelm's {name} app") + } else { + format!("your own {name} app") + }; + let st = own_app_state(o, &cs("not_connected", "", "connect")); + ways.push(Way::new(&how, st, &[Use::Runs]).by( + o["connected_by"].as_str().unwrap_or(""), + o["connected_at"].as_str().unwrap_or(""), + )); + } + if let Some((r, token)) = w.remote { + let mut way = Way::new( + &format!("{name}'s own server"), + remote_state(r, token), + &[Use::Runs], + ); + if let Some(t) = token { + way = way.by(&t.connected_by, &t.connected_at); + } + // A member's sign-in on Sanity's server is the one Knowledge syncs with. + if kind == Some(SourceKind::Sanity) { + way = way.extend( + Use::Knowledge, + "Knowledge can sync with this sign-in: add a source there.", + Some(Action::link("Add a source in Knowledge", KNOWLEDGE_HREF)), + ); + } + ways.push(way); + } + if let Some(st) = &w.key { + // Notion's and Sanity's saved keys also sync Knowledge's sources. + let syncs = matches!(kind, Some(SourceKind::Notion | SourceKind::Sanity)); + let serves: &[Use] = if syncs && w.knowledge.is_none() && w.sources > 0 { + &[Use::Runs, Use::Knowledge] + } else { + &[Use::Runs] + }; + let mut way = Way::new("a key", st.clone(), serves).by("", w.key_at); + if syncs { + way = way.extend( + Use::Knowledge, + "Knowledge can sync with the same key: add a source there.", + Some(Action::link("Add a source in Knowledge", KNOWLEDGE_HREF)), + ); + } + ways.push(way); + } + let needs: Vec = match kind { + Some(SourceKind::Notion) => vec![ + Need { + for_use: Use::Runs, + detail: "Using Notion in runs needs Notion's own sign-in for agents, or a key: Notion grants that separately from Knowledge.".into(), + action: Some(Action::new("connect", "Connect for runs")), + }, + Need { + for_use: Use::Knowledge, + detail: "Syncing Notion into Knowledge needs the Notion sign-in Knowledge uses, or a key: Notion grants that separately.".into(), + action: Some(Action::link("Connect in Knowledge", KNOWLEDGE_HREF)), + }, + ], + Some(SourceKind::Sanity) => vec![Need { + for_use: Use::Runs, + detail: "Using Sanity in runs needs Sanity connected here, so an admin can pick its tools.".into(), + action: Some(Action::new("connect", "Connect for runs")), + }], + _ => Vec::new(), + }; + let uses: &[Use] = if kind.is_some() { + &[Use::Runs, Use::Knowledge] + } else { + &[Use::Runs] + }; + product_state(uses, &ways, &needs) +} + +/// The sign-ins the team made for Knowledge, by kind. +async fn knowledge_sign_ins( + rt: &common::mcp_remote::runtime::Runtime, + email: &str, + sources: &[common::knowledge::sources::Source], +) -> Vec { + let mut out = Vec::new(); + for kind in [ + SourceKind::Confluence, + SourceKind::Notion, + SourceKind::Sanity, + SourceKind::GoogleDrive, + ] { + let id = common::knowledge::sources::oauth::connection_id(kind); + let Ok(Some(server)) = rt.store.get_server(&rt.team, &id).await else { + continue; + }; + let owner = match server.sharing { + Sharing::Personal => Owner::user(email), + Sharing::Shared => Owner::Team, + }; + // A record nobody finished signing in to is no connection. + let Ok(Some(token)) = rt.store.get_token(&rt.team, &id, &owner).await else { + continue; + }; + out.push(KnowledgeSignIn { + kind, + server, + token, + sources: sources_of(sources, kind), + }); + } + out +} + +fn sources_of(sources: &[common::knowledge::sources::Source], kind: SourceKind) -> usize { + sources.iter().filter(|s| s.kind == Some(kind)).count() +} + /// Checks the account's role (read-only) and saves what it can do. pub(crate) async fn check_and_save( state: &AppState, @@ -514,7 +838,7 @@ pub async fn list( aws_account::list(&state.dynamo, &state.config.aws_insights_table_name, &team) .await .map_err(|e| internal("list aws accounts", e))?; - with_knowledge_bases(&state, &team, &mut accounts).await; + let sources = with_knowledge_bases(&state, &team, &mut accounts).await; // A support view only reads: no migration, no checks into the team's // AWS accounts (they would run as the support admin). let support_view = claims.support_view.is_some(); @@ -584,6 +908,18 @@ pub async fn list( my_tokens.insert(r.id.clone(), t); } } + // The sign-ins made for Knowledge (kept apart from MCP servers): a + // product signed in to there is connected here too. + let knowledge = knowledge_sign_ins(&rt, &claims.email, &sources).await; + let knowledge_of = |kind: SourceKind| knowledge.iter().find(|k| k.kind == kind); + // Sign-ins nobody finished are removed once they expire, whether or + // not the table expires records on its own. + if !support_view { + let swept = rt.sweep_pending().await; + if swept > 0 { + info!(team_id = %team, swept, "Expired sign-ins in progress removed"); + } + } let mut items = Vec::new(); @@ -689,6 +1025,24 @@ pub async fn list( } None => (kind.as_str().to_string(), kind.label().to_string()), }; + if kind == ConnKind::Confluence { + // One status from every way the team reaches Confluence: + // the connection agents read with and the Knowledge sign-in. + let k = knowledge_of(SourceKind::Confluence); + let p = confluence_product(c, k, sources_of(&sources, SourceKind::Confluence)); + let mut detail = detail; + detail["knowledge"] = json!(k.map(KnowledgeSignIn::json)); + items.push(product_card( + &id, + &name, + does, + &p, + c.map(|c| c.updated_at.as_str()).unwrap_or(""), + "", + detail, + )); + continue; + } items.push(card( &id, &name, @@ -755,27 +1109,34 @@ pub async fn list( !tested_at.is_empty() && tested_at >= creds_at, ); let custom_prompt = rec.map(|r| s(r, "custom_prompt")).unwrap_or_default(); - // Connected through the vendor's remote server: that connection's - // state is the card's (the key form stays as a fallback). + // The vendor's own remote server, when the team set it up. let remote = remotes.iter().find(|r| r.id == id && r.catalog_id == id); - // A sign-in started but never finished doesn't hide a key that works. - let st = match remote { - Some(r) => { - let rs = remote_state(r, my_tokens.get(&r.id)); - if rs.status == "not_connected" && enabled == Some(true) { - st - } else { - rs - } - } - None => st, + // A record for a vendor's server the catalog no longer offers + // (Figma's takes only apps Figma approved) that was never + // connected: kept, said on the card as unused, and not a second + // sign-in beside the one that works. + let offered = !p["remote_url"].as_str().unwrap_or("").is_empty(); + let (remote, unused) = match remote { + Some(r) if !offered && remote_state(r, my_tokens.get(&r.id)).status != "connected" => ( + None, + vec![json!({ + "id": r.id, + "name": r.name, + "kind": "remote", + "note": format!( + "A sign-in through {}'s own server was started and never finished. Coderhelm doesn't use it.", + r.name + ), + })], + ), + r => (r, Vec::new()), }; let tested_at = match remote { Some(r) => r.tools_listed_at.clone(), None => tested_at, }; - // Signed in with the team's own app: that sign-in is what agents - // use (the key stays as a fallback), so its state is the card's. + // The sign-in with an app (CoderHelm's or the team's own): what + // agents use first when it is there. let own = match common::mcp_remote::own_app::load(&rt, &id).await { Ok(o) => o, Err(e) => { @@ -787,10 +1148,23 @@ pub async fn list( Some(o) => Some(super::mcp_servers::own_app_json(&state, &rt, o).await), None => None, }; - let st = match own_json.as_ref().map(|o| own_app_state(o, &st)) { - Some(s) => s, - None => st, - }; + // One status from every way the team reaches it: the app sign-in + // agents use first, the vendor's server, the key, and the sign-in + // made for Knowledge. + let kind = knowledge_kind(&id); + let k = kind.and_then(&knowledge_of); + let product = catalog_product( + &id, + p["name"].as_str().unwrap_or(&id), + &CatalogWays { + own_app: own_json.as_ref(), + remote: remote.map(|r| (r, my_tokens.get(&r.id))), + key: enabled.is_some().then_some(st), + key_at: &creds_at, + knowledge: k, + sources: kind.map_or(0, |kind| sources_of(&sources, kind)), + }, + ); // Where the team's own app sends people back, for its setup steps. let own_redirect = common::mcp_catalog::own_app(&id) .map(|_| super::mcp_servers::redirect_uri(&state.config.stage)); @@ -808,18 +1182,35 @@ pub async fn list( "custom_prompt": if can_edit { custom_prompt } else { String::new() }, "last_test_ok": rec.and_then(|r| ob(r, "last_test_ok")), "last_test_message": rec.map(|r| s(r, "last_test_message")).unwrap_or_default(), + "knowledge": k.map(KnowledgeSignIn::json), + "unused": unused, }); - items.push(card( + items.push(product_card( &id, p["name"].as_str().unwrap_or(&id), p["description"].as_str().unwrap_or(""), - st, + &product, &tested_at, "", detail, )); } + // Google Drive is only ever synced into Knowledge: it has a card here + // once the team signed in, so the sign-in is seen where sign-ins are. + if let Some(k) = knowledge_of(SourceKind::GoogleDrive) { + let p = product_state(&[Use::Knowledge], &[k.way()], &[]); + items.push(product_card( + "google_drive", + "Google Drive", + "Syncs the folders, Docs, Sheets, Slides and PDFs you pick into Knowledge. It only reads.", + &p, + "", + KNOWLEDGE_HREF, + json!({ "knowledge": k.json() }), + )); + } + // Servers added by address. for r in remotes.iter().filter(|r| r.catalog_id.is_empty()) { let host = reqwest::Url::parse(&r.url) @@ -879,13 +1270,18 @@ async fn load_account( /// 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]) { +async fn with_knowledge_bases( + state: &AppState, + team_id: &str, + accounts: &mut [AwsAccount], +) -> Vec { 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); } + sources } /// Every knowledge source of the team (the buckets it imports from). @@ -1283,6 +1679,517 @@ mod tests { assert!(AbilityChange::parse(&json!({ "airflow_environments": "prod" })).is_err()); } + // ── One status per product, from every record the team has ────────── + + fn token(status: Status, reason: &str) -> TokenRecord { + TokenRecord { + owner: Owner::Team, + sealed: String::new(), + expires_at: None, + scope: String::new(), + version: 1, + status, + status_reason: reason.into(), + step_up: vec![], + connected_by: "ada@example.com".into(), + connected_at: "2026-11-11T10:00:00Z".into(), + } + } + + /// The sign-in Knowledge made for `kind` (`MCPSERVER#ks-` and its + /// `MCPTOKEN`). + fn signed_in(kind: SourceKind, status: Status) -> KnowledgeSignIn { + let id = common::knowledge::sources::oauth::connection_id(kind); + let mut server = ServerRecord::new( + &id, + &format!("{} (knowledge)", kind.label()), + "https://auth.example.com", + ); + server.catalog_id = common::knowledge::sources::oauth::catalog_id(kind); + server.auth = common::mcp_remote::store::AuthKind::OAuth; + if kind == SourceKind::Sanity { + server.sharing = Sharing::Personal; + } + let reason = if status == Status::Connected { + "" + } else { + "The provider ended the sign-in." + }; + KnowledgeSignIn { + kind, + server, + token: token(status, reason), + sources: 0, + } + } + + fn confluence_token() -> Connector { + Connector { + enabled: true, + status: "ready".into(), + key_sealed: "sealed".into(), + site: "https://example.atlassian.net".into(), + email: "bot@example.com".into(), + updated_by: "grace@example.com".into(), + updated_at: "2026-11-01T09:00:00Z".into(), + ..Connector::new(ConnKind::Confluence) + } + } + + fn jira_app_confluence() -> Connector { + common::live::jira_app::JiraApp { + site: "https://example.atlassian.net".into(), + confluence_url: "https://example.invalid/x1/confluence".into(), + secret: "s".into(), + } + .default_confluence() + } + + fn use_state(p: &ProductState, u: Use) -> &str { + p.uses.iter().find(|s| s.of == u).unwrap().state + } + + /// The report: a connected-app record for Confluence as a knowledge + /// source and its team sign-in, no saved connector, and a Jira app that + /// can't reach Confluence. The card read "Not connected". + #[test] + fn confluence_signed_in_for_knowledge_only_is_connected() { + let k = signed_in(SourceKind::Confluence, Status::Connected); + let p = confluence_product(None, Some(&k), 0); + assert_eq!((p.card.status, p.card.action), ("connected", "manage")); + assert_eq!( + p.card.reason, + "Connected for Knowledge. The same sign-in can read pages during runs and reviews. Turn it on: no second sign-in." + ); + assert_eq!(use_state(&p, Use::Knowledge), "on"); + assert_eq!(use_state(&p, Use::Runs), "ready"); + assert_eq!(p.how, "the team's Atlassian sign-in"); + assert_eq!(p.connected_by, "ada@example.com"); + assert_eq!(p.connected_at, "2026-11-11T10:00:00Z"); + } + + #[test] + fn confluence_in_every_combination_of_its_records() { + let k_ok = signed_in(SourceKind::Confluence, Status::Connected); + let k_renew = signed_in(SourceKind::Confluence, Status::NeedsReconnect); + let token = confluence_token(); + let app = jira_app_confluence(); + let signed = Connector { + enabled: true, + status: "ready".into(), + via: common::live::connectors::VIA_SIGN_IN.into(), + site: "https://example.atlassian.net".into(), + ..Connector::new(ConnKind::Confluence) + }; + + // Nothing at all. + let p = confluence_product(None, None, 0); + assert_eq!((p.card.status, p.card.action), ("not_connected", "connect")); + + // An API token only: runs work, Knowledge can use the same token. + let p = confluence_product(Some(&token), None, 0); + assert_eq!(p.card.status, "connected"); + assert_eq!( + p.card.reason, + "Connected for runs and reviews. Knowledge can sync with the same token: add a source there." + ); + assert_eq!(use_state(&p, Use::Knowledge), "ready"); + assert_eq!(p.connected_by, "grace@example.com"); + // Once a source syncs with that token, both uses are on. + let p = confluence_product(Some(&token), None, 2); + assert_eq!(p.card.reason, "Used in runs and reviews, and in Knowledge."); + + // The Jira app only: Knowledge needs a different grant, said exactly. + let p = confluence_product(Some(&app), None, 0); + assert_eq!(p.card.status, "connected"); + assert!( + p.card.reason.starts_with("Connected for runs and reviews."), + "{}", + p.card.reason + ); + assert!( + p.card.reason.contains( + "Syncing pages into Knowledge needs an Atlassian sign-in or an API token" + ), + "{}", + p.card.reason + ); + assert_eq!(use_state(&p, Use::Knowledge), "needs"); + + // Token and Knowledge sign-in, the Jira app and Knowledge sign-in. + for c in [&token, &app] { + let p = confluence_product(Some(c), Some(&k_ok), 1); + assert_eq!(p.card.status, "connected"); + assert!( + p.card + .reason + .starts_with("Used in runs and reviews, and in Knowledge."), + "{}", + p.card.reason + ); + } + + // Runs switched on with the Knowledge sign-in: one sign-in, both uses. + let p = confluence_product(Some(&signed), Some(&k_ok), 1); + assert_eq!(p.card.status, "connected"); + assert_eq!( + p.card.reason, + "Used in runs and reviews, and in Knowledge. Agents read pages with the team's Atlassian sign-in." + ); + // That sign-in ends: both uses need it renewed, with one action. + let p = confluence_product(Some(&signed), Some(&k_renew), 1); + assert_eq!( + (p.card.status, p.card.action), + ("needs_reconnect", "reconnect") + ); + assert_eq!(p.card.reason, "The provider ended the sign-in."); + // ... or was removed from under the connection. + let p = confluence_product(Some(&signed), None, 0); + assert_eq!(p.card.status, "needs_reconnect"); + assert!(p.card.reason.contains("isn't signed in to Confluence")); + + // The Knowledge sign-in needs renewing while a token still works: + // attention, never "not connected". + let p = confluence_product(Some(&token), Some(&k_renew), 1); + assert_eq!( + (p.card.status, p.card.action), + ("needs_reconnect", "reconnect") + ); + assert_eq!( + p.card.reason, + "Runs and reviews still work. Knowledge: The provider ended the sign-in." + ); + + // Only a Knowledge sign-in that needs renewing. + let p = confluence_product(None, Some(&k_renew), 0); + assert_eq!(p.card.status, "needs_reconnect"); + assert_eq!(use_state(&p, Use::Runs), "off"); + + // A token Confluence refuses beside a working Knowledge sign-in. + let bad = Connector { + status: "error".into(), + status_message: "Confluence didn't accept the email and token.".into(), + ..confluence_token() + }; + let p = confluence_product(Some(&bad), Some(&k_ok), 1); + assert_eq!((p.card.status, p.card.action), ("error", "check_again")); + assert!( + p.card.reason.starts_with("Knowledge still works."), + "{}", + p.card.reason + ); + } + + fn remote(id: &str, name: &str, status: Status) -> ServerRecord { + let mut r = ServerRecord::new(id, name, &format!("https://mcp.{id}.example/mcp")); + r.catalog_id = id.into(); + r.auth = common::mcp_remote::store::AuthKind::OAuth; + r.status = status; + r.allowed = ["search".to_string()].into(); + r.approved = r.allowed.clone(); + r + } + + fn key_on() -> CardState { + plugin_state(Some(true), true, Some(true), "", true) + } + + #[test] + fn notion_in_every_combination_of_its_records() { + let k = signed_in(SourceKind::Notion, Status::Connected); + let r = remote("notion", "Notion", Status::Connected); + let r_off = remote("notion", "Notion", Status::NotConnected); + let ways = |own: Option<(&ServerRecord, Option<&TokenRecord>)>, + key: Option, + knowledge: Option<&KnowledgeSignIn>, + sources: usize| { + let w = CatalogWays { + remote: own, + key, + knowledge, + sources, + ..Default::default() + }; + catalog_product("notion", "Notion", &w) + }; + + assert_eq!(ways(None, None, None, 0).card.status, "not_connected"); + + // Signed in for Knowledge only: connected, and runs really do need + // another grant (Notion's sign-in for agents is a different one). + let p = ways(None, None, Some(&k), 1); + assert_eq!(p.card.status, "connected"); + assert_eq!( + p.card.reason, + "Connected for Knowledge. Using Notion in runs needs Notion's own sign-in for agents, or a key: Notion grants that separately from Knowledge." + ); + assert_eq!(use_state(&p, Use::Runs), "needs"); + assert_eq!(p.how, "the team's Notion sign-in"); + // A sign-in for agents that was started and never finished changes nothing. + let p2 = ways(Some((&r_off, None)), None, Some(&k), 1); + assert_eq!(p2.card, p.card); + + // Notion's own server only: runs work, Knowledge needs its own grant. + let p = ways(Some((&r, None)), None, None, 0); + assert_eq!(p.card.status, "connected"); + assert!(p.card.reason.starts_with("Connected for runs and reviews.")); + assert!(p + .card + .reason + .contains("Syncing Notion into Knowledge needs")); + assert_eq!(use_state(&p, Use::Knowledge), "needs"); + + // A key only: it serves runs and Knowledge can use it too. + let p = ways(None, Some(key_on()), None, 0); + assert_eq!(use_state(&p, Use::Knowledge), "ready"); + assert!(p + .card + .reason + .contains("Knowledge can sync with the same key")); + let p = ways(None, Some(key_on()), None, 3); + assert_eq!(p.card.reason, "Used in runs and reviews, and in Knowledge."); + + // Everything: one card, both uses on. + let p = ways(Some((&r, None)), Some(key_on()), Some(&k), 1); + assert_eq!(p.card.status, "connected"); + assert_eq!(p.card.reason, "Used in runs and reviews, and in Knowledge."); + assert_eq!(p.how, "Notion's own server"); + + // A sign-in started and never finished doesn't hide a key that works. + let p = ways(Some((&r_off, None)), Some(key_on()), None, 0); + assert_eq!(p.card.status, "connected"); + assert_eq!(p.how, "a key"); + } + + #[test] + fn sanity_in_every_combination_of_its_records() { + let mine = signed_in(SourceKind::Sanity, Status::Connected); + let mut r = remote("sanity", "Sanity", Status::Connected); + r.sharing = Sharing::Personal; + let my_token = TokenRecord { + owner: Owner::user("ada@example.com"), + ..token(Status::Connected, "") + }; + let product = |w: CatalogWays| catalog_product("sanity", "Sanity", &w); + + // A member's sign-in for Knowledge only. + let p = product(CatalogWays { + knowledge: Some(&mine), + ..Default::default() + }); + assert_eq!(p.card.status, "connected"); + assert_eq!(p.how, "your Sanity sign-in"); + assert!(p.card.reason.starts_with("Connected for Knowledge.")); + assert!(p + .card + .reason + .contains("Using Sanity in runs needs Sanity connected here")); + + // The connected app only, signed in to by this person: runs work + // and the same sign-in syncs Knowledge. + let p = product(CatalogWays { + remote: Some((&r, Some(&my_token))), + ..Default::default() + }); + assert_eq!(p.card.status, "connected"); + assert_eq!(use_state(&p, Use::Knowledge), "ready"); + assert!(p + .card + .reason + .contains("Knowledge can sync with this sign-in")); + + // The connected app that this person hasn't signed in to yet, and + // their Knowledge sign-in: connected, never "not connected". + let p = product(CatalogWays { + remote: Some((&r, None)), + knowledge: Some(&mine), + ..Default::default() + }); + assert_eq!(p.card.status, "connected"); + assert_eq!(use_state(&p, Use::Knowledge), "on"); + + // A key and a Knowledge sign-in that needs renewing. + let renew = signed_in(SourceKind::Sanity, Status::NeedsReconnect); + let p = product(CatalogWays { + key: Some(key_on()), + knowledge: Some(&renew), + ..Default::default() + }); + assert_eq!(p.card.status, "needs_reconnect"); + assert!(p.card.reason.starts_with("Runs and reviews still work.")); + } + + /// Figma: a sign-in through Coderhelm's app (`MCPSERVER#app-figma`), an + /// older record for Figma's own server (`MCPSERVER#figma`) and the old + /// switch (`PLUGIN#figma`). One card. + #[test] + fn figma_with_several_records_is_one_card() { + let ours = |status: &str| { + json!({ "status": status, "status_reason": "", "source": "coderhelm", + "connected_by": "ada@example.com", "connected_at": "2026-11-12T08:00:00Z" }) + }; + let product = |w: CatalogWays| catalog_product("figma", "Figma", &w); + let stale = remote("figma", "Figma", Status::NotConnected); + let old_switch = plugin_state(Some(false), false, None, "", false); + + // Signed in with Coderhelm's app; the other records change nothing. + let app = ours("connected"); + let p = product(CatalogWays { + own_app: Some(&app), + remote: Some((&stale, None)), + key: Some(old_switch.clone()), + ..Default::default() + }); + assert_eq!( + p.card, + cs("connected", "Signed in with Coderhelm's app.", "manage") + ); + assert_eq!(p.how, "Coderhelm's Figma app"); + assert_eq!(p.connected_by, "ada@example.com"); + assert_eq!(p.uses.len(), 1, "Figma has one use"); + + // A sign-in with the app started and never finished, beside the + // other unfinished records: not connected, one Connect. + let pending = ours("not_connected"); + let p = product(CatalogWays { + own_app: Some(&pending), + remote: Some((&stale, None)), + key: Some(old_switch), + ..Default::default() + }); + assert_eq!(p.card, cs("not_connected", "", "connect")); + + // The app sign-in has to be renewed: that is what agents use, so it + // shows even with a key saved. + let renew = ours("needs_reconnect"); + let p = product(CatalogWays { + own_app: Some(&renew), + key: Some(key_on()), + ..Default::default() + }); + assert_eq!( + (p.card.status, p.card.action), + ("needs_reconnect", "reconnect") + ); + + // The team's own app, saved but not signed in to, and a key that works. + let own = json!({ "status": "not_connected", "status_reason": "", "source": "own" }); + let p = product(CatalogWays { + own_app: Some(&own), + key: Some(key_on()), + ..Default::default() + }); + assert_eq!(p.card.status, "connected"); + assert_eq!(p.how, "a key"); + let p = product(CatalogWays { + own_app: Some(&own), + ..Default::default() + }); + assert_eq!( + p.card.reason, + "Your own app is saved. Connect it to sign in." + ); + } + + /// Sentry: the vendor's server and a key. + #[test] + fn sentry_with_a_sign_in_and_a_key() { + let product = |w: CatalogWays| catalog_product("sentry", "Sentry", &w); + let r = remote("sentry", "Sentry", Status::Connected); + let failed = remote("sentry", "Sentry", Status::Failed); + let p = product(CatalogWays { + remote: Some((&r, None)), + key: Some(plugin_state(Some(true), false, None, "", false)), + ..Default::default() + }); + assert_eq!(p.card, cs("connected", "", "manage")); + assert_eq!(p.uses.len(), 1); + // The sign-in agents would use stopped working: it shows. + let p = product(CatalogWays { + remote: Some((&failed, None)), + key: Some(key_on()), + ..Default::default() + }); + assert_eq!((p.card.status, p.card.action), ("error", "check_again")); + // Switched on with no credentials and no sign-in. + let p = product(CatalogWays { + key: Some(plugin_state(Some(true), false, None, "", false)), + ..Default::default() + }); + assert_eq!( + (p.card.status, p.card.action), + ("needs_credentials", "add_credentials") + ); + // No tools allowed yet is still said on the card. + let mut bare = remote("sentry", "Sentry", Status::Connected); + bare.allowed.clear(); + let p = product(CatalogWays { + remote: Some((&bare, None)), + ..Default::default() + }); + assert_eq!( + p.card.reason, + "No tools are allowed yet, so agents don't get it." + ); + } + + #[test] + fn google_drive_signed_in_for_knowledge_has_a_card() { + let k = signed_in(SourceKind::GoogleDrive, Status::Connected); + let p = product_state(&[Use::Knowledge], &[k.way()], &[]); + let v = product_card( + "google_drive", + "Google Drive", + "", + &p, + "", + KNOWLEDGE_HREF, + json!({}), + ); + assert_eq!(v["status"], "connected"); + assert_eq!(v["section"], "docs"); + assert_eq!(v["how"], "the team's Google sign-in"); + assert_eq!(v["connected_by"], "ada@example.com"); + assert_eq!(v["uses"][0]["id"], "knowledge"); + assert_eq!(v["uses"][0]["state"], "on"); + let renew = signed_in(SourceKind::GoogleDrive, Status::NeedsReconnect); + let p = product_state(&[Use::Knowledge], &[renew.way()], &[]); + assert_eq!( + (p.card.status, p.card.action), + ("needs_reconnect", "reconnect") + ); + // Every card carries the same fields, filled in or not. + let plain = card( + "github", + "GitHub", + "", + cs("connected", "", "manage"), + "", + "", + json!({}), + ); + assert_eq!(plain["uses"], json!([])); + assert_eq!(plain["connected_by"], ""); + } + + #[test] + fn a_knowledge_sign_in_says_whose_it_is() { + let json = signed_in(SourceKind::Confluence, Status::Connected).json(); + assert_eq!(json["server_id"], "ks-confluence"); + assert_eq!(json["kind"], "confluence"); + assert_eq!(json["status"], "connected"); + assert_eq!(json["personal"], false); + assert_eq!( + signed_in(SourceKind::Sanity, Status::Connected).json()["personal"], + true + ); + for id in ["confluence", "notion", "sanity", "google_drive"] { + assert!(knowledge_kind(id).is_some(), "{id}"); + } + assert!(knowledge_kind("figma").is_none()); + assert!(knowledge_kind("sentry").is_none()); + } + #[test] fn remote_servers_show_the_viewers_own_connection() { use common::mcp_remote::store::{ diff --git a/services/gateway/src/routes/knowledge_sources.rs b/services/gateway/src/routes/knowledge_sources.rs index c26dab106..78d487db5 100644 --- a/services/gateway/src/routes/knowledge_sources.rs +++ b/services/gateway/src/routes/knowledge_sources.rs @@ -454,11 +454,17 @@ pub async fn connectors( } /// The `return_to` a sign-in start may send (`{"return_to": "/knowledge/..."}`): -/// a Knowledge page only, else nothing (the callback goes to Knowledge). +/// a Knowledge page, or the Integrations page (a sign-in renewed from the +/// product's card there), else nothing (the callback goes to Knowledge). pub fn return_to_of(body: &[u8]) -> String { let v: Value = serde_json::from_slice(body).unwrap_or_default(); let p = common::mcp_remote::oauth::clean_return_path(v["return_to"].as_str().unwrap_or("")); - if p == "/knowledge" || p.starts_with("/knowledge/") || p.starts_with("/knowledge?") { + let under = |root: &str| { + p == root + || p.strip_prefix(root) + .is_some_and(|rest| rest.starts_with(['/', '?', '#'])) + }; + if under("/knowledge") || under("/settings/integrations") { p } else { String::new() @@ -520,7 +526,11 @@ pub async fn connect( oauth::StartError::Refused(e) => fail(StatusCode::BAD_REQUEST, &e), })?; info!(team = %claims.team_id, kind = kind.key(), "Knowledge sign-in started"); - Ok(Json(json!({ "authorize_url": url }))) + Ok(Json(json!({ + "authorize_url": url, + "server_id": oauth::connection_id(kind), + "expires_in": super::mcp_servers::SIGN_IN_SECS, + }))) } /// Starts `claims`' own sign-in to `kind` through its remote MCP server, on @@ -2352,6 +2362,12 @@ mod tests { assert_eq!(r(r#"{"return_to":"/settings/"}"#), ""); assert_eq!(r(r#"{"return_to":"//evil.example/knowledge/"}"#), ""); assert_eq!(r(r#"{"return_to":"/knowledgeX"}"#), ""); + // A sign-in renewed from the product's card goes back to that card. + assert_eq!( + r(r#"{"return_to":"/settings/integrations/#integration-confluence"}"#), + "/settings/integrations/#integration-confluence" + ); + assert_eq!(r(r#"{"return_to":"/settings/integrationsX"}"#), ""); assert_eq!(r(""), "", "an older dashboard sends no body"); } diff --git a/services/gateway/src/routes/mcp_servers.rs b/services/gateway/src/routes/mcp_servers.rs index fd2466edb..e447b5348 100644 --- a/services/gateway/src/routes/mcp_servers.rs +++ b/services/gateway/src/routes/mcp_servers.rs @@ -715,10 +715,16 @@ pub async fn connect_coderhelm_app( info!(team = %rt.team, server = %s.id, brokered = brokered.is_some(), "CoderHelm app sign-in started"); Ok(Json(json!({ "authorize_url": url, + "server_id": s.id, + "expires_in": SIGN_IN_SECS, "own_app": own_app_json(&state, &rt, &s).await, }))) } +/// How long a started sign-in can still be finished, for the page that +/// waits on it: after this it says the sign-in timed out. +pub const SIGN_IN_SECS: i64 = common::mcp_remote::store::PENDING_TTL_SECS; + /// PUT /api/mcp-servers/:id/key { header_name?, header_value } — replace a /// static key (checked against the server before it is saved). pub async fn set_key( @@ -817,7 +823,31 @@ pub async fn connect( fail(StatusCode::BAD_REQUEST, &with_key_help(&e, &s.id)) })?; info!(team = %rt.team, server = %s.id, owner = %owner.key(), "MCP sign-in started"); - Ok(Json(json!({ "authorize_url": url }))) + Ok(Json(json!({ + "authorize_url": url, + "server_id": s.id, + "expires_in": SIGN_IN_SECS, + }))) +} + +/// DELETE /api/mcp-servers/:id/sign-in — cancel the sign-ins this person +/// started for a connection and didn't finish (an MCP server, a catalog +/// app `app-`, a knowledge source `ks-`). Their `state` stops +/// working at once, so an answer that arrives later is refused. Nothing +/// that is connected changes. +pub async fn cancel_sign_in( + State(state): State>, + Extension(claims): Extension, + Path(id): Path, +) -> Reply { + claims.require_role(1).map_err(member_only)?; + if id.is_empty() || id.len() > 200 { + return Err(fail(StatusCode::NOT_FOUND, "That server isn't set up.")); + } + let rt = runtime(&state, &claims.team_id); + let cancelled = rt.end_pending(&id, None, Some(&claims.sub)).await; + info!(team = %rt.team, server = %id, cancelled, "Sign-in cancelled"); + Ok(Json(json!({ "cancelled": cancelled }))) } /// POST /api/mcp-servers/oauth/callback { state, code?, error?, error_description?, iss? } diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 10c0686a0..a16a9aa34 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -37,6 +37,7 @@ pub mod infra_security; pub mod infrastructure; pub mod install_progress; pub mod installation_owner; +pub mod integration_status; pub mod integrations; pub mod jira_webhook; pub mod knowledge; diff --git a/services/worker/src/passes/ops_tools.rs b/services/worker/src/passes/ops_tools.rs index ee01b6559..07f508c24 100644 --- a/services/worker/src/passes/ops_tools.rs +++ b/services/worker/src/passes/ops_tools.rs @@ -44,9 +44,11 @@ const RESULT_CHARS: usize = 12_000; struct Loaded { conn: Connector, /// The opened key (New Relic, Confluence); empty for AWS ones. For - /// Confluence through the Jira app, the app's shared secret. + /// Confluence through the Jira app, the app's shared secret; with the + /// team's Atlassian sign-in, its `Bearer` header. key: String, - /// Confluence through the Jira app: the app's Confluence trigger. + /// Confluence through the Jira app: the app's Confluence trigger. With + /// the team's Atlassian sign-in: where its REST API is. app_url: String, } @@ -402,7 +404,13 @@ fn describe_line(c: &Connector) -> String { ConnKind::Confluence => format!( "Confluence at {}{}: search and read pages, list a page's children{}{}", c.site, - if c.via_jira_app() { " (through the Jira app)" } else { "" }, + if c.via_jira_app() { + " (through the Jira app)" + } else if c.via_sign_in() { + " (with the team's Atlassian sign-in, reading only)" + } else { + "" + }, if c.spaces.is_empty() { String::new() } else { format!(" in spaces {}", c.spaces.join(", ")) }, if c.write_enabled && !c.write_pages.is_empty() { format!("; may append to pages {}", c.write_pages.join(", ")) @@ -511,6 +519,26 @@ impl OpsTools { } continue; } + if conn.via_sign_in() { + // Confluence with the sign-in the team made for + // Knowledge: no key, opened for this pass. + match common::live::atlassian::confluence( + &sign_in_runtime(state, team_id), + &conn.site, + ) + .await + { + Ok(a) => loaded.push(Loaded { + conn, + key: a.bearer, + app_url: a.base, + }), + Err(e) => { + warn!(error = %e, "Could not open the team's Atlassian sign-in; skipping Confluence") + } + } + continue; + } let key = match secret::open(&state.kms, team_id, &conn.key_sealed).await { Ok(k) => k, Err(e) => { @@ -1111,6 +1139,11 @@ impl OpsTools { url: &l.app_url, secret: &l.key, } + } else if l.conn.via_sign_in() { + Access::SignIn { + base: &l.app_url, + bearer: &l.key, + } } else { Access::Token(&l.key) }, @@ -1223,6 +1256,23 @@ fn pick_named<'a>( )) } +/// Where the team's sign-ins are kept, to open the one a Confluence +/// connection reads with. +fn sign_in_runtime(state: &WorkerState, team_id: &str) -> common::mcp_remote::runtime::Runtime { + let table = if state.config.mcp_configs_table_name.is_empty() { + &state.config.settings_table_name + } else { + &state.config.mcp_configs_table_name + }; + common::mcp_remote::runtime::Runtime::aws( + state.dynamo.clone(), + table, + state.kms.clone(), + &state.config.secrets_key_id, + team_id, + ) +} + /// The team's connections, with Confluence through its Jira app folded in. async fn team_connections(state: &WorkerState, team_id: &str) -> Vec { jira_app::list_connectors(