diff --git a/crates/devstack-hub/src/pool.rs b/crates/devstack-hub/src/pool.rs index a1900b8c..ac34e291 100644 --- a/crates/devstack-hub/src/pool.rs +++ b/crates/devstack-hub/src/pool.rs @@ -578,11 +578,17 @@ pub async fn role( } } +/// The pool's upstreams as the dashboard shows them: a client secret only +/// as `true`. +fn redacted(v: &[devstack_node::upstreams::PoolUpstream]) -> Json> { + Json(v.iter().map(|u| u.redacted()).collect()) +} + /// `GET /hub/pool/upstreams`: the MCP upstreams the pool names for its /// members (ADR-0069 option B). pub async fn upstreams(Query(q): Query) -> Response { match blocking(&q, |l| l.upstreams()).await { - Ok(v) => Json(v).into_response(), + Ok(v) => redacted(&v).into_response(), Err(e) => error(&e), } } @@ -603,7 +609,7 @@ pub async fn upstream_put( match blocking(&q, move |l| l.admin_upstream_put(&u)).await { Ok(v) => { refresh(&s); - Json(v).into_response() + redacted(&v).into_response() } Err(e) => error(&e), } diff --git a/crates/devstack-hub/src/upstreams.rs b/crates/devstack-hub/src/upstreams.rs index 513925bb..5addef3f 100644 --- a/crates/devstack-hub/src/upstreams.rs +++ b/crates/devstack-hub/src/upstreams.rs @@ -14,11 +14,19 @@ //! upstream as `resource` (RFC 8707). The browser comes back to the hub's //! own loopback port; a callback is taken only for a flow the hub started, //! by its one-time `state`, within ten minutes. No route hands a token out. +//! - **A client secret** (review card approved 2026-10-30): for an +//! authorization server that wants one even with PKCE (GitHub), an +//! upstream with a client id may have the secret of an app registered for +//! desktop clients (RFC 8252 §8.5: not confidential by nature). The hub +//! sends it only to the token endpoint. The user's own goes into the +//! secrets store, a pool's comes with its list; no route gives it out +//! ([`ClientSecret`] serialises as `true`). //! - **A pool's upstreams** (ADR-0069 option B; review card approved //! 2026-10-28): each pool this machine is an approved member of may name -//! upstreams (URL only, never a secret). The hub keeps the last list it got -//! in `pool-upstreams.json` and offers them in the dashboard; one is used, -//! as `:`, only once the user accepted it at its URL. The +//! upstreams (URL only, no credential but an OAuth app's client secret). +//! The hub keeps the last list it got in `pool-upstreams.json` and offers +//! them in the dashboard; one is used, as `:`, only once the +//! user accepted it at its URL. The //! user's own configuration goes first: an entry with the name or prefix //! of one of theirs is not taken, nor two entries of different pools with //! one prefix until the user gives one another. An entry the pool drops, @@ -90,15 +98,67 @@ pub enum Auth { env: Option, }, /// The hub's OAuth login. `client_id` where the authorization server - /// does not register clients itself. + /// does not register clients itself, `client_secret` with it where the + /// server wants one even with PKCE. Oauth { #[serde(default, skip_serializing_if = "Option::is_none")] client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + client_secret: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] scopes: Vec, }, } +/// An OAuth app's client secret: taken as its value, never given out. +/// Written (to the dashboard, to `upstreams.toml`) it is `true`: one is set. +/// Read, `true` is [`ClientSecret::Set`], a string its value, and an empty +/// string or `false` takes the one set away. +#[derive(Clone, PartialEq, Eq)] +pub enum ClientSecret { + /// One is set: for the user's own upstream, in the secrets store. + Set, + /// The value: as the user gave it (before the hub keeps it), or a pool's. + Value(String), +} + +impl std::fmt::Debug for ClientSecret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ClientSecret(..)") + } +} + +impl Serialize for ClientSecret { + fn serialize(&self, s: S) -> Result { + s.serialize_bool(true) + } +} + +impl<'de> Deserialize<'de> for ClientSecret { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Flag(bool), + Value(String), + } + Ok(match Raw::deserialize(d)? { + Raw::Flag(true) => Self::Set, + Raw::Flag(false) => Self::Value(String::new()), + Raw::Value(v) => Self::Value(v), + }) + } +} + +/// At most this long, a client secret. +const SECRET_MAX: usize = 1024; + +/// Where the secrets store keeps the client secret of the user's upstream +/// `name`: beside its login, which logging out forgets. +fn client_key(name: &str) -> String { + format!("{name}#client") +} + impl Upstream { /// It is a command the hub starts (stdio), not a URL. pub fn is_command(&self) -> bool { @@ -176,6 +236,23 @@ impl Upstream { { return Err(format!("`{e}`: not the name of an environment variable")); } + if let Auth::Oauth { + client_id, + client_secret: Some(c), + .. + } = &self.auth + { + if client_id.is_none() { + return Err("a client secret comes with its client id".into()); + } + if let ClientSecret::Value(v) = c + && (v.len() > SECRET_MAX || v.chars().any(char::is_whitespace)) + { + return Err(format!( + "a client secret is up to {SECRET_MAX} characters without spaces" + )); + } + } Ok(()) } } @@ -246,6 +323,9 @@ enum Secret { #[serde(default)] expires_at: Option, client_id: String, + /// The client secret it logged in with, for its refresh. + #[serde(default, skip_serializing_if = "Option::is_none")] + client_secret: Option, token_endpoint: String, resource: String, }, @@ -259,6 +339,7 @@ struct Flow { upstream: String, verifier: String, client_id: String, + client_secret: Option, token_endpoint: String, resource: String, redirect: String, @@ -484,8 +565,13 @@ impl Upstreams { let auth = match &e.auth { PoolAuth::None => Auth::None, PoolAuth::Token => Auth::Token { env: None }, - PoolAuth::Oauth { client_id, scopes } => Auth::Oauth { + PoolAuth::Oauth { + client_id, + client_secret, + scopes, + } => Auth::Oauth { client_id: client_id.clone(), + client_secret: client_secret.clone().map(ClientSecret::Value), scopes: scopes.clone(), }, }; @@ -690,12 +776,54 @@ impl Upstreams { } /// Add `u`, or replace the one of its name. A change of its URL or of how - /// it logs in forgets its credential: it was for the other. - pub fn put(&self, u: Upstream) -> Result<(), String> { - u.check()?; + /// it logs in forgets its credential: it was for the other. A client + /// secret given goes into the secrets store; a change without one keeps + /// the one set, an empty one takes it away. + pub fn put(&self, mut u: Upstream) -> Result<(), String> { let name = u.name.clone(); let _one = self.write.lock().unwrap(); let mut all = self.own()?; + let had = all.iter().any(|o| { + o.name == name + && matches!( + o.auth, + Auth::Oauth { + client_secret: Some(_), + .. + } + ) + }); + // The one to keep now, if one is given. + let mut given = None; + if let Auth::Oauth { client_secret, .. } = &mut u.auth { + *client_secret = match client_secret.take() { + Some(ClientSecret::Value(v)) if v.is_empty() => None, + Some(ClientSecret::Value(v)) => { + given = Some(v.clone()); + Some(ClientSecret::Value(v)) + } + Some(ClientSecret::Set) | None if had => Some(ClientSecret::Set), + Some(ClientSecret::Set) | None => None, + }; + } + u.check()?; + let keeps = matches!( + u.auth, + Auth::Oauth { + client_secret: Some(_), + .. + } + ); + match given { + Some(v) => { + self.secrets.set(&client_key(&name), &v)?; + if let Auth::Oauth { client_secret, .. } = &mut u.auth { + *client_secret = Some(ClientSecret::Set); + } + } + None if !keeps => self.secrets.delete(&client_key(&name))?, + None => {} + } if all .iter() .any(|o| o.name != u.name && o.prefix() == u.prefix()) @@ -729,6 +857,7 @@ impl Upstreams { } self.procs.lock().unwrap().remove(name); self.secrets.delete(name)?; + self.secrets.delete(&client_key(name))?; self.save(&all)?; Ok(true) } @@ -775,9 +904,23 @@ impl Upstreams { /// browser to; `redirect` is the hub's callback (`CALLBACK` on its port). pub fn begin(&self, http: &ureq::Agent, name: &str, redirect: &str) -> Result { let u = self.get(name)?; - let Auth::Oauth { client_id, scopes } = &u.auth else { + let Auth::Oauth { + client_id, + client_secret, + scopes, + } = &u.auth + else { return Err(format!("`{name}` does not log in with OAuth")); }; + let client_secret = match client_secret { + Some(ClientSecret::Value(v)) => Some(v.clone()), + Some(ClientSecret::Set) => { + Some(self.secrets.get(&client_key(name))?.ok_or_else(|| { + format!("the client secret of `{name}` is gone: give it again") + })?) + } + None => None, + }; let server = discover(http, &u.url)?; let client_id = match (client_id, &server.registration_endpoint) { (Some(c), _) => c.clone(), @@ -814,6 +957,7 @@ impl Upstreams { upstream: name.to_string(), verifier, client_id, + client_secret, token_endpoint: server.token_endpoint, resource: server.resource, redirect: redirect.to_string(), @@ -833,18 +977,18 @@ impl Upstreams { flows.remove(state) } .ok_or("no login of this hub waits for that answer (started elsewhere, used, or older than ten minutes)")?; - let t = token_request( - http, - &flow.token_endpoint, - &[ - ("grant_type", "authorization_code"), - ("code", code), - ("redirect_uri", &flow.redirect), - ("client_id", &flow.client_id), - ("code_verifier", &flow.verifier), - ("resource", &flow.resource), - ], - )?; + let mut form = vec![ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", flow.redirect.as_str()), + ("client_id", flow.client_id.as_str()), + ("code_verifier", flow.verifier.as_str()), + ("resource", flow.resource.as_str()), + ]; + if let Some(c) = &flow.client_secret { + form.push(("client_secret", c)); + } + let t = token_request(http, &flow.token_endpoint, &form)?; self.put_secret( &flow.upstream, &Secret::Oauth { @@ -852,6 +996,7 @@ impl Upstreams { refresh_token: t.refresh_token, expires_at: t.expires_in.map(|s| now_s() + s), client_id: flow.client_id, + client_secret: flow.client_secret, token_endpoint: flow.token_endpoint, resource: flow.resource, }, @@ -884,6 +1029,7 @@ impl Upstreams { refresh_token, expires_at, client_id, + client_secret, token_endpoint, resource, } => { @@ -891,16 +1037,16 @@ impl Upstreams { let Some(refresh) = refresh_token.filter(|_| due || stale) else { return Ok(Some(access_token)); }; - let t = token_request( - http, - &token_endpoint, - &[ - ("grant_type", "refresh_token"), - ("refresh_token", &refresh), - ("client_id", &client_id), - ("resource", &resource), - ], - )?; + let mut form = vec![ + ("grant_type", "refresh_token"), + ("refresh_token", refresh.as_str()), + ("client_id", client_id.as_str()), + ("resource", resource.as_str()), + ]; + if let Some(c) = &client_secret { + form.push(("client_secret", c)); + } + let t = token_request(http, &token_endpoint, &form)?; let access = t.access_token.clone(); self.put_secret( name, @@ -910,6 +1056,7 @@ impl Upstreams { refresh_token: t.refresh_token.or(Some(refresh)), expires_at: t.expires_in.map(|s| now_s() + s), client_id, + client_secret, token_endpoint, resource, }, @@ -1363,12 +1510,13 @@ fn token_request( .send(body.join("&")) .map_err(|e| format!("{endpoint}: {e}"))?; let text = r.body_mut().read_to_string().unwrap_or_default(); - if r.status() != 200 { - // The server's error, never the request: it held the code. - let why = serde_json::from_str::(&text) - .ok() - .and_then(|v| v["error"].as_str().map(str::to_string)) - .unwrap_or_else(|| r.status().to_string()); + // The server's error, never the request: it held the code. GitHub + // answers one with `200`. + let error = serde_json::from_str::(&text) + .ok() + .and_then(|v| v["error"].as_str().map(str::to_string)); + if r.status() != 200 || error.is_some() { + let why = error.unwrap_or_else(|| r.status().to_string()); return Err(format!("{endpoint} refused: {why}")); } serde_json::from_str(&text).map_err(|e| format!("{endpoint}: {e}")) @@ -1541,6 +1689,11 @@ mod tests { serde_json::json!({ "access_token": "access-1", "refresh_token": "refresh-1", "expires_in": 30 }), ) } + // GitHub's way to refuse. + "/auth/token" if body.contains("code=refused-with-200") => ( + 200, + serde_json::json!({ "error": "incorrect_client_credentials" }), + ), "/auth/token" if body.contains("grant_type=refresh_token") => ( 200, serde_json::json!({ "access_token": "access-2", "refresh_token": "refresh-2", "expires_in": 3600 }), @@ -1572,6 +1725,7 @@ mod tests { allow: Vec::new(), auth: Auth::Oauth { client_id: None, + client_secret: None, scopes: Vec::new(), }, ..Default::default() @@ -1628,6 +1782,119 @@ mod tests { let _ = ups.remove(&name); } + #[test] + fn a_client_secret_goes_to_the_token_endpoint_only_and_is_never_shown() { + let (base, seen) = fake_server(); + let d = tempfile::tempdir().unwrap(); + let ups = Upstreams::for_test(d.path().to_path_buf(), Vec::new); + let name = format!("s{}", std::process::id()); + let mut u = Upstream { + name: name.clone(), + url: format!("{base}/mcp"), + auth: Auth::Oauth { + client_id: Some("the-app".into()), + client_secret: Some(ClientSecret::Value("app-secret".into())), + scopes: Vec::new(), + }, + ..Default::default() + }; + ups.put(u.clone()).unwrap(); + let text = std::fs::read_to_string(d.path().join("upstreams.toml")).unwrap(); + assert!( + text.contains("client_secret = true") && !text.contains("app-secret"), + "{text}" + ); + let shown = serde_json::to_string(&ups.views().unwrap()).unwrap(); + assert!( + shown.contains(r#""client_secret":true"#) && !shown.contains("app-secret"), + "{shown}" + ); + assert!(!format!("{:?}", ups.list().unwrap()).contains("app-secret")); + // A change without it (as the dashboard sends one) keeps it. + if let Auth::Oauth { client_secret, .. } = &mut u.auth { + *client_secret = None; + } + u.allow = vec!["search".into()]; + ups.put(u.clone()).unwrap(); + + let http = http(); + let redirect = "http://127.0.0.1:4250/oauth/upstream/callback"; + let url = ups.begin(&http, &name, redirect).unwrap(); + assert!( + url.contains("client_id=the-app") && !url.contains("app-secret"), + "{url}" + ); + let state_of = |url: &str| { + let s = url.split("state=").nth(1).unwrap(); + s.split('&').next().unwrap().to_string() + }; + // A refusal with `200` (GitHub's) is a refusal, with its reason. + let refused = ups.begin(&http, &name, redirect).unwrap(); + let why = ups + .complete(&http, &state_of(&refused), "refused-with-200") + .unwrap_err(); + assert!(why.contains("incorrect_client_credentials"), "{why}"); + ups.complete(&http, &state_of(&url), "the-code").unwrap(); + assert_eq!( + ups.bearer(&http, &name, false).unwrap().as_deref(), + Some("access-2") + ); + let sent = seen.lock().unwrap().clone(); + assert!(!sent.iter().any(|(p, _)| p == "/auth/register")); + let with: Vec<_> = sent + .iter() + .filter(|(_, b)| b.contains("client_secret=app-secret") && !b.contains("refused")) + .map(|(p, b)| (p.as_str(), b.split('&').next().unwrap())) + .collect(); + assert_eq!( + with, + [ + ("/auth/token", "grant_type=authorization_code"), + ("/auth/token", "grant_type=refresh_token") + ] + ); + // Logging out keeps it; an empty one takes it away. + ups.logout(&name).unwrap(); + assert!(ups.secrets.get(&client_key(&name)).unwrap().is_some()); + if let Auth::Oauth { client_secret, .. } = &mut u.auth { + *client_secret = Some(ClientSecret::Value(String::new())); + } + ups.put(u).unwrap(); + assert!(ups.secrets.get(&client_key(&name)).unwrap().is_none()); + assert!( + !serde_json::to_string(&ups.views().unwrap()) + .unwrap() + .contains("client_secret") + ); + let _ = ups.remove(&name); + } + + #[test] + fn a_pools_client_secret_is_used_and_shown_as_set() { + let mut e = entry("gh", "https://gh.example.com/mcp", None); + e.auth = PoolAuth::Oauth { + client_id: Some("the-app".into()), + client_secret: Some("pool-secret".into()), + scopes: vec!["repo".into()], + }; + let d = tempfile::tempdir().unwrap(); + let ups = Upstreams::for_test(d.path().to_path_buf(), move || { + vec![("team".into(), Some(vec![e.clone()]))] + }); + ups.refresh_pools(); + let shown = serde_json::to_string(&ups.views().unwrap()).unwrap(); + assert!( + shown.contains(r#""client_secret":true"#) && !shown.contains("pool-secret"), + "{shown}" + ); + ups.accept("team", "gh", None).unwrap(); + let u = ups.get("team:gh").unwrap(); + assert!(matches!( + u.auth, + Auth::Oauth { client_secret: Some(ClientSecret::Value(ref v)), .. } if v == "pool-secret" + )); + } + /// An MCP server over Streamable HTTP that wants `Bearer good`: a /// session, `search` and `drop`, `tools/call` answered as an event /// stream. What each request named as its method. @@ -1809,6 +2076,7 @@ mod tests { let mut bad = cmd.clone(); bad.auth = Auth::Oauth { client_id: None, + client_secret: None, scopes: Vec::new(), }; assert!(ups.put(bad).is_err()); diff --git a/crates/devstack-node/src/coordinator.rs b/crates/devstack-node/src/coordinator.rs index afd83305..b3da52c3 100644 --- a/crates/devstack-node/src/coordinator.rs +++ b/crates/devstack-node/src/coordinator.rs @@ -3463,7 +3463,8 @@ async fn admin_role( } /// `GET /v1/upstreams`: the MCP upstreams this pool names for its members -/// (ADR-0069 option B), never a secret. +/// (ADR-0069 option B), with an OAuth app's client secret where one is set +/// (the members' hubs log in with it; never a user's credential). async fn upstreams_list( AxState(s): AxState, Extension(peer): Extension, diff --git a/crates/devstack-node/src/upstreams.rs b/crates/devstack-node/src/upstreams.rs index 329b8fd8..9fb50262 100644 --- a/crates/devstack-node/src/upstreams.rs +++ b/crates/devstack-node/src/upstreams.rs @@ -1,12 +1,17 @@ //! The MCP upstreams a pool names for its members (ADR-0069, option B; //! review card approved 2026-10-28): what each member's hub may offer its -//! user, never a secret. The member's hub logs in itself and uses an entry -//! only once its user accepted it. +//! user. The member's hub logs in itself and uses an entry only once its +//! user accepted it. //! //! - **URL only** (card point 2): an entry is never a command, so a pool's //! admin cannot run anything on a member's machine. //! - **No credential, no variable**: an entry says how its upstream logs in //! (OAuth, a token the member gives its own hub, or none), not with what. +//! The one exception (review card approved 2026-10-30): the client secret +//! of an OAuth app registered for desktop clients, for an authorization +//! server that wants one even with PKCE (GitHub). Such a secret is not +//! confidential by nature (RFC 8252 §8.5); members get it with the list, +//! and nothing that shows the list shows it ([`PoolUpstream::redacted`]). //! - Kept in `upstreams.json` in the coordinator's directory; every change //! in the audit log (card point 5). @@ -47,15 +52,21 @@ pub enum PoolAuth { /// A static bearer token each member gives their own hub. Token, /// The hub's OAuth login. `client_id` (public) where the authorization - /// server does not register clients itself. + /// server does not register clients itself, `client_secret` with it + /// where the server wants one even with PKCE. Oauth { #[serde(default, skip_serializing_if = "Option::is_none")] client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + client_secret: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] scopes: Vec, }, } +/// At most this long, a client secret. +const SECRET_MAX: usize = 1024; + impl PoolUpstream { pub fn prefix(&self) -> String { self.prefix @@ -96,8 +107,34 @@ impl PoolUpstream { "the tool allowlist names 1 to 128 characters per tool, 256 at most".into(), ); } + if let PoolAuth::Oauth { + client_id, + client_secret: Some(c), + .. + } = &self.auth + && !c.is_empty() + { + if client_id.is_none() { + return Err("a client secret comes with its client id".into()); + } + if c.len() > SECRET_MAX || c.chars().any(char::is_whitespace) { + return Err(format!( + "a client secret is up to {SECRET_MAX} characters without spaces" + )); + } + } Ok(()) } + + /// The entry as the dashboard and the CLI show it: a client secret + /// only as `true` (one is set). + pub fn redacted(&self) -> serde_json::Value { + let mut v = serde_json::to_value(self).expect("an entry serialises"); + if let Some(c) = v["auth"].get_mut("client_secret") { + *c = serde_json::Value::Bool(true); + } + v + } } #[derive(Debug, Default, Serialize, Deserialize)] @@ -129,11 +166,28 @@ fn save(dir: &Path, all: &[PoolUpstream]) -> std::io::Result<()> { }) } -/// Add `u` to the list in `dir`, or replace the entry of its name. `Err` -/// with why not (the caller's mistake), or an I/O error as `Ok(Err)`. -pub fn put(dir: &Path, u: PoolUpstream) -> Result, String> { - u.check()?; +/// Add `u` to the list in `dir`, or replace the entry of its name. A +/// change without a client secret keeps the one set (the dashboard never +/// has it to send back); an empty one takes it away. `Err` with why not +/// (the caller's mistake), or an I/O error as `Ok(Err)`. +pub fn put(dir: &Path, mut u: PoolUpstream) -> Result, String> { let mut all = load(dir); + if let PoolAuth::Oauth { client_secret, .. } = &mut u.auth { + match client_secret.as_deref() { + Some("") => *client_secret = None, + Some(_) => {} + None => { + *client_secret = + all.iter() + .find(|o| o.name == u.name) + .and_then(|o| match &o.auth { + PoolAuth::Oauth { client_secret, .. } => client_secret.clone(), + _ => None, + }); + } + } + } + u.check()?; if all .iter() .any(|o| o.name != u.name && o.prefix() == u.prefix()) @@ -172,12 +226,62 @@ mod tests { url: url.into(), auth: PoolAuth::Oauth { client_id: None, + client_secret: None, scopes: Vec::new(), }, ..Default::default() } } + fn with_secret(u: &mut PoolUpstream, secret: Option<&str>) { + u.auth = PoolAuth::Oauth { + client_id: Some("app".into()), + client_secret: secret.map(str::to_string), + scopes: Vec::new(), + }; + } + + fn secret_of(dir: &Path) -> Option { + match &load(dir)[0].auth { + PoolAuth::Oauth { client_secret, .. } => client_secret.clone(), + _ => None, + } + } + + #[test] + fn a_client_secret_is_kept_across_a_change_without_one_and_never_shown() { + let dir = tempfile::tempdir().unwrap(); + let mut u = up("gh", "https://a.example.com/mcp"); + with_secret(&mut u, Some("s3cret")); + put(dir.path(), u.clone()).unwrap().unwrap(); + assert_eq!(secret_of(dir.path()).as_deref(), Some("s3cret")); + // The dashboard sends the entry back without it. + u.url = "https://b.example.com/mcp".into(); + with_secret(&mut u, None); + put(dir.path(), u.clone()).unwrap().unwrap(); + assert_eq!(secret_of(dir.path()).as_deref(), Some("s3cret")); + let shown = load(dir.path())[0].redacted(); + assert_eq!(shown["auth"]["client_secret"], true); + assert!(!shown.to_string().contains("s3cret")); + // An empty one takes it away. + with_secret(&mut u, Some("")); + put(dir.path(), u.clone()).unwrap().unwrap(); + assert_eq!(secret_of(dir.path()), None); + assert!( + load(dir.path())[0].redacted()["auth"] + .get("client_secret") + .is_none() + ); + // Without a client id, none. + let mut bare = up("x", "https://x.example.com/mcp"); + bare.auth = PoolAuth::Oauth { + client_id: None, + client_secret: Some("s".into()), + scopes: Vec::new(), + }; + assert!(put(dir.path(), bare).unwrap_err().contains("client id")); + } + #[test] fn an_entry_is_reached_over_https_and_never_on_the_members_machine() { assert!(up("wiki", "https://wiki.example.com/mcp").check().is_ok()); diff --git a/crates/devstack-node/tests/events.rs b/crates/devstack-node/tests/events.rs index b648c87f..77004500 100644 --- a/crates/devstack-node/tests/events.rs +++ b/crates/devstack-node/tests/events.rs @@ -98,6 +98,7 @@ fn a_member_hears_every_part_first_then_what_changed_and_the_end_when_removed() url: "https://wiki.example.com/mcp".into(), auth: PoolAuth::Oauth { client_id: None, + client_secret: None, scopes: Vec::new(), }, ..Default::default() diff --git a/crates/devstack-node/tests/upstreams.rs b/crates/devstack-node/tests/upstreams.rs index b8a83393..d3e3fc78 100644 --- a/crates/devstack-node/tests/upstreams.rs +++ b/crates/devstack-node/tests/upstreams.rs @@ -42,6 +42,7 @@ fn wiki(url: &str) -> PoolUpstream { url: url.into(), auth: PoolAuth::Oauth { client_id: None, + client_secret: None, scopes: Vec::new(), }, ..Default::default() diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index 4371b596..eab7d00e 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -389,6 +389,14 @@ enum PoolUpstreamsAction { /// The OAuth client id, where the server registers no clients itself. #[arg(long)] client_id: Option, + /// The client secret of that app, where the server wants one even + /// with PKCE (GitHub); members get it with the list. Left out on a + /// change: the one set stays; `""`: none. + #[arg(long)] + client_secret: Option, + /// The OAuth scopes the login asks for, comma-separated. + #[arg(long = "scope", value_delimiter = ',')] + scopes: Vec, }, /// Take an upstream off the pool's list. Remove { name: String }, @@ -1073,6 +1081,11 @@ mod tests { Cmd::Pool { action: Some(PoolAction::Upstreams { action: Some(PoolUpstreamsAction::Add { name, allow, login, .. }) }), .. } if name == "wiki" && allow == ["search", "get"] && login == "oauth" )); + assert!(matches!( + parse(&["pool", "upstreams", "add", "gh", "https://gh.example.com/mcp", "--client-id", "app", "--client-secret", "s", "--scope", "repo,read:org"]).cmd, + Cmd::Pool { action: Some(PoolAction::Upstreams { action: Some(PoolUpstreamsAction::Add { client_id: Some(c), client_secret: Some(s), scopes, .. }) }), .. } + if c == "app" && s == "s" && scopes == ["repo", "read:org"] + )); assert!(matches!( parse(&["pool", "skills", "add", "core", "--github", "org/skills", "--path", "skills", "--to", "team,*"]).cmd, Cmd::Pool { action: Some(PoolAction::Skills { action: Some(PoolSkillsAction::Add { name, github: Some(repo), reference, path, to, .. }) }), .. } diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index e6dce0e7..222109ed 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -1203,14 +1203,22 @@ pub fn upstreams(pool: &str, action: Option) -> Resu allow, login, client_id, + client_secret, + scopes, } => { let auth = match login.as_str() { "oauth" => PoolAuth::Oauth { client_id, - scopes: Vec::new(), + client_secret, + scopes: scopes + .into_iter() + .filter(|s| !s.trim().is_empty()) + .collect(), }, - "token" | "none" if client_id.is_some() => { - bail!("`--client-id` is for `--login oauth`") + "token" | "none" + if client_id.is_some() || client_secret.is_some() || !scopes.is_empty() => + { + bail!("`--client-id`, `--client-secret` and `--scope` are for `--login oauth`") } "token" => PoolAuth::Token, "none" => PoolAuth::None, @@ -1247,9 +1255,26 @@ pub fn upstreams(pool: &str, action: Option) -> Resu PoolAuth::None => "no login".to_string(), PoolAuth::Token => "a token each member gives".to_string(), PoolAuth::Oauth { - client_id: Some(c), .. - } => format!("OAuth (client id {c})"), - PoolAuth::Oauth { .. } => "OAuth".to_string(), + client_id, + client_secret, + scopes, + } => { + let mut about = Vec::new(); + if let Some(c) = client_id { + about.push(format!("client id {c}")); + } + if client_secret.is_some() { + about.push("a client secret".to_string()); + } + if !scopes.is_empty() { + about.push(format!("scopes {}", scopes.join(" "))); + } + if about.is_empty() { + "OAuth".to_string() + } else { + format!("OAuth ({})", about.join(", ")) + } + } }; let tools = if u.allow.is_empty() { "all tools".to_string() diff --git a/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md b/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md index 00d96b26..e7445849 100644 --- a/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md +++ b/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md @@ -1,6 +1,6 @@ # ADR-0069: `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub -- **Status:** Accepted (2026-10-27, [card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)); amended 2026-10-27 (the keychain spike: `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, card approved 2026-10-28) +- **Status:** Accepted (2026-10-27, [card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)); amended 2026-10-27 (the keychain spike: `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, card approved 2026-10-28); addendum 2026-10-30 (an OAuth app's client secret, card approved 2026-10-30) - **Date:** 2026-10-27 - **Deciders:** project owner - **Related:** [#316](https://github.com/nuetzliches/devstack/issues/316), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0019](0019-control-api-security.md), [ADR-0021](0021-a-hub-serves-the-dashboard.md), [ADR-0032](0032-the-pool-is-administered-in-the-dashboard.md), [ADR-0054](0054-macos-is-a-developer-platform-in-preview.md), [ADR-0060](0060-the-tray-is-a-client-of-the-hub.md), [ADR-0067](0067-a-change-at-runtime-says-who-made-it.md) @@ -193,6 +193,46 @@ its URL does. A pool names at most 64. Building it showed that the Windows Credential Manager loses writes and deletes made side by side from several threads: the hub now makes one keychain call at a time. +## Addendum 2026-10-30: an OAuth app's client secret + +GitHub's MCP server (`api.githubcopilot.com/mcp`) names its authorization +server (`github.com/login/oauth`, PKCE with S256), but GitHub registers no +clients itself and wants a client secret at its token endpoint even with +PKCE. Its review card was approved by the owner on 2026-10-30 (all four +points) and is in the description of the pull request that built it. + +1. **An OAuth upstream may carry a client secret**, with its client id, for + an authorization server that wants one even with PKCE. It is the secret + of an app registered for desktop clients, not confidential by nature + (RFC 8252 §8.5, as with the `gh` CLI), and the hub sends it only to the + token endpoint the upstream's metadata names (code exchange and + refresh). A device flow would need no secret, but a second login path + and its own UI; a personal access token per member would need no change, + but is kept by hand and never refreshed. +2. **On the user's own upstream it goes into the keychain**, never into + `upstreams.toml`; the API takes it and only ever answers whether one is + set. +3. **A pool may name one** with its client id: the coordinator gives it to + approved members with the list (`GET /v1/upstreams`), their hubs keep it + with the pool's list (`pool-upstreams.json`), and the dashboard, the CLI + and the audit log show only that one is set. This is the one exception + to point 1 of the 2026-10-28 addendum ("never a secret"). +4. **API and CLI:** `auth: {kind: "oauth", client_id?, client_secret?, + scopes?}` on write; reads answer `client_secret: true` instead of the + value; an edit without a secret keeps the one set, an empty one takes it + away; `devstack pool upstreams add --client-secret … --scope …`. + +Decided while building: the login the hub keeps holds the secret it logged +in with, for its refresh; logging out keeps the client secret, removing the +upstream or giving up OAuth drops it (a keychain entry `#client` +beside the login). A secret is up to 1024 characters without spaces. The +dashboard's forms gained the client secret and the scopes for both the +user's and a pool's upstreams; until now an edit there dropped the scopes. +GitHub refuses at its token endpoint with `200` and an `error`: the hub +takes any answer with an `error` as a refusal, with that reason. +An older coordinator drops the field on a change; an older member's hub +ignores it, and its login fails as before. + ## Enforced by `crates/devstack-hub/src/secrets.rs` (the store, with its test against diff --git a/docs/adr/README.md b/docs/adr/README.md index 2770234c..242f0b67 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -151,7 +151,7 @@ stay. | [0066](0066-a-measured-cpu-need-is-capped-at-half-of-what-its-node-gives-lanes.md) | A measured CPU need is capped at half of what its node gives lanes | Accepted | | [0067](0067-a-change-at-runtime-says-who-made-it.md) | A change at runtime says where it came from, and a journal keeps the last ones | Accepted; built 2026-10-27 (point 2 for the main slot and services); addendum 2026-10-27: the dashboard shows the journal | | [0068](0068-a-stop-takes-the-containers-too.md) | A stop takes the stack's containers too, unless asked to keep them | Accepted | -| [0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) | `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub | Accepted ([card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)): a proxy in the hub, per user; amended 2026-10-27 (keychain via `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, a member accepts each) | +| [0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) | `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub | Accepted ([card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)): a proxy in the hub, per user; amended 2026-10-27 (keychain via `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, a member accepts each); addendum 2026-10-30 (an OAuth app's client secret, for GitHub) | | [0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) | A review card comes before the code; an ADR records what was built | Accepted (supersedes ADR-0001); point 1 amended 2026-10-28 (the card in the conversation and the pull request, no issue) | | [0071](0071-the-dashboard-writes-no-file-of-a-repository.md) | The dashboard writes no file of a repository; a change to one is a prompt for a coding agent | Accepted | | [0072](0072-a-restart-is-warm-a-rebuild-or-cold.md) | A restart is warm, a rebuild or cold; a group acts on its containers too | Accepted ([card](https://github.com/nuetzliches/devstack/pull/351)) | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 07e78908..924a6676 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -84,8 +84,8 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/pool/history?node=&range=1h\|24h` | cookie | a node's capacity over time, or the pool's without `node` ([ADR-0036](adr/0036-the-pool-shows-its-capacity-over-time.md)): `[{at, total_cpus, total_memory, offered_cpus, offered_memory, used_cpus, used_memory, gpus, gpus_offered, gpu_load, gpu_memory, gpu_memory_used}]`; the last hour as reported (every 15 s), or with `range=24h` the last day by minute (any other `range` is the hour); kept by the coordinator in memory, since it started | | `GET /hub/pool/telemetry` | cookie | `{consent, collects, what}`: whether this machine agreed to send the pool telemetry, whether the pool collects it (its coordinator has a collector), and what is sent ([ADR-0037](adr/0037-telemetry-goes-to-the-pools-collector-with-consent.md)) | | `PUT /hub/pool/telemetry {"enabled"}` | cookie + Origin | agree to send it, or take it back; off until given, per pool | -| `GET /hub/pool/upstreams` | cookie | the MCP upstreams the pool names for its members: `[{name, url, prefix?, allow?, auth: {kind: "none"} \| {kind: "token"} \| {kind: "oauth", client_id?, scopes?}}]`, never a secret ([pool.md](pool.md#mcp-upstreams-for-the-members)) | -| `POST /hub/pool/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | admins only: add one, or change the one of that name; the list after it. `400` with why (a URL over `https://` only, a prefix another entry has, at most 64); the coordinator audits it | +| `GET /hub/pool/upstreams` | cookie | the MCP upstreams the pool names for its members: `[{name, url, prefix?, allow?, auth: {kind: "none"} \| {kind: "token"} \| {kind: "oauth", client_id?, client_secret?, scopes?}}]`, never a user's credential: an OAuth app's client secret is answered as `client_secret: true` (one is set; members' hubs get the value from the coordinator) ([pool.md](pool.md#mcp-upstreams-for-the-members)) | +| `POST /hub/pool/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | admins only: add one, or change the one of that name; the list after it. `auth.client_secret` (with a `client_id`): a string sets it, `""` takes it away, left out keeps the one set. `400` with why (a URL over `https://` only, a prefix another entry has, at most 64, a client secret without a client id); the coordinator audits it | | `DELETE /hub/pool/upstreams/{name}` | cookie + Origin | admins only: take one off the list: `204`, `404` when the pool names none such; audited | | `GET /hub/pool/skills` | cookie | admins only ([ADR-0074](adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md)): `{sets: [{name, source: {kind: "github", repo, ref, path} \| {kind: "folder", path}, to: [string], manifest: {source, fetched?, commit?, error?, skills: [{name, description, sha256, size, group?, tags?}], skipped?}}], github_token, refresh_signed}`; `404` from a coordinator before skill sets | | `POST /hub/pool/skills {name, source, to}` | cookie + Origin | admins only: add a set, or change the one of that name, and have it fetched; `400` with why; audited | @@ -101,13 +101,13 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/pool/shared/{lease}/connect` | cookie + Origin | connect to the lane ([ADR-0053](adr/0053-whoever-a-lane-is-shared-with-connects-to-it.md)): a forward on this machine to each service it shares with `http` or `https` that has none yet, through its node (which checks the sharing at every connection), on the owner's port `here` if free, else another; `{services: [{name, port, url}], warning?}` (`warning` as for `open`). It stays connected until `disconnect`, the hub stops, or the lane is no longer shared with this machine | | `POST /hub/pool/shared/{lease}/disconnect` | cookie + Origin | its forwards close, the connections through them too, the ports are free again; `{closed}`: how many (`0`: it was not connected) | | `POST /hub/pool/shared/{lease}/open {"service"}` | cookie + Origin | connect the lane if it is not (as `connect` does; ADR-0053 point 2), and answer for that service: `{url, port, warning?}`. Up to 0.19 it forwarded that service only, until the hub stopped. `warning`: the node runs another devstack than this machine or does not say which, or the owner's and the node's pool protocols differ ([ADR-0031](adr/0031-a-coordinator-places-lanes.md) point 8) `502` for a service shared with a scheme other than `http` or `https` | -| `GET /hub/upstreams` | cookie | the user's MCP upstreams ([ADR-0069](adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md)): `{store, upstreams: [{name, url?, command?, env?, token_var?, prefix, allow?, auth: {kind: "none"} \| {kind: "token", env?} \| {kind: "oauth", client_id?, scopes?}, logged_in, pool?}]}`, kept in `upstreams.toml` in the hub's state directory, never a secret. `store`: `keychain`, or `file` on a Linux machine without a Secret Service. The upstreams the machine's pools name follow the user's own, named `:`, with `pool: {pool, name, status, why?, pool_prefix}`: `status` `offered` (not answered), `accepted` (in use), `declined`, `changed` (the pool changed its URL since it was accepted) or `conflict` (`why`: one of the user's has its name or prefix, or another pool's accepted one its prefix); only `accepted` ones are used ([pool.md](pool.md#mcp-upstreams-for-the-members)) | -| `POST /hub/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | add an upstream or change the one of that name: `204`; `400` with why (a name of a-z, 0-9, -; https, plain http on this machine only; a prefix another upstream has). Instead of `url`, `command` (program and arguments) makes it a command the hub starts (stdio), with `env` (no secret) on top of a base environment; with `auth.kind = "token"` the kept token goes into the variable `token_var`; OAuth is not for a command. A change restarts it. A new URL or another kind of login forgets its credential | +| `GET /hub/upstreams` | cookie | the user's MCP upstreams ([ADR-0069](adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md)): `{store, upstreams: [{name, url?, command?, env?, token_var?, prefix, allow?, auth: {kind: "none"} \| {kind: "token", env?} \| {kind: "oauth", client_id?, client_secret?, scopes?}, logged_in, pool?}]}`, kept in `upstreams.toml` in the hub's state directory, never a secret: an OAuth app's client secret is `client_secret: true` (one is set; it is in the keychain, or for a pool's upstream with the pool's list). `store`: `keychain`, or `file` on a Linux machine without a Secret Service. The upstreams the machine's pools name follow the user's own, named `:`, with `pool: {pool, name, status, why?, pool_prefix}`: `status` `offered` (not answered), `accepted` (in use), `declined`, `changed` (the pool changed its URL since it was accepted) or `conflict` (`why`: one of the user's has its name or prefix, or another pool's accepted one its prefix); only `accepted` ones are used ([pool.md](pool.md#mcp-upstreams-for-the-members)) | +| `POST /hub/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | add an upstream or change the one of that name: `204`; `400` with why (a name of a-z, 0-9, -; https, plain http on this machine only; a prefix another upstream has). Instead of `url`, `command` (program and arguments) makes it a command the hub starts (stdio), with `env` (no secret) on top of a base environment; with `auth.kind = "token"` the kept token goes into the variable `token_var`; OAuth is not for a command. A change restarts it. A new URL or another kind of login forgets its credential. `auth.client_secret` (with a `client_id`, for a server that wants one even with PKCE, such as GitHub): a string goes into the keychain, `""` takes it away, left out keeps the one set; logging out keeps it | | `DELETE /hub/upstreams/{name}` | cookie + Origin | it and its credential go: `204` | | `POST /hub/upstreams/pool/{pool}/{name}/accept {prefix?}` | cookie + Origin | use an upstream a pool names, at the URL it names now, with `prefix` instead of the pool's if given: `204`; `400` with why (the pool names none such; a prefix one of the user's or another accepted one has). A login for another URL goes | | `POST /hub/upstreams/pool/{pool}/{name}/decline` | cookie + Origin | do not use it; its login goes: `204` | | `POST /hub/upstreams/{name}/token {token}` | cookie + Origin | the static token of an upstream with `auth.kind = "token"` and no `env`, into the keychain: `204` | -| `POST /hub/upstreams/{name}/login` | cookie + Origin | start its OAuth login: the authorization server found from the upstream (RFC 9728, RFC 8414), the hub registered where the server allows it (RFC 7591), PKCE with S256, the upstream as `resource`: `{url}` to open in the browser; `502 {"error"}` when the server cannot be found or refuses | +| `POST /hub/upstreams/{name}/login` | cookie + Origin | start its OAuth login: the authorization server found from the upstream (RFC 9728, RFC 8414), the hub registered where the server allows it (RFC 7591), else the configured client id (with its client secret, sent to the token endpoint only), PKCE with S256, the upstream as `resource`: `{url}` to open in the browser; `502 {"error"}` when the server cannot be found or refuses | | `GET /hub/upstreams/tools` | user token (or cookie) | the upstreams' tools as `devstack mcp` offers them: `{tools: [Tool]}`, each named `__`, the allowlist applied, the description saying which upstream. One that cannot be asked (logged out, refused, unreachable) keeps the tools it listed last (kept in `upstream-tools.json` beside `upstreams.toml`), its description saying why; one never listed shows `__login`. Asked at most once a minute per upstream | | `POST /hub/upstreams/call {name, arguments}` | user token (or cookie + Origin) | call the tool `__` on its upstream with the hub's credential (refreshed once when refused): the upstream's `CallToolResult`, or one with `isError` and why (not logged in, with the dashboard's page; not allowed; unreachable). The credential never leaves the hub | | `POST /hub/upstreams/{name}/logout` | cookie + Origin | its credential goes: `204` | diff --git a/docs/pool.md b/docs/pool.md index 02b38278..2f906b3c 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -606,19 +606,32 @@ the same mock (`devstack_node::provision::mock`). A pool can name the MCP servers its members work with ([ADR-0069](adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md), option B): name, URL, prefix, tool allowlist and how each logs in. Never a -secret, and never a command: an entry is a URL over `https://`, so an admin -cannot run anything on a member's machine. +user's credential, and never a command: an entry is a URL over `https://`, so +an admin cannot run anything on a member's machine. ```sh devstack pool upstreams add tracker https://mcp.example.com/mcp # OAuth by default devstack pool upstreams add wiki https://wiki.example.com/mcp --login token --allow search,get_page +devstack pool upstreams add github https://api.githubcopilot.com/mcp/ \ + --client-id --client-secret --scope repo,read:org # an OAuth app of the pool's devstack pool upstreams remove wiki devstack pool upstreams # the list, for any member ``` `--login` is `oauth` (each member's hub logs in, in the browser; `--client-id` -where the server registers no clients itself), `token` (each member gives -their hub one) or `none`. Only an admin changes the list; each change is in +where the server registers no clients itself, `--scope` for what the login +asks for), `token` (each member gives their hub one) or `none`. + +Some servers want a client secret even with PKCE: GitHub does, for its OAuth +apps and GitHub apps alike. For those, register an app for desktop clients +(GitHub: an OAuth app with the callback URL +`http://127.0.0.1/oauth/upstream/callback`; GitHub takes any port on a +loopback address) and give its id and secret. Such a secret is not +confidential by nature (RFC 8252 §8.5; the `gh` CLI ships its own): members' +hubs get it with the list and send it only to the token endpoint, while the +dashboard, `devstack pool upstreams` and the audit log only say that one is +set. A change without `--client-secret` keeps it; `--client-secret ""` +takes it away. Only an admin changes the list; each change is in the audit log. The pool area of the dashboard shows the list to every member and lets an admin add, change and remove entries. diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 01083b19..638e84c2 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -821,8 +821,15 @@ export type NotifySettings = { muted: string[]; }; +/** + * An OAuth app's client secret: the hub answers `true` (one is set), never + * the value; sent, a string sets it, `''` takes it away, and leaving it out + * keeps the one set. + */ +export type OauthClientSecret = true | string; + /** How an MCP upstream logs in (ADR-0069). */ -export type McpUpstreamAuth = { kind: 'none' } | { kind: 'token'; env?: string } | { kind: 'oauth'; client_id?: string; scopes?: string[] }; +export type McpUpstreamAuth = { kind: 'none' } | { kind: 'token'; env?: string } | { kind: 'oauth'; client_id?: string; client_secret?: OauthClientSecret; scopes?: string[] }; /** An MCP upstream as the hub lists it: never a secret. */ export type McpUpstream = { @@ -862,7 +869,7 @@ export type PoolUpstream = { url: string; prefix?: string; allow?: string[]; - auth: { kind: 'none' } | { kind: 'token' } | { kind: 'oauth'; client_id?: string; scopes?: string[] }; + auth: { kind: 'none' } | { kind: 'token' } | { kind: 'oauth'; client_id?: string; client_secret?: OauthClientSecret; scopes?: string[] }; }; /** `GET /hub/upstreams`. `file`: no keychain on this machine (Linux without a Secret Service). */ diff --git a/ui/src/components/PoolUpstreams.vue b/ui/src/components/PoolUpstreams.vue index a4bb0e2e..6fedda3b 100644 --- a/ui/src/components/PoolUpstreams.vue +++ b/ui/src/components/PoolUpstreams.vue @@ -1,13 +1,16 @@ @@ -126,6 +146,19 @@ function how(u: PoolUpstream): string { + + +
@@ -171,6 +204,12 @@ function how(u: PoolUpstream): string { .form .wide { grid-column: 1 / -1; } +.form label.check { + grid-column: 1 / -1; + flex-direction: row; + align-items: center; + gap: 6px; +} .form .row { grid-column: 1 / -1; display: flex; diff --git a/ui/src/lib/oauthAuth.test.ts b/ui/src/lib/oauthAuth.test.ts new file mode 100644 index 00000000..de9847e7 --- /dev/null +++ b/ui/src/lib/oauthAuth.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { oauthAuth } from './oauthAuth'; + +const base = { client_id: '', client_secret: '', drop_secret: false, scopes: '' }; + +describe('oauthAuth', () => { + it('sends a new secret, keeps the one set when left empty, and drops it on request', () => { + expect(oauthAuth({ ...base, client_id: ' app ', client_secret: ' s3cret ' })).toEqual({ kind: 'oauth', client_id: 'app', client_secret: 's3cret' }); + expect(oauthAuth({ ...base, client_id: 'app' })).toEqual({ kind: 'oauth', client_id: 'app' }); + expect(oauthAuth({ ...base, client_id: 'app', client_secret: 'typed', drop_secret: true })).toEqual({ kind: 'oauth', client_id: 'app', client_secret: '' }); + }); + + it('takes a secret away with the client id, and splits scopes', () => { + expect(oauthAuth({ ...base, client_secret: 'orphan', scopes: 'repo, read:org gist' })).toEqual({ + kind: 'oauth', + client_secret: '', + scopes: ['repo', 'read:org', 'gist'], + }); + }); +}); diff --git a/ui/src/lib/oauthAuth.ts b/ui/src/lib/oauthAuth.ts new file mode 100644 index 00000000..9dc6f7ef --- /dev/null +++ b/ui/src/lib/oauthAuth.ts @@ -0,0 +1,27 @@ +// The OAuth part of an MCP upstream's form (ADR-0069), the user's own or a +// pool's: the client id, a client secret the hub never shows back, scopes. +import type { OauthClientSecret } from '@/api/types'; + +export type OauthFields = { + client_id: string; + /** A new client secret; empty keeps the one set. */ + client_secret: string; + /** Take the one set away. */ + drop_secret: boolean; + /** Space- or comma-separated. */ + scopes: string; +}; + +/** The `auth` an OAuth upstream's form sends. */ +export function oauthAuth(f: OauthFields): { kind: 'oauth'; client_id?: string; client_secret?: OauthClientSecret; scopes?: string[] } { + const id = f.client_id.trim(); + const secret = f.client_secret.trim(); + const scopes = f.scopes.split(/[\s,]+/).filter(Boolean); + return { + kind: 'oauth', + ...(id ? { client_id: id } : {}), + // Without a client id there is none to keep. + ...(id && secret && !f.drop_secret ? { client_secret: secret } : f.drop_secret || !id ? { client_secret: '' } : {}), + ...(scopes.length ? { scopes } : {}), + }; +} diff --git a/ui/src/views/UpstreamsView.vue b/ui/src/views/UpstreamsView.vue index fe373b83..507bc675 100644 --- a/ui/src/views/UpstreamsView.vue +++ b/ui/src/views/UpstreamsView.vue @@ -1,14 +1,16 @@ @@ -280,6 +308,19 @@ function how(u: McpUpstream): string { + + +