From 6ae6758836ea8ddf8a1f1dac9ba792c6b17b78f5 Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 10:17:18 +0000 Subject: [PATCH] mcp: OAuth for HTTP servers (discovery, DCR, PKCE, refresh, hx mcp login/logout) --- README.md | 8 +- crates/hx-ai/src/auth.rs | 42 ++-- crates/hx-cli/src/main.rs | 38 +++- crates/hx-mcp/Cargo.toml | 4 +- crates/hx-mcp/src/client.rs | 31 ++- crates/hx-mcp/src/config.rs | 15 ++ crates/hx-mcp/src/lib.rs | 8 +- crates/hx-mcp/src/oauth.rs | 391 ++++++++++++++++++++++++++++++++ crates/hx-mcp/src/tests.rs | 71 ++++++ crates/hx-mcp/tests/fake_mcp.py | 36 ++- 10 files changed, 621 insertions(+), 23 deletions(-) create mode 100644 crates/hx-mcp/src/oauth.rs diff --git a/README.md b/README.md index 69fc20d..3fb21cc 100644 --- a/README.md +++ b/README.md @@ -135,10 +135,16 @@ name), in the Claude Code `mcpServers` shape. `${VAR}` and `${VAR:-default}` are }} ``` -Transports: stdio and streamable HTTP (static headers; no OAuth). hx extras: `allow` (tool allowlist), +Transports: stdio and streamable HTTP (static headers, or OAuth). hx extras: `allow` (tool allowlist), `eager`, `timeoutSecs` (per call, default 60), `disabled`. Output is capped at 30k chars; a crashed stdio server is restarted on the next call (at most 3 times). +OAuth (HTTP servers without an `Authorization` header): `hx mcp login ` discovers the auth server +(RFC 9728/8414), registers dynamically (RFC 7591), runs PKCE in the browser (URL printed; redirect on a random +localhost port, or paste the redirect URL) and stores tokens in `~/.hx/mcp-auth.json` (0600). Tokens refresh on +401. `hx mcp logout ` forgets them. Servers without dynamic registration: `"oauth": {"clientId": "…", +"clientSecret": "…", "scope": "…", "callbackPort": 8123}`. A server needing login shows `(run hx mcp login …)` in `/mcp`. + Lazy by default: the system prompt carries one line per tool (`server.tool: description`); the model gets the schema with `mcp_describe` and calls through `mcp_call` (arguments are checked against the cached schema). Servers whose full schemas cost at most ~400 tokens are registered as native tools instead (`server__tool`); diff --git a/crates/hx-ai/src/auth.rs b/crates/hx-ai/src/auth.rs index 5f9d955..5660705 100644 --- a/crates/hx-ai/src/auth.rs +++ b/crates/hx-ai/src/auth.rs @@ -281,6 +281,14 @@ async fn await_code(c: &Oauth) -> Result { let listener = tokio::net::TcpListener::bind(("127.0.0.1", c.port)) .await .ok(); + await_redirect(listener, c.path).await +} + +/// Like the login wait, on a caller-bound listener (`None` = paste only). Returns the redirect request target. +pub async fn await_redirect( + listener: Option, + path: &str, +) -> Result { // Detached std thread: tokio's stdin would block runtime shutdown until a line arrives. let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { @@ -290,6 +298,7 @@ async fn await_code(c: &Oauth) -> Result { } } }); + let mut stdin_open = true; loop { tokio::select! { acc = async { listener.as_ref().unwrap().accept().await }, if listener.is_some() => { @@ -298,19 +307,33 @@ async fn await_code(c: &Oauth) -> Result { let n = s.read(&mut buf).await.unwrap_or(0); let req = String::from_utf8_lossy(&buf[..n]); let target = req.split_whitespace().nth(1).unwrap_or(""); - if !target.starts_with(c.path) { let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n").await; continue; } + if !target.starts_with(path) { let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n").await; continue; } let _ = s.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\nconnection: close\r\n\r\nhx: login complete, you can close this tab.").await; return Ok(target.to_string()); } - line = rx.recv() => match line { + line = rx.recv(), if stdin_open => match line { Some(Ok(l)) if !l.trim().is_empty() => return Ok(l), Some(Ok(_)) => continue, + // stdin closed (non-interactive): keep waiting for the browser redirect if we can + _ if listener.is_some() => stdin_open = false, _ => return Err(Error::Http("login cancelled".into())), } } } } +/// Percent-encode everything except RFC 3986 unreserved characters. +pub fn urlenc(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} + pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String { let c = cfg(k); let mut p = vec![ @@ -330,17 +353,10 @@ pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String { ("originator", "hx"), ]), } - let enc = |s: &str| { - s.bytes() - .map(|b| match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - (b as char).to_string() - } - _ => format!("%{b:02X}"), - }) - .collect::() - }; - let qs: Vec = p.iter().map(|(k, v)| format!("{k}={}", enc(v))).collect(); + let qs: Vec = p + .iter() + .map(|(k, v)| format!("{k}={}", urlenc(v))) + .collect(); format!("{}?{}", c.authorize, qs.join("&")) } diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index ab26212..32a57fa 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -62,11 +62,22 @@ enum Cmd { /// Token size of the fixed request prefix (system prompt parts, tool schemas, MCP index). Prefix, /// Connect to configured MCP servers and print tools + index/eager token cost. - Mcp, + Mcp { + #[command(subcommand)] + action: Option, + }, /// Serve lens diagnostics + LSP navigation as an MCP server over stdio. McpServe, } +#[derive(Subcommand)] +enum McpAction { + /// OAuth login for an HTTP MCP server from mcp.json. + Login { server: String }, + /// Forget the stored OAuth token for an HTTP MCP server. + Logout { server: String }, +} + /// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project. #[derive(Default, serde::Deserialize)] #[serde(default, deny_unknown_fields)] @@ -372,7 +383,30 @@ async fn main() -> Result<()> { mgr.shutdown().await; return Ok(()); } - Some(Cmd::Mcp) => { + Some(Cmd::Mcp { action: Some(a) }) => { + let cwd = std::env::current_dir()?; + let cfgs = + hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?; + let (McpAction::Login { server } | McpAction::Logout { server }) = &a; + let s = cfgs + .get(server) + .filter(|s| s.url.is_some()) + .ok_or_else(|| anyhow::anyhow!("no HTTP MCP server `{server}` in mcp.json"))?; + if matches!(a, McpAction::Logout { .. }) { + hx_mcp::oauth::logout(s).map_err(anyhow::Error::msg)?; + return Ok(()); + } + hx_mcp::oauth::login(s, |u| { + eprintln!( + "Open this URL to log in (or paste the final redirect URL here):\n\n{u}\n" + ) + }) + .await + .map_err(anyhow::Error::msg)?; + eprintln!("logged in to {server}"); + return Ok(()); + } + Some(Cmd::Mcp { action: None }) => { let cwd = std::env::current_dir()?; let hub = hx_mcp::Hub::start( hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?, diff --git a/crates/hx-mcp/Cargo.toml b/crates/hx-mcp/Cargo.toml index 9c1a516..be3890c 100644 --- a/crates/hx-mcp/Cargo.toml +++ b/crates/hx-mcp/Cargo.toml @@ -9,10 +9,10 @@ async-trait = "0.1.92" futures = "0.3.34" hx-ai = { version = "0.1.0", path = "../hx-ai" } hx-core = { version = "0.1.0", path = "../hx-core" } -reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream", "rustls", "http2"] } +reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream", "rustls", "http2", "form"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" -tokio = { version = "1.53.1", features = ["process", "io-util", "sync", "time", "rt", "macros"] } +tokio = { version = "1.53.1", features = ["process", "net", "io-util", "sync", "time", "rt", "macros"] } [lints] workspace = true diff --git a/crates/hx-mcp/src/client.rs b/crates/hx-mcp/src/client.rs index 46b9648..15f31cd 100644 --- a/crates/hx-mcp/src/client.rs +++ b/crates/hx-mcp/src/client.rs @@ -1,7 +1,7 @@ //! Minimal MCP client: JSON-RPC 2.0 over stdio (newline-delimited) or streamable HTTP (JSON or SSE replies). //! //! ponytail: hand-rolled instead of `rmcp` (~1 dep tree less); covers initialize, tools, resources, prompts, -//! ping. No server->client sampling/elicitation/roots (answered with "method not found"), no HTTP OAuth. +//! ping. No server->client sampling/elicitation/roots (answered with "method not found"), HTTP OAuth lives in `oauth.rs`. use crate::config::Server; use serde_json::{Value, json}; @@ -27,6 +27,7 @@ enum Transport { url: String, headers: Vec<(String, String)>, session: Mutex>, + cfg: Box, }, } @@ -124,6 +125,7 @@ impl Client { .map(|(k, v)| (k.clone(), v.clone())) .collect(), session: Mutex::new(None), + cfg: Box::new(s.clone()), }, _ => return Err("server needs `command` or `url`".into()), }; @@ -165,11 +167,35 @@ impl Client { /// POST one message; returns the JSON-RPC response matching its id (if it had one). async fn post(&self, v: &Value) -> Result, String> { + let Transport::Http { headers, cfg, .. } = &self.t else { + unreachable!() + }; + // a configured Authorization header wins; otherwise use the stored OAuth token + if headers + .iter() + .any(|(k, _)| k.eq_ignore_ascii_case("authorization")) + { + return self.post_with(v, None).await; + } + let tok = crate::oauth::access(cfg, false).await; + match self.post_with(v, tok.as_deref()).await { + Err(e) if e.starts_with("HTTP 401") => match crate::oauth::access(cfg, true).await { + Some(t) => self.post_with(v, Some(&t)).await, + None => Err(format!( + "{e} (OAuth login needed: run `hx mcp login `)" + )), + }, + r => r, + } + } + + async fn post_with(&self, v: &Value, bearer: Option<&str>) -> Result, String> { let Transport::Http { http, url, headers, session, + .. } = &self.t else { unreachable!() @@ -182,6 +208,9 @@ impl Client { for (k, x) in headers { rq = rq.header(k, x); } + if let Some(t) = bearer { + rq = rq.bearer_auth(t); + } if let Some(s) = session.lock().await.as_ref() { rq = rq.header("mcp-session-id", s); } diff --git a/crates/hx-mcp/src/config.rs b/crates/hx-mcp/src/config.rs index cf7c300..ff9d45c 100644 --- a/crates/hx-mcp/src/config.rs +++ b/crates/hx-mcp/src/config.rs @@ -25,6 +25,21 @@ pub struct Server { #[serde(alias = "timeout_secs")] pub timeout_secs: Option, pub disabled: bool, + /// hx: HTTP OAuth overrides (`hx mcp login ` works without; needed for servers lacking dynamic registration) + pub oauth: OauthCfg, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Default)] +#[serde(default, rename_all = "camelCase")] +pub struct OauthCfg { + pub client_id: Option, + pub client_secret: Option, + pub scope: Option, + /// fixed redirect port (default: random free port) + pub callback_port: Option, + /// token store override (tests) + #[serde(skip)] + pub store: Option, } #[derive(Debug, Default, Deserialize)] diff --git a/crates/hx-mcp/src/lib.rs b/crates/hx-mcp/src/lib.rs index ddfbf5d..e34bfe6 100644 --- a/crates/hx-mcp/src/lib.rs +++ b/crates/hx-mcp/src/lib.rs @@ -6,6 +6,7 @@ pub mod client; pub mod config; +pub mod oauth; pub mod serve; use async_trait::async_trait; @@ -321,7 +322,12 @@ impl Hub { .iter() .map(|(n, s)| { if let Some(e) = &s.error { - return format!("{n}: error: {e}"); + let auth = if s.cfg.url.is_some() && e.contains("HTTP 401") && !oauth::logged_in(&s.cfg) { + format!(" (run `hx mcp login {n}`)") + } else { + String::new() + }; + return format!("{n}: error: {e}{auth}"); } let eager_tok = spec_tokens(&s.tools); let idx_tok = idx.get(n).map_or(0, |b| b.len() / 4); diff --git a/crates/hx-mcp/src/oauth.rs b/crates/hx-mcp/src/oauth.rs new file mode 100644 index 0000000..55aac14 --- /dev/null +++ b/crates/hx-mcp/src/oauth.rs @@ -0,0 +1,391 @@ +//! OAuth 2.1 for HTTP MCP servers (MCP authorization spec 2025-06-18): protected-resource + auth-server +//! discovery (RFC 9728 / 8414), dynamic client registration (RFC 7591), PKCE S256, resource indicators +//! (RFC 8707), refresh. Tokens live in `~/.hx/mcp-auth.json` (0600), keyed by server URL. +//! +//! ponytail: public clients only via DCR or a configured `clientId`; no client_credentials/device flow, no +//! token revocation on logout (just forget). Browser is never opened automatically: `hx mcp login` prints the URL. + +use crate::config::Server; +use hx_ai::auth::{await_redirect, now_ms, parse_code, pkce, urlenc}; +use reqwest::Url; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Entry { + pub client_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + pub token_endpoint: String, + pub access: String, + #[serde(default)] + pub refresh: Option, + /// unix ms + pub expires: u64, +} + +type Store = BTreeMap; + +pub fn store_path() -> PathBuf { + hx_core::context::hx_home().join("mcp-auth.json") +} + +fn path_of(s: &Server) -> PathBuf { + s.oauth.store.clone().unwrap_or_else(store_path) +} + +fn read(p: &Path) -> Store { + std::fs::read(p) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +fn write(p: &Path, url: &str, e: Option) -> Result<(), String> { + let mut s = read(p); + match e { + Some(e) => s.insert(url.into(), e), + None => s.remove(url), + }; + let io = |e: std::io::Error| format!("{}: {e}", p.display()); + std::fs::create_dir_all(p.parent().unwrap_or(p)).map_err(io)?; + let tmp = p.with_extension("tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(&s).unwrap_or_default()).map_err(io)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)).map_err(io)?; + } + std::fs::rename(&tmp, p).map_err(io) +} + +pub fn logout(s: &Server) -> Result<(), String> { + write( + &path_of(s), + s.url.as_deref().ok_or("not an HTTP server")?, + None, + ) +} + +pub fn logged_in(s: &Server) -> bool { + s.url + .as_deref() + .is_some_and(|u| read(&path_of(s)).contains_key(u)) +} + +/// `resource_metadata` URL from a `WWW-Authenticate: Bearer ...` header. +pub fn resource_metadata(h: &str) -> Option { + let i = h.find("resource_metadata=")? + "resource_metadata=".len(); + let r = &h[i..]; + Some(match r.strip_prefix('"') { + Some(q) => q.split('"').next()?.to_string(), + None => r.split([',', ' ']).next()?.to_string(), + }) + .filter(|s| !s.is_empty()) +} + +/// Well-known URLs to try for an issuer (RFC 8414, then OIDC discovery). +pub fn as_metadata_urls(issuer: &str) -> Vec { + let Ok(u) = Url::parse(issuer) else { + return vec![]; + }; + let origin = u.origin().ascii_serialization(); + let p = u.path().trim_matches('/'); + if p.is_empty() { + vec![ + format!("{origin}/.well-known/oauth-authorization-server"), + format!("{origin}/.well-known/openid-configuration"), + ] + } else { + vec![ + format!("{origin}/.well-known/oauth-authorization-server/{p}"), + format!("{origin}/.well-known/openid-configuration/{p}"), + format!("{origin}/{p}/.well-known/openid-configuration"), + ] + } +} + +async fn get_json(h: &reqwest::Client, url: &str) -> Option { + let r = h.get(url).send().await.ok()?; + r.status().is_success().then_some(())?; + r.json().await.ok() +} + +#[derive(Deserialize)] +struct TokenResp { + access_token: String, + refresh_token: Option, + expires_in: Option, +} + +async fn token_req( + h: &reqwest::Client, + endpoint: &str, + form: &[(&str, &str)], +) -> Result { + let r = h + .post(endpoint) + .header("accept", "application/json") + .form(form) + .send() + .await + .map_err(|e| e.to_string())?; + let st = r.status(); + let body = r.text().await.map_err(|e| e.to_string())?; + if !st.is_success() { + return Err(format!( + "token endpoint HTTP {st}: {}", + body.chars().take(300).collect::() + )); + } + serde_json::from_str(&body).map_err(|e| format!("bad token response: {e}")) +} + +fn expiry(t: &TokenResp) -> u64 { + // refresh 60 s early + now_ms() + + t.expires_in + .unwrap_or(3600) + .saturating_mul(1000) + .saturating_sub(60_000) +} + +/// Interactive login. `announce` receives the authorize URL (CLI: print it). Waits for the browser redirect +/// on localhost or a pasted redirect URL on stdin. +pub async fn login(s: &Server, announce: impl Fn(&str)) -> Result<(), String> { + let url = s.url.as_deref().ok_or("not an HTTP server")?; + let h = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(30)) + .build() + .map_err(|e| e.to_string())?; + // 1. unauthenticated probe -> 401 + resource metadata pointer + let probe = h + .post(url) + .header("accept", "application/json, text/event-stream") + .json( + &json!({"jsonrpc":"2.0","id":0,"method":"initialize","params":{ + "protocolVersion": crate::client::PROTOCOL, "capabilities": {}, + "clientInfo": {"name":"hx","version":env!("CARGO_PKG_VERSION")}}}), + ) + .send() + .await + .map_err(|e| e.to_string())?; + if probe.status().as_u16() != 401 { + return Err(format!( + "server did not ask for auth (HTTP {})", + probe.status() + )); + } + let origin = Url::parse(url) + .map_err(|e| e.to_string())? + .origin() + .ascii_serialization(); + let hdr = probe + .headers() + .get("www-authenticate") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + // 2. protected resource metadata -> authorization server + let prm_url = resource_metadata(hdr) + .unwrap_or_else(|| format!("{origin}/.well-known/oauth-protected-resource")); + let issuer = get_json(&h, &prm_url) + .await + .and_then(|m| m["authorization_servers"][0].as_str().map(String::from)) + .unwrap_or(origin); + // 3. authorization server metadata + let mut meta = None; + for u in as_metadata_urls(&issuer) { + if let Some(m) = get_json(&h, &u).await { + meta = Some(m); + break; + } + } + let meta = meta.ok_or_else(|| format!("no OAuth metadata found for {issuer}"))?; + let ep = |k: &str| { + meta[k] + .as_str() + .map(String::from) + .ok_or_else(|| format!("auth server metadata lacks {k}")) + }; + let (authorize, token) = (ep("authorization_endpoint")?, ep("token_endpoint")?); + // 4. redirect listener, then client registration + let listener = tokio::net::TcpListener::bind(("127.0.0.1", s.oauth.callback_port.unwrap_or(0))) + .await + .map_err(|e| format!("bind callback port: {e}"))?; + let redirect = format!( + "http://127.0.0.1:{}/callback", + listener.local_addr().map_err(|e| e.to_string())?.port() + ); + let (client_id, client_secret) = match &s.oauth.client_id { + Some(id) => (id.clone(), s.oauth.client_secret.clone()), + None => { + let reg = meta["registration_endpoint"].as_str().ok_or( + "server has no dynamic client registration: set `oauth.clientId` in the mcp.json entry", + )?; + let r = h + .post(reg) + .json(&json!({ + "client_name": "hx", "redirect_uris": [redirect], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], "token_endpoint_auth_method": "none"})) + .send() + .await + .map_err(|e| e.to_string())?; + let st = r.status(); + let b: Value = r + .json() + .await + .map_err(|e| format!("bad registration reply: {e}"))?; + if !st.is_success() { + return Err(format!("client registration HTTP {st}: {b}")); + } + let id = b["client_id"] + .as_str() + .ok_or("registration: no client_id")?; + (id.into(), b["client_secret"].as_str().map(String::from)) + } + }; + // 5. authorize + let (verifier, challenge) = pkce(); + let state = pkce().0; + let mut q = vec![ + ("response_type", "code"), + ("client_id", &client_id), + ("redirect_uri", &redirect), + ("code_challenge", &challenge), + ("code_challenge_method", "S256"), + ("state", &state), + ("resource", url), + ]; + if let Some(sc) = &s.oauth.scope { + q.push(("scope", sc)); + } + let qs: Vec = q + .iter() + .map(|(k, v)| format!("{k}={}", urlenc(v))) + .collect(); + let sep = if authorize.contains('?') { '&' } else { '?' }; + announce(&format!("{authorize}{sep}{}", qs.join("&"))); + let (code, got) = parse_code( + &await_redirect(Some(listener), "/callback") + .await + .map_err(|e| e.to_string())?, + ); + if got.as_deref().is_some_and(|g| g != state) { + return Err("OAuth state mismatch".into()); + } + let code = code.ok_or("missing authorization code")?; + // 6. token exchange + let mut form = vec![ + ("grant_type", "authorization_code"), + ("code", code.as_str()), + ("redirect_uri", redirect.as_str()), + ("client_id", client_id.as_str()), + ("code_verifier", verifier.as_str()), + ("resource", url), + ]; + if let Some(sec) = &client_secret { + form.push(("client_secret", sec)); + } + let t = token_req(&h, &token, &form).await?; + write( + &path_of(s), + url, + Some(Entry { + client_id, + client_secret, + token_endpoint: token, + expires: expiry(&t), + access: t.access_token, + refresh: t.refresh_token, + }), + ) +} + +/// Bearer token for `s`: stored one, refreshed when expired or `force`. `None` = not logged in / refresh failed. +pub async fn access(s: &Server, force: bool) -> Option { + let url = s.url.as_deref()?; + let p = path_of(s); + let e = read(&p).remove(url)?; + if !force && e.expires > now_ms() { + return Some(e.access); + } + let rt = e.refresh.clone()?; + let mut form = vec![ + ("grant_type", "refresh_token"), + ("refresh_token", rt.as_str()), + ("client_id", e.client_id.as_str()), + ("resource", url), + ]; + if let Some(sec) = &e.client_secret { + form.push(("client_secret", sec)); + } + let t = token_req(&reqwest::Client::new(), &e.token_endpoint, &form) + .await + .ok()?; + let n = Entry { + expires: expiry(&t), + access: t.access_token.clone(), + refresh: t.refresh_token.or(Some(rt)), + ..e + }; + write(&p, url, Some(n)).ok()?; + Some(t.access_token) +} + +#[cfg(test)] +mod t { + use super::*; + + #[test] + fn www_authenticate() { + assert_eq!( + resource_metadata(r#"Bearer realm="x", resource_metadata="https://a/b""#).as_deref(), + Some("https://a/b") + ); + assert_eq!(resource_metadata("Bearer realm=x"), None); + } + + #[test] + fn metadata_candidates() { + assert_eq!( + as_metadata_urls("https://a.com"), + [ + "https://a.com/.well-known/oauth-authorization-server", + "https://a.com/.well-known/openid-configuration" + ] + ); + assert_eq!( + as_metadata_urls("https://a.com/t1")[0], + "https://a.com/.well-known/oauth-authorization-server/t1" + ); + } + + #[test] + fn store_roundtrip_0600() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("x/mcp-auth.json"); + let e = Entry { + client_id: "c".into(), + client_secret: None, + token_endpoint: "t".into(), + access: "a".into(), + refresh: Some("r".into()), + expires: 1, + }; + write(&p, "https://u", Some(e.clone())).unwrap(); + assert_eq!(read(&p)["https://u"], e); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + write(&p, "https://u", None).unwrap(); + assert!(read(&p).is_empty()); + } +} diff --git a/crates/hx-mcp/src/tests.rs b/crates/hx-mcp/src/tests.rs index f41874e..5d96834 100644 --- a/crates/hx-mcp/src/tests.rs +++ b/crates/hx-mcp/src/tests.rs @@ -232,3 +232,74 @@ async fn reference_server_everything() { .to_string(); assert!(!h.read("e", &uri).await.is_error); } + +#[tokio::test] +async fn http_oauth_login_and_refresh() { + let port = 20000 + std::process::id() % 20000; + let mut srv = tokio::process::Command::new("python3") + .arg(fake()) + .args(["http", &port.to_string(), "oauth"]) + .kill_on_drop(true) + .spawn() + .unwrap(); + let store = tempfile::tempdir().unwrap().keep().join("mcp-auth.json"); + let mut cfg: Server = serde_json::from_value(json!({ + "type": "http", "url": format!("http://127.0.0.1:{port}/mcp") + })) + .unwrap(); + cfg.oauth.store = Some(store.clone()); + let start = || async { Hub::start(BTreeMap::from([("o".to_string(), cfg.clone())])).await }; + let mut h = Hub::default(); + for _ in 0..50 { + h = start().await; + // server up once the error is the 401 (not a connection error) + if h.servers["o"] + .error + .as_deref() + .is_some_and(|e| e.contains("401")) + { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + let st = h.status().join("\n"); + assert!(st.contains("hx mcp login o"), "{st}"); + // login: the "browser" hits the redirect with the right state + oauth::login(&cfg, |u| { + let q: BTreeMap = u + .split_once('?') + .unwrap() + .1 + .split('&') + .filter_map(|kv| kv.split_once('=')) + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + assert_eq!(q["code_challenge_method"], "S256"); + assert!(q["resource"].contains("%2Fmcp"), "{u}"); + let redirect = q["redirect_uri"].replace("%3A", ":").replace("%2F", "/"); + let url = format!("{redirect}?code=abc&state={}", q["state"]); + tokio::spawn(async move { reqwest::get(url).await }); + }) + .await + .unwrap(); + assert!(oauth::logged_in(&cfg)); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&store).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + // a1 is rejected by the server -> 401 -> forced refresh -> a2 + let h = start().await; + assert_eq!(h.servers["o"].error, None); + assert_eq!(h.servers["o"].tools.len(), 5); + assert_eq!( + h.call("o", "echo", json!({"message":"auth"})).await, + ToolResult::ok("echo: auth") + ); + oauth::logout(&cfg).unwrap(); + assert!(!oauth::logged_in(&cfg)); + let _ = srv.kill().await; +} diff --git a/crates/hx-mcp/tests/fake_mcp.py b/crates/hx-mcp/tests/fake_mcp.py index 3611381..d52652a 100644 --- a/crates/hx-mcp/tests/fake_mcp.py +++ b/crates/hx-mcp/tests/fake_mcp.py @@ -57,15 +57,45 @@ def handle(m): if len(sys.argv) > 1 and sys.argv[1] == "http": - import http.server + import http.server, urllib.parse + + # `http PORT oauth`: OAuth-protected. Code login yields a1 (3600s) which the server rejects, so the client + # must refresh (r1 -> a2). Only a2 is accepted. + OAUTH = len(sys.argv) > 3 and sys.argv[3] == "oauth" + ORIGIN = "http://127.0.0.1:" + sys.argv[2] class H(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass + def _json(self, o): + self.send_response(200); self.send_header("content-type", "application/json"); self.end_headers() + self.wfile.write(json.dumps(o).encode()) + + def do_GET(self): + if self.path == "/prm": + return self._json({"authorization_servers": [ORIGIN]}) + if self.path == "/.well-known/oauth-authorization-server": + return self._json({"authorization_endpoint": ORIGIN + "/authorize", "token_endpoint": ORIGIN + "/token", + "registration_endpoint": ORIGIN + "/register"}) + self.send_response(404); self.end_headers() + def do_POST(self): - if self.headers.get("authorization") != "Bearer t0k": - self.send_response(401); self.end_headers(); return + if OAUTH and self.path in ("/register", "/token"): + body = self.rfile.read(int(self.headers["content-length"])) + if self.path == "/register": + return self._json({"client_id": "c1"}) + f = {k: v[0] for k, v in urllib.parse.parse_qs(body.decode()).items()} + if f.get("grant_type") == "authorization_code" and f.get("code") == "abc" and f.get("code_verifier") and f.get("client_id") == "c1" and f.get("resource", "").endswith("/mcp"): + return self._json({"access_token": "a1", "refresh_token": "r1", "expires_in": 3600}) + if f.get("grant_type") == "refresh_token" and f.get("refresh_token") == "r1": + return self._json({"access_token": "a2", "expires_in": 3600}) + self.send_response(400); self.end_headers(); return + if self.headers.get("authorization") != ("Bearer a2" if OAUTH else "Bearer t0k"): + self.send_response(401) + if OAUTH: + self.send_header("www-authenticate", 'Bearer resource_metadata="%s/prm"' % ORIGIN) + self.end_headers(); return m = json.loads(self.rfile.read(int(self.headers["content-length"]))) if m.get("method") != "initialize" and self.headers.get("mcp-session-id") != "s1": self.send_response(400); self.end_headers(); return -- 2.54.1