//! 連接器登入 (M6): a remote connector that signs people in with OAuth — MCP's authorization //! (2025-06-18): the server's 401 names its Protected Resource Metadata (RFC 9728), which names //! the authorization server; its metadata (RFC 8414, or OpenID's) gives the endpoints; AnyBot //! registers itself there (Dynamic Client Registration, RFC 7591), sends the person to log in //! with PKCE (S256) and the resource indicator (RFC 8707), and swaps the code for tokens. //! //! It runs on the brain. The login page opens in the person's browser; it comes back to a //! listener on this computer (`http://127.0.0.1:port/callback`). When the browser is on another //! computer (a brain on a server), that page can't load: the person copies its address back into //! the chat, and the bot hands it over (manage_connectors login with `callback`). //! //! The tokens are kept in `<資料夾>/connectors/oauth.json`, sealed with the same key as the //! settings' secrets (the keychain's); never in the connector list, which screens and the phone //! get. An access token near its end is renewed with the refresh token. use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::HashMap; use std::io::{BufRead, BufReader, Write}; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; /// How long a login waits for the person. const LOGIN_WAIT: Duration = Duration::from_secs(10 * 60); const HTTP_SECS: u64 = 20; /// One connector's tokens and where to renew them. #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct Tokens { pub access: String, #[serde(default)] pub refresh: String, /// When the access token ends (ms; 0: not said). #[serde(default)] pub expires_at: i64, pub token_endpoint: String, pub client_id: String, #[serde(default)] pub client_secret: String, #[serde(default)] pub resource: String, /// The connector's address when it was logged in: the token goes nowhere else. #[serde(default)] pub url: String, } fn file() -> std::path::PathBuf { crate::model::State::path().parent().map(|d| d.join("connectors").join("oauth.json")).unwrap_or_else(|| std::path::PathBuf::from("oauth.json")) } fn store() -> &'static Mutex<()> { static S: OnceLock> = OnceLock::new(); S.get_or_init(|| Mutex::new(())) } fn read_all() -> HashMap { let text = std::fs::read_to_string(file()).unwrap_or_default(); let mut v: Value = serde_json::from_str(&text).unwrap_or(json!({})); if let Some(o) = v.as_object_mut() { for t in o.values_mut() { for k in ["access", "refresh", "client_secret"] { if let Some(s) = t[k].as_str().filter(|s| s.starts_with("sealed:")).map(String::from) { // (One that can't be opened now — the keychain is locked — stays sealed: // it isn't used, and saving another connector's doesn't empty it.) if let Some(plain) = crate::vault_store::open_text(&s) { t[k] = json!(plain); } } } } } // (Each on its own: one entry that can't be read doesn't lose the others.) v.as_object().map(|o| o.iter().filter_map(|(k, t)| serde_json::from_value::(t.clone()).ok().map(|t| (k.clone(), t))).collect()).unwrap_or_default() } fn write_all(all: &HashMap) -> Result<(), String> { let mut v = serde_json::to_value(all).map_err(|e| e.to_string())?; if let Some(o) = v.as_object_mut() { for t in o.values_mut() { for k in ["access", "refresh", "client_secret"] { if let Some(sealed) = t[k].as_str().and_then(crate::vault_store::seal_text) { t[k] = json!(sealed); } } } } let p = file(); if let Some(d) = p.parent() { std::fs::create_dir_all(d).map_err(|e| e.to_string())?; } std::fs::write(&p, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)); } Ok(()) } /// This connector's tokens, if it is logged in. pub fn tokens(server: &str) -> Option { let _g = store().lock().unwrap_or_else(|e| e.into_inner()); read_all().remove(server).filter(|t| !t.access.is_empty() && !t.access.starts_with("sealed:")) } fn save(server: &str, t: Option) -> Result<(), String> { let _g = store().lock().unwrap_or_else(|e| e.into_inner()); let mut all = read_all(); match t { Some(t) => all.insert(server.to_string(), t), None => all.remove(server), }; write_all(&all) } /// A connector renamed: its sign-in goes with it (kept under its name). A login on its way /// under the old name finishes under the new one. pub fn rename(old: &str, new: &str) { if old == new { return; } if let Some(t) = tokens(old) { if save(new, Some(t)).is_ok() { let _ = save(old, None); } } for p in pending().lock().unwrap_or_else(|e| e.into_inner()).values_mut() { if p.server == old { p.server = new.to_string(); } } } /// Log a connector out (its tokens go). pub fn logout(server: &str) -> Result<(), String> { save(server, None) } /// The access token to send, renewed first when it is about to end. pub fn bearer(server: &str, url: &str) -> Option { // (A connector renamed onto, or pointed at, another address doesn't get this one's token.) let t = tokens(server).filter(|t| t.url.trim_end_matches('/') == url.trim().trim_end_matches('/'))?; if t.expires_at > 0 && t.expires_at - 60_000 < crate::model::now_ms() && !t.refresh.is_empty() { return renew(server).ok().or(Some(t.access)); } Some(t.access) } /// A new access token with the refresh token (after a 401, or near its end). pub fn renew(server: &str) -> Result { let t = tokens(server).ok_or("沒有登入")?; if t.refresh.is_empty() { return Err("登入過期了,要重新登入".into()); } let mut form = vec![("grant_type", "refresh_token".to_string()), ("refresh_token", t.refresh.clone()), ("client_id", t.client_id.clone())]; if !t.resource.is_empty() { form.push(("resource", t.resource.clone())); } if !t.client_secret.is_empty() { form.push(("client_secret", t.client_secret.clone())); } let v = post_form(&t.token_endpoint, &form)?; let fresh = tokens_from(&v, &t)?; save(server, Some(fresh.clone()))?; Ok(fresh.access) } fn tokens_from(v: &Value, base: &Tokens) -> Result { let access = v["access_token"].as_str().unwrap_or("").to_string(); if access.is_empty() { return Err(format!("登入伺服器沒有給 token:{}", v["error_description"].as_str().or(v["error"].as_str()).unwrap_or("(沒有說原因)"))); } Ok(Tokens { access, refresh: v["refresh_token"].as_str().map(String::from).unwrap_or_else(|| base.refresh.clone()), expires_at: v["expires_in"].as_i64().map(|s| crate::model::now_ms() + s * 1000).unwrap_or(0), ..base.clone() }) } // ---------- the protocol ---------- /// Percent-encoding for a URL's query or a form (everything but the unreserved characters). pub fn enc(s: &str) -> String { s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } fn dec(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; while i < b.len() { match b[i] { b'+' => out.push(b' '), b'%' if i + 2 < b.len() => match std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { Some(x) => { out.push(x); i += 3; continue; } None => out.push(b'%'), }, c => out.push(c), } i += 1; } String::from_utf8_lossy(&out).into_owned() } /// A query's `key=value` pairs. fn query_pairs(q: &str) -> HashMap { q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (dec(k), dec(v))).collect() } /// An address a connector (or its login server) named: a web address, and not one the safety /// rules keep every browser and connector from (cloud metadata, Docker's own). fn allowed(url: &str) -> Result<(), String> { if !(url.starts_with("https://") || url.starts_with("http://")) || crate::web::is_forbidden_browser_url(url) { return Err(format!("這個連接器給的登入位址不能用:{}", url.chars().take(120).collect::())); } Ok(()) } fn get_json(url: &str) -> Result { allowed(url)?; let mut resp = crate::net::agent(HTTP_SECS).get(url).header("Accept", "application/json").call().map_err(|e| format!("連不上 {url}:{e}"))?; if !(200..300).contains(&resp.status().as_u16()) { return Err(format!("{url} 回 HTTP {}", resp.status().as_u16())); } let body = resp.body_mut().read_to_string().unwrap_or_default(); serde_json::from_str(&body).map_err(|e| format!("{url} 回的不是 JSON:{e}")) } fn post_form(url: &str, form: &[(&str, String)]) -> Result { allowed(url)?; let body: String = form.iter().map(|(k, v)| format!("{}={}", enc(k), enc(v))).collect::>().join("&"); let mut resp = crate::net::agent(HTTP_SECS).post(url).header("Content-Type", "application/x-www-form-urlencoded").header("Accept", "application/json").send(body.as_bytes()).map_err(|e| format!("連不上 {url}:{e}"))?; let status = resp.status().as_u16(); let text = resp.body_mut().read_to_string().unwrap_or_default(); let v: Value = serde_json::from_str(&text).unwrap_or(json!({"error": text.chars().take(200).collect::()})); if !(200..300).contains(&status) { return Err(format!("登入伺服器回 HTTP {status}:{}", v["error_description"].as_str().or(v["error"].as_str()).unwrap_or(""))); } Ok(v) } /// `scheme://host[:port]` of an address. fn origin(url: &str) -> String { let (scheme, rest) = url.split_once("://").unwrap_or(("https", url)); format!("{scheme}://{}", rest.split('/').next().unwrap_or("")) } /// The path of an address ("" for none or "/"). fn path_of(url: &str) -> String { let rest = url.split_once("://").map(|x| x.1).unwrap_or(url); let p = rest.find('/').map(|i| &rest[i..]).unwrap_or(""); let p = p.split(['?', '#']).next().unwrap_or(""); if p == "/" { String::new() } else { p.trim_end_matches('/').to_string() } } /// What a 401's WWW-Authenticate names as the resource's metadata. pub fn resource_metadata(www_authenticate: &str) -> Option { let i = www_authenticate.find("resource_metadata=")?; let rest = &www_authenticate[i + "resource_metadata=".len()..]; let v = if let Some(r) = rest.strip_prefix('"') { r.split('"').next()? } else { rest.split([',', ' ']).next()? }; Some(v.to_string()).filter(|s| !s.is_empty()) } /// Where a login goes. #[derive(Clone, Debug, PartialEq)] pub struct Endpoints { pub authorize: String, pub token: String, pub register: String, pub scopes: Vec, /// The resource the tokens are for (the connector's address). pub resource: String, } /// Ask the connector who signs people in, and that server where. pub fn discover(mcp_url: &str) -> Result { // The 401 names the resource's metadata (RFC 9728); else its well-known places. let probe = crate::net::agent(HTTP_SECS) .post(mcp_url) .header("Content-Type", "application/json") .header("Accept", "application/json, text/event-stream") .send(json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}}).to_string().as_bytes()); let named = probe.ok().and_then(|r| r.headers().get("www-authenticate").and_then(|v| v.to_str().ok()).and_then(resource_metadata)); let (o, p) = (origin(mcp_url), path_of(mcp_url)); let mut tries: Vec = named.into_iter().collect(); if !p.is_empty() { tries.push(format!("{o}/.well-known/oauth-protected-resource{p}")); } tries.push(format!("{o}/.well-known/oauth-protected-resource")); let prm = tries.iter().find_map(|u| get_json(u).ok()); let issuer = prm.as_ref().and_then(|m| m["authorization_servers"][0].as_str().map(String::from)).unwrap_or_else(|| o.clone()); // (The tokens are for this connector: a resource on another site is not taken from it.) let resource = prm.as_ref().and_then(|m| m["resource"].as_str().map(String::from)).filter(|r| origin(r) == o).unwrap_or_else(|| mcp_url.to_string()); // The authorization server's metadata (RFC 8414, then OpenID's), path-aware. let (io, ip) = (origin(&issuer), path_of(&issuer)); let mut meta_tries = vec![]; if !ip.is_empty() { meta_tries.push(format!("{io}/.well-known/oauth-authorization-server{ip}")); meta_tries.push(format!("{io}/.well-known/openid-configuration{ip}")); meta_tries.push(format!("{io}{ip}/.well-known/openid-configuration")); } else { meta_tries.push(format!("{io}/.well-known/oauth-authorization-server")); meta_tries.push(format!("{io}/.well-known/openid-configuration")); } let meta = meta_tries.iter().find_map(|u| get_json(u).ok()); let s = |k: &str, default: &str| meta.as_ref().and_then(|m| m[k].as_str().map(String::from)).unwrap_or_else(|| format!("{io}{default}")); let scopes: Vec = prm .as_ref() .and_then(|m| m["scopes_supported"].as_array().cloned()) .or_else(|| meta.as_ref().and_then(|m| m["scopes_supported"].as_array().cloned())) .unwrap_or_default() .iter() .filter_map(|x| x.as_str().map(String::from)) .collect(); if let Some(methods) = meta.as_ref().and_then(|m| m["code_challenge_methods_supported"].as_array()) { if !methods.iter().any(|m| m == "S256") { return Err("這個連接器的登入伺服器不支援 PKCE(S256),AnyBot 不能安全地登入它。".into()); } } let e = Endpoints { authorize: s("authorization_endpoint", "/authorize"), token: s("token_endpoint", "/token"), register: s("registration_endpoint", "/register"), scopes, resource }; for u in [&e.authorize, &e.token, &e.register] { allowed(u)?; } Ok(e) } /// Register AnyBot with the authorization server (RFC 7591): its client id (and secret, if it /// gives one). fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> { allowed(&e.register)?; let mut resp = crate::net::agent(HTTP_SECS) .post(e.register.as_str()) .header("Content-Type", "application/json") .send(json!({"client_name": "AnyBot", "redirect_uris": [redirect], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "token_endpoint_auth_method": "none"}).to_string().as_bytes()) .map_err(|e| format!("連不上登入伺服器:{e}"))?; let status = resp.status().as_u16(); let v: Value = serde_json::from_str(&resp.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); match v["client_id"].as_str() { Some(id) if (200..300).contains(&status) => Ok((id.to_string(), v["client_secret"].as_str().unwrap_or("").to_string())), _ => Err(format!("這個連接器的登入伺服器不讓 App 自己註冊(HTTP {status}):要先在它那邊建一個 OAuth App 才能登入,AnyBot 還不支援填 client_id。")), } } /// A login waiting for the person. #[derive(Clone)] struct Pending { server: String, url: String, verifier: String, redirect: String, endpoints: Endpoints, client_id: String, client_secret: String, started: Instant, } fn pending() -> &'static Mutex> { static P: OnceLock>> = OnceLock::new(); P.get_or_init(Default::default) } /// A finished login: the connector, and whether it worked. type Finished = (String, Result<(), String>); /// Logins that finished since last asked. fn finished() -> &'static Mutex> { static F: OnceLock>> = OnceLock::new(); F.get_or_init(Default::default) } /// Logins of the connectors `mine` takes that finished since last time (the window reconnects /// those and says so; another AnyBot in this process — tests — takes its own). pub fn take_finished(mine: impl Fn(&str) -> bool) -> Vec<(String, Result<(), String>)> { let mut all = finished().lock().unwrap_or_else(|e| e.into_inner()); let (taken, left): (Vec<_>, Vec<_>) = std::mem::take(&mut *all).into_iter().partition(|(n, _)| mine(n)); *all = left; taken } fn challenge(verifier: &str) -> String { use base64::Engine; base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(ring::digest::digest(&ring::digest::SHA256, verifier.as_bytes()).as_ref()) } /// Start logging connector `server` (its address `mcp_url`) in: the address to open in the /// person's browser. A listener on this computer waits for the browser to come back. pub fn start(server: &str, mcp_url: &str) -> Result { let endpoints = discover(mcp_url)?; let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| format!("開不了接登入結果的連接埠:{e}"))?; let port = listener.local_addr().map_err(|e| e.to_string())?.port(); let redirect = format!("http://127.0.0.1:{port}/callback"); let (client_id, client_secret) = register(&endpoints, &redirect)?; let verifier = crate::httpd::random_hex(32); let state = crate::httpd::random_hex(16); let mut url = format!( "{}{}response_type=code&client_id={}&redirect_uri={}&code_challenge={}&code_challenge_method=S256&state={}&resource={}", endpoints.authorize, if endpoints.authorize.contains('?') { "&" } else { "?" }, enc(&client_id), enc(&redirect), enc(&challenge(&verifier)), enc(&state), enc(&endpoints.resource) ); if !endpoints.scopes.is_empty() { url.push_str(&format!("&scope={}", enc(&endpoints.scopes.join(" ")))); } { let mut p = pending().lock().unwrap_or_else(|e| e.into_inner()); p.retain(|_, x| x.started.elapsed() < LOGIN_WAIT && x.server != server); p.insert(state.clone(), Pending { server: server.to_string(), url: mcp_url.trim().to_string(), verifier, redirect, endpoints, client_id, client_secret, started: Instant::now() }); } std::thread::spawn(move || listen(listener, &state)); Ok(url) } /// Wait for the browser to come back (or the time to run out). fn listen(listener: std::net::TcpListener, state: &str) { let _ = listener.set_nonblocking(true); let t0 = Instant::now(); while t0.elapsed() < LOGIN_WAIT { if !pending().lock().unwrap_or_else(|e| e.into_inner()).contains_key(state) { return; // (finished another way: the address pasted in the chat) } let Ok((mut stream, _)) = listener.accept() else { std::thread::sleep(Duration::from_millis(100)); continue; }; let _ = stream.set_nonblocking(false); let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); let mut line = String::new(); let _ = BufReader::new(&stream).read_line(&mut line); let target = line.split_whitespace().nth(1).unwrap_or(""); let Some(query) = target.strip_prefix("/callback?") else { let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); continue; }; let r = finish_query(query); let page = match &r { Ok(name) => format!("已登入「{name}」,可以關掉這頁,回到 AnyBot。"), Err(e) => format!("沒有登入成功:{e}"), }; let html = format!("AnyBot{}", page.replace('<', "<")); let _ = stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{html}", html.len()).as_bytes()); if r.is_ok() || !pending().lock().unwrap_or_else(|e| e.into_inner()).contains_key(state) { return; } } if let Some(p) = pending().lock().unwrap_or_else(|e| e.into_inner()).remove(state) { finished().lock().unwrap_or_else(|e| e.into_inner()).push((p.server, Err("等了 10 分鐘都沒有登入,取消了".into()))); } } /// The address the browser came back to, pasted in the chat: finish that login. pub fn finish_from_url(callback: &str) -> Result { let query = callback.split_once('?').map(|x| x.1).ok_or("這個網址裡沒有登入的結果(要有 ?code=…&state=…)")?; finish_query(query.split('#').next().unwrap_or(query)) } /// Swap the code for tokens and keep them: the connector's name. fn finish_query(query: &str) -> Result { let q = query_pairs(query); let state = q.get("state").cloned().unwrap_or_default(); let p = pending().lock().unwrap_or_else(|e| e.into_inner()).remove(&state).ok_or("這個登入結果對不上任何進行中的登入(過期了,或已經用過):重新登入一次")?; let r = (|| { if let Some(e) = q.get("error") { return Err(format!("登入伺服器說:{}", q.get("error_description").unwrap_or(e))); } let code = q.get("code").filter(|c| !c.is_empty()).ok_or("網址裡沒有 code")?; let mut form = vec![ ("grant_type", "authorization_code".to_string()), ("code", code.clone()), ("redirect_uri", p.redirect.clone()), ("client_id", p.client_id.clone()), ("code_verifier", p.verifier.clone()), ("resource", p.endpoints.resource.clone()), ]; if !p.client_secret.is_empty() { form.push(("client_secret", p.client_secret.clone())); } let v = post_form(&p.endpoints.token, &form)?; let base = Tokens { token_endpoint: p.endpoints.token.clone(), client_id: p.client_id.clone(), client_secret: p.client_secret.clone(), resource: p.endpoints.resource.clone(), url: p.url.clone(), ..Default::default() }; save(&p.server, Some(tokens_from(&v, &base)?)) })(); finished().lock().unwrap_or_else(|e| e.into_inner()).push((p.server.clone(), r.clone())); r.map(|_| p.server) } #[cfg(test)] pub mod tests { use super::*; use std::io::Read; use std::sync::Arc; /// A connector that only answers with a token, and the server that hands them out — both in /// one: it checks the PKCE challenge, the redirect, and the resource. pub struct FakeOAuth { pub port: u16, pub url: String, pub tokens_given: Arc>, } fn respond(s: &mut std::net::TcpStream, status: &str, headers: &[(&str, String)], body: &str) { let mut h = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n", body.len()); for (k, v) in headers { h.push_str(&format!("{k}: {v}\r\n")); } let _ = s.write_all(format!("{h}\r\n{body}").as_bytes()); } impl FakeOAuth { pub fn start() -> FakeOAuth { let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let base = format!("http://127.0.0.1:{port}"); let given = Arc::new(Mutex::new(0u32)); let g = given.clone(); let url = format!("{base}/mcp"); std::thread::spawn(move || { let mut challenge_seen = String::new(); let mut token_n = 0; for s in l.incoming().flatten() { let mut s = s; let mut r = BufReader::new(s.try_clone().unwrap()); let mut first = String::new(); if r.read_line(&mut first).is_err() { continue; } let mut len = 0usize; let mut auth = String::new(); loop { let mut h = String::new(); if r.read_line(&mut h).is_err() || h.trim().is_empty() { break; } let lower = h.to_ascii_lowercase(); if let Some(v) = lower.strip_prefix("content-length:") { len = v.trim().parse().unwrap_or(0); } if lower.starts_with("authorization:") { auth = h.split_once(':').unwrap().1.trim().to_string(); } } let mut body = vec![0u8; len]; let _ = r.read_exact(&mut body); let body = String::from_utf8_lossy(&body).to_string(); let target = first.split_whitespace().nth(1).unwrap_or("").to_string(); let (path, query) = target.split_once('?').unwrap_or((&target, "")); let json_h = || vec![("Content-Type", "application/json".to_string())]; match path { "/mcp" if auth.starts_with("Bearer good-") => { let v: Value = serde_json::from_str(&body).unwrap_or(Value::Null); let result = match v["method"].as_str().unwrap_or("") { "initialize" => json!({"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "1"}}), "tools/list" => json!({"tools": [{"name": "whoami", "description": "Who is logged in", "inputSchema": {"type": "object"}}]}), _ => json!({}), }; if v["id"].is_null() { respond(&mut s, "202 Accepted", &[], ""); } else { respond(&mut s, "200 OK", &json_h(), &json!({"jsonrpc": "2.0", "id": v["id"], "result": result}).to_string()); } } "/mcp" => respond(&mut s, "401 Unauthorized", &[("WWW-Authenticate", format!("Bearer resource_metadata=\"{base}/.well-known/oauth-protected-resource/mcp\""))], ""), "/.well-known/oauth-protected-resource/mcp" => respond(&mut s, "200 OK", &json_h(), &json!({"resource": format!("{base}/mcp"), "authorization_servers": [base], "scopes_supported": ["mcp:tools"]}).to_string()), "/.well-known/oauth-authorization-server" => respond(&mut s, "200 OK", &json_h(), &json!({"issuer": base, "authorization_endpoint": format!("{base}/authorize"), "token_endpoint": format!("{base}/token"), "registration_endpoint": format!("{base}/register"), "code_challenge_methods_supported": ["S256"]}).to_string()), "/register" => respond(&mut s, "201 Created", &json_h(), &json!({"client_id": "anybot-client"}).to_string()), "/authorize" => { // (The person logs in and allows it: back to AnyBot with a code.) let q = query_pairs(query); assert_eq!(q.get("code_challenge_method").map(String::as_str), Some("S256")); assert_eq!(q.get("resource"), Some(&format!("{base}/mcp"))); assert_eq!(q.get("scope").map(String::as_str), Some("mcp:tools")); challenge_seen = q["code_challenge"].clone(); let to = format!("{}?code=the-code&state={}", q["redirect_uri"], enc(&q["state"])); respond(&mut s, "302 Found", &[("Location", to)], ""); } "/token" => { let f = query_pairs(&body); let ok = match f.get("grant_type").map(String::as_str) { Some("authorization_code") => f.get("code").map(String::as_str) == Some("the-code") && challenge(&f["code_verifier"]) == challenge_seen, Some("refresh_token") => f.get("refresh_token").map(String::as_str) == Some("r-1"), _ => false, }; if ok { token_n += 1; *g.lock().unwrap() += 1; respond(&mut s, "200 OK", &json_h(), &json!({"access_token": format!("good-{token_n}"), "refresh_token": "r-1", "expires_in": 3600, "token_type": "Bearer"}).to_string()); } else { respond(&mut s, "400 Bad Request", &json_h(), &json!({"error": "invalid_grant"}).to_string()); } } _ => respond(&mut s, "404 Not Found", &[], ""), } } }); FakeOAuth { port, url, tokens_given: given } } } #[test] fn the_words_of_a_login() { assert_eq!(resource_metadata(r#"Bearer error="invalid_token", resource_metadata="https://a.example/.well-known/oauth-protected-resource""#).as_deref(), Some("https://a.example/.well-known/oauth-protected-resource")); assert_eq!(resource_metadata("Bearer realm=x"), None); assert_eq!((origin("https://mcp.notion.com/mcp?x=1"), path_of("https://mcp.notion.com/mcp?x=1")), ("https://mcp.notion.com".into(), "/mcp".into())); assert_eq!(path_of("https://a.example/"), ""); assert_eq!(enc("a b/c?d=é"), "a%20b%2Fc%3Fd%3D%C3%A9"); assert_eq!(dec("a%20b%2Fc+d%C3%A9%"), "a b/c dé%"); // S256 = base64url(sha256(verifier)), no padding (checked against Python's hashlib). assert_eq!(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWwjXk"), "qBDSUaImE-WxTq4xZVKSKIi4bDy4teecLEwvWS_LsfQ"); } #[test] fn a_renamed_connector_keeps_its_sign_in() { let (a, b) = (format!("oauth-old-{}", crate::httpd::random_hex(4)), format!("oauth-new-{}", crate::httpd::random_hex(4))); save(&a, Some(Tokens { access: "tok".into(), url: "https://x.example/mcp".into(), ..Default::default() })).unwrap(); rename(&a, &b); assert!(tokens(&a).is_none()); assert_eq!(bearer(&b, "https://x.example/mcp").as_deref(), Some("tok")); let _ = logout(&b); } /// Against a test OAuth server: the login address is right, the browser's way back is caught, /// the code becomes tokens (PKCE checked by the server), and a token near its end is renewed. #[test] fn logging_a_connector_in() { let fake = FakeOAuth::start(); let name = format!("oauth-test-{}", fake.port); let url = start(&name, &fake.url).unwrap(); assert!(url.starts_with(&format!("http://127.0.0.1:{}/authorize?response_type=code&client_id=anybot-client", fake.port)), "{url}"); // The person's browser: the login page sends it back to AnyBot's listener. let mut page = crate::net::agent(10).get(url.as_str()).call().unwrap(); let text = page.body_mut().read_to_string().unwrap(); assert!(text.contains("已登入"), "{text}"); let t = tokens(&name).unwrap(); assert_eq!((t.access.as_str(), t.refresh.as_str(), t.resource.as_str()), ("good-1", "r-1", fake.url.as_str())); assert!(take_finished(|n| n == name).iter().any(|(_, r)| r.is_ok())); // Near its end: renewed before it is sent. let mut all = read_all(); all.get_mut(&name).unwrap().expires_at = crate::model::now_ms() + 1000; write_all(&all).unwrap(); assert_eq!(bearer(&name, &fake.url).as_deref(), Some("good-2")); // The connector pointed somewhere else: this token doesn't go there. assert_eq!(bearer(&name, "https://other.example/mcp"), None); assert!(allowed("http://169.254.169.254/latest").is_err() && allowed("smb://x/y").is_err() && allowed("https://a.example/t").is_ok()); assert_eq!(*fake.tokens_given.lock().unwrap(), 2, "one for the code, one renewal"); // The same address again: that login is used up. assert!(finish_from_url("http://127.0.0.1:1/callback?code=the-code&state=nope").is_err()); logout(&name).unwrap(); assert!(tokens(&name).is_none()); } /// The connector itself: before the login it says to log in; after it, it connects with the /// token and its tools are there. #[test] fn a_logged_in_connector_connects() { // (sync keeps only the servers it is given: one test at a time touches the table.) let _one = crate::mcp::test_lock(); let fake = FakeOAuth::start(); let name = format!("oauth-conn-{}", fake.port); let server = crate::mcp::Server { name: name.clone(), url: fake.url.clone(), enabled: true, ..Default::default() }; let errs = crate::mcp::sync(std::slice::from_ref(&server)); assert!(errs.iter().any(|(n, e)| n == &name && e.contains("登入")), "{errs:?}"); let url = start(&name, &fake.url).unwrap(); crate::net::agent(10).get(url.as_str()).call().unwrap(); crate::mcp::forget(&name); let errs = crate::mcp::sync(std::slice::from_ref(&server)); assert!(errs.iter().all(|(n, _)| n != &name), "{errs:?}"); assert_eq!(crate::mcp::status().get(&name).copied(), Some(1), "its one tool"); crate::mcp::forget(&name); let _ = logout(&name); } /// The browser on another computer: the address it came back to is pasted in the chat. #[test] fn a_pasted_address_finishes_the_login() { let fake = FakeOAuth::start(); let name = format!("oauth-paste-{}", fake.port); let url = start(&name, &fake.url).unwrap(); let no_follow: ureq::Agent = crate::net::config().max_redirects(0).http_status_as_error(false).build().into(); let resp = no_follow.get(url.as_str()).call().unwrap(); let back = resp.headers().get("location").unwrap().to_str().unwrap().to_string(); assert_eq!(finish_from_url(&back).unwrap(), name); assert_eq!(tokens(&name).unwrap().access, "good-1"); let _ = logout(&name); } }