Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
MCP OAuth: sign-in for http MCP servers (discovery, DCR, PKCE, refresh)
Lin (kwant bot)50b84e56ab61
diff --git a/Cargo.lock b/Cargo.lockindex be144798..9bfb382f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1152,6 +1152,7 @@ version = "0.1.0"dependencies = ["async-trait","axum",+ "base64 0.22.1","chrono","clap","dirs",@@ -1161,6 +1162,7 @@ dependencies = ["rust-embed","serde","serde_json",+ "sha2 0.10.9","sqlx","tempfile","thiserror 1.0.69",@@ -1173,6 +1175,7 @@ dependencies = ["tower-http 0.5.2","tracing","tracing-subscriber",+ "url","uuid",]diff --git a/Cargo.toml b/Cargo.tomlindex b4711a11..fdb2ebd2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -36,6 +36,9 @@ toml = "0.8"thiserror = "1.0"dirs = "5.0"tokio-tungstenite = { version = "0.24", features = ["connect"] }+sha2 = "0.10"+base64 = "0.22"+url = "2"[dev-dependencies]tempfile = "3"diff --git a/docs/mcp-api.md b/docs/mcp-api.mdindex 889d70e7..2eefb6f6 100644--- a/docs/mcp-api.md+++ b/docs/mcp-api.md@@ -20,7 +20,8 @@ All endpoints are JSON. Errors use the status code plus `{"error": "<message>"}`"headers": {},"enabled": true,"timeout_secs": 30,- "created_at": "2026-10-16T12:00:00Z"+ "created_at": "2026-10-16T12:00:00Z",+ "oauth": { "connected": false, "expires_at": null }}```@@ -37,6 +38,7 @@ All endpoints are JSON. Errors use the status code plus `{"error": "<message>"}`| `enabled` | bool | Disabled servers are kept but never offered to any kwant. Default `true`. || `timeout_secs` | int | Per-request timeout (initialize, list, call), 1–600. Default `30`. || `created_at` | string \| null | RFC 3339. |+| `oauth` | object | Read-only sign-in status (see [Sign-in](#sign-in-oauth)): `connected` bool, `expires_at` RFC 3339 or null. Never contains tokens. Always `{"connected": false, …}` for stdio servers. |### Secrets@@ -82,6 +84,60 @@ Connects with the stored config (works for disabled servers too), runs `initiali{ "ok": false, "error": "timed out after 30s waiting for initialize", "stderr_tail": "…", "duration_ms": 30004 }```+An http server that answers 401 while kwnt has no usable sign-in (and the user set no+`Authorization` header of their own) gives:++```json+{ "ok": false, "auth_required": true, "error": "Sign-in required", "duration_ms": 120 }+```++## Sign-in (OAuth)++http servers that require sign-in (e.g. `https://mcp.notion.com/mcp`) use the MCP authorization+spec (2025-06-18): kwnt reads the 401's `WWW-Authenticate: Bearer resource_metadata=…` (or+`/.well-known/oauth-protected-resource`), then the authorization server's metadata+(`/.well-known/oauth-authorization-server`, falling back to OpenID discovery), registers itself+as client `kwnt` (dynamic client registration, RFC 7591), and runs the authorization code flow+with PKCE S256 and the `resource` parameter (RFC 8707). Authorization-server endpoints must be+https (plain http only on loopback).++### `POST /api/mcp/servers/:id/oauth/start`+Body: `{"origin": "https://kwnt.example.com"}`: the browser's `location.origin`. It must be http(s)+with no path, and its host must equal the request's `Host` or `X-Forwarded-Host`. The callback is+`<origin>/api/mcp/oauth/callback`, so the same build works on localhost and behind a proxy.+`200` → `{"authorize_url": "https://…"}`: open it in a popup. `400` bad origin or a stdio server,+`404` unknown server, `502` discovery or registration failed (`{"error": "…"}`).+The sign-in must finish within 10 minutes; starting again for the same server replaces the+earlier attempt. Registrations are reused per server, callback URL and authorization server.++### `GET /api/mcp/oauth/callback?code=…&state=…` (or `?error=…&state=…`)+Where the provider redirects the popup. kwnt exchanges the code and stores the tokens, then+returns a small HTML page that runs+`window.opener.postMessage({type: "kwnt-mcp-oauth", server_id, ok, error?}, location.origin)`+and closes itself (or goes to `/` when it has no opener). `server_id` is null when the `state`+is unknown, expired or already used. `error` is a short readable reason.++### `DELETE /api/mcp/servers/:id/oauth`+Forgets the tokens. `200` → `{"status": "disconnected"}`. `404` unknown server.++### How tokens are used+- Before every connection (test, API-agent turns, the claude CLI config) kwnt refreshes a+ token that expires within 60 s and sends `Authorization: Bearer <token>`.+- A user-set `Authorization` header always wins; kwnt's token is then not sent.+- If the authorization server rejects a refresh, the token is dropped and the server needs+ sign-in again. A network failure keeps it (and uses it while it is still valid).+- On `POST /test`, a 401 despite a token triggers one forced refresh and retry; if that fails+ too, the token is dropped and the answer is `auth_required`.+- Tokens are stored in the database like other secrets, never returned or logged, and redacted+ from tool output and errors. Changing a server's `url` or `transport`, or deleting it, drops+ its tokens and registrations.+- The claude CLI gets the current access token in its per-turn config file; a turn longer than+ the token's lifetime is not refreshed mid-turn.++For local checks, `kwnt mcp-oauth-mock-server [--port 7790] [--expires-in 3600]` runs an+OAuth-protected mock MCP server at `http://127.0.0.1:<port>/mcp` whose sign-in page has an+"Allow" link (no credentials).+### `GET /api/kwants/:id/mcp-servers``200` → `{"server_ids": ["…"]}`. `404` unknown kwant.diff --git a/src/db/mod.rs b/src/db/mod.rsindex 7205aca0..8ec77927 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -564,14 +564,16 @@ impl Database {self.get_mcp_server(&server.id).await}- /// Deletes the server and its kwant assignments. `foreign_keys` is only set on one pooled+ /// Deletes the server, its kwant assignments and its OAuth tokens and registrations. `foreign_keys` is only set on one pooled/// connection, so the cascade is done here rather than trusted to SQLite.pub async fn delete_mcp_server(&self, id: &str) -> Result<bool, DbError> {let mut tx = self.pool.begin().await?;- sqlx::query("DELETE FROM kwant_mcp_servers WHERE server_id = ?")- .bind(id)- .execute(&mut *tx)- .await?;+ for table in ["kwant_mcp_servers", "mcp_oauth_tokens", "mcp_oauth_clients"] {+ sqlx::query(&format!("DELETE FROM {table} WHERE server_id = ?"))+ .bind(id)+ .execute(&mut *tx)+ .await?;+ }let res = sqlx::query("DELETE FROM mcp_servers WHERE id = ?").bind(id).execute(&mut *tx)@@ -620,5 +622,101 @@ impl Database {.await?;Ok(rows.into_iter().map(McpServer::from_row).collect())}+ // MCP OAuth+ pub async fn get_mcp_oauth_token(&self, server_id: &str) -> Result<Option<McpOAuthToken>, DbError> {+ Ok(sqlx::query_as::<_, McpOAuthToken>(+ "SELECT server_id, access_token, refresh_token, expires_at, token_endpoint, client_id, client_secret, \+ auth_method, resource FROM mcp_oauth_tokens WHERE server_id = ?",+ )+ .bind(server_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// Token status for every server that has one: `server_id -> expires_at`.+ pub async fn list_mcp_oauth_expiries(+ &self,+ ) -> Result<std::collections::HashMap<String, Option<chrono::DateTime<chrono::Utc>>>, DbError> {+ let rows: Vec<(String, Option<chrono::DateTime<chrono::Utc>>)> =+ sqlx::query_as("SELECT server_id, expires_at FROM mcp_oauth_tokens").fetch_all(&self.pool).await?;+ Ok(rows.into_iter().collect())+ }++ pub async fn save_mcp_oauth_token(&self, token: &McpOAuthToken) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO mcp_oauth_tokens (server_id, access_token, refresh_token, expires_at, token_endpoint, \+ client_id, client_secret, auth_method, resource, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) \+ ON CONFLICT(server_id) DO UPDATE SET access_token = excluded.access_token, \+ refresh_token = excluded.refresh_token, expires_at = excluded.expires_at, \+ token_endpoint = excluded.token_endpoint, client_id = excluded.client_id, \+ client_secret = excluded.client_secret, auth_method = excluded.auth_method, \+ resource = excluded.resource, updated_at = CURRENT_TIMESTAMP",+ )+ .bind(&token.server_id)+ .bind(&token.access_token)+ .bind(&token.refresh_token)+ .bind(token.expires_at)+ .bind(&token.token_endpoint)+ .bind(&token.client_id)+ .bind(&token.client_secret)+ .bind(&token.auth_method)+ .bind(&token.resource)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Drops the server's tokens. Returns whether there were any.+ pub async fn delete_mcp_oauth_token(&self, server_id: &str) -> Result<bool, DbError> {+ let res = sqlx::query("DELETE FROM mcp_oauth_tokens WHERE server_id = ?")+ .bind(server_id)+ .execute(&self.pool)+ .await?;+ Ok(res.rows_affected() > 0)+ }++ pub async fn get_mcp_oauth_client(+ &self,+ server_id: &str,+ redirect_uri: &str,+ issuer: &str,+ ) -> Result<Option<McpOAuthClient>, DbError> {+ Ok(sqlx::query_as::<_, McpOAuthClient>(+ "SELECT server_id, redirect_uri, issuer, client_id, client_secret, auth_method FROM mcp_oauth_clients \+ WHERE server_id = ? AND redirect_uri = ? AND issuer = ?",+ )+ .bind(server_id)+ .bind(redirect_uri)+ .bind(issuer)+ .fetch_optional(&self.pool)+ .await?)+ }++ pub async fn save_mcp_oauth_client(&self, client: &McpOAuthClient) -> Result<(), DbError> {+ sqlx::query(+ "INSERT OR REPLACE INTO mcp_oauth_clients (server_id, redirect_uri, issuer, client_id, client_secret, auth_method) \+ VALUES (?, ?, ?, ?, ?, ?)",+ )+ .bind(&client.server_id)+ .bind(&client.redirect_uri)+ .bind(&client.issuer)+ .bind(&client.client_id)+ .bind(&client.client_secret)+ .bind(&client.auth_method)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Forgets tokens and registrations, e.g. when the server's url changes.+ pub async fn clear_mcp_oauth(&self, server_id: &str) -> Result<(), DbError> {+ for table in ["mcp_oauth_tokens", "mcp_oauth_clients"] {+ sqlx::query(&format!("DELETE FROM {table} WHERE server_id = ?"))+ .bind(server_id)+ .execute(&self.pool)+ .await?;+ }+ Ok(())+ }}diff --git a/src/db/models.rs b/src/db/models.rsindex 77e08e16..440d7f90 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -211,3 +211,68 @@ impl std::fmt::Debug for McpServer {.finish()}}++/// A dynamic client registration with one authorization server, for one redirect URI.+#[derive(Clone, PartialEq, FromRow)]+pub struct McpOAuthClient {+ pub server_id: String,+ pub redirect_uri: String,+ pub issuer: String,+ pub client_id: String,+ pub client_secret: Option<String>,+ /// Token endpoint auth: "none", "client_secret_post" or "client_secret_basic".+ pub auth_method: String,+}++impl std::fmt::Debug for McpOAuthClient {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("McpOAuthClient")+ .field("server_id", &self.server_id)+ .field("redirect_uri", &self.redirect_uri)+ .field("issuer", &self.issuer)+ .field("client_id", &self.client_id)+ .field("client_secret", &self.client_secret.as_ref().map(|_| "<set>"))+ .field("auth_method", &self.auth_method)+ .finish()+ }+}++/// OAuth tokens for an http MCP server, with what a refresh needs. Deliberately not `Serialize`;+/// the API only exposes [`crate::mcp::OAuthStatus`].+#[derive(Clone, PartialEq, FromRow)]+pub struct McpOAuthToken {+ pub server_id: String,+ pub access_token: String,+ pub refresh_token: Option<String>,+ pub expires_at: Option<DateTime<Utc>>,+ pub token_endpoint: String,+ pub client_id: String,+ pub client_secret: Option<String>,+ pub auth_method: String,+ pub resource: String,+}++impl McpOAuthToken {+ pub fn secret_values(&self) -> Vec<String> {+ [Some(&self.access_token), self.refresh_token.as_ref(), self.client_secret.as_ref()]+ .into_iter()+ .flatten()+ .cloned()+ .collect()+ }+}++/// Never prints token values.+impl std::fmt::Debug for McpOAuthToken {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("McpOAuthToken")+ .field("server_id", &self.server_id)+ .field("refresh_token", &self.refresh_token.as_ref().map(|_| "<set>"))+ .field("expires_at", &self.expires_at)+ .field("token_endpoint", &self.token_endpoint)+ .field("client_id", &self.client_id)+ .field("auth_method", &self.auth_method)+ .field("resource", &self.resource)+ .finish()+ }+}diff --git a/src/db/schema.sql b/src/db/schema.sqlindex 6dc6b716..543e3967 100644--- a/src/db/schema.sql+++ b/src/db/schema.sql@@ -88,3 +88,31 @@ CREATE TABLE IF NOT EXISTS kwant_mcp_servers (FOREIGN KEY(kwant_id) REFERENCES kwants(id) ON DELETE CASCADE,FOREIGN KEY(server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE);++-- OAuth client registrations (RFC 7591), one per server, redirect URI and authorization server+CREATE TABLE IF NOT EXISTS mcp_oauth_clients (+ server_id TEXT NOT NULL,+ redirect_uri TEXT NOT NULL,+ issuer TEXT NOT NULL,+ client_id TEXT NOT NULL,+ client_secret TEXT,+ auth_method TEXT NOT NULL DEFAULT 'none',+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, redirect_uri, issuer),+ FOREIGN KEY(server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE+);++-- OAuth tokens for http MCP servers, plus what a refresh needs. Secrets: never serialized+CREATE TABLE IF NOT EXISTS mcp_oauth_tokens (+ server_id TEXT PRIMARY KEY,+ access_token TEXT NOT NULL,+ refresh_token TEXT,+ expires_at TIMESTAMP,+ token_endpoint TEXT NOT NULL,+ client_id TEXT NOT NULL,+ client_secret TEXT,+ auth_method TEXT NOT NULL DEFAULT 'none',+ resource TEXT NOT NULL,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY(server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE+);diff --git a/src/main.rs b/src/main.rsindex 10b5360f..3333002d 100644--- a/src/main.rs+++ b/src/main.rs@@ -59,6 +59,18 @@ pub enum Commands {/// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)#[command(hide = true)]McpEchoServer,++ /// Run an OAuth-protected mock MCP server over HTTP (for tests and smoke checks)+ #[command(hide = true)]+ McpOauthMockServer {+ #[arg(long, default_value = "127.0.0.1")]+ host: String,+ #[arg(long, default_value_t = 7790)]+ port: u16,+ /// expires_in of issued access tokens; under 60 makes kwnt refresh on every use+ #[arg(long, default_value_t = 3600)]+ expires_in: i64,+ },}#[tokio::main]@@ -70,6 +82,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {return Ok(());}tracing_subscriber::fmt::init();+ if let Some(Commands::McpOauthMockServer { host, port, expires_in }) = &cli.command {+ let listener = tokio::net::TcpListener::bind((host.as_str(), *port)).await?;+ println!("mock OAuth MCP server: http://{}/mcp", listener.local_addr()?);+ kwnt::mcp::oauth_mock::serve(listener, kwnt::mcp::oauth_mock::MockOptions { expires_in: *expires_in }).await?;+ return Ok(());+ }let mut config = match cli.config {Some(path) => Config::from_file(path)?,@@ -154,6 +172,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Some(Commands::Teams) => print_teams(&config).await?,Some(Commands::Channels) => print_channels(&config).await?,Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),+ Some(Commands::McpOauthMockServer { .. }) => unreachable!("handled before config loading"),None => {println!("⚡ Kwant: your team of super-intelligent bots (kwants)");println!("Run `kwnt serve` to start the server, or `kwnt --help` for options.");diff --git a/src/mcp/client.rs b/src/mcp/client.rsindex d351292f..cd285965 100644--- a/src/mcp/client.rs+++ b/src/mcp/client.rs@@ -35,6 +35,9 @@ pub enum McpError {Rpc { code: i64, message: String },#[error("transport error: {0}")]Transport(String),+ /// HTTP 401: the server wants a (new) access token. Keeps its `WWW-Authenticate` header.+ #[error("transport error: HTTP 401 Unauthorized (sign in to this server from the Tools screen)")]+ Unauthorized { www_authenticate: Option<String> },#[error("invalid response: {0}")]Protocol(String),/// The server failed before the handshake completed; keeps what it wrote to stderr.@@ -147,6 +150,7 @@ impl McpClient {};match client.handshake().await {Ok(()) => Ok(client),+ Err(e @ McpError::Unauthorized { .. }) => Err(e),Err(e) => {client.shutdown().await;Err(McpError::Startup { message: e.to_string(), stderr_tail: client.stderr_tail() })@@ -396,6 +400,14 @@ impl McpClient {}let resp = req.send().await.map_err(|e| McpError::Transport(e.without_url().to_string()))?;let status = resp.status();+ if status == reqwest::StatusCode::UNAUTHORIZED {+ let www_authenticate = resp+ .headers()+ .get(reqwest::header::WWW_AUTHENTICATE)+ .and_then(|v| v.to_str().ok())+ .map(str::to_string);+ return Err(McpError::Unauthorized { www_authenticate });+ }if !status.is_success() {return Err(McpError::Transport(format!("HTTP {status}")));}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 88bcaa6d..4a070ba5 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -4,9 +4,12 @@pub mod cli_config;pub mod client;pub mod echo_server;+pub mod oauth;+pub mod oauth_mock;pub mod session;pub use client::{McpClient, McpError, McpTool};+pub use oauth::OAuthStatus;use crate::db::models::McpServer;use async_trait::async_trait;@@ -43,6 +46,9 @@ pub struct McpServerView {pub enabled: bool,pub timeout_secs: i64,pub created_at: Option<chrono::DateTime<chrono::Utc>>,+ /// OAuth sign-in status (http servers); filled in by the routes, never contains tokens.+ #[serde(default)]+ pub oauth: OAuthStatus,}impl From<&McpServer> for McpServerView {@@ -60,6 +66,7 @@ impl From<&McpServer> for McpServerView {enabled: s.enabled,timeout_secs: s.timeout_secs,created_at: s.created_at,+ oauth: OAuthStatus::default(),}}}diff --git a/src/mcp/oauth.rs b/src/mcp/oauth.rsnew file mode 100644index 00000000..8c4caedc--- /dev/null+++ b/src/mcp/oauth.rs@@ -0,0 +1,803 @@+//! OAuth sign-in for http MCP servers (MCP authorization spec 2025-06-18): protected-resource+//! and authorization-server discovery, dynamic client registration (RFC 7591), the+//! authorization code flow with PKCE S256 and `resource` (RFC 8707), and token refresh.+//!+//! This module talks HTTP but not to the database; `server::mcp_oauth` stores what it returns.++use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};+use chrono::{DateTime, Utc};+use reqwest::Url;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::sync::Mutex;+use std::time::{Duration, Instant};+use thiserror::Error;++/// How long a started sign-in may take before its `state` stops working.+pub const PENDING_TTL: Duration = Duration::from_secs(600);+/// Tokens expiring sooner than this are refreshed before use.+pub const REFRESH_MARGIN_SECS: i64 = 60;+const MAX_PENDING: usize = 64;+const HTTP_TIMEOUT: Duration = Duration::from_secs(15);+const CLIENT_NAME: &str = "kwnt";++#[derive(Error, Debug)]+pub enum OAuthError {+ #[error("{0}")]+ Discovery(String),+ #[error("this server's sign-in does not support automatic client registration")]+ NoRegistration,+ #[error("client registration failed: {0}")]+ Registration(String),+ #[error("token request failed: {0}")]+ Token(String),+ #[error("{0}")]+ Http(String),+}++fn http_err(e: reqwest::Error) -> OAuthError {+ OAuthError::Http(e.without_url().to_string())+}++/// Sign-in status for the API; never includes tokens.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct OAuthStatus {+ pub connected: bool,+ pub expires_at: Option<DateTime<Utc>>,+}++/// What the `WWW-Authenticate: Bearer …` challenge of a 401 tells us.+#[derive(Debug, Clone, Default, PartialEq)]+pub struct BearerChallenge {+ pub resource_metadata: Option<String>,+ pub scope: Option<String>,+}++/// Parses the auth-params of a Bearer challenge (RFC 6750 §3 / RFC 9728 §5.1). Quoted and+/// token values are accepted; other schemes in the same header are skipped.+pub fn parse_www_authenticate(header: &str) -> BearerChallenge {+ let mut out = BearerChallenge::default();+ let mut rest = header.trim();+ let mut in_bearer = false;+ while !rest.is_empty() {+ rest = rest.trim_start_matches(|c: char| c == ',' || c.is_whitespace());+ // A name: either a scheme (followed by space or end) or a param (followed by '=')+ let name_end = rest.find(|c: char| c == '=' || c == ',' || c.is_whitespace()).unwrap_or(rest.len());+ let name = &rest[..name_end];+ if name.is_empty() {+ break;+ }+ let after = rest[name_end..].trim_start();+ if let Some(value_part) = after.strip_prefix('=') {+ let value_part = value_part.trim_start();+ let (value, remaining) = if let Some(q) = value_part.strip_prefix('"') {+ let mut value = String::new();+ let mut chars = q.char_indices();+ let mut end = q.len();+ while let Some((i, c)) = chars.next() {+ match c {+ '\\' => {+ if let Some((_, n)) = chars.next() {+ value.push(n);+ }+ }+ '"' => {+ end = i + 1;+ break;+ }+ c => value.push(c),+ }+ }+ (value, &q[end.min(q.len())..])+ } else {+ let end = value_part.find(',').unwrap_or(value_part.len());+ (value_part[..end].trim().to_string(), &value_part[end..])+ };+ if in_bearer {+ match name.to_ascii_lowercase().as_str() {+ "resource_metadata" => out.resource_metadata = Some(value),+ "scope" => out.scope = Some(value),+ _ => {}+ }+ }+ rest = remaining;+ } else {+ in_bearer = name.eq_ignore_ascii_case("bearer");+ rest = after;+ }+ }+ out+}++/// Where to look for protected-resource metadata (RFC 9728 §3): the path-specific location,+/// then the origin root.+pub fn protected_resource_metadata_urls(server_url: &str) -> Vec<String> {+ let Ok(url) = Url::parse(server_url) else { return vec![] };+ let origin = url.origin().ascii_serialization();+ let path = url.path().trim_end_matches('/');+ let mut urls = Vec::new();+ if !path.is_empty() {+ urls.push(format!("{origin}/.well-known/oauth-protected-resource{path}"));+ }+ urls.push(format!("{origin}/.well-known/oauth-protected-resource"));+ urls+}++/// Where to look for authorization-server metadata: RFC 8414 first, then OpenID Connect+/// discovery in both its path-inserted and path-appended forms.+pub fn auth_server_metadata_urls(issuer: &str) -> Vec<String> {+ let Ok(url) = Url::parse(issuer) else { return vec![] };+ let origin = url.origin().ascii_serialization();+ let path = url.path().trim_end_matches('/');+ let mut urls = vec![format!("{origin}/.well-known/oauth-authorization-server{path}")];+ if path.is_empty() {+ urls.push(format!("{origin}/.well-known/openid-configuration"));+ } else {+ urls.push(format!("{origin}/.well-known/openid-configuration{path}"));+ urls.push(format!("{origin}{path}/.well-known/openid-configuration"));+ }+ urls+}++/// The canonical resource identifier for a server URL (RFC 8707): no fragment, no trailing '/'+/// on a bare origin.+pub fn canonical_resource(server_url: &str) -> String {+ match Url::parse(server_url) {+ Ok(mut url) => {+ url.set_fragment(None);+ let s = url.to_string();+ if url.path() == "/" && url.query().is_none() {+ s.trim_end_matches('/').to_string()+ } else {+ s+ }+ }+ Err(_) => server_url.to_string(),+ }+}++/// Endpoints must be https; plain http is only accepted on loopback (local servers and tests).+pub fn acceptable_endpoint(endpoint: &str) -> bool {+ let Ok(url) = Url::parse(endpoint) else { return false };+ match url.scheme() {+ "https" => url.host().is_some(),+ "http" => match url.host() {+ Some(url::Host::Domain(d)) => d.eq_ignore_ascii_case("localhost"),+ Some(url::Host::Ipv4(ip)) => ip.is_loopback(),+ Some(url::Host::Ipv6(ip)) => ip.is_loopback(),+ None => false,+ },+ _ => false,+ }+}++fn random_token() -> String {+ // Two v4 UUIDs: 244 random bits from the OS generator, 64 unreserved characters+ format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple())+}++/// A PKCE pair: the verifier stays here, the S256 challenge goes in the authorize URL.+#[derive(Clone)]+pub struct Pkce {+ pub verifier: String,+ pub challenge: String,+}++impl Pkce {+ pub fn new() -> Self {+ Self::from_verifier(random_token())+ }++ pub fn from_verifier(verifier: String) -> Self {+ let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));+ Self { verifier, challenge }+ }+}++impl Default for Pkce {+ fn default() -> Self {+ Self::new()+ }+}++/// What the token endpoint needs to finish a sign-in, kept between start and callback.+#[derive(Clone)]+pub struct PendingAuth {+ pub server_id: String,+ pub verifier: String,+ pub redirect_uri: String,+ pub token_endpoint: String,+ pub client_id: String,+ pub client_secret: Option<String>,+ pub auth_method: String,+ pub resource: String,+ created: Instant,+}++/// Started sign-ins keyed by their random `state`. Entries expire after [`PENDING_TTL`] and are+/// removed when used, so a `state` works once.+#[derive(Default)]+pub struct PendingStore {+ entries: Mutex<HashMap<String, PendingAuth>>,+}++impl PendingStore {+ pub fn insert(&self, auth: PendingAuth) -> String {+ self.insert_at(auth, Instant::now())+ }++ fn insert_at(&self, mut auth: PendingAuth, now: Instant) -> String {+ auth.created = now;+ let state = random_token();+ let mut entries = self.entries.lock().unwrap();+ entries.retain(|_, a| now.duration_since(a.created) < PENDING_TTL);+ // One open sign-in per server; a new Connect replaces the old one+ entries.retain(|_, a| a.server_id != auth.server_id);+ if entries.len() >= MAX_PENDING {+ if let Some(oldest) = entries.iter().min_by_key(|(_, a)| a.created).map(|(k, _)| k.clone()) {+ entries.remove(&oldest);+ }+ }+ entries.insert(state.clone(), auth);+ state+ }++ /// Removes and returns the sign-in for `state` if it exists and has not expired.+ pub fn take(&self, state: &str) -> Option<PendingAuth> {+ self.take_at(state, Instant::now())+ }++ fn take_at(&self, state: &str, now: Instant) -> Option<PendingAuth> {+ let auth = self.entries.lock().unwrap().remove(state)?;+ (now.duration_since(auth.created) < PENDING_TTL).then_some(auth)+ }+}++/// Whether a token with this expiry should be refreshed before use at `now`.+pub fn needs_refresh(expires_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {+ expires_at.is_some_and(|t| (t - now).num_seconds() < REFRESH_MARGIN_SECS)+}++/// Adds `Authorization: Bearer <token>` unless the user configured their own Authorization+/// header, which always wins. Returns whether the token was added.+pub fn apply_bearer(headers: &mut std::collections::BTreeMap<String, String>, access_token: &str) -> bool {+ if headers.keys().any(|k| k.eq_ignore_ascii_case("authorization")) {+ return false;+ }+ headers.insert("Authorization".into(), format!("Bearer {access_token}"));+ true+}++pub fn has_user_authorization(headers: &std::collections::BTreeMap<String, String>) -> bool {+ headers.keys().any(|k| k.eq_ignore_ascii_case("authorization"))+}++/// The parts of authorization-server metadata kwnt uses.+#[derive(Debug, Clone, Deserialize, PartialEq)]+pub struct AuthServerMetadata {+ #[serde(default)]+ pub issuer: Option<String>,+ pub authorization_endpoint: String,+ pub token_endpoint: String,+ #[serde(default)]+ pub registration_endpoint: Option<String>,+ #[serde(default)]+ pub code_challenge_methods_supported: Option<Vec<String>>,+ #[serde(default)]+ pub token_endpoint_auth_methods_supported: Option<Vec<String>>,+}++/// Everything discovery found for one MCP server.+#[derive(Debug, Clone)]+pub struct Discovery {+ /// Identifies the authorization server; registrations are stored per issuer.+ pub issuer: String,+ pub metadata: AuthServerMetadata,+ pub resource: String,+ pub scope: Option<String>,+}++/// A registered client.+#[derive(Clone)]+pub struct ClientRegistration {+ pub client_id: String,+ pub client_secret: Option<String>,+ pub auth_method: String,+}++/// A token endpoint's answer.+#[derive(Clone)]+pub struct TokenSet {+ pub access_token: String,+ pub refresh_token: Option<String>,+ pub expires_at: Option<DateTime<Utc>>,+}++pub fn http_client() -> reqwest::Client {+ reqwest::Client::builder()+ .timeout(HTTP_TIMEOUT)+ .redirect(reqwest::redirect::Policy::limited(3))+ .build()+ .unwrap_or_default()+}++async fn get_json(http: &reqwest::Client, url: &str) -> Result<Option<Value>, OAuthError> {+ let resp = http+ .get(url)+ .header("Accept", "application/json")+ .header("MCP-Protocol-Version", super::client::PROTOCOL_VERSION)+ .send()+ .await+ .map_err(http_err)?;+ if !resp.status().is_success() {+ return Ok(None);+ }+ Ok(resp.json::<Value>().await.ok())+}++/// Sends an unauthenticated `initialize` to read the 401 challenge, if the server sends one.+pub async fn probe_challenge(http: &reqwest::Client, server_url: &str) -> Option<BearerChallenge> {+ let body = json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {+ "protocolVersion": super::client::PROTOCOL_VERSION, "capabilities": {},+ "clientInfo": {"name": CLIENT_NAME, "version": env!("CARGO_PKG_VERSION")}}});+ let resp = http+ .post(server_url)+ .header("Accept", "application/json, text/event-stream")+ .json(&body)+ .send()+ .await+ .ok()?;+ if resp.status() != reqwest::StatusCode::UNAUTHORIZED {+ return None;+ }+ let header = resp.headers().get(reqwest::header::WWW_AUTHENTICATE)?.to_str().ok()?;+ Some(parse_www_authenticate(header))+}++/// Finds the authorization server for `server_url`: protected-resource metadata (from the+/// challenge or the well-known locations), then the authorization server's own metadata.+/// Servers without protected-resource metadata are treated as their own authorization server+/// (the 2025-03-26 behaviour).+pub async fn discover(+ http: &reqwest::Client,+ server_url: &str,+ challenge: Option<&BearerChallenge>,+) -> Result<Discovery, OAuthError> {+ let mut resource_urls: Vec<String> =+ challenge.and_then(|c| c.resource_metadata.clone()).into_iter().collect();+ resource_urls.extend(protected_resource_metadata_urls(server_url));++ let mut resource_meta = None;+ for url in resource_urls.iter().filter(|u| acceptable_endpoint(u)) {+ if let Some(meta) = get_json(http, url).await? {+ if meta["authorization_servers"].as_array().is_some_and(|a| !a.is_empty()) {+ resource_meta = Some(meta);+ break;+ }+ }+ }++ let origin = Url::parse(server_url)+ .map(|u| u.origin().ascii_serialization())+ .map_err(|_| OAuthError::Discovery("server url is not valid".into()))?;+ let issuer = resource_meta+ .as_ref()+ .and_then(|m| m["authorization_servers"][0].as_str())+ .map(str::to_string)+ .unwrap_or_else(|| origin.clone());+ if !acceptable_endpoint(&issuer) {+ return Err(OAuthError::Discovery("the authorization server must use https".into()));+ }+ let resource = resource_meta+ .as_ref()+ .and_then(|m| m["resource"].as_str())+ .map(str::to_string)+ .unwrap_or_else(|| canonical_resource(server_url));+ let scope = challenge.and_then(|c| c.scope.clone()).or_else(|| {+ let scopes: Vec<&str> = resource_meta+ .as_ref()?+ .get("scopes_supported")?+ .as_array()?+ .iter()+ .filter_map(Value::as_str)+ .collect();+ (!scopes.is_empty()).then(|| scopes.join(" "))+ });++ let mut metadata = None;+ for url in auth_server_metadata_urls(&issuer) {+ if let Some(meta) = get_json(http, &url).await? {+ if let Ok(parsed) = serde_json::from_value::<AuthServerMetadata>(meta) {+ metadata = Some(parsed);+ break;+ }+ }+ }+ let metadata = match metadata {+ Some(m) => m,+ None if resource_meta.is_none() => AuthServerMetadata {+ // 2025-03-26 default endpoints, relative to the server origin+ issuer: None,+ authorization_endpoint: format!("{origin}/authorize"),+ token_endpoint: format!("{origin}/token"),+ registration_endpoint: Some(format!("{origin}/register")),+ code_challenge_methods_supported: None,+ token_endpoint_auth_methods_supported: None,+ },+ None => return Err(OAuthError::Discovery("could not find the server's sign-in metadata".into())),+ };+ for endpoint in [Some(&metadata.authorization_endpoint), Some(&metadata.token_endpoint), metadata.registration_endpoint.as_ref()]+ .into_iter()+ .flatten()+ {+ if !acceptable_endpoint(endpoint) {+ return Err(OAuthError::Discovery("the server's sign-in endpoints must use https".into()));+ }+ }+ if let Some(methods) = &metadata.code_challenge_methods_supported {+ if !methods.iter().any(|m| m == "S256") {+ return Err(OAuthError::Discovery("the server's sign-in does not support PKCE (S256)".into()));+ }+ }+ Ok(Discovery { issuer, metadata, resource, scope })+}++/// Registers kwnt as a public client when the server allows it, otherwise as a confidential one.+pub async fn register_client(+ http: &reqwest::Client,+ meta: &AuthServerMetadata,+ redirect_uri: &str,+) -> Result<ClientRegistration, OAuthError> {+ let endpoint = meta.registration_endpoint.as_deref().ok_or(OAuthError::NoRegistration)?;+ let supported = meta.token_endpoint_auth_methods_supported.as_deref().unwrap_or(&[]);+ let requested = if supported.is_empty() || supported.iter().any(|m| m == "none") {+ "none"+ } else if supported.iter().any(|m| m == "client_secret_post") {+ "client_secret_post"+ } else {+ "client_secret_basic"+ };+ let body = json!({+ "client_name": CLIENT_NAME,+ "redirect_uris": [redirect_uri],+ "grant_types": ["authorization_code", "refresh_token"],+ "response_types": ["code"],+ "token_endpoint_auth_method": requested,+ });+ let resp = http.post(endpoint).json(&body).send().await.map_err(http_err)?;+ let status = resp.status();+ let reply: Value = resp.json().await.unwrap_or(Value::Null);+ if !status.is_success() {+ return Err(OAuthError::Registration(oauth_error_text(&reply, status)));+ }+ let client_id = reply["client_id"]+ .as_str()+ .filter(|s| !s.is_empty())+ .ok_or_else(|| OAuthError::Registration("no client_id in the response".into()))?+ .to_string();+ let client_secret = reply["client_secret"].as_str().filter(|s| !s.is_empty()).map(str::to_string);+ let auth_method = reply["token_endpoint_auth_method"]+ .as_str()+ .map(str::to_string)+ .unwrap_or_else(|| if client_secret.is_some() { "client_secret_post".into() } else { "none".into() });+ Ok(ClientRegistration { client_id, client_secret, auth_method })+}++/// The URL the user's browser opens to sign in.+pub fn authorize_url(+ discovery: &Discovery,+ client_id: &str,+ redirect_uri: &str,+ state: &str,+ pkce: &Pkce,+) -> Result<String, OAuthError> {+ let mut url = Url::parse(&discovery.metadata.authorization_endpoint)+ .map_err(|_| OAuthError::Discovery("invalid authorization endpoint".into()))?;+ {+ let mut q = url.query_pairs_mut();+ q.append_pair("response_type", "code")+ .append_pair("client_id", client_id)+ .append_pair("redirect_uri", redirect_uri)+ .append_pair("code_challenge", &pkce.challenge)+ .append_pair("code_challenge_method", "S256")+ .append_pair("state", state)+ .append_pair("resource", &discovery.resource);+ if let Some(scope) = &discovery.scope {+ q.append_pair("scope", scope);+ }+ }+ Ok(url.into())+}++fn oauth_error_text(body: &Value, status: reqwest::StatusCode) -> String {+ let code = body["error"].as_str().unwrap_or("");+ let description = body["error_description"].as_str().unwrap_or("");+ let text = match (code.is_empty(), description.is_empty()) {+ (false, false) => format!("{code}: {description}"),+ (false, true) => code.to_string(),+ _ => format!("HTTP {status}"),+ };+ super::truncate_text(&text, 300)+}++/// Client credentials for a token request.+pub struct ClientAuth<'a> {+ pub client_id: &'a str,+ pub client_secret: Option<&'a str>,+ pub auth_method: &'a str,+}++async fn token_request(+ http: &reqwest::Client,+ token_endpoint: &str,+ client: &ClientAuth<'_>,+ mut form: Vec<(&str, String)>,+ previous_refresh: Option<&str>,+) -> Result<TokenSet, OAuthError> {+ let mut req = http.post(token_endpoint).header("Accept", "application/json");+ match (client.auth_method, client.client_secret) {+ ("client_secret_basic", Some(secret)) => req = req.basic_auth(client.client_id, Some(secret)),+ (_, Some(secret)) => {+ form.push(("client_id", client.client_id.to_string()));+ form.push(("client_secret", secret.to_string()));+ }+ (_, None) => form.push(("client_id", client.client_id.to_string())),+ }+ let resp = req.form(&form).send().await.map_err(http_err)?;+ let status = resp.status();+ let body: Value = resp.json().await.unwrap_or(Value::Null);+ if !status.is_success() {+ return Err(OAuthError::Token(oauth_error_text(&body, status)));+ }+ let access_token = body["access_token"]+ .as_str()+ .filter(|s| !s.is_empty())+ .ok_or_else(|| OAuthError::Token("no access_token in the response".into()))?+ .to_string();+ let expires_at = body["expires_in"]+ .as_i64()+ .or_else(|| body["expires_in"].as_str().and_then(|s| s.parse().ok()))+ .filter(|s| *s > 0)+ .map(|s| Utc::now() + chrono::Duration::seconds(s));+ // A refresh response may omit refresh_token; the old one stays valid then+ let refresh_token = body["refresh_token"]+ .as_str()+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .or_else(|| previous_refresh.map(str::to_string));+ Ok(TokenSet { access_token, refresh_token, expires_at })+}++/// Exchanges an authorization code (with its PKCE verifier) for tokens.+pub async fn exchange_code(http: &reqwest::Client, pending: &PendingAuth, code: &str) -> Result<TokenSet, OAuthError> {+ let client = ClientAuth {+ client_id: &pending.client_id,+ client_secret: pending.client_secret.as_deref(),+ auth_method: &pending.auth_method,+ };+ let form = vec![+ ("grant_type", "authorization_code".to_string()),+ ("code", code.to_string()),+ ("redirect_uri", pending.redirect_uri.clone()),+ ("code_verifier", pending.verifier.clone()),+ ("resource", pending.resource.clone()),+ ];+ token_request(http, &pending.token_endpoint, &client, form, None).await+}++pub async fn refresh(+ http: &reqwest::Client,+ token_endpoint: &str,+ client: &ClientAuth<'_>,+ refresh_token: &str,+ resource: &str,+) -> Result<TokenSet, OAuthError> {+ let form = vec![+ ("grant_type", "refresh_token".to_string()),+ ("refresh_token", refresh_token.to_string()),+ ("resource", resource.to_string()),+ ];+ token_request(http, token_endpoint, client, form, Some(refresh_token)).await+}++/// Builds a [`PendingAuth`]; `created` is set when it is stored.+pub fn pending_auth(+ server_id: &str,+ pkce: &Pkce,+ redirect_uri: &str,+ discovery: &Discovery,+ client: &ClientRegistration,+) -> PendingAuth {+ PendingAuth {+ server_id: server_id.to_string(),+ verifier: pkce.verifier.clone(),+ redirect_uri: redirect_uri.to_string(),+ token_endpoint: discovery.metadata.token_endpoint.clone(),+ client_id: client.client_id.clone(),+ client_secret: client.client_secret.clone(),+ auth_method: client.auth_method.clone(),+ resource: discovery.resource.clone(),+ created: Instant::now(),+ }+}++/// Validates the browser-supplied origin for the callback: http(s), no path, query or+/// credentials, and the same host the request came in on (directly or via a proxy).+pub fn validate_origin(origin: &str, hosts: &[&str]) -> Result<String, String> {+ let url = Url::parse(origin.trim()).map_err(|_| "origin is not a valid URL".to_string())?;+ if !matches!(url.scheme(), "http" | "https") {+ return Err("origin must be http or https".into());+ }+ if !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some() {+ return Err("origin must not contain credentials, a query or a fragment".into());+ }+ if url.path() != "/" && !url.path().is_empty() {+ return Err("origin must not contain a path".into());+ }+ let serialized = url.origin().ascii_serialization();+ let authority = serialized.split_once("://").map(|(_, a)| a.to_ascii_lowercase()).unwrap_or_default();+ // Host headers may carry the default port explicitly; Url drops it+ let default_port = if url.scheme() == "https" { ":443" } else { ":80" };+ let matches = hosts.iter().any(|h| {+ let h = h.trim().to_ascii_lowercase();+ h == authority || h.strip_suffix(default_port) == Some(authority.as_str())+ });+ if !matches {+ return Err("origin does not match the host this request was sent to".into());+ }+ Ok(serialized)+}++pub fn callback_url(origin: &str) -> String {+ format!("{origin}/api/mcp/oauth/callback")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_bearer_challenges() {+ let c = parse_www_authenticate(+ r#"Bearer realm="mcp", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource", scope="read write""#,+ );+ assert_eq!(c.resource_metadata.as_deref(), Some("https://mcp.example.com/.well-known/oauth-protected-resource"));+ assert_eq!(c.scope.as_deref(), Some("read write"));++ let c = parse_www_authenticate("Bearer error=invalid_token, resource_metadata=https://x.dev/prm");+ assert_eq!(c.resource_metadata.as_deref(), Some("https://x.dev/prm"));++ // Another scheme's params are ignored; escapes in quoted strings are handled+ let c = parse_www_authenticate(r#"Basic resource_metadata="https://evil.test", Bearer scope="a \"b\"""#);+ assert_eq!(c.resource_metadata, None);+ assert_eq!(c.scope.as_deref(), Some(r#"a "b""#));++ assert_eq!(parse_www_authenticate(""), BearerChallenge::default());+ assert_eq!(parse_www_authenticate("Bearer"), BearerChallenge::default());+ assert_eq!(parse_www_authenticate(r#"Bearer resource_metadata="unterminated"#).resource_metadata.as_deref(), Some("unterminated"));+ }++ #[test]+ fn builds_metadata_urls() {+ assert_eq!(+ protected_resource_metadata_urls("https://mcp.notion.com/mcp"),+ vec![+ "https://mcp.notion.com/.well-known/oauth-protected-resource/mcp",+ "https://mcp.notion.com/.well-known/oauth-protected-resource",+ ]+ );+ assert_eq!(protected_resource_metadata_urls("https://a.dev/"), vec!["https://a.dev/.well-known/oauth-protected-resource"]);+ assert_eq!(+ auth_server_metadata_urls("https://auth.dev"),+ vec!["https://auth.dev/.well-known/oauth-authorization-server", "https://auth.dev/.well-known/openid-configuration"]+ );+ assert_eq!(+ auth_server_metadata_urls("https://auth.dev/tenant1"),+ vec![+ "https://auth.dev/.well-known/oauth-authorization-server/tenant1",+ "https://auth.dev/.well-known/openid-configuration/tenant1",+ "https://auth.dev/tenant1/.well-known/openid-configuration",+ ]+ );+ assert_eq!(canonical_resource("https://mcp.notion.com/mcp#x"), "https://mcp.notion.com/mcp");+ assert_eq!(canonical_resource("https://mcp.dev/"), "https://mcp.dev");+ }++ #[test]+ fn only_https_or_loopback_endpoints() {+ assert!(acceptable_endpoint("https://auth.dev/token"));+ assert!(acceptable_endpoint("http://127.0.0.1:9/token"));+ assert!(acceptable_endpoint("http://localhost/token"));+ assert!(acceptable_endpoint("http://[::1]:8/token"));+ assert!(!acceptable_endpoint("http://auth.dev/token"));+ assert!(!acceptable_endpoint("http://10.0.0.1/token"));+ assert!(!acceptable_endpoint("javascript:alert(1)"));+ assert!(!acceptable_endpoint("file:///etc/passwd"));+ }++ #[test]+ fn pkce_s256_matches_rfc7636_example() {+ let p = Pkce::from_verifier("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk".into());+ assert_eq!(p.challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");+ let a = Pkce::new();+ let b = Pkce::new();+ assert_ne!(a.verifier, b.verifier);+ assert!((43..=128).contains(&a.verifier.len()));+ assert!(a.verifier.chars().all(|c| c.is_ascii_alphanumeric()));+ }++ fn pending(server: &str) -> PendingAuth {+ PendingAuth {+ server_id: server.into(),+ verifier: "v".into(),+ redirect_uri: "https://k.dev/api/mcp/oauth/callback".into(),+ token_endpoint: "https://a.dev/token".into(),+ client_id: "c".into(),+ client_secret: None,+ auth_method: "none".into(),+ resource: "https://m.dev/mcp".into(),+ created: Instant::now(),+ }+ }++ #[test]+ fn state_is_single_use_and_expires() {+ let store = PendingStore::default();+ let state = store.insert(pending("s1"));+ assert!(state.len() >= 43);+ assert!(store.take("not-a-state").is_none());+ assert_eq!(store.take(&state).unwrap().server_id, "s1");+ assert!(store.take(&state).is_none(), "a state works once");++ let now = Instant::now();+ let old = store.insert_at(pending("s2"), now);+ assert!(store.take_at(&old, now + PENDING_TTL + Duration::from_secs(1)).is_none(), "expired");++ // A new start for the same server replaces the earlier one+ let first = store.insert(pending("s3"));+ let second = store.insert(pending("s3"));+ assert!(store.take(&first).is_none());+ assert_eq!(store.take(&second).unwrap().server_id, "s3");+ }++ #[test]+ fn refresh_decision() {+ let now = Utc::now();+ assert!(!needs_refresh(None, now), "no expiry: use as is");+ assert!(!needs_refresh(Some(now + chrono::Duration::seconds(3600)), now));+ assert!(!needs_refresh(Some(now + chrono::Duration::seconds(61)), now));+ assert!(needs_refresh(Some(now + chrono::Duration::seconds(59)), now));+ assert!(needs_refresh(Some(now - chrono::Duration::seconds(5)), now));+ }++ #[test]+ fn user_authorization_header_wins() {+ let mut headers = std::collections::BTreeMap::new();+ assert!(apply_bearer(&mut headers, "tok"));+ assert_eq!(headers["Authorization"], "Bearer tok");++ let mut headers = std::collections::BTreeMap::from([("authorization".to_string(), "Bearer mine".to_string())]);+ assert!(!apply_bearer(&mut headers, "tok"));+ assert_eq!(headers.len(), 1);+ assert_eq!(headers["authorization"], "Bearer mine");+ assert!(has_user_authorization(&headers));+ }++ #[test]+ fn validates_callback_origin() {+ assert_eq!(validate_origin("https://maus.jumpin.games", &["maus.jumpin.games"]).unwrap(), "https://maus.jumpin.games");+ assert_eq!(validate_origin("http://127.0.0.1:7777", &["127.0.0.1:7777"]).unwrap(), "http://127.0.0.1:7777");+ assert_eq!(validate_origin("https://k.dev/", &["k.dev:443"]).unwrap(), "https://k.dev");+ // Proxy: Host is internal, X-Forwarded-Host is public+ assert!(validate_origin("https://k.dev", &["127.0.0.1:7777", "k.dev"]).is_ok());+ assert!(validate_origin("https://evil.test", &["k.dev"]).is_err());+ assert!(validate_origin("https://k.dev.evil.test", &["k.dev"]).is_err());+ assert!(validate_origin("https://k.dev/x", &["k.dev"]).is_err());+ assert!(validate_origin("https://u:[email protected]", &["k.dev"]).is_err());+ assert!(validate_origin("javascript:alert(1)", &["k.dev"]).is_err());+ assert!(validate_origin("http://k.dev:8080", &["k.dev"]).is_err());+ assert_eq!(callback_url("https://k.dev"), "https://k.dev/api/mcp/oauth/callback");+ }+}diff --git a/src/mcp/oauth_mock.rs b/src/mcp/oauth_mock.rsnew file mode 100644index 00000000..07732f37--- /dev/null+++ b/src/mcp/oauth_mock.rs@@ -0,0 +1,267 @@+//! A small OAuth-protected streamable-HTTP MCP server, run with the hidden+//! `kwnt mcp-oauth-mock-server` subcommand. It implements just enough of the MCP authorization+//! spec (protected-resource and authorization-server metadata, dynamic registration, PKCE S256,+//! `resource`, refresh with rotation) for tests and live checks of kwnt's sign-in without a+//! real provider.+//!+//! `/authorize` shows an "Allow" link instead of asking for credentials; its target is also sent+//! in the `X-Mock-Redirect` header so tests can follow it without a browser.++use axum::{+ extract::{Query, State},+ http::{HeaderMap, StatusCode},+ response::{Html, IntoResponse, Response},+ routing::{get, post},+ Form, Json, Router,+};+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};++#[derive(Debug, Clone)]+pub struct MockOptions {+ /// `expires_in` of issued access tokens. Below 60 makes kwnt refresh on every use.+ pub expires_in: i64,+}++impl Default for MockOptions {+ fn default() -> Self {+ Self { expires_in: 3600 }+ }+}++struct Grant {+ client_id: String,+ redirect_uri: String,+ challenge: String,+ resource: String,+}++#[derive(Default)]+struct Inner {+ clients: HashMap<String, Vec<String>>, // client_id -> redirect_uris+ codes: HashMap<String, Grant>,+ access: HashSet<String>,+ refresh: HashMap<String, String>, // refresh token -> client_id+}++pub struct MockState {+ pub base_url: String,+ pub options: MockOptions,+ counter: AtomicU64,+ pub registrations: AtomicU64,+ pub code_exchanges: AtomicU64,+ pub refreshes: AtomicU64,+ inner: Mutex<Inner>,+}++impl MockState {+ fn next(&self, prefix: &str) -> String {+ format!("{prefix}-{}-{}", self.counter.fetch_add(1, Ordering::SeqCst), uuid::Uuid::new_v4().simple())+ }++ /// Revokes every access token, as a provider would when the user removes the app.+ pub fn revoke_access_tokens(&self) {+ self.inner.lock().unwrap().access.clear();+ }++ /// Revokes every access and refresh token: the user removed the app at the provider.+ pub fn revoke_all(&self) {+ let mut inner = self.inner.lock().unwrap();+ inner.access.clear();+ inner.refresh.clear();+ }++ fn resource(&self) -> String {+ format!("{}/mcp", self.base_url)+ }+}++type Shared = Arc<MockState>;++fn oauth_error(code: &str, description: &str) -> Response {+ (StatusCode::BAD_REQUEST, Json(json!({"error": code, "error_description": description}))).into_response()+}++async fn resource_metadata(State(s): State<Shared>) -> Json<Value> {+ Json(json!({+ "resource": s.resource(),+ "authorization_servers": [s.base_url],+ "scopes_supported": ["mcp"],+ "bearer_methods_supported": ["header"],+ }))+}++async fn server_metadata(State(s): State<Shared>) -> Json<Value> {+ let b = &s.base_url;+ Json(json!({+ "issuer": b,+ "authorization_endpoint": format!("{b}/authorize"),+ "token_endpoint": format!("{b}/token"),+ "registration_endpoint": format!("{b}/register"),+ "response_types_supported": ["code"],+ "grant_types_supported": ["authorization_code", "refresh_token"],+ "code_challenge_methods_supported": ["S256"],+ "token_endpoint_auth_methods_supported": ["none"],+ }))+}++async fn register(State(s): State<Shared>, Json(body): Json<Value>) -> Response {+ let uris: Vec<String> = body["redirect_uris"]+ .as_array()+ .map(|a| a.iter().filter_map(|u| u.as_str().map(str::to_string)).collect())+ .unwrap_or_default();+ if uris.is_empty() {+ return oauth_error("invalid_redirect_uri", "redirect_uris is required");+ }+ s.registrations.fetch_add(1, Ordering::SeqCst);+ let client_id = s.next("client");+ s.inner.lock().unwrap().clients.insert(client_id.clone(), uris.clone());+ (StatusCode::CREATED, Json(json!({"client_id": client_id, "redirect_uris": uris, "token_endpoint_auth_method": "none"})))+ .into_response()+}++fn escape(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")+}++async fn authorize(State(s): State<Shared>, Query(q): Query<HashMap<String, String>>) -> Response {+ let get = |k: &str| q.get(k).cloned().unwrap_or_default();+ let (client_id, redirect_uri, state) = (get("client_id"), get("redirect_uri"), get("state"));+ let known = s.inner.lock().unwrap().clients.get(&client_id).is_some_and(|u| u.contains(&redirect_uri));+ if !known {+ return (StatusCode::BAD_REQUEST, "unknown client or redirect_uri").into_response();+ }+ if get("response_type") != "code" || get("code_challenge_method") != "S256" || get("code_challenge").is_empty() {+ return (StatusCode::BAD_REQUEST, "PKCE S256 and response_type=code are required").into_response();+ }+ if get("resource") != s.resource() {+ return (StatusCode::BAD_REQUEST, "resource does not match this server").into_response();+ }+ let code = s.next("code");+ s.inner.lock().unwrap().codes.insert(+ code.clone(),+ Grant { client_id, redirect_uri: redirect_uri.clone(), challenge: get("code_challenge"), resource: get("resource") },+ );+ let mut target = url::Url::parse(&redirect_uri).expect("registered redirect_uri is a URL");+ target.query_pairs_mut().append_pair("code", &code).append_pair("state", &state);+ let mut denied = url::Url::parse(&redirect_uri).expect("registered redirect_uri is a URL");+ denied+ .query_pairs_mut()+ .append_pair("error", "access_denied")+ .append_pair("error_description", "The user said no")+ .append_pair("state", &state);+ let page = format!(+ "<!doctype html><title>Mock sign-in</title><h1>kwnt mock sign-in</h1>\+ <p><a id=\"allow\" href=\"{}\">Allow</a> · <a id=\"deny\" href=\"{}\">Deny</a></p>",+ escape(target.as_str()),+ escape(denied.as_str())+ );+ let mut resp = Html(page).into_response();+ if let Ok(v) = target.as_str().parse() {+ resp.headers_mut().insert("x-mock-redirect", v);+ }+ resp+}++async fn token(State(s): State<Shared>, Form(f): Form<HashMap<String, String>>) -> Response {+ let get = |k: &str| f.get(k).cloned().unwrap_or_default();+ let mut inner = s.inner.lock().unwrap();+ let client_id = match get("grant_type").as_str() {+ "authorization_code" => {+ let Some(grant) = inner.codes.remove(&get("code")) else {+ return oauth_error("invalid_grant", "unknown or used code");+ };+ let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(get("code_verifier").as_bytes()));+ if challenge != grant.challenge {+ return oauth_error("invalid_grant", "PKCE verification failed");+ }+ if grant.client_id != get("client_id") || grant.redirect_uri != get("redirect_uri") || grant.resource != get("resource") {+ return oauth_error("invalid_grant", "client, redirect_uri or resource mismatch");+ }+ s.code_exchanges.fetch_add(1, Ordering::SeqCst);+ grant.client_id+ }+ "refresh_token" => {+ // Rotation: the old refresh token stops working+ let Some(client_id) = inner.refresh.remove(&get("refresh_token")) else {+ return oauth_error("invalid_grant", "unknown refresh token");+ };+ if client_id != get("client_id") || get("resource") != s.resource() {+ return oauth_error("invalid_grant", "client or resource mismatch");+ }+ s.refreshes.fetch_add(1, Ordering::SeqCst);+ client_id+ }+ _ => return oauth_error("unsupported_grant_type", "only authorization_code and refresh_token"),+ };+ let access = s.next("at");+ let refresh = s.next("rt");+ inner.access.insert(access.clone());+ inner.refresh.insert(refresh.clone(), client_id);+ Json(json!({"access_token": access, "token_type": "Bearer", "expires_in": s.options.expires_in, "refresh_token": refresh}))+ .into_response()+}++async fn mcp(State(s): State<Shared>, headers: HeaderMap, Json(msg): Json<Value>) -> Response {+ let token = headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .unwrap_or("");+ if !s.inner.lock().unwrap().access.contains(token) {+ let challenge = format!(+ "Bearer resource_metadata=\"{}/.well-known/oauth-protected-resource/mcp\", scope=\"mcp\"",+ s.base_url+ );+ return (StatusCode::UNAUTHORIZED, [("www-authenticate", challenge)], Json(json!({"error": "invalid_token"})))+ .into_response();+ }+ let Some(id) = msg.get("id").cloned() else {+ return StatusCode::ACCEPTED.into_response();+ };+ let result = match msg["method"].as_str().unwrap_or("") {+ "initialize" => json!({+ "protocolVersion": super::client::PROTOCOL_VERSION,+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "kwnt-oauth-mock", "version": env!("CARGO_PKG_VERSION")},+ }),+ "tools/list" => json!({"tools": [{"name": "whoami", "description": "Says who you are signed in as.",+ "inputSchema": {"type": "object", "properties": {}}}]}),+ "tools/call" => json!({"content": [{"type": "text", "text": "signed in to the mock"}], "isError": false}),+ _ => return Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found"}})).into_response(),+ };+ Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response()+}++pub fn router(base_url: &str, options: MockOptions) -> (Router, Shared) {+ let state = Arc::new(MockState {+ base_url: base_url.trim_end_matches('/').to_string(),+ options,+ counter: AtomicU64::new(1),+ registrations: AtomicU64::new(0),+ code_exchanges: AtomicU64::new(0),+ refreshes: AtomicU64::new(0),+ inner: Mutex::default(),+ });+ let app = Router::new()+ .route("/.well-known/oauth-protected-resource", get(resource_metadata))+ .route("/.well-known/oauth-protected-resource/mcp", get(resource_metadata))+ .route("/.well-known/oauth-authorization-server", get(server_metadata))+ .route("/register", post(register))+ .route("/authorize", get(authorize))+ .route("/token", post(token))+ .route("/mcp", post(mcp).delete(|| async { StatusCode::OK }))+ .with_state(state.clone());+ (app, state)+}++/// Serves on `listener` until the process ends. The base URL is the listener's address.+pub async fn serve(listener: tokio::net::TcpListener, options: MockOptions) -> std::io::Result<()> {+ let base = format!("http://{}", listener.local_addr()?);+ let (app, _) = router(&base, options);+ axum::serve(listener, app).await+}diff --git a/src/server/mcp_oauth.rs b/src/server/mcp_oauth.rsnew file mode 100644index 00000000..73716db9--- /dev/null+++ b/src/server/mcp_oauth.rs@@ -0,0 +1,367 @@+//! OAuth sign-in for http MCP servers: the start/callback/disconnect endpoints, and the token+//! handling every connection goes through (refresh before expiry, inject `Authorization`).+//! Contract: docs/mcp-api.md.++use super::AppState;+use crate::db::models::{McpOAuthClient, McpOAuthToken, McpServer};+use crate::db::DbError;+use crate::mcp::oauth::{self, ClientAuth, OAuthError, OAuthStatus, PendingStore};+use axum::{+ extract::{Path, Query, State},+ http::{header, HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use chrono::Utc;+use serde::Deserialize;+use serde_json::{json, Value};++/// Process-wide sign-in state: open sign-ins and the lock that serializes refreshes, so two+/// turns never spend the same (rotating) refresh token.+pub struct OAuthState {+ pub pending: PendingStore,+ pub http: reqwest::Client,+ refresh_lock: tokio::sync::Mutex<()>,+}++impl Default for OAuthState {+ fn default() -> Self {+ Self { pending: PendingStore::default(), http: oauth::http_client(), refresh_lock: tokio::sync::Mutex::new(()) }+ }+}++/// How a server's `Authorization` header was decided for one connection.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TokenUse {+ /// stdio, or http without a stored token.+ None,+ /// The user configured their own Authorization header; kwnt's token is not used.+ UserHeader,+ /// kwnt added `Authorization: Bearer <stored token>`.+ Injected,+}++type ApiError = (StatusCode, Json<Value>);++fn err(status: StatusCode, message: impl Into<String>) -> ApiError {+ (status, Json(json!({ "error": message.into() })))+}++fn db_err(e: DbError) -> ApiError {+ tracing::warn!(error = %e, "MCP OAuth database error");+ err(StatusCode::INTERNAL_SERVER_ERROR, "database error")+}++async fn refresh_stored(state: &AppState, server_id: &str, force: bool) -> Result<Option<McpOAuthToken>, DbError> {+ let _guard = state.mcp_oauth.refresh_lock.lock().await;+ // Re-read under the lock: another turn may have refreshed already+ let Some(token) = state.db.get_mcp_oauth_token(server_id).await? else {+ return Ok(None);+ };+ let now = Utc::now();+ if !force && !oauth::needs_refresh(token.expires_at, now) {+ return Ok(Some(token));+ }+ let expired = token.expires_at.is_some_and(|t| t <= now);+ let Some(refresh_token) = token.refresh_token.clone() else {+ if force || expired {+ state.db.delete_mcp_oauth_token(server_id).await?;+ return Ok(None);+ }+ return Ok(Some(token));+ };+ let client = ClientAuth {+ client_id: &token.client_id,+ client_secret: token.client_secret.as_deref(),+ auth_method: &token.auth_method,+ };+ match oauth::refresh(&state.mcp_oauth.http, &token.token_endpoint, &client, &refresh_token, &token.resource).await {+ Ok(set) => {+ let updated = McpOAuthToken {+ access_token: set.access_token,+ refresh_token: set.refresh_token,+ expires_at: set.expires_at,+ ..token+ };+ state.db.save_mcp_oauth_token(&updated).await?;+ Ok(Some(updated))+ }+ // The authorization server said no: the grant is gone, so the user has to sign in again+ Err(e @ OAuthError::Token(_)) => {+ tracing::info!(server_id, error = %e, "MCP OAuth refresh rejected; sign-in needed");+ state.db.delete_mcp_oauth_token(server_id).await?;+ Ok(None)+ }+ // Network trouble: keep the grant, and use the current token while it is still valid+ Err(e) => {+ tracing::warn!(server_id, error = %e, "MCP OAuth refresh failed");+ Ok((!expired && !force).then_some(token))+ }+ }+}++/// Adds the stored access token to an http server's headers, refreshing it first if it+/// expires within a minute. A user-set Authorization header wins.+pub async fn authorize_server(state: &AppState, server: &mut McpServer) -> TokenUse {+ if server.transport != "http" {+ return TokenUse::None;+ }+ if oauth::has_user_authorization(&server.headers) {+ return TokenUse::UserHeader;+ }+ match refresh_stored(state, &server.id, false).await {+ Ok(Some(token)) if oauth::apply_bearer(&mut server.headers, &token.access_token) => TokenUse::Injected,+ Ok(_) => TokenUse::None,+ Err(e) => {+ tracing::warn!(error = %e, "could not load MCP OAuth token");+ TokenUse::None+ }+ }+}++/// [`authorize_server`] for every server of a turn.+pub async fn authorize_servers(state: &AppState, servers: &mut [McpServer]) {+ for server in servers {+ authorize_server(state, server).await;+ }+}++/// After a 401 with kwnt's token: refresh once and return the server with the new token, or+/// drop the token (the server then needs sign-in) and return `None`.+pub async fn retry_after_unauthorized(state: &AppState, original: &McpServer) -> Option<McpServer> {+ match refresh_stored(state, &original.id, true).await {+ Ok(Some(token)) => {+ let mut server = original.clone();+ oauth::apply_bearer(&mut server.headers, &token.access_token);+ Some(server)+ }+ Ok(None) => None,+ Err(e) => {+ tracing::warn!(error = %e, "could not refresh MCP OAuth token");+ None+ }+ }+}++/// Sign-in status for every server, for list/get responses.+pub async fn statuses(state: &AppState) -> std::collections::HashMap<String, OAuthStatus> {+ state+ .db+ .list_mcp_oauth_expiries()+ .await+ .unwrap_or_default()+ .into_iter()+ .map(|(id, expires_at)| (id, OAuthStatus { connected: true, expires_at }))+ .collect()+}++#[derive(Debug, Deserialize)]+pub struct StartBody {+ pub origin: String,+}++/// Hosts the request was addressed to: `Host` and every `X-Forwarded-Host` value.+fn request_hosts(headers: &HeaderMap) -> Vec<String> {+ let mut hosts = Vec::new();+ for name in [header::HOST.as_str(), "x-forwarded-host"] {+ for value in headers.get_all(name) {+ if let Ok(v) = value.to_str() {+ hosts.extend(v.split(',').map(|h| h.trim().to_string()).filter(|h| !h.is_empty()));+ }+ }+ }+ hosts+}++/// `POST /api/mcp/servers/:id/oauth/start` `{origin}` → `{authorize_url}`.+pub async fn start(+ State(state): State<AppState>,+ Path(id): Path<String>,+ headers: HeaderMap,+ Json(body): Json<StartBody>,+) -> Result<Json<Value>, ApiError> {+ let server = state+ .db+ .get_mcp_server(&id)+ .await+ .map_err(db_err)?+ .ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;+ let Some(server_url) = server.url.clone().filter(|_| server.transport == "http") else {+ return Err(err(StatusCode::BAD_REQUEST, "sign-in only applies to http servers"));+ };+ let hosts = request_hosts(&headers);+ let host_refs: Vec<&str> = hosts.iter().map(String::as_str).collect();+ let origin = oauth::validate_origin(&body.origin, &host_refs).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;+ let redirect_uri = oauth::callback_url(&origin);+ let http = &state.mcp_oauth.http;+ let upstream = |e: OAuthError| err(StatusCode::BAD_GATEWAY, e.to_string());++ let challenge = oauth::probe_challenge(http, &server_url).await;+ let discovery = oauth::discover(http, &server_url, challenge.as_ref()).await.map_err(upstream)?;+ let client = match state.db.get_mcp_oauth_client(&id, &redirect_uri, &discovery.issuer).await.map_err(db_err)? {+ Some(c) => oauth::ClientRegistration {+ client_id: c.client_id,+ client_secret: c.client_secret,+ auth_method: c.auth_method,+ },+ None => {+ let reg = oauth::register_client(http, &discovery.metadata, &redirect_uri).await.map_err(upstream)?;+ state+ .db+ .save_mcp_oauth_client(&McpOAuthClient {+ server_id: id.clone(),+ redirect_uri: redirect_uri.clone(),+ issuer: discovery.issuer.clone(),+ client_id: reg.client_id.clone(),+ client_secret: reg.client_secret.clone(),+ auth_method: reg.auth_method.clone(),+ })+ .await+ .map_err(db_err)?;+ reg+ }+ };+ let pkce = oauth::Pkce::new();+ let pending = oauth::pending_auth(&id, &pkce, &redirect_uri, &discovery, &client);+ let state_param = state.mcp_oauth.pending.insert(pending);+ let authorize_url = oauth::authorize_url(&discovery, &client.client_id, &redirect_uri, &state_param, &pkce).map_err(upstream)?;+ Ok(Json(json!({ "authorize_url": authorize_url })))+}++#[derive(Debug, Deserialize)]+pub struct CallbackQuery {+ pub code: Option<String>,+ pub state: Option<String>,+ pub error: Option<String>,+ pub error_description: Option<String>,+}++fn html_escape(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")+}++/// JSON that is safe inside a `<script>` element.+fn script_json(v: &Value) -> String {+ v.to_string()+ .replace('<', "\\u003c")+ .replace('>', "\\u003e")+ .replace('&', "\\u0026")+ .replace('\u{2028}', "\\u2028")+ .replace('\u{2029}', "\\u2029")+}++/// The page the sign-in popup lands on: tells the opener the outcome and closes, or goes to+/// the app when there is no opener.+pub fn callback_page(server_id: Option<&str>, result: Result<(), String>) -> Response {+ let (ok, error) = match &result {+ Ok(()) => (true, None),+ Err(e) => (false, Some(crate::mcp::truncate_text(e, 300))),+ };+ let mut message = json!({ "type": "kwnt-mcp-oauth", "server_id": server_id, "ok": ok });+ if let Some(e) = &error {+ message["error"] = json!(e);+ }+ let text = match &error {+ None => "Signed in. You can close this window.".to_string(),+ Some(e) => format!("Sign-in failed: {e}"),+ };+ let page = format!(+ "<!doctype html><html><head><meta charset=\"utf-8\"><title>kwnt sign-in</title></head>\+ <body><p>{}</p><script>(function(){{var m={};\+ if(window.opener){{try{{window.opener.postMessage(m,location.origin)}}catch(e){{}}window.close()}}\+ else{{location.replace(\"/\")}}}})();</script></body></html>",+ html_escape(&text),+ script_json(&message)+ );+ (+ StatusCode::OK,+ [+ (header::CONTENT_TYPE, "text/html; charset=utf-8"),+ (header::CACHE_CONTROL, "no-store"),+ (header::REFERRER_POLICY, "no-referrer"),+ (header::CONTENT_SECURITY_POLICY, "default-src 'none'; script-src 'unsafe-inline'"),+ ],+ page,+ )+ .into_response()+}++/// `GET /api/mcp/oauth/callback?code&state` (or `?error&state`).+pub async fn callback(State(state): State<AppState>, Query(q): Query<CallbackQuery>) -> Response {+ let Some(pending) = q.state.as_deref().and_then(|s| state.mcp_oauth.pending.take(s)) else {+ return callback_page(None, Err("this sign-in link has expired or was already used; try Connect again".into()));+ };+ let server_id = pending.server_id.clone();+ if let Some(code) = q.error.as_deref() {+ let detail = q.error_description.as_deref().map(|d| format!("{code}: {d}")).unwrap_or_else(|| code.to_string());+ return callback_page(Some(&server_id), Err(detail));+ }+ let Some(code) = q.code.as_deref().filter(|c| !c.is_empty()) else {+ return callback_page(Some(&server_id), Err("the sign-in response had no code".into()));+ };+ match state.db.get_mcp_server(&server_id).await {+ Ok(Some(_)) => {}+ Ok(None) => return callback_page(Some(&server_id), Err("this server was deleted".into())),+ Err(e) => {+ tracing::warn!(error = %e, "MCP OAuth callback database error");+ return callback_page(Some(&server_id), Err("database error".into()));+ }+ }+ let set = match oauth::exchange_code(&state.mcp_oauth.http, &pending, code).await {+ Ok(set) => set,+ Err(e) => return callback_page(Some(&server_id), Err(e.to_string())),+ };+ let token = McpOAuthToken {+ server_id: server_id.clone(),+ access_token: set.access_token,+ refresh_token: set.refresh_token,+ expires_at: set.expires_at,+ token_endpoint: pending.token_endpoint,+ client_id: pending.client_id,+ client_secret: pending.client_secret,+ auth_method: pending.auth_method,+ resource: pending.resource,+ };+ if let Err(e) = state.db.save_mcp_oauth_token(&token).await {+ tracing::warn!(error = %e, "could not store MCP OAuth token");+ return callback_page(Some(&server_id), Err("could not store the sign-in".into()));+ }+ callback_page(Some(&server_id), Ok(()))+}++/// `DELETE /api/mcp/servers/:id/oauth`: forgets the tokens (the registration is kept).+pub async fn disconnect(State(state): State<AppState>, Path(id): Path<String>) -> Result<Json<Value>, ApiError> {+ if state.db.get_mcp_server(&id).await.map_err(db_err)?.is_none() {+ return Err(err(StatusCode::NOT_FOUND, "MCP server not found"));+ }+ state.db.delete_mcp_oauth_token(&id).await.map_err(db_err)?;+ Ok(Json(json!({ "status": "disconnected" })))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn callback_page_escapes_everything() {+ let resp = callback_page(Some("id\"</script>"), Err("<img src=x onerror=alert(1)>\u{2028}".into()));+ let headers = resp.headers().clone();+ assert_eq!(headers[header::CACHE_CONTROL], "no-store");+ let body = futures::executor::block_on(axum::body::to_bytes(resp.into_body(), 1 << 16)).unwrap();+ let body = String::from_utf8(body.to_vec()).unwrap();+ assert!(!body.contains("<img"), "{body}");+ assert!(!body.contains("</script>\""), "{body}");+ assert_eq!(body.matches("</script>").count(), 1, "{body}");+ assert!(body.contains("<img"));+ assert!(body.contains("\\u003cimg"));+ assert!(body.contains("postMessage(m,location.origin)"));+ }++ #[test]+ fn collects_request_hosts() {+ let mut h = HeaderMap::new();+ h.insert(header::HOST, "127.0.0.1:7777".parse().unwrap());+ h.insert("x-forwarded-host", "k.dev, proxy.internal".parse().unwrap());+ assert_eq!(request_hosts(&h), vec!["127.0.0.1:7777", "k.dev", "proxy.internal"]);+ }+}diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rsindex d55b0deb..e9ec26ba 100644--- a/src/server/mcp_routes.rs+++ b/src/server/mcp_routes.rs@@ -1,7 +1,7 @@//! MCP server registry and per-kwant assignment endpoints. Contract: docs/mcp-api.md.-use super::AppState;-use crate::db::DbError;+use super::{mcp_oauth::{self, TokenUse}, AppState};+use crate::db::{models::McpServer, DbError};use crate::mcp::{self, McpClient, McpError, McpServerInput, McpServerView};use axum::{extract::{Path, State},@@ -29,14 +29,27 @@ fn db_err(e: DbError) -> ApiError {err(StatusCode::INTERNAL_SERVER_ERROR, "database error")}+/// The API view of `server`, with its sign-in status.+async fn view(state: &AppState, server: &McpServer) -> McpServerView {+ let mut view = McpServerView::from(server);+ view.oauth = mcp_oauth::statuses(state).await.remove(&server.id).unwrap_or_default();+ view+}+pub async fn list_servers(State(state): State<AppState>) -> ApiResult<Vec<McpServerView>> {let servers = state.db.list_mcp_servers().await.map_err(db_err)?;- Ok(Json(servers.iter().map(McpServerView::from).collect()))+ let mut statuses = mcp_oauth::statuses(&state).await;+ Ok(Json(+ servers+ .iter()+ .map(|s| McpServerView { oauth: statuses.remove(&s.id).unwrap_or_default(), ..McpServerView::from(s) })+ .collect(),+ ))}pub async fn get_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<McpServerView> {match state.db.get_mcp_server(&id).await.map_err(db_err)? {- Some(s) => Ok(Json(McpServerView::from(&s))),+ Some(s) => Ok(Json(view(&state, &s).await)),None => Err(err(StatusCode::NOT_FOUND, "MCP server not found")),}}@@ -59,8 +72,13 @@ pub async fn update_server(.map_err(db_err)?.ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;let server = mcp::build_server(input, Some(&existing)).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;- match state.db.update_mcp_server(&server).await.map_err(db_err)? {- Some(s) => Ok(Json(McpServerView::from(&s))),+ let updated = state.db.update_mcp_server(&server).await.map_err(db_err)?;+ if updated.is_some() && (server.url != existing.url || server.transport != existing.transport) {+ // Tokens and registrations belong to the old address+ state.db.clear_mcp_oauth(&id).await.map_err(db_err)?;+ }+ match updated {+ Some(s) => Ok(Json(view(&state, &s).await)),None => Err(err(StatusCode::NOT_FOUND, "MCP server not found")),}}@@ -73,37 +91,60 @@ pub async fn delete_server(State(state): State<AppState>, Path(id): Path<String>}}-/// Connects with the stored config, lists the tools and disconnects. Errors are redacted.-pub async fn test_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<Value> {- let server = state- .db- .get_mcp_server(&id)- .await- .map_err(db_err)?- .ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;- let secrets = server.secret_values();- let start = Instant::now();- let cwd = state.config.data_dir.join("workspace");-- let mut outcome = match McpClient::connect(&server, Some(&cwd)).await {+/// Connects once and lists the tools.+async fn try_list(server: &McpServer, cwd: &std::path::Path) -> Result<(Value, Vec<mcp::McpTool>), (McpError, String)> {+ match McpClient::connect(server, Some(cwd)).await {Ok(mut client) => {let tools = client.list_tools().await;let stderr_tail = client.stderr_tail();client.shutdown().await;- match tools {- Ok(tools) => json!({ "ok": true, "server_info": client.server_info, "tools": tools }),- Err(e) => json!({ "ok": false, "error": mcp::redact(&e.to_string(), &secrets),- "stderr_tail": mcp::redact(&stderr_tail, &secrets) }),- }+ tools.map(|t| (client.server_info.clone(), t)).map_err(|e| (e, stderr_tail))}Err(e) => {let stderr_tail = match e {McpError::Startup { ref stderr_tail, .. } => stderr_tail.clone(),_ => String::new(),};- json!({ "ok": false, "error": mcp::redact(&e.to_string(), &secrets),- "stderr_tail": mcp::redact(&stderr_tail, &secrets) })+ Err((e, stderr_tail))+ }+ }+}++/// Connects with the stored config (and sign-in), lists the tools and disconnects. Errors are+/// redacted. A 401 without a usable sign-in answers `auth_required: true`.+pub async fn test_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<Value> {+ let stored = state+ .db+ .get_mcp_server(&id)+ .await+ .map_err(db_err)?+ .ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;+ let start = Instant::now();+ let cwd = state.config.data_dir.join("workspace");++ let mut server = stored.clone();+ let token_use = mcp_oauth::authorize_server(&state, &mut server).await;+ let mut secrets = server.secret_values();+ let mut result = try_list(&server, &cwd).await;+ if token_use == TokenUse::Injected && matches!(result, Err((McpError::Unauthorized { .. }, _))) {+ // The token was rejected early (revoked, or the server's clock): refresh once+ if let Some(retry) = mcp_oauth::retry_after_unauthorized(&state, &stored).await {+ secrets.extend(retry.secret_values());+ result = try_list(&retry, &cwd).await;+ }+ }++ let mut outcome = match result {+ Ok((server_info, tools)) => json!({ "ok": true, "server_info": server_info, "tools": tools }),+ Err((McpError::Unauthorized { .. }, _)) if token_use != TokenUse::UserHeader => {+ if token_use == TokenUse::Injected {+ // Still rejected after a refresh: the sign-in is no longer valid+ let _ = state.db.delete_mcp_oauth_token(&id).await;+ }+ json!({ "ok": false, "auth_required": true, "error": "Sign-in required" })}+ Err((e, stderr_tail)) => json!({ "ok": false, "error": mcp::redact(&e.to_string(), &secrets),+ "stderr_tail": mcp::redact(&stderr_tail, &secrets) }),};outcome["duration_ms"] = json!(start.elapsed().as_millis() as u64);Ok(Json(outcome))diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex d38cdcbd..0c23aec0 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -150,7 +150,7 @@ fn local_base_url(state: &AppState) -> String {/// permission session claude will call. Returns `None` (no behaviour change) otherwise./// Pair with [`finish_turn`].pub async fn prepare_turn(state: &AppState, kwant: &Kwant) -> Option<(McpTurnContext, String)> {- let servers = match state.db.list_active_mcp_servers_for_kwant(&kwant.id).await {+ let mut servers = match state.db.list_active_mcp_servers_for_kwant(&kwant.id).await {Ok(s) if !s.is_empty() => s,Ok(_) => return None,Err(e) => {@@ -158,6 +158,8 @@ pub async fn prepare_turn(state: &AppState, kwant: &Kwant) -> Option<(McpTurnConreturn None;}};+ // Signed-in http servers get their (refreshed) access token as a secret header+ super::mcp_oauth::authorize_servers(state, &mut servers).await;let token = uuid::Uuid::new_v4().simple().to_string();let setting = state.db.get_setting("mcp_max_tool_iterations").await.ok().flatten();let ctx = McpTurnContext {diff --git a/src/server/mod.rs b/src/server/mod.rsindex da3ac505..c0d3eed1 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -2,6 +2,7 @@ pub mod discussion;pub mod routes;pub mod sse;pub mod browser_stream;+pub mod mcp_oauth;pub mod mcp_routes;pub mod mcp_runtime;@@ -36,6 +37,7 @@ pub struct AppState {pub browser_service: Arc<crate::sandbox::service::BrowserService>,/// Live claude CLI turns whose MCP permission prompts kwnt answers, by URL token.pub mcp_sessions: Arc<Mutex<HashMap<String, mcp_runtime::PermissionSession>>>,+ pub mcp_oauth: Arc<mcp_oauth::OAuthState>,}impl AppState {@@ -62,6 +64,7 @@ impl AppState {browser_controllers,browser_service,mcp_sessions: Arc::new(Mutex::new(HashMap::new())),+ mcp_oauth: Arc::new(mcp_oauth::OAuthState::default()),}}@@ -109,6 +112,9 @@ pub fn create_router(state: AppState) -> Router {get(mcp_routes::get_server).put(mcp_routes::update_server).delete(mcp_routes::delete_server),).route("/api/mcp/servers/:id/test", post(mcp_routes::test_server))+ .route("/api/mcp/servers/:id/oauth/start", post(mcp_oauth::start))+ .route("/api/mcp/servers/:id/oauth", delete(mcp_oauth::disconnect))+ .route("/api/mcp/oauth/callback", get(mcp_oauth::callback)).route("/api/kwants/:id/mcp-servers", get(mcp_routes::get_kwant_servers).put(mcp_routes::set_kwant_servers)).route("/api/mcp/permission/:token", post(mcp_runtime::permission_endpoint)).route("/api/events", get(sse::sse_handler))diff --git a/tests/mcp_oauth_test.rs b/tests/mcp_oauth_test.rsnew file mode 100644index 00000000..46ff6a3c--- /dev/null+++ b/tests/mcp_oauth_test.rs@@ -0,0 +1,321 @@+//! OAuth sign-in for http MCP servers, end to end against the mock OAuth + MCP server:+//! 401 → start → (browser) → callback → test ok, refresh, revocation and disconnect.++use axum::{+ body::Body,+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ mcp::{cli_config, oauth_mock},+ router::LayaRouter,+ server::{create_router, mcp_runtime, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::sync::atomic::Ordering;+use std::sync::Arc;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++const ORIGIN: &str = "https://kwnt.example.test";+const HOST: &str = "kwnt.example.test";++struct Env {+ app: Router,+ state: AppState,+ mock: Arc<oauth_mock::MockState>,+ _tmp: TempDir,+}++async fn env(options: oauth_mock::MockOptions) -> Env {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ let (mock_app, mock) = oauth_mock::router(&base, options);+ tokio::spawn(async move { axum::serve(listener, mock_app).await.unwrap() });++ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ Env { app: create_router(state.clone()), state, mock, _tmp: tmp }+}++async fn send(app: &Router, method: &str, uri: &str, body: Option<Value>, host: &str) -> (StatusCode, String) {+ let req = Request::builder()+ .method(method)+ .uri(uri)+ .header("host", host)+ .header("content-type", "application/json")+ .body(body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let status = resp.status();+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, String::from_utf8_lossy(&bytes).into_owned())+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let (status, text) = send(app, method, uri, body, HOST).await;+ (status, serde_json::from_str(&text).unwrap_or(Value::Null))+}++async fn create_http_server(e: &Env) -> String {+ let (status, created) = call(+ &e.app,+ "POST",+ "/api/mcp/servers",+ Some(json!({"name": "notionish", "transport": "http", "url": format!("{}/mcp", e.mock.base_url)})),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{created}");+ assert_eq!(created["oauth"], json!({"connected": false, "expires_at": null}));+ created["id"].as_str().unwrap().to_string()+}++/// Start → follow the mock's Allow link → callback. Returns the callback page.+async fn sign_in(e: &Env, id: &str) -> String {+ let (status, started) =+ call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;+ assert_eq!(status, StatusCode::OK, "{started}");+ let authorize_url = started["authorize_url"].as_str().unwrap();+ let parsed = url::Url::parse(authorize_url).unwrap();+ let q: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect();+ assert_eq!(q["response_type"], "code");+ assert_eq!(q["code_challenge_method"], "S256");+ assert_eq!(q["redirect_uri"], format!("{ORIGIN}/api/mcp/oauth/callback"));+ assert_eq!(q["resource"], format!("{}/mcp", e.mock.base_url));+ assert_eq!(q["scope"], "mcp");+ assert!(!q.contains_key("code_verifier"));++ let resp = reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .unwrap()+ .get(authorize_url)+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);+ let redirect = resp.headers()["x-mock-redirect"].to_str().unwrap().to_string();+ let redirect = url::Url::parse(&redirect).unwrap();+ assert_eq!(redirect.origin().ascii_serialization(), ORIGIN);+ let path_and_query = format!("{}?{}", redirect.path(), redirect.query().unwrap());+ let (status, page) = send(&e.app, "GET", &path_and_query, None, HOST).await;+ assert_eq!(status, StatusCode::OK);++ // The state is single use+ let (_, again) = send(&e.app, "GET", &path_and_query, None, HOST).await;+ assert!(again.contains("\"ok\":false") && again.contains("expired or was already used"), "{again}");+ page+}++async fn stored_token(e: &Env, id: &str) -> Option<kwnt::db::models::McpOAuthToken> {+ e.state.db.get_mcp_oauth_token(id).await.unwrap()+}++#[tokio::test]+async fn sign_in_flow_end_to_end() {+ let e = env(oauth_mock::MockOptions::default()).await;+ let id = create_http_server(&e).await;++ // Before sign-in: the 401 becomes auth_required+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["ok"], false);+ assert_eq!(tested["auth_required"], true);+ assert_eq!(tested["error"], "Sign-in required");++ // Origin must match the request host+ for bad in ["https://evil.test", "javascript:alert(1)", "https://kwnt.example.test/path"] {+ let (status, body) =+ call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": bad}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}: {body}");+ }+ let (status, _) = call(&e.app, "POST", "/api/mcp/servers/nope/oauth/start", Some(json!({"origin": ORIGIN}))).await;+ assert_eq!(status, StatusCode::NOT_FOUND);++ let page = sign_in(&e, &id).await;+ assert!(page.contains(&format!("\"server_id\":\"{id}\"")), "{page}");+ assert!(page.contains("\"ok\":true"), "{page}");+ assert!(page.contains("kwnt-mcp-oauth") && page.contains("location.origin"));+ let token = stored_token(&e, &id).await.expect("token stored");+ assert!(token.refresh_token.is_some());+ assert_eq!(e.mock.registrations.load(Ordering::SeqCst), 1);+ assert_eq!(e.mock.code_exchanges.load(Ordering::SeqCst), 1);++ // Test now connects with the token+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["ok"], true, "{tested}");+ assert_eq!(tested["tools"][0]["name"], "whoami");++ // List and get show the status, never the tokens+ let (_, list) = call(&e.app, "GET", "/api/mcp/servers", None).await;+ assert_eq!(list[0]["oauth"]["connected"], true);+ assert!(list[0]["oauth"]["expires_at"].is_string());+ let (_, one) = call(&e.app, "GET", &format!("/api/mcp/servers/{id}"), None).await;+ assert_eq!(one["oauth"]["connected"], true);+ for body in [list.to_string(), one.to_string()] {+ assert!(!body.contains(&token.access_token) && !body.contains(token.refresh_token.as_deref().unwrap()));+ }+ assert!(!format!("{token:?}").contains(&token.access_token));++ // Turns get the Bearer header; the claude CLI config carries it in its private file+ let kwant = e.state.db.list_kwants().await.unwrap().into_iter().next().unwrap();+ e.state.db.set_kwant_mcp_servers(&kwant.id, &[id.clone()]).await.unwrap();+ let (ctx, turn) = mcp_runtime::prepare_turn(&e.state, &kwant).await.unwrap();+ let bearer = format!("Bearer {}", token.access_token);+ assert_eq!(ctx.servers[0].headers["Authorization"], bearer);+ assert!(ctx.secret_values().contains(&bearer), "token is redacted from tool output");+ let config = cli_config::claude_config(&ctx);+ assert_eq!(config["mcpServers"]["notionish"]["headers"]["Authorization"], bearer);+ mcp_runtime::finish_turn(&e.state, &turn).await;++ // A second sign-in reuses the client registration+ sign_in(&e, &id).await;+ assert_eq!(e.mock.registrations.load(Ordering::SeqCst), 1);++ // Disconnect drops the tokens+ let (status, body) = call(&e.app, "DELETE", &format!("/api/mcp/servers/{id}/oauth"), None).await;+ assert_eq!((status, body), (StatusCode::OK, json!({"status": "disconnected"})));+ assert!(stored_token(&e, &id).await.is_none());+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["auth_required"], true);++ // Deleting the server deletes its tokens and registrations+ sign_in(&e, &id).await;+ assert!(stored_token(&e, &id).await.is_some());+ call(&e.app, "DELETE", &format!("/api/mcp/servers/{id}"), None).await;+ assert!(stored_token(&e, &id).await.is_none());+ assert!(e.state.db.get_mcp_oauth_client(&id, &format!("{ORIGIN}/api/mcp/oauth/callback"), &e.mock.base_url).await.unwrap().is_none());+}++#[tokio::test]+async fn short_lived_tokens_are_refreshed_before_use() {+ let e = env(oauth_mock::MockOptions { expires_in: 30 }).await;+ let id = create_http_server(&e).await;+ sign_in(&e, &id).await;+ let first = stored_token(&e, &id).await.unwrap();++ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["ok"], true, "{tested}");+ assert_eq!(e.mock.refreshes.load(Ordering::SeqCst), 1);+ let second = stored_token(&e, &id).await.unwrap();+ assert_ne!(first.access_token, second.access_token);+ assert_ne!(first.refresh_token, second.refresh_token, "rotated refresh token is stored");++ // Concurrent turns refresh once each in turn, never with a spent refresh token+ let kwant = e.state.db.list_kwants().await.unwrap().into_iter().next().unwrap();+ e.state.db.set_kwant_mcp_servers(&kwant.id, &[id.clone()]).await.unwrap();+ let (a, b) = tokio::join!(mcp_runtime::prepare_turn(&e.state, &kwant), mcp_runtime::prepare_turn(&e.state, &kwant));+ for (ctx, _) in [a.unwrap(), b.unwrap()] {+ assert!(ctx.servers[0].headers["Authorization"].starts_with("Bearer at-"));+ }+ assert!(stored_token(&e, &id).await.is_some(), "no refresh was rejected");++ // Refresh rejected (the user revoked kwnt): token cleared, sign-in needed+ e.mock.revoke_all();+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["auth_required"], true, "{tested}");+ assert!(stored_token(&e, &id).await.is_none());+ let (_, one) = call(&e.app, "GET", &format!("/api/mcp/servers/{id}"), None).await;+ assert_eq!(one["oauth"]["connected"], false);+}++#[tokio::test]+async fn rejected_token_is_refreshed_once_then_cleared() {+ let e = env(oauth_mock::MockOptions::default()).await;+ let id = create_http_server(&e).await;+ sign_in(&e, &id).await;++ // Access token revoked early, refresh token still good: one refresh, then ok+ e.mock.revoke_access_tokens();+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["ok"], true, "{tested}");+ assert_eq!(e.mock.refreshes.load(Ordering::SeqCst), 1);++ e.mock.revoke_all();+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["auth_required"], true);+ assert!(stored_token(&e, &id).await.is_none());+}++#[tokio::test]+async fn user_authorization_header_wins_over_sign_in() {+ let e = env(oauth_mock::MockOptions::default()).await;+ let id = create_http_server(&e).await;+ sign_in(&e, &id).await;+ let token = stored_token(&e, &id).await.unwrap();++ let url = format!("{}/mcp", e.mock.base_url);+ let (status, _) = call(+ &e.app,+ "PUT",+ &format!("/api/mcp/servers/{id}"),+ Some(json!({"name": "notionish", "transport": "http", "url": url, "headers": {"Authorization": "Bearer user-own-key"}})),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ // The user's (wrong) key was used, so this is a plain error, not a sign-in prompt+ assert_eq!(tested["ok"], false);+ assert!(tested.get("auth_required").is_none(), "{tested}");+ assert!(tested["error"].as_str().unwrap().contains("401"));+ assert!(!tested.to_string().contains("user-own-key") && !tested.to_string().contains(&token.access_token));+ assert!(stored_token(&e, &id).await.is_some(), "kwnt's sign-in is kept");++ // Changing the url forgets the sign-in+ let (status, updated) = call(+ &e.app,+ "PUT",+ &format!("/api/mcp/servers/{id}"),+ Some(json!({"name": "notionish", "transport": "http", "url": format!("{url}/v2")})),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(updated["oauth"]["connected"], false);+ assert!(stored_token(&e, &id).await.is_none());+}++#[tokio::test]+async fn callback_reports_provider_errors_and_bad_state() {+ let e = env(oauth_mock::MockOptions::default()).await;+ let id = create_http_server(&e).await;+ let (_, page) = send(&e.app, "GET", "/api/mcp/oauth/callback?code=x&state=forged", None, HOST).await;+ assert!(page.contains("\"ok\":false") && page.contains("\"server_id\":null"), "{page}");++ let (_, started) =+ call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;+ let authorize = url::Url::parse(started["authorize_url"].as_str().unwrap()).unwrap();+ let state = authorize.query_pairs().find(|(k, _)| k == "state").unwrap().1.into_owned();+ let (_, page) = send(+ &e.app,+ "GET",+ &format!("/api/mcp/oauth/callback?error=access_denied&error_description=%3Cscript%3Ex&state={state}"),+ None,+ HOST,+ )+ .await;+ assert!(page.contains("\"ok\":false") && page.contains("access_denied"), "{page}");+ assert!(!page.contains("<script>x"), "provider text is escaped: {page}");+ assert!(stored_token(&e, &id).await.is_none());++ // Behind a proxy the public host comes in X-Forwarded-Host+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/mcp/servers/{id}/oauth/start"))+ .header("host", "127.0.0.1:7777")+ .header("x-forwarded-host", HOST)+ .header("content-type", "application/json")+ .body(Body::from(json!({"origin": ORIGIN}).to_string()))+ .unwrap();+ assert_eq!(e.app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);+}