diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index edc269074..84163fa54 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -961,6 +961,35 @@ export class ApiStack extends cdk.Stack { integration: lambdaIntegration, }); + // CoderHelm's MCP server (Streamable HTTP, POST; GET and DELETE answer + // 405) and how MCP clients sign in to it: the metadata documents and the + // OAuth endpoints (gateway mcp_server.rs, routes/mcp_oauth.rs). OPTIONS + // too, for browser-based MCP clients: the gateway answers preflights. + httpApi.addRoutes({ + path: "/mcp", + methods: [ + apigatewayv2.HttpMethod.GET, + apigatewayv2.HttpMethod.POST, + apigatewayv2.HttpMethod.DELETE, + apigatewayv2.HttpMethod.OPTIONS, + ], + integration: lambdaIntegration, + }); + httpApi.addRoutes({ + path: "/.well-known/{proxy+}", + methods: [apigatewayv2.HttpMethod.GET, apigatewayv2.HttpMethod.OPTIONS], + integration: lambdaIntegration, + }); + httpApi.addRoutes({ + path: "/oauth/{proxy+}", + methods: [ + apigatewayv2.HttpMethod.GET, + apigatewayv2.HttpMethod.POST, + apigatewayv2.HttpMethod.OPTIONS, + ], + integration: lambdaIntegration, + }); + // Auth routes httpApi.addRoutes({ path: "/auth/{proxy+}", diff --git a/infra/lib/web-stack.ts b/infra/lib/web-stack.ts index a2a62876a..74c6be936 100644 --- a/infra/lib/web-stack.ts +++ b/infra/lib/web-stack.ts @@ -5,7 +5,7 @@ * service paths to their backends, all on one hostname: * * /api/plans/chat/stream /api/brain/stream → the streaming function URL (SSE) - * /api/* /auth/* /webhooks/* /email/* /integrations/* → the HTTP API + * /api/* /auth/* /webhooks/* /email/* /integrations/* /mcp /oauth/* → the HTTP API * everything else → the dashboard (static export in S3) * * One hostname means the session cookie (`__Host-`, SameSite=Strict) is @@ -45,6 +45,11 @@ export const API_PATHS = [ "/agent-approvals/*", "/plugins/approve*", "/openapi.json", + // The MCP server and how its clients sign in (the dashboard's consent + // page is /authorize, outside these). + "/mcp", + "/.well-known/oauth-*", + "/oauth/*", ]; /** The chat stream (SSE, served by the streaming function). */ export const STREAM_PATH = "/api/plans/chat/stream"; diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 3ca8c59fb..ec9cdf3ac 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -471,6 +471,34 @@ test("single origin: every public route the gateway serves outside /api reaches assert.ok(covered("/agent-approvals/link")); }); +test("the MCP server and its sign-in reach the gateway, hosted and self-hosted", () => { + const cfg = loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }); + const api = synth(cfg, zoneContext("654654210434", "us-east-1", "coderhelm.com"))["coderhelm-prod-api"]; + const keys = Object.values(api.findResources("AWS::ApiGatewayV2::Route")).map((r: any) => String(r.Properties.RouteKey)); + for (const [m, p] of [ + ["POST", "/mcp"], + ["GET", "/mcp"], + ["OPTIONS", "/mcp"], + ["GET", "/.well-known/oauth-protected-resource/mcp"], + ["GET", "/.well-known/oauth-authorization-server"], + ["POST", "/oauth/register"], + ["GET", "/oauth/authorize"], + ["POST", "/oauth/token"], + ["POST", "/oauth/revoke"], + ]) { + assert.ok(keys.some((k) => routeTakes(k, m, p)), `no HTTP API route for ${m} ${p}`); + } + // Single origin: CloudFront sends them to the API, and the dashboard's + // consent page (/authorize) to the dashboard. + const covered = (p: string) => + API_PATHS.some((a) => (a.endsWith("*") ? p.startsWith(a.slice(0, -1)) : p === a)); + for (const p of ["/mcp", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp", "/.well-known/oauth-authorization-server", "/oauth/token"]) { + assert.ok(covered(p), `${p} isn't in API_PATHS`); + } + assert.ok(!covered("/authorize")); + assert.ok(!covered("/settings/connected-apps")); +}); + test("self-host serves the OpenAPI document through CloudFront", () => { assert.ok(API_PATHS.includes("/openapi.json")); }); diff --git a/services/gateway/Cargo.toml b/services/gateway/Cargo.toml index 0fa7bffdf..90fc6ba57 100644 --- a/services/gateway/Cargo.toml +++ b/services/gateway/Cargo.toml @@ -75,6 +75,8 @@ uuid = { version = "1", features = ["v4"] } regex = "1" md5 = "0.7" futures = "0.3" +# mcp_server: a tool call runs through the API router (ServiceExt::oneshot) +tower = { version = "0.5", features = ["util"] } tokio-stream = "0.1" # MenteDB (agent memory browsing) @@ -86,7 +88,5 @@ tar = "0.4" [dev-dependencies] # rsa 0.9 key generation needs the rand 0.8 RNG traits (tests only) rand08 = { package = "rand", version = "0.8" } -# middleware tests drive a small router -tower = { version = "0.5", features = ["util"] } # signs test messages the way CoderHelm's KMS key does (hosted_sig) ed25519-dalek = { version = "2", default-features = false, features = ["std"] } diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 868dda969..4980efc96 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -13,6 +13,8 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilte mod api_keys; mod auth; mod clients; +mod mcp_oauth; +mod mcp_server; mod middleware; mod model_call; mod models; @@ -395,6 +397,9 @@ async fn main() -> Result<(), Error> { ) .route("/search", get(routes::search::search)) .route("/runs", get(routes::api::list_runs)) + // A person starts a run on a ticket from outside its tracker (a + // connected app's start_run). + .route("/runs/start", post(routes::run_start::start_run)) .route("/runs/:run_id", get(routes::api::get_run)) .route("/runs/:run_id/traces", get(routes::api::get_run_traces)) .route("/runs/:run_id/agent-log", get(routes::api::get_agent_log)) @@ -637,6 +642,18 @@ async fn main() -> Result<(), Error> { get(routes::api_keys::list).post(routes::api_keys::create), ) .route("/api-keys/:key_id", delete(routes::api_keys::revoke)) + // Connecting apps to CoderHelm's MCP server: the consent page, and + // the apps people connected (routes::mcp_oauth). + .route( + "/mcp/authorize/describe", + post(routes::mcp_oauth::describe_request), + ) + .route("/mcp/authorize", post(routes::mcp_oauth::decide_request)) + .route("/mcp/connections", get(routes::mcp_oauth::list_connections)) + .route( + "/mcp/connections/:grant_id", + delete(routes::mcp_oauth::revoke_connection), + ) .route( "/roles/:role_id", put(routes::roles::update_role).delete(routes::roles::delete_role), @@ -1396,6 +1413,21 @@ async fn main() -> Result<(), Error> { middleware::rate_limit::rate_limit_email, )); + // Signing in to CoderHelm's MCP server (public; routes::mcp_oauth). + let oauth_routes = Router::new() + .route("/register", post(routes::mcp_oauth::register)) + .route("/authorize", get(routes::mcp_oauth::authorize)) + .route("/token", post(routes::mcp_oauth::token)) + .route("/revoke", post(routes::mcp_oauth::revoke)); + + // The tools of the MCP server call the API router as the person who + // connected the app, through its auth middleware (mcp_server::call). + let mcp_api = mcp_server::McpApi( + Router::new() + .nest("/api", api_routes.clone()) + .with_state(state.clone()), + ); + let app = Router::new() // Root health/info .route( @@ -1475,6 +1507,28 @@ async fn main() -> Result<(), Error> { routes::mcp_servers::METADATA_DOCUMENT_PATH, get(routes::mcp_servers::client_metadata_document), ) + // CoderHelm's MCP server, for Claude, Cursor, VS Code and other MCP + // clients (mcp_server), and where its clients learn how to sign in. + .route( + "/mcp", + post(mcp_server::post) + .get(mcp_server::not_allowed) + .delete(mcp_server::not_allowed) + .layer(axum::Extension(mcp_api)), + ) + .route( + "/.well-known/oauth-protected-resource", + get(routes::mcp_oauth::protected_resource), + ) + .route( + "/.well-known/oauth-protected-resource/mcp", + get(routes::mcp_oauth::protected_resource), + ) + .route( + "/.well-known/oauth-authorization-server", + get(routes::mcp_oauth::authorization_server), + ) + .nest("/oauth", oauth_routes) // The sign-in methods that work here: the sign-in page reads it on // every load, so it stays out of the sign-in attempts' rate limit. .route("/auth/methods", get(routes::auth::methods)) diff --git a/services/gateway/src/mcp_oauth.rs b/services/gateway/src/mcp_oauth.rs new file mode 100644 index 000000000..612a89ece --- /dev/null +++ b/services/gateway/src/mcp_oauth.rs @@ -0,0 +1,2233 @@ +//! Signing in to CoderHelm's MCP server: OAuth 2.1 the way the MCP +//! authorization spec asks for it, so a person can add CoderHelm to Claude, +//! Cursor, VS Code or any other MCP client and act as themselves. +//! +//! The pieces, in the order a client meets them: +//! +//! 1. `POST /mcp` without a token answers `401` with a `WWW-Authenticate` +//! header naming this server's protected resource metadata +//! (`/.well-known/oauth-protected-resource/mcp`), which names the +//! authorization server (this same API; its metadata is at +//! `/.well-known/oauth-authorization-server`). +//! 2. The client registers itself (`POST /oauth/register`, RFC 7591). Every +//! client is public: no secret, PKCE with S256 always. +//! 3. `GET /oauth/authorize` checks the request and sends the person to the +//! dashboard's consent page with the request signed into the link. The +//! dashboard shows who is asking and what it may do; the person decides +//! with their own signed-in session (`/api/mcp/authorize`), and the answer +//! goes back to the client with a one-time code. +//! 4. `POST /oauth/token` swaps the code (with its PKCE verifier) for an +//! access token (an hour) and a refresh token (30 days, renewed on use, +//! replaced on every use; a replaced one used again ends the connection). +//! 5. Every MCP call checks the access token against its connection (a +//! revoked connection stops at once), then runs as the person through the +//! same checks a dashboard request gets (`middleware::auth`). +//! +//! The rules live here, apart from DynamoDB, so they are tested without it +//! ([`OAuthStore`]). Storage, in the settings table: +//! - `pk = MCP_CLIENT#`, `sk = MCP_CLIENT`: a registered client; +//! - `pk = MCP_CODE#`, `sk = MCP_CODE`: a code waiting to be swapped +//! (deleted by the swap, so it works once); +//! - `pk = MCP_GRANT#`, `sk = MCP_GRANT`: a connection, with its refresh +//! token's hash, read on every call; +//! - `pk = `, `sk = MCP_GRANT#`: the team's copy, listed on the +//! Connected apps page. + +use aws_sdk_dynamodb::types::{AttributeValue, Put, TransactWriteItem, Update}; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeSet, HashMap}; +use subtle::ConstantTimeEq; + +/// Reading runs and reviews. +pub const READ_SCOPE: &str = "runs:read"; +/// Starting and retrying runs, and asking for reviews. +pub const WRITE_SCOPE: &str = "runs:write"; +/// Every scope, in the order they are shown. +pub const SCOPES: &[&str] = &[READ_SCOPE, WRITE_SCOPE]; + +/// What a scope lets an app do, as the consent page says it. +pub fn scope_label(scope: &str) -> &'static str { + match scope { + READ_SCOPE => "See your team's runs and reviews", + WRITE_SCOPE => "Start and retry runs, and ask for reviews", + _ => "", + } +} + +/// An access token lasts an hour. +pub const ACCESS_TTL_SECS: u64 = 3600; +/// A code must be swapped within five minutes. +pub const CODE_TTL_SECS: i64 = 300; +/// The consent page link works for ten minutes. +pub const REQUEST_TTL_SECS: u64 = 600; +/// A refresh token works for 30 days after its last use. +pub const REFRESH_TTL_DAYS: i64 = 30; +/// A registered client nobody signs in with is forgotten after this long. +pub const CLIENT_TTL_DAYS: i64 = 180; + +/// The audience of an access token: accepted only by `/mcp`, never as a +/// session, a brain token or a consent link. +pub const ACCESS_AUDIENCE: &str = "coderhelm-mcp"; +/// The audience of a consent link's signed request. +pub const REQUEST_AUDIENCE: &str = "coderhelm-mcp-consent"; + +pub const REFRESH_PREFIX: &str = "chr_"; +pub const CODE_PREFIX: &str = "chc_"; +pub const CLIENT_PREFIX: &str = "mcpc_"; + +const MAX_REDIRECT_URIS: usize = 10; +const MAX_URI_LEN: usize = 2000; +const MAX_CLIENT_NAME: usize = 100; +const MAX_STATE_LEN: usize = 1000; + +// ── Where things are ──────────────────────────────────────────────── + +/// The authorization server's identifier: this install's API address. On a +/// self-hosted install that is its one address; on hosted CoderHelm, +/// `https://api.coderhelm.com`. +pub fn issuer() -> String { + common::public_urls::api_url_from_env().to_string() +} + +/// The MCP server's address, what people add to their client. +pub fn resource() -> String { + resource_for(&issuer()) +} + +pub fn resource_for(issuer: &str) -> String { + format!("{issuer}/mcp") +} + +/// The protected resource metadata for `/mcp` (RFC 9728). +pub fn resource_metadata_url() -> String { + format!("{}/.well-known/oauth-protected-resource/mcp", issuer()) +} + +/// Is `given` this server's resource? A trailing slash is the same address. +pub fn is_our_resource(given: &str, ours: &str) -> bool { + given.trim_end_matches('/') == ours.trim_end_matches('/') +} + +// ── Scopes ────────────────────────────────────────────────────────── + +/// The scopes a request asks for. Reading is always included; a scope this +/// server doesn't have is left out (RFC 6749 lets the server grant less), +/// so a client that also asks for something like `offline_access` still +/// signs in. +pub fn parse_scope(raw: Option<&str>) -> BTreeSet<&'static str> { + let mut out = BTreeSet::from([READ_SCOPE]); + for word in raw.unwrap_or("").split_whitespace() { + if let Some(s) = SCOPES.iter().find(|s| **s == word) { + out.insert(s); + } + } + out +} + +/// Scopes as one space-separated string, in [`SCOPES`] order. +pub fn scope_string<'a>(scopes: impl IntoIterator) -> String { + let set: BTreeSet<&str> = scopes.into_iter().collect(); + SCOPES + .iter() + .filter(|s| set.contains(**s)) + .copied() + .collect::>() + .join(" ") +} + +/// Stored scope strings, as the known scopes they name. +pub fn known_scopes(stored: &[String]) -> BTreeSet<&'static str> { + stored + .iter() + .filter_map(|s| SCOPES.iter().find(|k| **k == s.as_str()).copied()) + .collect() +} + +// ── Redirect addresses ────────────────────────────────────────────── + +/// Schemes that are never a place to send a code. +const UNSAFE_SCHEMES: &[&str] = &[ + "javascript", + "data", + "file", + "vbscript", + "about", + "blob", + "ftp", + "ws", + "wss", +]; + +fn is_loopback(u: &url::Url) -> bool { + u.scheme() == "http" + && match u.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, + } +} + +/// Where a client may ask for its code to be sent: `https`, `http` only on +/// this machine (`localhost`, `127.0.0.1`, `[::1]`; RFC 8252), or an app's +/// own scheme (`cursor://...`, `vscode://...`). Never a fragment, never a +/// user name, never a scheme that runs or reads something. +pub fn check_redirect_uri(raw: &str) -> Result { + if raw.len() > MAX_URI_LEN { + return Err("A redirect address is too long.".into()); + } + let u = url::Url::parse(raw).map_err(|_| format!("\"{raw}\" isn't an address."))?; + if u.fragment().is_some() { + return Err("A redirect address can't have a fragment (#...).".into()); + } + if !u.username().is_empty() || u.password().is_some() { + return Err("A redirect address can't carry a user name or password.".into()); + } + match u.scheme() { + "https" if u.host().is_some() => Ok(u), + "https" => Err("An https redirect address needs a host.".into()), + "http" if is_loopback(&u) => Ok(u), + "http" => { + Err("Plain http is allowed only for this computer (localhost or 127.0.0.1).".into()) + } + s if UNSAFE_SCHEMES.contains(&s) => Err(format!("\"{s}:\" can't be a redirect address.")), + _ => Ok(u), + } +} + +/// Does `given` match one of the client's registered addresses? Exactly, or +/// for an `http` address on this computer, with any port (RFC 8252 7.3: a +/// native app picks a free port each time). +pub fn redirect_matches(registered: &[String], given: &str) -> bool { + if registered.iter().any(|r| r == given) { + return true; + } + let Ok(g) = url::Url::parse(given) else { + return false; + }; + if !is_loopback(&g) { + return false; + } + registered.iter().any(|r| { + url::Url::parse(r).is_ok_and(|r| { + is_loopback(&r) + && r.host_str() == g.host_str() + && r.path() == g.path() + && r.query() == g.query() + }) + }) +} + +/// The host a redirect goes to, as the consent page names it (an app's own +/// scheme shows as `cursor://`). +pub fn redirect_host(uri: &str) -> String { + match url::Url::parse(uri) { + Ok(u) => match u.host_str() { + Some(h) if matches!(u.scheme(), "http" | "https") => match u.port() { + Some(p) if is_loopback(&u) => format!("{h}:{p}"), + _ => h.to_string(), + }, + Some(h) => format!("{}://{h}", u.scheme()), + None => format!("{}:", u.scheme()), + }, + Err(_) => String::new(), + } +} + +/// `uri` with `params` added to its query, keeping what it had. +pub fn redirect_with(uri: &str, params: &[(&str, &str)]) -> String { + match url::Url::parse(uri) { + Ok(mut u) => { + { + let mut q = u.query_pairs_mut(); + for (k, v) in params { + q.append_pair(k, v); + } + } + u.to_string() + } + Err(_) => uri.to_string(), + } +} + +// ── Clients ───────────────────────────────────────────────────────── + +/// A registration request (RFC 7591). Only what CoderHelm uses is read; a +/// `token_endpoint_auth_method` asked for is answered with `none`. +#[derive(Debug, Default, Deserialize)] +pub struct Registration { + #[serde(default)] + pub redirect_uris: Vec, + #[serde(default)] + pub client_name: Option, + #[serde(default)] + pub client_uri: Option, + #[serde(default)] + pub grant_types: Option>, + #[serde(default)] + pub response_types: Option>, +} + +/// A registered client. It has no secret: every client here is public and +/// proves each sign-in with PKCE. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredClient { + pub client_id: String, + pub client_name: String, + pub redirect_uris: Vec, + #[serde(default)] + pub client_uri: Option, + pub created_at: String, +} + +/// Why a registration was refused: `(error, description)` as RFC 7591 names them. +pub type RegisterError = (&'static str, String); + +/// A client's name as it is shown: printable, trimmed, at most 100 +/// characters. It is the client's own claim, and the consent page says so. +pub fn clean_name(raw: Option<&str>) -> String { + let name: String = raw + .unwrap_or("") + .chars() + .filter(|c| !c.is_control()) + .collect::() + .split_whitespace() + .collect::>() + .join(" "); + let name: String = name.chars().take(MAX_CLIENT_NAME).collect(); + if name.is_empty() { + "An app without a name".to_string() + } else { + name + } +} + +/// Checks a registration and makes the client it describes. +pub fn register( + reg: &Registration, + now: chrono::DateTime, +) -> Result { + if reg.redirect_uris.is_empty() { + return Err(( + "invalid_redirect_uri", + "Send at least one redirect address in redirect_uris.".into(), + )); + } + if reg.redirect_uris.len() > MAX_REDIRECT_URIS { + return Err(( + "invalid_redirect_uri", + format!("Send at most {MAX_REDIRECT_URIS} redirect addresses."), + )); + } + for uri in ®.redirect_uris { + check_redirect_uri(uri).map_err(|e| ("invalid_redirect_uri", e))?; + } + if let Some(types) = ®.grant_types { + if !types.iter().any(|t| t == "authorization_code") + || types + .iter() + .any(|t| t != "authorization_code" && t != "refresh_token") + { + return Err(( + "invalid_client_metadata", + "grant_types may hold only authorization_code and refresh_token.".into(), + )); + } + } + if let Some(types) = ®.response_types { + if types.iter().any(|t| t != "code") { + return Err(( + "invalid_client_metadata", + "response_types may hold only code.".into(), + )); + } + } + let client_uri = reg + .client_uri + .as_deref() + .filter(|u| u.len() <= MAX_URI_LEN && u.starts_with("https://")) + .map(str::to_string); + Ok(StoredClient { + client_id: format!( + "{CLIENT_PREFIX}{}", + ulid::Ulid::new().to_string().to_ascii_lowercase() + ), + client_name: clean_name(reg.client_name.as_deref()), + redirect_uris: reg.redirect_uris.clone(), + client_uri, + created_at: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + }) +} + +/// The registration answer (RFC 7591 3.2.1). `token_endpoint_auth_method` +/// is always `none`, whatever was asked: every client here is public. +pub fn registration_answer(c: &StoredClient, issued_at: i64) -> serde_json::Value { + serde_json::json!({ + "client_id": c.client_id, + "client_id_issued_at": issued_at, + "client_name": c.client_name, + "client_uri": c.client_uri, + "redirect_uris": c.redirect_uris, + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + "scope": scope_string(SCOPES.iter().copied()), + }) +} + +// ── PKCE ──────────────────────────────────────────────────────────── + +fn b64url(bytes: &[u8]) -> String { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) +} + +fn is_b64url(s: &str) -> bool { + s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +/// The S256 challenge of a verifier (RFC 7636 4.2). +pub fn pkce_challenge(verifier: &str) -> String { + b64url(&Sha256::digest(verifier.as_bytes())) +} + +/// Does `verifier` answer `challenge`? Verifiers are 43 to 128 characters +/// of `A-Z a-z 0-9 - . _ ~`. Constant time. +pub fn pkce_matches(verifier: &str, challenge: &str) -> bool { + let ok_chars = verifier + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '~')); + if !(43..=128).contains(&verifier.len()) || !ok_chars { + return false; + } + let got = pkce_challenge(verifier); + got.len() == challenge.len() && bool::from(got.as_bytes().ct_eq(challenge.as_bytes())) +} + +// ── Authorization requests ────────────────────────────────────────── + +/// `GET /oauth/authorize`'s query. +#[derive(Debug, Default, Clone, Deserialize)] +pub struct AuthorizeParams { + pub response_type: Option, + pub client_id: Option, + pub redirect_uri: Option, + pub code_challenge: Option, + pub code_challenge_method: Option, + pub scope: Option, + pub state: Option, + pub resource: Option, +} + +/// Why an authorization request was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AuthorizeError { + /// The client or its redirect address can't be trusted: shown to the + /// person on a page, never sent anywhere. + Page(String), + /// Sent back to the client's (checked) redirect address. + Redirect { + redirect_uri: String, + error: &'static str, + description: String, + state: Option, + }, +} + +/// A checked request, signed into the consent page's link. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PendingRequest { + pub client_id: String, + pub redirect_uri: String, + pub code_challenge: String, + pub scopes: Vec, + #[serde(default)] + pub state: Option, + pub resource: String, + #[serde(default)] + pub aud: String, + #[serde(default)] + pub iat: u64, + #[serde(default)] + pub exp: u64, +} + +/// Checks an authorization request against its client. The client and the +/// redirect address are checked first: until both are known good, nothing +/// is sent to the address. +pub fn check_authorize( + p: &AuthorizeParams, + client: Option<&StoredClient>, + resource: &str, +) -> Result { + let Some(client) = client else { + return Err(AuthorizeError::Page( + "This app isn't registered with CoderHelm, or its registration has expired. Remove CoderHelm from the app and add it again.".into(), + )); + }; + if p.client_id.as_deref() != Some(client.client_id.as_str()) { + return Err(AuthorizeError::Page( + "The app's request is not valid.".into(), + )); + } + let redirect_uri = match p.redirect_uri.as_deref() { + Some(r) if redirect_matches(&client.redirect_uris, r) => r.to_string(), + Some(_) => { + return Err(AuthorizeError::Page( + "The app asked to be sent somewhere it didn't register. CoderHelm stopped here to keep your account safe.".into(), + )) + } + None if client.redirect_uris.len() == 1 => client.redirect_uris[0].clone(), + None => { + return Err(AuthorizeError::Page( + "The app didn't say where to send you back to.".into(), + )) + } + }; + let state = p.state.clone().filter(|s| !s.is_empty()); + let back = |error: &'static str, description: &str| AuthorizeError::Redirect { + redirect_uri: redirect_uri.clone(), + error, + description: description.to_string(), + state: state.clone(), + }; + if state.as_ref().is_some_and(|s| s.len() > MAX_STATE_LEN) { + return Err(back("invalid_request", "state is too long.")); + } + if p.response_type.as_deref() != Some("code") { + return Err(back( + "unsupported_response_type", + "Only response_type=code is supported.", + )); + } + let Some(challenge) = p.code_challenge.as_deref().filter(|c| !c.is_empty()) else { + return Err(back( + "invalid_request", + "PKCE is required: send code_challenge with code_challenge_method=S256.", + )); + }; + if p.code_challenge_method.as_deref() != Some("S256") { + return Err(back( + "invalid_request", + "Only code_challenge_method=S256 is supported.", + )); + } + if challenge.len() != 43 || !is_b64url(challenge) { + return Err(back( + "invalid_request", + "code_challenge must be the base64url SHA-256 of the verifier (43 characters).", + )); + } + if let Some(r) = p.resource.as_deref().filter(|r| !r.is_empty()) { + if !is_our_resource(r, resource) { + return Err(back( + "invalid_target", + "This server signs in only to its own MCP address.", + )); + } + } + Ok(PendingRequest { + client_id: client.client_id.clone(), + redirect_uri, + code_challenge: challenge.to_string(), + scopes: parse_scope(p.scope.as_deref()) + .into_iter() + .map(str::to_string) + .collect(), + state, + resource: resource.to_string(), + aud: String::new(), + iat: 0, + exp: 0, + }) +} + +/// Where a refused request goes back to, with the error (and the state the +/// client sent, and who answered: RFC 9207). +pub fn error_redirect(err: &AuthorizeError, issuer: &str) -> Option { + let AuthorizeError::Redirect { + redirect_uri, + error, + description, + state, + } = err + else { + return None; + }; + let mut params = vec![ + ("error", *error), + ("error_description", description.as_str()), + ("iss", issuer), + ]; + if let Some(s) = state { + params.push(("state", s.as_str())); + } + Some(redirect_with(redirect_uri, ¶ms)) +} + +/// The request, signed for the consent page's link. +pub fn sign_request( + req: &PendingRequest, + secret: &str, + now_secs: u64, +) -> Result { + let signed = PendingRequest { + aud: REQUEST_AUDIENCE.to_string(), + iat: now_secs, + exp: now_secs + REQUEST_TTL_SECS, + ..req.clone() + }; + encode( + &Header::default(), + &signed, + &EncodingKey::from_secret(secret.as_bytes()), + ) +} + +/// A consent link's request, when it is ours and still current. +pub fn read_request(token: &str, secret: &str, now_secs: u64) -> Option { + let mut v = Validation::default(); + v.set_audience(&[REQUEST_AUDIENCE]); + v.validate_exp = false; + let req = decode::(token, &DecodingKey::from_secret(secret.as_bytes()), &v) + .ok()? + .claims; + (req.exp > now_secs).then_some(req) +} + +// ── Codes ─────────────────────────────────────────────────────────── + +/// Who said yes, from their signed-in session. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Consent { + pub team_id: String, + pub user_id: String, + pub email: String, + /// The session passed a second factor. + pub mfa: bool, + pub via: Option, + /// The person let the app start runs and ask for reviews. + pub allow_write: bool, +} + +/// A code waiting to be swapped, with everything the swap checks. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredCode { + pub hash: String, + pub client_id: String, + pub client_name: String, + pub redirect_uri: String, + pub code_challenge: String, + pub scopes: Vec, + pub resource: String, + pub team_id: String, + pub user_id: String, + pub email: String, + pub mfa: bool, + #[serde(default)] + pub via: Option, + /// Seconds since the epoch. + pub expires_at: i64, +} + +/// A random secret: 32 bytes, base64url. +fn secret() -> String { + use rand::RngCore; + let mut b = [0u8; 32]; + rand::rng().fill_bytes(&mut b); + b64url(&b) +} + +/// SHA-256 as hex. Codes and refresh tokens carry 256 random bits, so a +/// fast hash is the right one. +pub fn hash(token: &str) -> String { + hex::encode(Sha256::digest(token.as_bytes())) +} + +fn hash_matches(token: &str, stored: &str) -> bool { + let got = hash(token); + !stored.is_empty() + && got.len() == stored.len() + && bool::from(got.as_bytes().ct_eq(stored.as_bytes())) +} + +/// The scopes a person granted: reading always, writing when they allowed it. +pub fn granted_scopes(allow_write: bool) -> Vec { + let mut s = vec![READ_SCOPE.to_string()]; + if allow_write { + s.push(WRITE_SCOPE.to_string()); + } + s +} + +/// The person said yes: a one-time code for the client, and what the swap +/// will check it against. +pub fn approve( + req: &PendingRequest, + client: &StoredClient, + who: &Consent, + now: chrono::DateTime, +) -> (String, StoredCode) { + let code = format!("{CODE_PREFIX}{}", secret()); + let stored = StoredCode { + hash: hash(&code), + client_id: req.client_id.clone(), + client_name: client.client_name.clone(), + redirect_uri: req.redirect_uri.clone(), + code_challenge: req.code_challenge.clone(), + scopes: granted_scopes(who.allow_write), + resource: req.resource.clone(), + team_id: who.team_id.clone(), + user_id: who.user_id.clone(), + email: who.email.clone(), + mfa: who.mfa, + via: who.via.clone(), + expires_at: now.timestamp() + CODE_TTL_SECS, + }; + (code, stored) +} + +// ── Connections ───────────────────────────────────────────────────── + +/// One app connected by one person, in one team: what every access token +/// and refresh token belongs to. Revoking it ends both at once. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredGrant { + pub id: String, + pub team_id: String, + pub user_id: String, + pub email: String, + pub client_id: String, + pub client_name: String, + /// Where the app's codes went, to tell apps with one name apart. + pub redirect_host: String, + pub scopes: Vec, + pub created_at: String, + /// When the person said yes, in seconds: sessions ended after this (a + /// removal, a role change, a reset second factor) end the connection too. + pub created_at_secs: u64, + pub mfa: bool, + #[serde(default)] + pub via: Option, + #[serde(default)] + pub refresh_hash: String, + #[serde(default)] + pub prev_refresh_hash: Option, + #[serde(default)] + pub refresh_expires_at: String, + #[serde(default)] + pub last_used_at: Option, + #[serde(default)] + pub revoked_at: Option, + #[serde(default)] + pub revoked_by: Option, +} + +impl StoredGrant { + pub fn scope_set(&self) -> BTreeSet<&'static str> { + known_scopes(&self.scopes) + } +} + +/// The claims of an access token. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AccessClaims { + pub sub: String, + pub team_id: String, + /// The connection. + pub gid: String, + pub client_id: String, + pub scope: String, + pub aud: String, + pub iss: String, + pub iat: u64, + pub exp: u64, +} + +/// An access token for a connection, with `scopes`. +pub fn issue_access( + g: &StoredGrant, + scopes: &BTreeSet<&'static str>, + issuer: &str, + secret: &str, + now_secs: u64, +) -> Result { + let claims = AccessClaims { + sub: g.user_id.clone(), + team_id: g.team_id.clone(), + gid: g.id.clone(), + client_id: g.client_id.clone(), + scope: scope_string(scopes.iter().copied()), + aud: ACCESS_AUDIENCE.to_string(), + iss: issuer.to_string(), + iat: now_secs, + exp: now_secs + ACCESS_TTL_SECS, + }; + encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(secret.as_bytes()), + ) +} + +/// Why an access token was refused (each is a `401`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AccessRefusal { + Invalid, + Expired, + Revoked, +} + +impl AccessRefusal { + pub fn description(self) -> &'static str { + match self { + Self::Invalid => "The access token isn't valid.", + Self::Expired => "The access token has expired. Use the refresh token for a new one.", + Self::Revoked => "This connection was removed in CoderHelm. Sign in again.", + } + } +} + +/// The claims of an access token signed here for `/mcp`, checked against +/// `now_secs` (so expiry is tested without waiting). +pub fn read_access( + token: &str, + secret: &str, + now_secs: u64, +) -> Result { + let mut v = Validation::default(); + v.set_audience(&[ACCESS_AUDIENCE]); + v.validate_exp = false; + let c = decode::(token, &DecodingKey::from_secret(secret.as_bytes()), &v) + .map_err(|_| AccessRefusal::Invalid)? + .claims; + if c.exp <= now_secs { + return Err(AccessRefusal::Expired); + } + Ok(c) +} + +/// A call's connection and the scopes its token holds. +#[derive(Debug, Clone)] +pub struct Authorized { + pub grant: StoredGrant, + pub scopes: BTreeSet<&'static str>, +} + +/// Checks an access token and its connection. The connection is read on +/// every call: one revoked in the dashboard stops at once, and a token's +/// team, person and app must be the connection's own. +pub async fn authenticate( + store: &impl OAuthStore, + token: &str, + secret: &str, + now_secs: u64, +) -> Result, String> { + let claims = match read_access(token, secret, now_secs) { + Ok(c) => c, + Err(r) => return Ok(Err(r)), + }; + let Some(grant) = store.get_grant(&claims.gid).await? else { + return Ok(Err(AccessRefusal::Revoked)); + }; + if grant.team_id != claims.team_id + || grant.user_id != claims.sub + || grant.client_id != claims.client_id + { + return Ok(Err(AccessRefusal::Invalid)); + } + if grant.revoked_at.is_some() { + return Ok(Err(AccessRefusal::Revoked)); + } + let token_scopes = parse_scope(Some(&claims.scope)); + let scopes = token_scopes + .intersection(&grant.scope_set()) + .copied() + .collect(); + Ok(Ok(Authorized { grant, scopes })) +} + +// ── The token endpoint ────────────────────────────────────────────── + +/// `POST /oauth/token`'s form. +#[derive(Debug, Default, Clone, Deserialize)] +pub struct TokenForm { + pub grant_type: Option, + pub code: Option, + pub redirect_uri: Option, + pub client_id: Option, + pub code_verifier: Option, + pub refresh_token: Option, + pub resource: Option, + pub scope: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct TokenAnswer { + pub access_token: String, + pub token_type: &'static str, + pub expires_in: u64, + pub refresh_token: String, + pub scope: String, +} + +/// A refused token request (RFC 6749 5.2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TokenError { + pub error: &'static str, + pub description: String, +} + +fn token_error(error: &'static str, description: &str) -> TokenError { + TokenError { + error, + description: description.to_string(), + } +} + +/// A new refresh token for connection `gid`: `chr__`. +pub fn new_refresh(gid: &str) -> String { + format!("{REFRESH_PREFIX}{gid}_{}", secret()) +} + +/// The connection id inside a refresh token. +pub fn refresh_grant_id(token: &str) -> Option<&str> { + let rest = token.strip_prefix(REFRESH_PREFIX)?; + let (id, secret) = rest.split_once('_')?; + (id.len() == 26 && id.chars().all(|c| c.is_ascii_alphanumeric()) && secret.len() == 43) + .then_some(id) +} + +fn refresh_expiry(now: chrono::DateTime) -> String { + (now + chrono::Duration::days(REFRESH_TTL_DAYS)) + .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} + +fn expired(at: &str, now: chrono::DateTime) -> bool { + chrono::DateTime::parse_from_rfc3339(at).map_or(true, |t| t <= now) +} + +/// Answers a token request: a code swapped for a new connection's tokens, +/// or a refresh token swapped for new ones. The store failing is an error +/// (the caller answers 503), never a token. +pub async fn token( + store: &impl OAuthStore, + form: &TokenForm, + issuer: &str, + secret: &str, + now: chrono::DateTime, +) -> Result, String> { + match form.grant_type.as_deref() { + Some("authorization_code") => swap_code(store, form, issuer, secret, now).await, + Some("refresh_token") => refresh(store, form, issuer, secret, now).await, + Some(_) => Ok(Err(token_error( + "unsupported_grant_type", + "Use authorization_code or refresh_token.", + ))), + None => Ok(Err(token_error( + "invalid_request", + "grant_type is missing.", + ))), + } +} + +async fn swap_code( + store: &impl OAuthStore, + form: &TokenForm, + issuer: &str, + secret: &str, + now: chrono::DateTime, +) -> Result, String> { + let bad = |d: &str| Ok(Err(token_error("invalid_grant", d))); + let Some(code) = form.code.as_deref().filter(|c| c.starts_with(CODE_PREFIX)) else { + return Ok(Err(token_error("invalid_request", "code is missing."))); + }; + let Some(verifier) = form.code_verifier.as_deref() else { + return Ok(Err(token_error( + "invalid_request", + "code_verifier is missing (PKCE is required).", + ))); + }; + // Taken out whatever happens next: a code works once, even a code sent + // with a wrong verifier. + let Some(c) = store.take_code(&hash(code)).await? else { + return bad("The code isn't valid, or was already used."); + }; + if c.expires_at <= now.timestamp() { + return bad("The code has expired. Sign in again."); + } + if form.client_id.as_deref() != Some(c.client_id.as_str()) { + return bad("The code was given to another app."); + } + if form + .redirect_uri + .as_deref() + .is_some_and(|r| r != c.redirect_uri) + { + return bad("redirect_uri isn't the one the code was sent to."); + } + if !pkce_matches(verifier, &c.code_challenge) { + return bad("code_verifier doesn't match the code_challenge."); + } + if let Some(r) = form.resource.as_deref().filter(|r| !r.is_empty()) { + if !is_our_resource(r, &c.resource) { + return Ok(Err(token_error( + "invalid_target", + "This server issues tokens only for its own MCP address.", + ))); + } + } + let id = ulid::Ulid::new().to_string().to_ascii_lowercase(); + let refresh_token = new_refresh(&id); + let grant = StoredGrant { + id, + team_id: c.team_id, + user_id: c.user_id, + email: c.email, + client_id: c.client_id, + client_name: c.client_name, + redirect_host: redirect_host(&c.redirect_uri), + scopes: c.scopes, + created_at: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + created_at_secs: now.timestamp().max(0) as u64, + mfa: c.mfa, + via: c.via, + refresh_hash: hash(&refresh_token), + prev_refresh_hash: None, + refresh_expires_at: refresh_expiry(now), + last_used_at: None, + revoked_at: None, + revoked_by: None, + }; + store.create_grant(&grant).await?; + let scopes = grant.scope_set(); + let access_token = issue_access(&grant, &scopes, issuer, secret, now.timestamp() as u64) + .map_err(|e| e.to_string())?; + Ok(Ok(TokenAnswer { + access_token, + token_type: "Bearer", + expires_in: ACCESS_TTL_SECS, + refresh_token, + scope: scope_string(scopes), + })) +} + +async fn refresh( + store: &impl OAuthStore, + form: &TokenForm, + issuer: &str, + secret: &str, + now: chrono::DateTime, +) -> Result, String> { + let bad = |d: &str| Ok(Err(token_error("invalid_grant", d))); + let Some(token) = form.refresh_token.as_deref() else { + return Ok(Err(token_error( + "invalid_request", + "refresh_token is missing.", + ))); + }; + let Some(gid) = refresh_grant_id(token) else { + return bad("The refresh token isn't valid."); + }; + let Some(g) = store.get_grant(gid).await? else { + return bad("This connection no longer exists. Sign in again."); + }; + if g.revoked_at.is_some() { + return bad("This connection was removed in CoderHelm. Sign in again."); + } + if form.client_id.as_deref().is_some_and(|c| c != g.client_id) { + return bad("The refresh token belongs to another app."); + } + if !hash_matches(token, &g.refresh_hash) { + if g.prev_refresh_hash + .as_deref() + .is_some_and(|p| hash_matches(token, p)) + { + // A replaced refresh token came back: someone else may hold a + // copy. End the connection (OAuth 2.1 4.3.1). + let at = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + store + .revoke_grant(&g.team_id, &g.id, "a refresh token used twice", &at) + .await?; + return bad( + "This refresh token was already used, so the connection was ended. Sign in again.", + ); + } + return bad("The refresh token isn't valid."); + } + if expired(&g.refresh_expires_at, now) { + return bad("The refresh token has expired. Sign in again."); + } + if let Some(r) = form.resource.as_deref().filter(|r| !r.is_empty()) { + if !is_our_resource(r, &resource_for(issuer)) { + return Ok(Err(token_error( + "invalid_target", + "This server issues tokens only for its own MCP address.", + ))); + } + } + // A narrower set may be asked for; never a wider one. + let held = g.scope_set(); + let scopes: BTreeSet<&'static str> = match form.scope.as_deref() { + Some(s) if !s.trim().is_empty() => { + let asked = parse_scope(Some(s)); + if !asked.is_subset(&held) { + return Ok(Err(token_error( + "invalid_scope", + "That is more than this connection was given. Sign in again to ask for it.", + ))); + } + asked + } + _ => held, + }; + let next = new_refresh(&g.id); + let rotated = store + .rotate_refresh(&g, &hash(next.as_str()), &refresh_expiry(now)) + .await?; + if !rotated { + return bad("The refresh token was just used. Use the newest one."); + } + let access_token = issue_access(&g, &scopes, issuer, secret, now.timestamp() as u64) + .map_err(|e| e.to_string())?; + Ok(Ok(TokenAnswer { + access_token, + token_type: "Bearer", + expires_in: ACCESS_TTL_SECS, + refresh_token: next, + scope: scope_string(scopes), + })) +} + +/// `POST /oauth/revoke` (RFC 7009): a refresh token ends its connection; an +/// access token ends the connection it belongs to. Anything else is +/// ignored, and the answer is the same either way. +pub async fn revoke_token( + store: &impl OAuthStore, + token: &str, + secret: &str, + now: chrono::DateTime, +) -> Result<(), String> { + let at = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + let grant = if let Some(gid) = refresh_grant_id(token) { + store + .get_grant(gid) + .await? + .filter(|g| hash_matches(token, &g.refresh_hash)) + } else { + // An expired access token can still be revoked. + let mut v = Validation::default(); + v.set_audience(&[ACCESS_AUDIENCE]); + v.validate_exp = false; + match decode::(token, &DecodingKey::from_secret(secret.as_bytes()), &v) { + Ok(t) => store + .get_grant(&t.claims.gid) + .await? + .filter(|g| g.team_id == t.claims.team_id && g.user_id == t.claims.sub), + Err(_) => None, + } + }; + if let Some(g) = grant.filter(|g| g.revoked_at.is_none()) { + store + .revoke_grant(&g.team_id, &g.id, "the app itself", &at) + .await?; + } + Ok(()) +} + +// ── Where it is kept ──────────────────────────────────────────────── + +/// A trait so the rules can be tested without DynamoDB. +pub trait OAuthStore { + async fn put_client(&self, c: &StoredClient) -> Result<(), String>; + async fn get_client(&self, id: &str) -> Result, String>; + async fn put_code(&self, c: &StoredCode) -> Result<(), String>; + /// Removes the code and returns it: at most one caller ever gets it. + async fn take_code(&self, hash: &str) -> Result, String>; + async fn create_grant(&self, g: &StoredGrant) -> Result<(), String>; + async fn get_grant(&self, id: &str) -> Result, String>; + /// Replaces the refresh token, only if `g.refresh_hash` is still the + /// current one. `false` when another request replaced it first. + async fn rotate_refresh( + &self, + g: &StoredGrant, + new_hash: &str, + expires_at: &str, + ) -> Result; + /// Marks a connection of this team revoked. `false` when the team has + /// no such live connection. + async fn revoke_grant( + &self, + team_id: &str, + id: &str, + by: &str, + at: &str, + ) -> Result; + /// The team's connections, live and revoked, newest first. + async fn list_grants(&self, team_id: &str) -> Result, String>; + /// Notes a call (`last_used_at`), at most once a minute per connection. + async fn note_use(&self, g: &StoredGrant, at: &str) -> Result<(), String>; +} + +pub struct DynamoOAuth<'a> { + pub dynamo: &'a aws_sdk_dynamodb::Client, + pub table: &'a str, +} + +pub fn store(state: &crate::AppState) -> DynamoOAuth<'_> { + DynamoOAuth { + dynamo: &state.dynamo, + table: &state.config.settings_table_name, + } +} + +const CLIENT_PK: &str = "MCP_CLIENT#"; +const CODE_PK: &str = "MCP_CODE#"; +const GRANT_PK: &str = "MCP_GRANT#"; +const GRANT_SK: &str = "MCP_GRANT"; +/// The team copy's sort key prefix. +pub const TEAM_GRANT_PREFIX: &str = "MCP_GRANT#"; + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn n(v: i64) -> AttributeValue { + AttributeValue::N(v.to_string()) +} + +fn err(e: aws_sdk_dynamodb::error::SdkError) -> String { + format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(&e)) +} + +fn data Deserialize<'de>>(item: &HashMap) -> Option { + item.get("data") + .and_then(|v| v.as_s().ok()) + .and_then(|d| serde_json::from_str(d).ok()) +} + +/// A connection from either of its records: the fixed part is `data`, what +/// changes is kept beside it. +fn grant_of(item: &HashMap) -> Option { + let mut g: StoredGrant = data(item)?; + let get = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + if let Some(h) = get("refresh_hash") { + g.refresh_hash = h; + } + g.prev_refresh_hash = get("prev_refresh_hash").or(g.prev_refresh_hash); + if let Some(e) = get("refresh_expires_at") { + g.refresh_expires_at = e; + } + g.last_used_at = get("last_used_at").or(g.last_used_at); + if let Some(at) = get("revoked_at") { + g.revoked_at = Some(at); + g.revoked_by = get("revoked_by"); + } + Some(g) +} + +/// Seconds since the epoch of an RFC 3339 time (0 when unreadable). +fn epoch(at: &str) -> i64 { + chrono::DateTime::parse_from_rfc3339(at).map_or(0, |t| t.timestamp()) +} + +impl OAuthStore for DynamoOAuth<'_> { + async fn put_client(&self, c: &StoredClient) -> Result<(), String> { + let ttl = epoch(&c.created_at) + CLIENT_TTL_DAYS * 86_400; + self.dynamo + .put_item() + .table_name(self.table) + .item("pk", s(&format!("{CLIENT_PK}{}", c.client_id))) + .item("sk", s("MCP_CLIENT")) + .item("record_type", s("mcp_client")) + .item( + "data", + s(&serde_json::to_string(c).map_err(|e| e.to_string())?), + ) + .item("ttl", n(ttl)) + .condition_expression("attribute_not_exists(pk)") + .send() + .await + .map_err(err)?; + Ok(()) + } + + async fn get_client(&self, id: &str) -> Result, String> { + if !id.starts_with(CLIENT_PREFIX) || id.len() > 64 { + return Ok(None); + } + let r = self + .dynamo + .get_item() + .table_name(self.table) + .key("pk", s(&format!("{CLIENT_PK}{id}"))) + .key("sk", s("MCP_CLIENT")) + .send() + .await + .map_err(err)?; + Ok(r.item().and_then(data)) + } + + async fn put_code(&self, c: &StoredCode) -> Result<(), String> { + self.dynamo + .put_item() + .table_name(self.table) + .item("pk", s(&format!("{CODE_PK}{}", c.hash))) + .item("sk", s("MCP_CODE")) + .item("record_type", s("mcp_code")) + .item( + "data", + s(&serde_json::to_string(c).map_err(|e| e.to_string())?), + ) + .item("ttl", n(c.expires_at + 60)) + .send() + .await + .map_err(err)?; + Ok(()) + } + + async fn take_code(&self, hash: &str) -> Result, String> { + let r = self + .dynamo + .delete_item() + .table_name(self.table) + .key("pk", s(&format!("{CODE_PK}{hash}"))) + .key("sk", s("MCP_CODE")) + .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) + .send() + .await + .map_err(err)?; + Ok(r.attributes().and_then(data)) + } + + async fn create_grant(&self, g: &StoredGrant) -> Result<(), String> { + // The hashes live beside `data`, on the checked record only. + let fixed = StoredGrant { + refresh_hash: String::new(), + prev_refresh_hash: None, + ..g.clone() + }; + let body = serde_json::to_string(&fixed).map_err(|e| e.to_string())?; + let ttl = epoch(&g.refresh_expires_at) + 86_400; + let main = Put::builder() + .table_name(self.table) + .item("pk", s(&format!("{GRANT_PK}{}", g.id))) + .item("sk", s(GRANT_SK)) + .item("record_type", s("mcp_grant")) + .item("data", s(&body)) + .item("refresh_hash", s(&g.refresh_hash)) + .item("refresh_expires_at", s(&g.refresh_expires_at)) + .item("ttl", n(ttl)) + .condition_expression("attribute_not_exists(pk)") + .build() + .map_err(|e| e.to_string())?; + let team = Put::builder() + .table_name(self.table) + .item("pk", s(&g.team_id)) + .item("sk", s(&format!("{TEAM_GRANT_PREFIX}{}", g.id))) + .item("record_type", s("mcp_grant")) + .item("data", s(&body)) + .item("refresh_expires_at", s(&g.refresh_expires_at)) + .item("ttl", n(ttl)) + .condition_expression("attribute_not_exists(pk)") + .build() + .map_err(|e| e.to_string())?; + self.dynamo + .transact_write_items() + .transact_items(TransactWriteItem::builder().put(main).build()) + .transact_items(TransactWriteItem::builder().put(team).build()) + .send() + .await + .map_err(err)?; + Ok(()) + } + + async fn get_grant(&self, id: &str) -> Result, String> { + if id.len() != 26 || !id.chars().all(|c| c.is_ascii_alphanumeric()) { + return Ok(None); + } + let r = self + .dynamo + .get_item() + .table_name(self.table) + .key("pk", s(&format!("{GRANT_PK}{id}"))) + .key("sk", s(GRANT_SK)) + .consistent_read(true) + .send() + .await + .map_err(err)?; + Ok(r.item().and_then(grant_of)) + } + + async fn rotate_refresh( + &self, + g: &StoredGrant, + new_hash: &str, + expires_at: &str, + ) -> Result { + let ttl = n(epoch(expires_at) + 86_400); + let main = Update::builder() + .table_name(self.table) + .key("pk", s(&format!("{GRANT_PK}{}", g.id))) + .key("sk", s(GRANT_SK)) + .update_expression( + "SET refresh_hash = :new, prev_refresh_hash = :old, refresh_expires_at = :exp, #ttl = :ttl", + ) + .condition_expression("refresh_hash = :old AND attribute_not_exists(revoked_at)") + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_values(":new", s(new_hash)) + .expression_attribute_values(":old", s(&g.refresh_hash)) + .expression_attribute_values(":exp", s(expires_at)) + .expression_attribute_values(":ttl", ttl.clone()) + .build() + .map_err(|e| e.to_string())?; + let team = Update::builder() + .table_name(self.table) + .key("pk", s(&g.team_id)) + .key("sk", s(&format!("{TEAM_GRANT_PREFIX}{}", g.id))) + .update_expression("SET refresh_expires_at = :exp, #ttl = :ttl") + .condition_expression("attribute_exists(pk)") + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_values(":exp", s(expires_at)) + .expression_attribute_values(":ttl", ttl) + .build() + .map_err(|e| e.to_string())?; + let out = self + .dynamo + .transact_write_items() + .transact_items(TransactWriteItem::builder().update(main).build()) + .transact_items(TransactWriteItem::builder().update(team).build()) + .send() + .await; + match out { + Ok(_) => Ok(true), + Err(e) => { + let text = err(e); + if text.contains("ConditionalCheckFailed") || text.contains("TransactionCanceled") { + Ok(false) + } else { + Err(text) + } + } + } + } + + async fn revoke_grant( + &self, + team_id: &str, + id: &str, + by: &str, + at: &str, + ) -> Result { + // The checked record must be this team's: an id from another team + // matches nothing here. + let Some(existing) = self.get_grant(id).await? else { + return Ok(false); + }; + if existing.team_id != team_id || existing.revoked_at.is_some() { + return Ok(false); + } + // Kept 90 days after revoking, for the page's history. + let ttl = n(epoch(at) + 90 * 86_400); + let update = |pk: String, sk: String| { + Update::builder() + .table_name(self.table) + .key("pk", s(&pk)) + .key("sk", s(&sk)) + .update_expression("SET revoked_at = :at, revoked_by = :by, #ttl = :ttl") + .condition_expression("attribute_exists(pk) AND attribute_not_exists(revoked_at)") + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_values(":at", s(at)) + .expression_attribute_values(":by", s(by)) + .expression_attribute_values(":ttl", ttl.clone()) + .build() + .map_err(|e| e.to_string()) + }; + let out = self + .dynamo + .transact_write_items() + .transact_items( + TransactWriteItem::builder() + .update(update(format!("{GRANT_PK}{id}"), GRANT_SK.into())?) + .build(), + ) + .transact_items( + TransactWriteItem::builder() + .update(update( + team_id.to_string(), + format!("{TEAM_GRANT_PREFIX}{id}"), + )?) + .build(), + ) + .send() + .await; + match out { + Ok(_) => Ok(true), + Err(e) => { + let text = err(e); + if text.contains("ConditionalCheckFailed") || text.contains("TransactionCanceled") { + Ok(false) + } else { + Err(text) + } + } + } + } + + async fn list_grants(&self, team_id: &str) -> Result, String> { + let r = self + .dynamo + .query() + .table_name(self.table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", s(team_id)) + .expression_attribute_values(":p", s(TEAM_GRANT_PREFIX)) + .scan_index_forward(false) + .send() + .await + .map_err(err)?; + Ok(r.items().iter().filter_map(grant_of).collect()) + } + + async fn note_use(&self, g: &StoredGrant, at: &str) -> Result<(), String> { + self.dynamo + .update_item() + .table_name(self.table) + .key("pk", s(&g.team_id)) + .key("sk", s(&format!("{TEAM_GRANT_PREFIX}{}", g.id))) + .update_expression("SET last_used_at = :at") + .condition_expression("attribute_exists(pk)") + .expression_attribute_values(":at", s(at)) + .send() + .await + .map_err(err)?; + Ok(()) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::sync::Mutex; + + pub const SECRET: &str = "test-jwt-secret-at-least-32-chars!"; + pub const ISSUER: &str = "https://api.example.org"; + + /// Clients, codes and connections kept in memory, the way DynamoOAuth keeps them. + #[derive(Default)] + pub struct Mem { + pub clients: Mutex>, + pub codes: Mutex>, + pub grants: Mutex>, + } + + impl OAuthStore for Mem { + async fn put_client(&self, c: &StoredClient) -> Result<(), String> { + self.clients + .lock() + .unwrap() + .insert(c.client_id.clone(), c.clone()); + Ok(()) + } + async fn get_client(&self, id: &str) -> Result, String> { + Ok(self.clients.lock().unwrap().get(id).cloned()) + } + async fn put_code(&self, c: &StoredCode) -> Result<(), String> { + self.codes.lock().unwrap().insert(c.hash.clone(), c.clone()); + Ok(()) + } + async fn take_code(&self, hash: &str) -> Result, String> { + Ok(self.codes.lock().unwrap().remove(hash)) + } + async fn create_grant(&self, g: &StoredGrant) -> Result<(), String> { + self.grants.lock().unwrap().insert(g.id.clone(), g.clone()); + Ok(()) + } + async fn get_grant(&self, id: &str) -> Result, String> { + Ok(self.grants.lock().unwrap().get(id).cloned()) + } + async fn rotate_refresh( + &self, + g: &StoredGrant, + new_hash: &str, + expires_at: &str, + ) -> Result { + let mut all = self.grants.lock().unwrap(); + match all.get_mut(&g.id) { + Some(cur) if cur.refresh_hash == g.refresh_hash && cur.revoked_at.is_none() => { + cur.prev_refresh_hash = Some(cur.refresh_hash.clone()); + cur.refresh_hash = new_hash.to_string(); + cur.refresh_expires_at = expires_at.to_string(); + Ok(true) + } + _ => Ok(false), + } + } + async fn revoke_grant( + &self, + team_id: &str, + id: &str, + by: &str, + at: &str, + ) -> Result { + let mut all = self.grants.lock().unwrap(); + match all.get_mut(id) { + Some(g) if g.team_id == team_id && g.revoked_at.is_none() => { + g.revoked_at = Some(at.into()); + g.revoked_by = Some(by.into()); + Ok(true) + } + _ => Ok(false), + } + } + async fn list_grants(&self, team_id: &str) -> Result, String> { + let mut v: Vec = self + .grants + .lock() + .unwrap() + .values() + .filter(|g| g.team_id == team_id) + .cloned() + .collect(); + v.sort_by(|a, b| b.id.cmp(&a.id)); + Ok(v) + } + async fn note_use(&self, g: &StoredGrant, at: &str) -> Result<(), String> { + if let Some(cur) = self.grants.lock().unwrap().get_mut(&g.id) { + cur.last_used_at = Some(at.into()); + } + Ok(()) + } + } + + pub fn now() -> chrono::DateTime { + chrono::Utc::now() + } + + pub const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + + pub fn client(mem: &Mem, redirect: &str) -> StoredClient { + let c = register( + &Registration { + redirect_uris: vec![redirect.into()], + client_name: Some("Claude".into()), + ..Default::default() + }, + now(), + ) + .unwrap(); + mem.clients + .lock() + .unwrap() + .insert(c.client_id.clone(), c.clone()); + c + } + + pub fn params(c: &StoredClient, scope: &str) -> AuthorizeParams { + AuthorizeParams { + response_type: Some("code".into()), + client_id: Some(c.client_id.clone()), + redirect_uri: Some(c.redirect_uris[0].clone()), + code_challenge: Some(pkce_challenge(VERIFIER)), + code_challenge_method: Some("S256".into()), + scope: Some(scope.into()), + state: Some("xyz".into()), + resource: Some(resource_for(ISSUER)), + } + } + + pub fn consent(team: &str, user: &str, write: bool) -> Consent { + Consent { + team_id: team.into(), + user_id: user.into(), + email: "ann@example.org".into(), + mfa: false, + via: Some("password".into()), + allow_write: write, + } + } + + /// A full sign-in: register, authorize, consent, swap. Returns the tokens. + pub async fn connect(mem: &Mem, team: &str, user: &str, write: bool) -> TokenAnswer { + let c = client(mem, "https://claude.ai/api/mcp/auth_callback"); + let req = check_authorize( + ¶ms(&c, "runs:read runs:write"), + Some(&c), + &resource_for(ISSUER), + ) + .unwrap(); + let (code, stored) = approve(&req, &c, &consent(team, user, write), now()); + mem.put_code(&stored).await.unwrap(); + token( + mem, + &TokenForm { + grant_type: Some("authorization_code".into()), + code: Some(code), + redirect_uri: Some(c.redirect_uris[0].clone()), + client_id: Some(c.client_id.clone()), + code_verifier: Some(VERIFIER.into()), + resource: Some(resource_for(ISSUER)), + ..Default::default() + }, + ISSUER, + SECRET, + now(), + ) + .await + .unwrap() + .unwrap() + } + + async fn refresh_with(mem: &Mem, refresh: &str) -> Result { + token( + mem, + &TokenForm { + grant_type: Some("refresh_token".into()), + refresh_token: Some(refresh.into()), + ..Default::default() + }, + ISSUER, + SECRET, + now(), + ) + .await + .unwrap() + } + + async fn auth(mem: &Mem, access: &str) -> Result { + authenticate(mem, access, SECRET, now().timestamp() as u64) + .await + .unwrap() + } + + #[test] + fn pkce_accepts_only_the_verifier_of_the_challenge() { + // RFC 7636 appendix B. + assert_eq!( + pkce_challenge(VERIFIER), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + let challenge = pkce_challenge(VERIFIER); + assert!(pkce_matches(VERIFIER, &challenge)); + let mut wrong = VERIFIER.to_string(); + wrong.replace_range(0..1, "e"); + assert!(!pkce_matches(&wrong, &challenge)); + // Too short, or with characters a verifier can't have. + assert!(!pkce_matches("short", &pkce_challenge("short"))); + let spaced = format!("{} ", &VERIFIER[..43]); + assert!(!pkce_matches(&spaced, &pkce_challenge(&spaced))); + } + + #[test] + fn an_authorization_request_needs_pkce_s256_and_a_registered_redirect() { + let mem = Mem::default(); + let c = client(&mem, "https://claude.ai/api/mcp/auth_callback"); + let res = resource_for(ISSUER); + let ok = check_authorize(¶ms(&c, "runs:read"), Some(&c), &res).unwrap(); + assert_eq!(ok.scopes, vec!["runs:read"]); + assert_eq!(ok.state.as_deref(), Some("xyz")); + + // No PKCE, or plain PKCE: refused back to the app. + let mut p = params(&c, "runs:read"); + p.code_challenge = None; + assert!(matches!( + check_authorize(&p, Some(&c), &res), + Err(AuthorizeError::Redirect { + error: "invalid_request", + .. + }) + )); + let mut p = params(&c, "runs:read"); + p.code_challenge_method = Some("plain".into()); + assert!(matches!( + check_authorize(&p, Some(&c), &res), + Err(AuthorizeError::Redirect { + error: "invalid_request", + .. + }) + )); + let mut p = params(&c, "runs:read"); + p.response_type = Some("token".into()); + assert!(matches!( + check_authorize(&p, Some(&c), &res), + Err(AuthorizeError::Redirect { + error: "unsupported_response_type", + .. + }) + )); + // Another server's resource. + let mut p = params(&c, "runs:read"); + p.resource = Some("https://evil.example/mcp".into()); + assert!(matches!( + check_authorize(&p, Some(&c), &res), + Err(AuthorizeError::Redirect { + error: "invalid_target", + .. + }) + )); + + // An address the app didn't register, or no app: a page, never a redirect. + let mut p = params(&c, "runs:read"); + p.redirect_uri = Some("https://evil.example/cb".into()); + let e = check_authorize(&p, Some(&c), &res).unwrap_err(); + assert!(matches!(e, AuthorizeError::Page(_))); + assert_eq!(error_redirect(&e, ISSUER), None); + assert!(matches!( + check_authorize(¶ms(&c, ""), None, &res), + Err(AuthorizeError::Page(_)) + )); + + // An error sent back carries the state and who answered. + let mut p = params(&c, "runs:read"); + p.code_challenge = None; + let url = + error_redirect(&check_authorize(&p, Some(&c), &res).unwrap_err(), ISSUER).unwrap(); + assert!(url.starts_with("https://claude.ai/api/mcp/auth_callback?error=invalid_request")); + assert!(url.contains("state=xyz") && url.contains("iss=https%3A%2F%2Fapi.example.org")); + } + + #[test] + fn redirect_addresses_are_https_this_computer_or_an_apps_own_scheme() { + for ok in [ + "https://claude.ai/api/mcp/auth_callback", + "http://localhost:6274/oauth/callback", + "http://127.0.0.1:33418/", + "http://[::1]:5000/cb", + "cursor://anysphere.cursor-retrieval/oauth/user-coderhelm/callback", + "vscode://vscode.github-authentication/did-authenticate", + ] { + assert!(check_redirect_uri(ok).is_ok(), "{ok}"); + } + for bad in [ + "http://example.com/cb", + "javascript:alert(1)", + "data:text/html,hi", + "file:///etc/passwd", + "https://claude.ai/cb#frag", + "https://user:pw@claude.ai/cb", + "not a url", + ] { + assert!(check_redirect_uri(bad).is_err(), "{bad}"); + } + // A loopback address matches on any port; nothing else does. + let reg = vec![ + "http://127.0.0.1/callback".to_string(), + "https://claude.ai/cb".to_string(), + ]; + assert!(redirect_matches(®, "http://127.0.0.1:51234/callback")); + assert!(!redirect_matches(®, "http://127.0.0.1:51234/other")); + assert!(!redirect_matches(®, "https://claude.ai/cb2")); + assert!(!redirect_matches(®, "https://claude.ai:8443/cb")); + assert_eq!(redirect_host("https://claude.ai/cb"), "claude.ai"); + assert_eq!(redirect_host("http://127.0.0.1:5123/cb"), "127.0.0.1:5123"); + assert_eq!( + redirect_host("cursor://anysphere.cursor-retrieval/oauth"), + "cursor://anysphere.cursor-retrieval" + ); + } + + #[test] + fn registration_makes_a_public_client_with_a_cleaned_name() { + let c = register( + &Registration { + redirect_uris: vec!["https://claude.ai/cb".into()], + client_name: Some(" Claude\u{0007} Desktop ".into()), + ..Default::default() + }, + now(), + ) + .unwrap(); + assert!(c.client_id.starts_with(CLIENT_PREFIX)); + assert_eq!(c.client_name, "Claude Desktop"); + let a = registration_answer(&c, 1); + assert_eq!(a["token_endpoint_auth_method"], "none"); + assert!(a.get("client_secret").is_none()); + assert_eq!(clean_name(None), "An app without a name"); + for bad in [ + Registration::default(), + Registration { + redirect_uris: vec!["http://example.com/cb".into()], + ..Default::default() + }, + Registration { + redirect_uris: vec!["https://claude.ai/cb".into()], + grant_types: Some(vec!["client_credentials".into()]), + ..Default::default() + }, + Registration { + redirect_uris: vec!["https://claude.ai/cb".into()], + response_types: Some(vec!["token".into()]), + ..Default::default() + }, + ] { + assert!(register(&bad, now()).is_err()); + } + } + + #[test] + fn scopes_always_include_reading_and_ignore_what_this_server_lacks() { + assert_eq!(parse_scope(None), BTreeSet::from([READ_SCOPE])); + assert_eq!( + parse_scope(Some("runs:write offline_access")), + BTreeSet::from([READ_SCOPE, WRITE_SCOPE]) + ); + assert_eq!( + scope_string([WRITE_SCOPE, READ_SCOPE]), + "runs:read runs:write" + ); + assert_eq!(granted_scopes(false), vec!["runs:read"]); + } + + #[test] + fn a_consent_link_is_signed_and_expires() { + let mem = Mem::default(); + let c = client(&mem, "https://claude.ai/cb"); + let req = + check_authorize(¶ms(&c, "runs:read"), Some(&c), &resource_for(ISSUER)).unwrap(); + let t0 = 1_800_000_000; + let link = sign_request(&req, SECRET, t0).unwrap(); + let back = read_request(&link, SECRET, t0 + 10).unwrap(); + assert_eq!(back.client_id, c.client_id); + assert!(read_request(&link, SECRET, t0 + REQUEST_TTL_SECS).is_none()); + assert!(read_request(&link, "another-secret-of-at-least-32-chars", t0).is_none()); + // A session or an access token is not a consent link. + let session = + crate::auth::jwt::create_token("u", "t", "e@x.com", "member", None, SECRET, 300) + .unwrap(); + assert!(read_request(&session, SECRET, t0).is_none()); + } + + #[tokio::test] + async fn a_code_swaps_once_for_tokens_with_the_right_verifier() { + let mem = Mem::default(); + let c = client(&mem, "https://claude.ai/cb"); + let req = check_authorize( + ¶ms(&c, "runs:read runs:write"), + Some(&c), + &resource_for(ISSUER), + ) + .unwrap(); + let (code, stored) = approve(&req, &c, &consent("TEAM#a", "USER#ann", true), now()); + assert!(!stored.hash.contains(&code[CODE_PREFIX.len()..])); + mem.put_code(&stored).await.unwrap(); + let form = |verifier: &str, client_id: &str| TokenForm { + grant_type: Some("authorization_code".into()), + code: Some(code.clone()), + redirect_uri: Some("https://claude.ai/cb".into()), + client_id: Some(client_id.into()), + code_verifier: Some(verifier.into()), + ..Default::default() + }; + // A wrong verifier: refused, and the code is used up. + let wrong = "x".repeat(43); + let e = token(&mem, &form(&wrong, &c.client_id), ISSUER, SECRET, now()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(e.error, "invalid_grant"); + let e = token(&mem, &form(VERIFIER, &c.client_id), ISSUER, SECRET, now()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(e.error, "invalid_grant"); + + // A fresh code with the right verifier, by the right app: tokens. + let (code, stored) = approve(&req, &c, &consent("TEAM#a", "USER#ann", true), now()); + mem.put_code(&stored).await.unwrap(); + let mut f = form(VERIFIER, "mcpc_someoneelse"); + f.code = Some(code.clone()); + let e = token(&mem, &f, ISSUER, SECRET, now()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(e.error, "invalid_grant", "another app can't swap it"); + + let (code, stored) = approve(&req, &c, &consent("TEAM#a", "USER#ann", true), now()); + mem.put_code(&stored).await.unwrap(); + let mut f = form(VERIFIER, &c.client_id); + f.code = Some(code.clone()); + let t = token(&mem, &f, ISSUER, SECRET, now()) + .await + .unwrap() + .unwrap(); + assert_eq!(t.token_type, "Bearer"); + assert_eq!(t.expires_in, ACCESS_TTL_SECS); + assert_eq!(t.scope, "runs:read runs:write"); + assert!(t.refresh_token.starts_with(REFRESH_PREFIX)); + // Used once: never again. + let e = token(&mem, &f, ISSUER, SECRET, now()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(e.error, "invalid_grant"); + // The refresh token is kept only as its hash. + let g = mem.grants.lock().unwrap().values().next().cloned().unwrap(); + assert_eq!(g.refresh_hash, hash(&t.refresh_token)); + assert_eq!(g.redirect_host, "claude.ai"); + } + + #[tokio::test] + async fn an_expired_code_is_refused() { + let mem = Mem::default(); + let c = client(&mem, "https://claude.ai/cb"); + let req = + check_authorize(¶ms(&c, "runs:read"), Some(&c), &resource_for(ISSUER)).unwrap(); + let then = now() - chrono::Duration::seconds(CODE_TTL_SECS + 1); + let (code, stored) = approve(&req, &c, &consent("TEAM#a", "USER#ann", false), then); + mem.put_code(&stored).await.unwrap(); + let e = token( + &mem, + &TokenForm { + grant_type: Some("authorization_code".into()), + code: Some(code), + client_id: Some(c.client_id.clone()), + code_verifier: Some(VERIFIER.into()), + ..Default::default() + }, + ISSUER, + SECRET, + now(), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(e.error, "invalid_grant"); + assert!(e.description.contains("expired")); + } + + #[tokio::test] + async fn an_access_token_works_until_it_expires() { + let mem = Mem::default(); + let t = connect(&mem, "TEAM#a", "USER#ann", false).await; + let ok = auth(&mem, &t.access_token).await.unwrap(); + assert_eq!(ok.grant.team_id, "TEAM#a"); + assert_eq!( + ok.scopes, + BTreeSet::from([READ_SCOPE]), + "write was not allowed" + ); + // An hour later it is expired; the refresh token gets a new one. + let later = now().timestamp() as u64 + ACCESS_TTL_SECS; + assert_eq!( + authenticate(&mem, &t.access_token, SECRET, later) + .await + .unwrap() + .unwrap_err(), + AccessRefusal::Expired + ); + // Signed with another secret, or a session token: not an access token. + assert_eq!( + auth(&mem, "eyJhbGciOiJIUzI1NiJ9.e30.x").await.unwrap_err(), + AccessRefusal::Invalid + ); + let session = crate::auth::jwt::create_token( + "USER#ann", "TEAM#a", "e@x.com", "owner", None, SECRET, 300, + ) + .unwrap(); + assert_eq!( + auth(&mem, &session).await.unwrap_err(), + AccessRefusal::Invalid + ); + // ...and an access token is not a session. + assert!(crate::auth::jwt::validate_token(&t.access_token, SECRET).is_err()); + } + + #[tokio::test] + async fn refresh_tokens_rotate_and_a_reused_one_ends_the_connection() { + let mem = Mem::default(); + let t = connect(&mem, "TEAM#a", "USER#ann", true).await; + let t2 = refresh_with(&mem, &t.refresh_token).await.unwrap(); + assert_ne!(t2.refresh_token, t.refresh_token); + assert_eq!(t2.scope, "runs:read runs:write"); + auth(&mem, &t2.access_token).await.unwrap(); + // A narrower token may be asked for, never a wider one. + let t3 = token( + &mem, + &TokenForm { + grant_type: Some("refresh_token".into()), + refresh_token: Some(t2.refresh_token.clone()), + scope: Some("runs:read".into()), + ..Default::default() + }, + ISSUER, + SECRET, + now(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(t3.scope, "runs:read"); + assert_eq!( + auth(&mem, &t3.access_token).await.unwrap().scopes, + BTreeSet::from([READ_SCOPE]) + ); + // The replaced token comes back: the connection ends, and every + // token of it stops. + let e = refresh_with(&mem, &t2.refresh_token).await.unwrap_err(); + assert_eq!(e.error, "invalid_grant"); + assert_eq!( + auth(&mem, &t3.access_token).await.unwrap_err(), + AccessRefusal::Revoked + ); + assert_eq!( + refresh_with(&mem, &t3.refresh_token) + .await + .unwrap_err() + .error, + "invalid_grant" + ); + // Garbage is refused without a lookup. + assert_eq!( + refresh_with(&mem, "chr_nope").await.unwrap_err().error, + "invalid_grant" + ); + } + + #[tokio::test] + async fn a_read_only_connection_cannot_refresh_into_writing() { + let mem = Mem::default(); + let t = connect(&mem, "TEAM#a", "USER#ann", false).await; + let e = token( + &mem, + &TokenForm { + grant_type: Some("refresh_token".into()), + refresh_token: Some(t.refresh_token.clone()), + scope: Some("runs:read runs:write".into()), + ..Default::default() + }, + ISSUER, + SECRET, + now(), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(e.error, "invalid_scope"); + } + + #[tokio::test] + async fn revoking_ends_access_and_refresh_at_once() { + let mem = Mem::default(); + let t = connect(&mem, "TEAM#a", "USER#ann", true).await; + let gid = auth(&mem, &t.access_token).await.unwrap().grant.id; + // Another team can't revoke it. + assert!(!mem + .revoke_grant("TEAM#b", &gid, "USER#bob", "now") + .await + .unwrap()); + auth(&mem, &t.access_token).await.unwrap(); + assert!(mem + .revoke_grant("TEAM#a", &gid, "USER#ann", "now") + .await + .unwrap()); + assert_eq!( + auth(&mem, &t.access_token).await.unwrap_err(), + AccessRefusal::Revoked + ); + assert_eq!( + refresh_with(&mem, &t.refresh_token) + .await + .unwrap_err() + .error, + "invalid_grant" + ); + // Twice finds nothing to revoke. + assert!(!mem + .revoke_grant("TEAM#a", &gid, "USER#ann", "now") + .await + .unwrap()); + + // The app revoking its own token (RFC 7009) ends the connection too. + let t = connect(&mem, "TEAM#a", "USER#ann", false).await; + revoke_token(&mem, &t.refresh_token, SECRET, now()) + .await + .unwrap(); + assert_eq!( + auth(&mem, &t.access_token).await.unwrap_err(), + AccessRefusal::Revoked + ); + let t = connect(&mem, "TEAM#a", "USER#ann", false).await; + revoke_token(&mem, &t.access_token, SECRET, now()) + .await + .unwrap(); + assert_eq!( + refresh_with(&mem, &t.refresh_token) + .await + .unwrap_err() + .error, + "invalid_grant" + ); + // Anything else is ignored. + revoke_token(&mem, "garbage", SECRET, now()).await.unwrap(); + } + + #[tokio::test] + async fn a_token_works_only_for_its_own_team_person_and_app() { + let mem = Mem::default(); + let a = connect(&mem, "TEAM#a", "USER#ann", true).await; + let b = connect(&mem, "TEAM#b", "USER#bob", true).await; + assert_eq!( + auth(&mem, &a.access_token).await.unwrap().grant.team_id, + "TEAM#a" + ); + assert_eq!( + auth(&mem, &b.access_token).await.unwrap().grant.team_id, + "TEAM#b" + ); + // A token claiming team b on team a's connection is nobody. + let ga = auth(&mem, &a.access_token).await.unwrap().grant; + let mut forged = ga.clone(); + forged.team_id = "TEAM#b".into(); + let t = issue_access( + &forged, + &BTreeSet::from([READ_SCOPE]), + ISSUER, + SECRET, + now().timestamp() as u64, + ) + .unwrap(); + assert_eq!(auth(&mem, &t).await.unwrap_err(), AccessRefusal::Invalid); + let mut forged = ga.clone(); + forged.user_id = "USER#bob".into(); + let t = issue_access( + &forged, + &BTreeSet::from([READ_SCOPE]), + ISSUER, + SECRET, + now().timestamp() as u64, + ) + .unwrap(); + assert_eq!(auth(&mem, &t).await.unwrap_err(), AccessRefusal::Invalid); + // A token for a write scope its connection doesn't hold gets only reading. + let ro = connect(&mem, "TEAM#a", "USER#ann", false).await; + let g = auth(&mem, &ro.access_token).await.unwrap().grant; + let t = issue_access( + &g, + &BTreeSet::from([READ_SCOPE, WRITE_SCOPE]), + ISSUER, + SECRET, + now().timestamp() as u64, + ) + .unwrap(); + assert_eq!( + auth(&mem, &t).await.unwrap().scopes, + BTreeSet::from([READ_SCOPE]) + ); + // Each team lists only its own connections. + assert!(mem + .list_grants("TEAM#b") + .await + .unwrap() + .iter() + .all(|g| g.team_id == "TEAM#b")); + // Team b's refresh token can't be revoked through team a. + let gb = auth(&mem, &b.access_token).await.unwrap().grant.id; + assert!(!mem + .revoke_grant("TEAM#a", &gb, "USER#ann", "now") + .await + .unwrap()); + } +} diff --git a/services/gateway/src/mcp_server.rs b/services/gateway/src/mcp_server.rs new file mode 100644 index 000000000..cafb2438d --- /dev/null +++ b/services/gateway/src/mcp_server.rs @@ -0,0 +1,1611 @@ +//! CoderHelm's MCP server: `/mcp`, Streamable HTTP, for Claude, Cursor, +//! VS Code and any other MCP client a person adds CoderHelm to. +//! +//! Each tool is a dashboard action, and runs as one: a tool call becomes a +//! request to the same API route the dashboard calls (`/api/runs`, +//! `/api/runs/:id/retry`, `/api/reviewer/re-review`, ...), sent through the +//! same router and the same auth middleware, as the person who connected +//! the app. So a call is checked exactly like that person's click: their +//! membership and current role (custom roles included), the team's +//! two-factor rule, the capability the route belongs to, and the route's own +//! role check. On top, the connection's scopes: `runs:read` reaches only the +//! routes the reading tools call, `runs:write` adds the routes of the tools +//! that act ([`decide`]). Every call is written to the team's log of access +//! changes before it runs. +//! +//! The server is stateless: no `Mcp-Session-Id`, answers are JSON (never a +//! stream), and `GET /mcp` answers 405 (no server-sent events). + +use axum::{ + body::{Body, Bytes}, + extract::{Extension, State}, + http::{header, HeaderMap, HeaderValue, Method, Request, StatusCode}, + response::{IntoResponse, Response}, + Json, Router, +}; +use serde_json::{json, Value}; +use std::collections::{BTreeSet, HashMap}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tower::ServiceExt; +use tracing::{error, warn}; + +use crate::mcp_oauth::{self, AccessRefusal, StoredGrant, READ_SCOPE, WRITE_SCOPE}; +use crate::models::Claims; +use crate::permissions::{self, Access, Capability, Holder}; +use crate::routes::roles::{self, AuditEntry}; +use crate::AppState; + +/// The protocol versions this server speaks, newest first. +pub const PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18", "2025-03-26"]; + +/// The routes the reading tools call. A token with `runs:read` reaches +/// these and nothing else. +pub const READ_HANDLERS: &[&str] = &[ + "api::list_runs", + "api::get_run", + "reviewer::list_reviews", + "reviewer::get_review", +]; + +/// The routes the acting tools call, reached with `runs:write`. +pub const WRITE_HANDLERS: &[&str] = &[ + "run_start::start_run", + "api::retry_run", + "plans::create_plan", + "plans::approve_all_and_execute", + "reviewer::re_review", +]; + +/// The API router the tools call through, as main() builds it. +#[derive(Clone)] +pub struct McpApi(pub Router); + +/// Who a tool call's API request is for: set by [`call`] on the requests it +/// makes, and only there (a request from outside never carries it). The +/// auth middleware checks it like a session (`middleware::auth`). +#[derive(Clone, Debug)] +pub struct McpCaller { + /// The person, from their member record now. `iat` is when they + /// connected the app: sessions ended after that end the connection too. + pub claims: Claims, + pub grant: StoredGrant, + pub scopes: BTreeSet<&'static str>, + /// The routes the tool being called may reach: a call reaches nothing + /// another tool would. + pub tool_handlers: &'static [&'static str], +} + +/// Why an app's request to a route was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + /// No tool calls this route. + NotForApps, + /// The connection wasn't given this scope. + Scope(&'static str), + /// The person's role doesn't include it. + Role(&'static Capability), +} + +impl Refusal { + pub fn response(self) -> Response { + let (code, msg) = match self { + Refusal::NotForApps => ( + "not_available_to_apps", + "Connected apps can't call this part of CoderHelm.".to_string(), + ), + Refusal::Scope(s) => ( + "insufficient_scope", + format!("This connection wasn't allowed to do this. Connect the app again and allow \"{}\".", mcp_oauth::scope_label(s)), + ), + Refusal::Role(c) => ( + "missing_capability", + format!( + "Your role doesn't include this ({}). Ask an admin or owner if you need it.", + c.label + ), + ), + }; + ( + StatusCode::FORBIDDEN, + Json(json!({ "error": msg, "code": code })), + ) + .into_response() + } +} + +/// The scope a route needs, when a tool calls it. +pub fn scope_for_handler(handler: &str) -> Option<&'static str> { + if READ_HANDLERS.contains(&handler) { + Some(READ_SCOPE) + } else if WRITE_HANDLERS.contains(&handler) { + Some(WRITE_SCOPE) + } else { + None + } +} + +/// The decision for one of an app's requests: the route must be one the +/// tool being called calls, the connection must hold its scope, and the person's role must +/// allow it exactly as it would in the dashboard (`resolve_access`). On +/// success, the built-in role the handler runs as. +pub fn decide( + scopes: &BTreeSet<&'static str>, + tool_handlers: &[&str], + holder: &Holder, + handler: Option<&str>, +) -> Result<&'static str, Refusal> { + let handler = handler.ok_or(Refusal::NotForApps)?; + if !tool_handlers.contains(&handler) { + return Err(Refusal::NotForApps); + } + let scope = scope_for_handler(handler).ok_or(Refusal::NotForApps)?; + if !scopes.contains(scope) { + return Err(Refusal::Scope(scope)); + } + match permissions::resolve_access(holder, Some(handler)) { + Access::Allow { effective_role } => Ok(effective_role), + Access::Deny { capability } => Err(Refusal::Role(capability)), + } +} + +// ── Tools ─────────────────────────────────────────────────────────── + +/// One tool, and the routes it may call. +pub struct Tool { + pub name: &'static str, + pub title: &'static str, + pub description: &'static str, + /// Needs `runs:write`; otherwise `runs:read`. + pub write: bool, + /// Every route the tool can call. + pub handlers: &'static [&'static str], + schema: fn() -> Value, +} + +impl Tool { + pub fn scope(&self) -> &'static str { + if self.write { + WRITE_SCOPE + } else { + READ_SCOPE + } + } + + fn listing(&self) -> Value { + json!({ + "name": self.name, + "title": self.title, + "description": self.description, + "inputSchema": (self.schema)(), + "annotations": { + "title": self.title, + "readOnlyHint": !self.write, + // Nothing here deletes or overwrites: starting, retrying and + // reviewing add work. + "destructiveHint": false, + "idempotentHint": !self.write, + // The acting tools open issues, branches and pull requests + // on GitHub; the reading ones stay inside CoderHelm. + "openWorldHint": self.write, + }, + }) + } +} + +fn obj(props: Value, required: &[&str]) -> Value { + json!({ + "type": "object", + "properties": props, + "required": required, + "additionalProperties": false, + }) +} + +pub const TOOLS: &[Tool] = &[ + Tool { + name: "list_runs", + title: "List runs", + description: "Lists the team's CoderHelm runs, newest first: status, ticket, repository, pull request and a link to each in the dashboard. Filter by status, repository and start time.", + write: false, + handlers: &["api::list_runs"], + schema: || { + obj( + json!({ + "status": { "type": "string", "description": "Only runs in these statuses, comma separated: pending, running, awaiting_ci, completed, failed, needs_input, needs_outside_change, covered_by_pr, cancelled, retried, closed." }, + "repo": { "type": "string", "description": "Only runs in this repository, owner/name." }, + "since": { "type": "string", "description": "Only runs started at or after this time (RFC 3339, or a date like 2026-11-01)." }, + "limit": { "type": "integer", "minimum": 1, "maximum": 100, "description": "Most runs to return. Default 20." }, + "cursor": { "type": "string", "description": "next from an earlier answer, to read older runs." } + }), + &[], + ) + }, + }, + Tool { + name: "get_run", + title: "Get a run", + description: "One run in full: its status and current step, the steps it went through, its pull requests, what it is waiting on (holds and open questions), its error if it stopped, and its latest notes.", + write: false, + handlers: &["api::get_run"], + schema: || { + obj( + json!({ "run_id": { "type": "string", "description": "The run's id, from list_runs." } }), + &["run_id"], + ) + }, + }, + Tool { + name: "start_run", + title: "Start a run", + description: "Starts CoderHelm on a piece of work. Give either a ticket (a GitHub issue URL such as https://github.com/acme/web/issues/42, or a Jira key such as WEB-42 that CoderHelm has seen before), or a task in plain words with the repository (owner/name) it is for. CoderHelm opens a pull request when it is done.", + write: true, + handlers: &[ + "run_start::start_run", + "plans::create_plan", + "plans::approve_all_and_execute", + ], + schema: || { + obj( + json!({ + "ticket": { "type": "string", "description": "A GitHub issue URL, owner/name#number, or a Jira key." }, + "task": { "type": "string", "description": "What to do, in plain words. Needs repo." }, + "repo": { "type": "string", "description": "The repository for task, owner/name." }, + "title": { "type": "string", "description": "A short title for task. Default: its first line." } + }), + &[], + ) + }, + }, + Tool { + name: "retry_run", + title: "Retry a run", + description: "Starts a run's ticket again, the same as Retry in the dashboard. Works on runs that failed, need input, were cancelled or closed; a run whose last fix round didn't finish resumes that round.", + write: true, + handlers: &["api::retry_run"], + schema: || { + obj( + json!({ "run_id": { "type": "string", "description": "The run's id, from list_runs." } }), + &["run_id"], + ) + }, + }, + Tool { + name: "list_reviews", + title: "List reviews", + description: "Lists CoderHelm's pull request reviews, newest first: repository, pull request, verdict, risk and how many findings each has.", + write: false, + handlers: &["reviewer::list_reviews"], + schema: || { + obj( + json!({ + "repo": { "type": "string", "description": "Only reviews in this repository, owner/name." }, + "limit": { "type": "integer", "minimum": 1, "maximum": 100, "description": "Most reviews to return. Default 20." }, + "cursor": { "type": "string", "description": "next from an earlier answer, to read older reviews." } + }), + &[], + ) + }, + }, + Tool { + name: "get_review", + title: "Get a review", + description: "One review in full, with its findings. Give review_id from list_reviews, or a pull request URL for that pull request's latest review.", + write: false, + handlers: &["reviewer::get_review", "reviewer::list_reviews"], + schema: || { + obj( + json!({ + "review_id": { "type": "string", "description": "review_id from list_reviews." }, + "pr_url": { "type": "string", "description": "A pull request URL, such as https://github.com/acme/web/pull/318." } + }), + &[], + ) + }, + }, + Tool { + name: "request_review", + title: "Ask for a review", + description: "Asks CoderHelm's reviewer to review a pull request's current head now, the same as Re-review in the dashboard. The review is posted on the pull request in a few minutes.", + write: true, + handlers: &["reviewer::re_review"], + schema: || { + obj( + json!({ "pr_url": { "type": "string", "description": "The pull request, such as https://github.com/acme/web/pull/318 or acme/web#318." } }), + &["pr_url"], + ) + }, + }, +]; + +pub fn find_tool(name: &str) -> Option<&'static Tool> { + TOOLS.iter().find(|t| t.name == name) +} + +// ── What the tools read from their arguments ──────────────────────── + +/// `owner/name` and a number from a GitHub URL (`.../issues/N` or +/// `.../pull/N`) or `owner/name#N`. +pub fn parse_github_ref(raw: &str, kind: &str) -> Option<(String, u64)> { + let raw = raw.trim(); + if let Some((repo, num)) = raw.split_once('#') { + let n: u64 = num.parse().ok()?; + return valid_repo(repo) + .then(|| (repo.to_string(), n)) + .filter(|_| n > 0); + } + let u = url::Url::parse(raw).ok()?; + if u.host_str() != Some("github.com") && u.host_str() != Some("www.github.com") { + return None; + } + let parts: Vec<&str> = u.path_segments()?.filter(|s| !s.is_empty()).collect(); + match parts.as_slice() { + [owner, name, k, num, ..] if *k == kind => { + let repo = format!("{owner}/{name}"); + let n: u64 = num.parse().ok()?; + (valid_repo(&repo) && n > 0).then_some((repo, n)) + } + _ => None, + } +} + +pub fn valid_repo(repo: &str) -> bool { + let Some((o, n)) = repo.split_once('/') else { + return false; + }; + let ok = |s: &str| { + !s.is_empty() + && s.len() <= 100 + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) + }; + ok(o) && ok(n) +} + +/// A time from `since`: RFC 3339, or a date (midnight UTC). +pub fn parse_since(raw: &str) -> Option> { + let raw = raw.trim(); + if let Ok(t) = chrono::DateTime::parse_from_rfc3339(raw) { + return Some(t.with_timezone(&chrono::Utc)); + } + chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d") + .ok() + .and_then(|d| d.and_hms_opt(0, 0, 0)) + .map(|d| d.and_utc()) +} + +fn arg<'a>(args: &'a Value, k: &str) -> Option<&'a str> { + args.get(k) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) +} + +fn q(s: &str) -> String { + urlencoding::encode(s).into_owned() +} + +/// A short account of a call's arguments for the log. Never a task's text. +pub fn audit_detail(tool: &str, args: &Value) -> String { + let mut parts: Vec = Vec::new(); + for k in [ + "run_id", + "ticket", + "repo", + "status", + "since", + "pr_url", + "review_id", + ] { + if let Some(v) = arg(args, k) { + parts.push(format!("{k} {}", common::truncate_str(v, 120))); + } + } + if arg(args, "task").is_some() { + parts.push("a task in words".into()); + } + if parts.is_empty() { + tool.to_string() + } else { + format!("{tool}: {}", parts.join(", ")) + } +} + +// ── Calling the API as the person ─────────────────────────────────── + +/// A refused or failed API request, as a tool shows it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CallError { + pub status: u16, + pub message: String, +} + +fn default_message(status: StatusCode) -> &'static str { + match status.as_u16() { + 400 => "CoderHelm couldn't do that with what was sent. Check the arguments.", + 401 => "This connection no longer works. Sign in to CoderHelm again from the app.", + 403 => "Your role in CoderHelm doesn't allow this.", + 404 => "CoderHelm found nothing like that in your team.", + 409 => "Something is already in progress for this.", + 429 => "The team has used its token limit for now. An admin can raise it in Settings.", + _ => "Something went wrong on CoderHelm's side. Try again shortly.", + } +} + +/// One request to the API router as `caller`. +pub async fn call( + api: &McpApi, + caller: &McpCaller, + method: Method, + uri: &str, + body: Option, +) -> Result { + let mut req = Request::builder() + .method(method) + .uri(uri) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.map(|b| b.to_string()).unwrap_or_default())) + .map_err(|e| CallError { + status: 500, + message: e.to_string(), + })?; + req.extensions_mut().insert(caller.clone()); + let res = match api.0.clone().oneshot(req).await { + Ok(r) => r, + Err(e) => match e {}, + }; + let status = res.status(); + let bytes = axum::body::to_bytes(res.into_body(), 8 * 1024 * 1024) + .await + .unwrap_or_default(); + let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if status.is_success() { + return Ok(value); + } + let message = value + .get("error") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .or_else(|| value.get("reason").and_then(Value::as_str)) + .unwrap_or_else(|| default_message(status)) + .to_string(); + Err(CallError { + status: status.as_u16(), + message, + }) +} + +fn link(path: &str) -> String { + format!("{}{path}", common::public_urls::app_url_from_env()) +} + +/// A run in a list, as a tool shows it. +fn run_line(r: &Value) -> Value { + let id = r["run_id"].as_str().unwrap_or(""); + json!({ + "run_id": id, + "status": r["status"], + "title": r["title"], + "ticket": r["ticket_id"], + "repo": r["repo"], + "pull_request": r["pr_url"], + "current_step": r["current_pass"], + "started_by": r["trigger"]["label"], + "created_at": r["created_at"], + "url": link(&format!("/runs/detail?id={}", q(id))), + }) +} + +fn keep_set(v: &Value) -> bool { + match v { + Value::Null => false, + Value::Array(a) => !a.is_empty(), + Value::String(s) => !s.is_empty(), + Value::Object(o) => !o.is_empty(), + _ => true, + } +} + +/// A run in full, as `get_run` shows it: what someone deciding what to do +/// next needs, without the run's internals. +pub fn run_detail(r: &Value) -> Value { + let id = r["run_id"].as_str().unwrap_or(""); + let mut holds = serde_json::Map::new(); + for k in [ + "waiting_on", + "draft_hold", + "github_wait", + "policy_approval", + "round_incomplete", + "codegen_env_missing", + "sign_in_prompts", + "tooling_failure", + ] { + if keep_set(&r[k]) { + holds.insert(k.to_string(), r[k].clone()); + } + } + let open_questions: Vec = r["questions"] + .as_array() + .map(|qs| { + qs.iter() + .filter(|q| !q["answered"].as_bool().unwrap_or(false)) + .cloned() + .collect() + }) + .unwrap_or_default(); + if !open_questions.is_empty() { + holds.insert("questions".into(), Value::Array(open_questions)); + } + let notes = r["progress_notes"].as_array().cloned().unwrap_or_default(); + let latest: Vec = notes.iter().rev().take(15).rev().cloned().collect(); + let mut out = json!({ + "run_id": id, + "status": r["status"], + "title": r["title"], + "ticket": r["ticket_id"], + "ticket_source": r["ticket_source"], + "repo": r["repo"], + "branch": r["branch"], + "current_step": r["current_pass"], + "started_by": r["trigger"], + "pull_requests": if keep_set(&r["prs"]) { r["prs"].clone() } else { r["pr_urls"].clone() }, + "pull_request": r["pr_url"], + "steps": r["pass_history"], + "holds": holds, + "error": r["error"], + "stop_kind": r["stop_kind"], + "policy_note": r["policy_note"], + "outside_change_report": r["outside_change_report"], + "covered_by": r["covered_by"], + "files_changed": r["files_modified"], + "log_summary": { "notes_total": notes.len(), "latest_notes": latest }, + "cost_usd": r["cost_usd"], + "tokens_in": r["tokens_in"], + "tokens_out": r["tokens_out"], + "duration_s": r["duration_s"], + "created_at": r["created_at"], + "updated_at": r["updated_at"], + "closed_by": r["closed_by"], + "close_reason": r["close_reason"], + "continued_run_id": r["continued_run_id"], + "url": link(&format!("/runs/detail?id={}", q(id))), + }); + if let Some(o) = out.as_object_mut() { + o.retain(|_, v| keep_set(v) || v.is_number() || v.is_boolean()); + } + out +} + +fn review_line(r: &Value) -> Value { + let sk = r["sk"].as_str().unwrap_or(""); + let findings = match &r["findings"] { + Value::Array(a) => a.len(), + Value::Object(o) => o + .get("items") + .and_then(Value::as_array) + .map_or(o.len(), Vec::len), + _ => 0, + }; + json!({ + "review_id": sk, + "repo": r["repo"], + "pr_number": r["pr_number"], + "pull_request": format!("https://github.com/{}/pull/{}", r["repo"].as_str().unwrap_or(""), r["pr_number"]), + "pr_title": r["pr_title"], + "verdict": r["verdict"], + "risk": r["risk"], + "findings": findings, + "created_at": r["created_at"], + "url": link(&format!("/reviewer/detail?sk={}", q(sk))), + }) +} + +fn review_detail(r: &Value) -> Value { + let mut out = review_line(r); + if let Some(o) = out.as_object_mut() { + o.insert("findings".into(), r["findings"].clone()); + o.insert("summary".into(), r["body"].clone()); + o.insert("action_summary".into(), r["action_summary"].clone()); + o.insert("head_sha".into(), r["head_sha"].clone()); + o.insert("posted_as".into(), r["posted_as"].clone()); + } + out +} + +/// A tool's answer, or what went wrong (shown to the model as a tool error). +type ToolResult = Result; + +fn from_call(e: CallError) -> String { + e.message +} + +async fn list_runs(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + let want = args["limit"].as_u64().unwrap_or(20).clamp(1, 100) as usize; + let since = match arg(args, "since") { + Some(s) => Some( + parse_since(s).ok_or("since must be a time (RFC 3339) or a date like 2026-11-01.")?, + ), + None => None, + }; + let mut cursor = arg(args, "cursor").map(str::to_string); + let mut runs: Vec = Vec::new(); + let mut next: Option = None; + // A few pages at most: the API reads a few hundred runs per page. + for _ in 0..5 { + let mut uri = format!("/api/runs?limit={}", want.min(100)); + if let Some(s) = arg(args, "status") { + uri.push_str(&format!("&status={}", q(s))); + } + if let Some(r) = arg(args, "repo") { + uri.push_str(&format!("&repo={}", q(r))); + } + if let Some(cur) = &cursor { + uri.push_str(&format!("&cursor={}", q(cur))); + } + let page = call(api, c, Method::GET, &uri, None) + .await + .map_err(from_call)?; + let mut older = false; + for r in page["runs"].as_array().cloned().unwrap_or_default() { + if let Some(since) = since { + let at = r["created_at"] + .as_str() + .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()); + if at.is_some_and(|t| t < since) { + older = true; + break; + } + } + if runs.len() < want { + runs.push(run_line(&r)); + } + } + next = page["next"].as_str().map(str::to_string); + if older { + next = None; + } + if runs.len() >= want || next.is_none() { + break; + } + cursor = next.clone(); + } + Ok(json!({ "runs": runs, "next": next })) +} + +async fn get_run(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + let id = arg(args, "run_id").ok_or("Give run_id.")?; + if id.len() > 64 { + return Err("That isn't a run id.".into()); + } + let r = call(api, c, Method::GET, &format!("/api/runs/{}", q(id)), None) + .await + .map_err(from_call)?; + Ok(run_detail(&r)) +} + +async fn start_run(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + if let Some(ticket) = arg(args, "ticket") { + let r = call( + api, + c, + Method::POST, + "/api/runs/start", + Some(json!({ "ticket": ticket })), + ) + .await + .map_err(from_call)?; + return Ok(json!({ + "status": r["status"], + "ticket": r["ticket_id"], + "message": r["message"], + "runs": link(&format!("/runs?q={}", q(r["ticket_id"].as_str().unwrap_or("")))), + })); + } + let task = arg(args, "task").ok_or("Give a ticket, or a task with its repo.")?; + let repo = arg(args, "repo").ok_or("Give the repository for the task, owner/name.")?; + if !valid_repo(repo) { + return Err("repo must be owner/name.".into()); + } + let title: String = arg(args, "title") + .unwrap_or_else(|| task.lines().next().unwrap_or(task)) + .chars() + .take(200) + .collect(); + let plan = call( + api, + c, + Method::POST, + "/api/plans", + Some(json!({ + "title": title, + "description": task, + "repo": repo, + "tasks": [{ "title": title, "description": task, "repo": repo }], + })), + ) + .await + .map_err(from_call)?; + let plan_id = plan["plan_id"].as_str().unwrap_or("").to_string(); + if plan_id.is_empty() { + return Err("CoderHelm couldn't make the plan for this task.".into()); + } + call( + api, + c, + Method::POST, + &format!("/api/plans/{}/approve-and-execute", q(&plan_id)), + None, + ) + .await + .map_err(|e| format!("The plan was made but didn't start: {}", e.message))?; + Ok(json!({ + "status": "queued", + "plan_id": plan_id, + "message": "CoderHelm opened an issue for the task and queued a run on it. It shows in list_runs within a minute.", + "plan": link(&format!("/plans/detail?id={}", q(&plan_id))), + })) +} + +async fn retry_run(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + let id = arg(args, "run_id").ok_or("Give run_id.")?; + if id.len() > 64 { + return Err("That isn't a run id.".into()); + } + let r = call( + api, + c, + Method::POST, + &format!("/api/runs/{}/retry", q(id)), + None, + ) + .await + .map_err(|e| { + if e.status == 400 { + "This run can't be retried now: only runs that failed, need input, were cancelled or closed can.".to_string() + } else { + e.message + } + })?; + Ok( + json!({ "status": r["status"], "run_id": id, "url": link(&format!("/runs/detail?id={}", q(id))) }), + ) +} + +async fn list_reviews(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + let limit = args["limit"].as_u64().unwrap_or(20).clamp(1, 100); + let mut uri = format!("/api/reviewer/reviews?limit={limit}"); + if let Some(r) = arg(args, "repo") { + if !valid_repo(r) { + return Err("repo must be owner/name.".into()); + } + uri.push_str(&format!("&repo={}", q(r))); + } + if let Some(cur) = arg(args, "cursor") { + uri.push_str(&format!("&cursor={}", q(cur))); + } + let page = call(api, c, Method::GET, &uri, None) + .await + .map_err(from_call)?; + let reviews: Vec = page["reviews"] + .as_array() + .map(|a| a.iter().map(review_line).collect()) + .unwrap_or_default(); + Ok(json!({ "reviews": reviews, "next": page["next"] })) +} + +async fn get_review(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + let sk = match (arg(args, "review_id"), arg(args, "pr_url")) { + (Some(id), _) => id.to_string(), + (None, Some(pr)) => { + let (repo, number) = parse_github_ref(pr, "pull").ok_or( + "pr_url must be a pull request URL such as https://github.com/acme/web/pull/318.", + )?; + let mut cursor: Option = None; + let mut found = None; + for _ in 0..5 { + let mut uri = format!("/api/reviewer/reviews?limit=100&repo={}", q(&repo)); + if let Some(cur) = &cursor { + uri.push_str(&format!("&cursor={}", q(cur))); + } + let page = call(api, c, Method::GET, &uri, None) + .await + .map_err(from_call)?; + found = page["reviews"].as_array().and_then(|a| { + a.iter() + .find(|r| r["pr_number"].as_u64() == Some(number)) + .and_then(|r| r["sk"].as_str().map(str::to_string)) + }); + cursor = page["next"].as_str().map(str::to_string); + if found.is_some() || cursor.is_none() { + break; + } + } + found.ok_or( + "CoderHelm hasn't reviewed that pull request yet. request_review asks for one.", + )? + } + (None, None) => return Err("Give review_id, or pr_url.".into()), + }; + let r = call( + api, + c, + Method::GET, + &format!("/api/reviewer/review?sk={}", q(&sk)), + None, + ) + .await + .map_err(from_call)?; + Ok(review_detail(&r)) +} + +async fn request_review(api: &McpApi, c: &McpCaller, args: &Value) -> ToolResult { + let pr = arg(args, "pr_url").ok_or("Give pr_url.")?; + let (repo, number) = parse_github_ref(pr, "pull") + .ok_or("pr_url must be a pull request URL such as https://github.com/acme/web/pull/318, or acme/web#318.")?; + let r = call( + api, + c, + Method::POST, + "/api/reviewer/re-review", + Some(json!({ "repo": repo, "pr": number })), + ) + .await + .map_err(from_call)?; + if r["status"] == "skipped" { + return Err(r["reason"] + .as_str() + .unwrap_or("The reviewer skipped this pull request.") + .to_string()); + } + Ok(json!({ + "status": r["status"], + "pull_request": format!("https://github.com/{repo}/pull/{number}"), + "message": "The review is queued. It is posted on the pull request in a few minutes; get_review with this pr_url reads it.", + })) +} + +async fn run_tool(api: &McpApi, c: &McpCaller, name: &str, args: &Value) -> ToolResult { + match name { + "list_runs" => list_runs(api, c, args).await, + "get_run" => get_run(api, c, args).await, + "start_run" => start_run(api, c, args).await, + "retry_run" => retry_run(api, c, args).await, + "list_reviews" => list_reviews(api, c, args).await, + "get_review" => get_review(api, c, args).await, + "request_review" => request_review(api, c, args).await, + _ => Err(format!("There is no tool called {name}.")), + } +} + +// ── HTTP ──────────────────────────────────────────────────────────── + +/// The bearer token of a request (anything but an API key, which never +/// reaches `/mcp`). +fn bearer(headers: &HeaderMap) -> Option<&str> { + let v = headers.get(header::AUTHORIZATION)?.to_str().ok()?; + let (scheme, token) = v.split_once(' ')?; + scheme + .eq_ignore_ascii_case("bearer") + .then(|| token.trim()) + .filter(|t| !t.is_empty()) +} + +fn quoted(s: &str) -> String { + s.replace('\\', "").replace('"', "'") +} + +/// `401`, with where to sign in (RFC 9728 5.1). A first sign-in asks for +/// reading only; acting is asked for when a tool needs it, or allowed on the +/// consent page. +pub fn unauthorized(refusal: Option) -> Response { + let mut challenge = format!( + "Bearer resource_metadata=\"{}\", scope=\"{READ_SCOPE}\"", + quoted(&mcp_oauth::resource_metadata_url()) + ); + let description = refusal.map(AccessRefusal::description); + if let Some(d) = description { + challenge.push_str(&format!( + ", error=\"invalid_token\", error_description=\"{}\"", + quoted(d) + )); + } + let mut res = ( + StatusCode::UNAUTHORIZED, + Json(json!({ + "error": if refusal.is_some() { "invalid_token" } else { "unauthorized" }, + "error_description": description.unwrap_or("Sign in to CoderHelm to use this server."), + })), + ) + .into_response(); + if let Ok(v) = HeaderValue::from_str(&challenge) { + res.headers_mut().insert(header::WWW_AUTHENTICATE, v); + } + res +} + +/// `403` for a tool that needs a scope the token lacks: the client may ask +/// the person for it (step-up, MCP authorization). +pub fn insufficient_scope(needed: &'static str) -> Response { + let challenge = format!( + "Bearer error=\"insufficient_scope\", scope=\"{}\", resource_metadata=\"{}\", error_description=\"This needs {}.\"", + mcp_oauth::scope_string([READ_SCOPE, needed]), + quoted(&mcp_oauth::resource_metadata_url()), + needed + ); + let mut res = ( + StatusCode::FORBIDDEN, + Json(json!({ + "error": "insufficient_scope", + "error_description": format!("This needs the {needed} scope. Connect the app to CoderHelm again and allow it."), + })), + ) + .into_response(); + if let Ok(v) = HeaderValue::from_str(&challenge) { + res.headers_mut().insert(header::WWW_AUTHENTICATE, v); + } + res +} + +fn rpc_result(id: &Value, result: Value) -> Response { + Json(json!({ "jsonrpc": "2.0", "id": id, "result": result })).into_response() +} + +fn rpc_error(status: StatusCode, id: &Value, code: i64, message: &str) -> Response { + ( + status, + Json(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })), + ) + .into_response() +} + +/// The version to answer `initialize` with: the client's, when this server +/// speaks it, else the newest. +pub fn negotiate(asked: Option<&str>) -> &'static str { + asked + .and_then(|a| PROTOCOL_VERSIONS.iter().find(|v| **v == a).copied()) + .unwrap_or(PROTOCOL_VERSIONS[0]) +} + +pub fn initialize_result(asked: Option<&str>) -> Value { + json!({ + "protocolVersion": negotiate(asked), + "capabilities": { "tools": { "listChanged": false } }, + "serverInfo": { + "name": "coderhelm", + "title": "CoderHelm", + "version": env!("CARGO_PKG_VERSION"), + }, + "instructions": "CoderHelm turns tickets into pull requests and reviews pull requests. Use list_runs and get_run to see work and why a run is waiting; start_run to start work from a GitHub issue, a Jira key or a task in words; retry_run to start a stopped run again; list_reviews, get_review and request_review for pull request reviews. Everything happens as the person who connected this app, with their role in their CoderHelm team.", + }) +} + +pub fn tools_list() -> Value { + json!({ "tools": TOOLS.iter().map(Tool::listing).collect::>() }) +} + +/// The person behind a connection, from their member record now. `None` +/// when they are no longer an active member of its team. +async fn member_claims(state: &AppState, g: &StoredGrant) -> Result, String> { + use aws_sdk_dynamodb::types::AttributeValue; + let r = state + .dynamo + .get_item() + .table_name(&state.config.users_table_name) + .key("pk", AttributeValue::S(g.team_id.clone())) + .key("sk", AttributeValue::S(g.user_id.clone())) + .send() + .await + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(&e)))?; + let Some(item) = r.item() else { + return Ok(None); + }; + let get = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + if get("status").as_deref() == Some("invited") { + return Ok(None); + } + Ok(Some(Claims { + sub: g.user_id.clone(), + team_id: g.team_id.clone(), + email: get("email").unwrap_or_else(|| g.email.clone()), + role: get("role").unwrap_or_else(|| "member".into()), + github_login: get("github_login"), + aud: mcp_oauth::ACCESS_AUDIENCE.into(), + exp: 0, + iat: g.created_at_secs, + support_view: None, + custom: None, + api_key: None, + })) +} + +/// Whether to write `last_used_at` for this connection now: once a minute +/// per connection per instance. +fn due_to_note(id: &str) -> bool { + static SEEN: OnceLock>> = OnceLock::new(); + let Ok(mut seen) = SEEN.get_or_init(Default::default).lock() else { + return false; + }; + let now = Instant::now(); + match seen.get(id) { + Some(at) if now.duration_since(*at) < Duration::from_secs(60) => false, + _ => { + if seen.len() > 10_000 { + seen.retain(|_, at| now.duration_since(*at) < Duration::from_secs(60)); + } + seen.insert(id.to_string(), now); + true + } + } +} + +/// `POST /mcp`: one JSON-RPC message from an MCP client. +pub async fn post( + State(state): State>, + Extension(api): Extension, + headers: HeaderMap, + body: Bytes, +) -> Response { + let Some(token) = bearer(&headers) else { + return unauthorized(None); + }; + let store = mcp_oauth::store(&state); + let now = chrono::Utc::now(); + let authorized = match mcp_oauth::authenticate( + &store, + token, + &state.secrets.jwt_secret, + now.timestamp().max(0) as u64, + ) + .await + { + Ok(Ok(a)) => a, + Ok(Err(refusal)) => return unauthorized(Some(refusal)), + Err(e) => { + error!(error = %e, "MCP connection not read"); + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + }; + let grant = authorized.grant; + if crate::middleware::rate_limit::allow( + &crate::middleware::rate_limit::ClientIp(grant.id.clone()), + "mcp", + 300, + 60, + ) + .is_err() + { + return ( + StatusCode::TOO_MANY_REQUESTS, + Json(json!({ "error": "Too many calls. Wait a minute and try again." })), + ) + .into_response(); + } + if let Some(v) = headers + .get("mcp-protocol-version") + .and_then(|v| v.to_str().ok()) + { + if !PROTOCOL_VERSIONS.contains(&v) { + return ( + StatusCode::BAD_REQUEST, + Json(json!({ "error": format!("MCP protocol version {v} isn't supported. This server speaks {}.", PROTOCOL_VERSIONS.join(", ")) })), + ) + .into_response(); + } + } + if due_to_note(&grant.id) { + let at = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + if let Err(e) = mcp_oauth::OAuthStore::note_use(&store, &grant, &at).await { + warn!(error = %e, "MCP connection use not noted"); + } + } + + let msg: Value = match serde_json::from_slice(&body) { + Ok(v) => v, + Err(_) => { + return rpc_error( + StatusCode::BAD_REQUEST, + &Value::Null, + -32700, + "The body isn't JSON.", + ) + } + }; + if msg.is_array() { + return rpc_error( + StatusCode::BAD_REQUEST, + &Value::Null, + -32600, + "Send one JSON-RPC message per request.", + ); + } + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let Some(method) = msg.get("method").and_then(Value::as_str) else { + // A response or a notification from the client: nothing to answer. + return StatusCode::ACCEPTED.into_response(); + }; + if msg.get("id").is_none() { + return StatusCode::ACCEPTED.into_response(); + } + let params = msg.get("params").cloned().unwrap_or(Value::Null); + match method { + "initialize" => rpc_result(&id, initialize_result(params["protocolVersion"].as_str())), + "ping" => rpc_result(&id, json!({})), + "tools/list" => rpc_result(&id, tools_list()), + "tools/call" => { + let name = params["name"].as_str().unwrap_or(""); + let Some(t) = find_tool(name) else { + return rpc_error( + StatusCode::OK, + &id, + -32602, + &format!("There is no tool called {name}."), + ); + }; + if !authorized.scopes.contains(t.scope()) { + return insufficient_scope(t.scope()); + } + let args = match ¶ms["arguments"] { + Value::Null => json!({}), + Value::Object(_) => params["arguments"].clone(), + _ => return rpc_error(StatusCode::OK, &id, -32602, "arguments must be an object."), + }; + let claims = match member_claims(&state, &grant).await { + Ok(Some(c)) => c, + Ok(None) => return unauthorized(Some(AccessRefusal::Revoked)), + Err(e) => { + error!(error = %e, "Member record not read for an MCP call"); + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + }; + // Written before the call runs: nothing happens without a record. + if roles::record( + &state, + &claims, + AuditEntry { + action: "mcp_call", + role_id: &grant.id, + role_name: &grant.client_name, + detail: audit_detail(t.name, &args), + }, + ) + .await + .is_err() + { + return rpc_result( + &id, + json!({ + "content": [{ "type": "text", "text": "CoderHelm couldn't record this call in the team's log, so it didn't run it. Try again." }], + "isError": true, + }), + ); + } + let caller = McpCaller { + claims, + grant, + scopes: authorized.scopes, + tool_handlers: t.handlers, + }; + match run_tool(&api, &caller, t.name, &args).await { + Ok(v) => rpc_result( + &id, + json!({ + "content": [{ "type": "text", "text": serde_json::to_string_pretty(&v).unwrap_or_default() }], + "structuredContent": v, + "isError": false, + }), + ), + Err(message) => rpc_result( + &id, + json!({ "content": [{ "type": "text", "text": message }], "isError": true }), + ), + } + } + _ => rpc_error( + StatusCode::OK, + &id, + -32601, + &format!("{method} isn't supported by this server."), + ), + } +} + +/// `GET /mcp` and `DELETE /mcp`: no event stream and no sessions here. +pub async fn not_allowed() -> Response { + let mut res = ( + StatusCode::METHOD_NOT_ALLOWED, + Json(json!({ "error": "This MCP server answers POST only." })), + ) + .into_response(); + res.headers_mut() + .insert(header::ALLOW, HeaderValue::from_static("POST")); + res +} + +#[cfg(test)] +mod tests { + use super::*; + + fn custom(caps: &[&str]) -> Holder { + let caps: Vec = caps.iter().map(|c| c.to_string()).collect(); + Holder::custom("r1", Some(("Custom", &caps))) + } + + fn read() -> BTreeSet<&'static str> { + BTreeSet::from([READ_SCOPE]) + } + + fn write() -> BTreeSet<&'static str> { + BTreeSet::from([READ_SCOPE, WRITE_SCOPE]) + } + + #[test] + fn every_tool_calls_only_routed_handlers_its_scope_reaches() { + let routed: BTreeSet<&str> = permissions::api_route_handlers() + .values() + .map(String::as_str) + .collect(); + for t in TOOLS { + assert!(!t.handlers.is_empty(), "{}", t.name); + for h in t.handlers { + assert!( + routed.contains(h), + "{} calls {h}, which main.rs doesn't route", + t.name + ); + let scope = + scope_for_handler(h).unwrap_or_else(|| panic!("{h} isn't reachable by apps")); + if !t.write { + assert_eq!(scope, READ_SCOPE, "the reading tool {} calls {h}", t.name); + } + } + } + // Every reachable route belongs to a tool. + for h in READ_HANDLERS.iter().chain(WRITE_HANDLERS) { + assert!( + TOOLS.iter().any(|t| t.handlers.contains(h)), + "{h} has no tool" + ); + } + } + + #[test] + fn annotations_say_which_tools_only_read() { + let list = tools_list(); + let tools = list["tools"].as_array().unwrap(); + assert_eq!(tools.len(), 7); + for t in tools { + let name = t["name"].as_str().unwrap(); + let read_only = t["annotations"]["readOnlyHint"].as_bool().unwrap(); + let want = matches!( + name, + "list_runs" | "get_run" | "list_reviews" | "get_review" + ); + assert_eq!(read_only, want, "{name}"); + assert_eq!(t["annotations"]["destructiveHint"], false, "{name}"); + assert_eq!(t["inputSchema"]["type"], "object", "{name}"); + } + assert_eq!(find_tool("start_run").unwrap().scope(), WRITE_SCOPE); + assert_eq!(find_tool("get_review").unwrap().scope(), READ_SCOPE); + } + + /// For every tool and every route it calls: allowed exactly when the + /// connection holds the tool's scope and the person's role allows the + /// route in the dashboard. + #[test] + fn each_tool_is_authorized_like_the_same_dashboard_action() { + let holders = [ + Holder::builtin("viewer"), + Holder::builtin("member"), + Holder::builtin("admin"), + Holder::builtin("owner"), + custom(&[]), + custom(&["runs"]), + custom(&["plans", "reviews"]), + ]; + for t in TOOLS { + for holder in &holders { + for scopes in [read(), write()] { + for h in t.handlers { + let dashboard = matches!( + permissions::resolve_access(holder, Some(h)), + Access::Allow { .. } + ); + let got = decide(&scopes, t.handlers, holder, Some(h)); + let want = scopes.contains(t.scope()) && dashboard; + assert_eq!( + got.is_ok(), + want, + "{} via {h} for {} with {scopes:?}", + t.name, + holder.role + ); + if !scopes.contains(t.scope()) { + assert_eq!(got, Err(Refusal::Scope(WRITE_SCOPE))); + } + } + } + } + } + } + + /// Every route any tool may call. + const ALL: &[&str] = &[ + "api::list_runs", + "api::get_run", + "reviewer::list_reviews", + "reviewer::get_review", + "run_start::start_run", + "api::retry_run", + "plans::create_plan", + "plans::approve_all_and_execute", + "reviewer::re_review", + ]; + + fn decide_any( + scopes: &BTreeSet<&'static str>, + holder: &Holder, + handler: Option<&str>, + ) -> Result<&'static str, Refusal> { + decide(scopes, ALL, holder, handler) + } + + #[test] + fn a_tool_reaches_only_its_own_routes() { + let owner = Holder::builtin("owner"); + let list = find_tool("list_runs").unwrap(); + assert!(decide(&write(), list.handlers, &owner, Some("api::list_runs")).is_ok()); + // Not another tool's, even one the connection's scopes reach. + assert_eq!( + decide(&write(), list.handlers, &owner, Some("api::retry_run")), + Err(Refusal::NotForApps) + ); + let get = find_tool("get_review").unwrap(); + assert!(decide( + &read(), + get.handlers, + &owner, + Some("reviewer::list_reviews") + ) + .is_ok()); + assert_eq!( + decide(&write(), get.handlers, &owner, Some("reviewer::re_review")), + Err(Refusal::NotForApps) + ); + } + + #[test] + fn the_decisions_people_would_expect() { + let viewer = Holder::builtin("viewer"); + let member = Holder::builtin("member"); + // A viewer reads, and can't act even with the write scope. + assert_eq!( + decide_any(&write(), &viewer, Some("api::list_runs")), + Ok("viewer") + ); + match decide_any(&write(), &viewer, Some("api::retry_run")) { + Err(Refusal::Role(c)) => assert_eq!(c.key, "runs"), + other => panic!("{other:?}"), + } + match decide_any(&write(), &viewer, Some("reviewer::re_review")) { + Err(Refusal::Role(c)) => assert_eq!(c.key, "reviews"), + other => panic!("{other:?}"), + } + // A member acts only with the write scope. + assert_eq!( + decide_any(&read(), &member, Some("api::retry_run")), + Err(Refusal::Scope(WRITE_SCOPE)) + ); + assert_eq!( + decide_any(&write(), &member, Some("api::retry_run")), + Ok("member") + ); + assert_eq!( + decide_any(&write(), &member, Some("run_start::start_run")), + Ok("member") + ); + // A custom role with runs but not plans starts from a ticket, not from words. + let runs_only = custom(&["runs"]); + assert!(decide_any(&write(), &runs_only, Some("run_start::start_run")).is_ok()); + assert!(matches!( + decide_any(&write(), &runs_only, Some("plans::create_plan")), + Err(Refusal::Role(c)) if c.key == "plans" + )); + // Nothing outside the tools, whatever the role: not the dashboard's + // own routes, not managing keys or connections, not an unknown route. + let owner = Holder::builtin("owner"); + for h in [ + "api::sync_repos", + "api_keys::create", + "mcp_oauth::list_connections", + "mcp_oauth::decide_request", + "users::invite_user", + "api::cancel_run", + ] { + assert_eq!( + decide_any(&write(), &owner, Some(h)), + Err(Refusal::NotForApps), + "{h}" + ); + } + assert_eq!(decide_any(&write(), &owner, None), Err(Refusal::NotForApps)); + } + + #[test] + fn github_refs_and_times_are_read() { + assert_eq!( + parse_github_ref("https://github.com/acme/web/issues/42", "issues"), + Some(("acme/web".into(), 42)) + ); + assert_eq!( + parse_github_ref("https://github.com/acme/web/pull/318/files", "pull"), + Some(("acme/web".into(), 318)) + ); + assert_eq!( + parse_github_ref("acme/web#7", "pull"), + Some(("acme/web".into(), 7)) + ); + assert_eq!( + parse_github_ref("https://github.com/acme/web/issues/42", "pull"), + None + ); + assert_eq!( + parse_github_ref("https://evil.example/acme/web/pull/1", "pull"), + None + ); + assert_eq!(parse_github_ref("acme/web#0", "pull"), None); + assert_eq!(parse_github_ref("acme/we b#3", "pull"), None); + assert!(parse_since("2026-11-01").is_some()); + assert!(parse_since("2026-11-01T10:00:00Z").is_some()); + assert!(parse_since("yesterday").is_none()); + } + + #[test] + fn the_log_line_names_the_call_but_never_a_tasks_words() { + let d = audit_detail( + "start_run", + &json!({ "task": "secret plans", "repo": "acme/web" }), + ); + assert_eq!(d, "start_run: repo acme/web, a task in words"); + assert_eq!(audit_detail("list_runs", &json!({})), "list_runs"); + } + + #[test] + fn a_run_shows_its_holds_and_latest_notes() { + let notes: Vec = (0..20) + .map(|i| json!({ "text": format!("n{i}") })) + .collect(); + let r = json!({ + "run_id": "r1", + "status": "needs_input", + "questions": [{ "text": "Which?", "answered": false }, { "text": "Done", "answered": true }], + "draft_hold": { "reason": "CI" }, + "waiting_on": null, + "progress_notes": notes, + "pr_url": "https://github.com/acme/web/pull/1", + "tokens_in": 0, + }); + let d = run_detail(&r); + assert_eq!(d["holds"]["questions"].as_array().unwrap().len(), 1); + assert_eq!(d["holds"]["draft_hold"]["reason"], "CI"); + assert!(d["holds"].get("waiting_on").is_none()); + assert_eq!(d["log_summary"]["notes_total"], 20); + assert_eq!( + d["log_summary"]["latest_notes"].as_array().unwrap().len(), + 15 + ); + assert_eq!(d["log_summary"]["latest_notes"][14]["text"], "n19"); + assert_eq!(d["pull_request"], "https://github.com/acme/web/pull/1"); + assert!(d["url"].as_str().unwrap().ends_with("/runs/detail?id=r1")); + } + + #[test] + fn the_client_is_told_where_to_sign_in_and_what_to_ask_for() { + let res = unauthorized(None); + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); + let h = res.headers()[header::WWW_AUTHENTICATE].to_str().unwrap(); + assert!(h.starts_with("Bearer resource_metadata=\""), "{h}"); + assert!(h.contains("/.well-known/oauth-protected-resource/mcp\"")); + assert!(h.contains("scope=\"runs:read\"")); + let res = unauthorized(Some(AccessRefusal::Expired)); + let h = res.headers()[header::WWW_AUTHENTICATE].to_str().unwrap(); + assert!(h.contains("error=\"invalid_token\"")); + let res = insufficient_scope(WRITE_SCOPE); + assert_eq!(res.status(), StatusCode::FORBIDDEN); + let h = res.headers()[header::WWW_AUTHENTICATE].to_str().unwrap(); + assert!( + h.contains("error=\"insufficient_scope\"") + && h.contains("scope=\"runs:read runs:write\"") + ); + } + + /// `/mcp` as main() mounts it: refusals come before any store read. + #[tokio::test] + async fn mcp_over_http_refuses_without_a_good_token_and_answers_post_only() { + use axum::routing::post; + let state = crate::tests::hosted_state(); + let app = Router::new() + .route( + "/mcp", + post(super::post) + .get(not_allowed) + .delete(not_allowed) + .layer(axum::Extension(McpApi(Router::new()))), + ) + .with_state(state); + let send = |method: &str, auth: Option<&str>| { + let mut b = Request::builder() + .method(method) + .uri("/mcp") + .header(header::CONTENT_TYPE, "application/json"); + if let Some(a) = auth { + b = b.header(header::AUTHORIZATION, a); + } + b.body(Body::from( + r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#, + )) + .unwrap() + }; + let r = app.clone().oneshot(send("POST", None)).await.unwrap(); + assert_eq!(r.status(), StatusCode::UNAUTHORIZED); + assert!(r.headers()[header::WWW_AUTHENTICATE] + .to_str() + .unwrap() + .contains("resource_metadata=")); + // A session token, an API key or garbage is not an access token. + let session = + crate::auth::jwt::create_token("u", "t", "e@x.com", "owner", None, "test", 300) + .unwrap(); + for bad in [format!("Bearer {session}"), "Bearer nope".to_string()] { + let r = app.clone().oneshot(send("POST", Some(&bad))).await.unwrap(); + assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{bad}"); + assert!(r.headers()[header::WWW_AUTHENTICATE] + .to_str() + .unwrap() + .contains("invalid_token")); + } + // An expired access token, signed right, is refused before its connection is read. + let g = crate::mcp_oauth::StoredGrant { + id: "01jbgrant00000000000000001".into(), + team_id: "TEAM#a".into(), + user_id: "USER#a".into(), + email: String::new(), + client_id: "mcpc_1".into(), + client_name: String::new(), + redirect_host: String::new(), + scopes: vec![READ_SCOPE.into()], + created_at: String::new(), + created_at_secs: 0, + mfa: false, + via: None, + refresh_hash: String::new(), + prev_refresh_hash: None, + refresh_expires_at: String::new(), + last_used_at: None, + revoked_at: None, + revoked_by: None, + }; + let old = crate::mcp_oauth::issue_access(&g, &read(), "https://x", "test", 1_000).unwrap(); + let r = app + .clone() + .oneshot(send("POST", Some(&format!("Bearer {old}")))) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::UNAUTHORIZED); + for m in ["GET", "DELETE"] { + let r = app.clone().oneshot(send(m, None)).await.unwrap(); + assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED, "{m}"); + assert_eq!(r.headers()[header::ALLOW], "POST"); + } + } + + #[test] + fn the_protocol_version_is_the_clients_when_spoken_here() { + assert_eq!(negotiate(Some("2025-06-18")), "2025-06-18"); + assert_eq!(negotiate(Some("1999-01-01")), PROTOCOL_VERSIONS[0]); + assert_eq!(negotiate(None), PROTOCOL_VERSIONS[0]); + let r = initialize_result(Some("2025-03-26")); + assert_eq!(r["capabilities"]["tools"]["listChanged"], false); + assert_eq!(r["serverInfo"]["name"], "coderhelm"); + } +} diff --git a/services/gateway/src/middleware/auth.rs b/services/gateway/src/middleware/auth.rs index 323837167..9687fda11 100644 --- a/services/gateway/src/middleware/auth.rs +++ b/services/gateway/src/middleware/auth.rs @@ -10,6 +10,7 @@ use std::time::{Duration, Instant}; use crate::api_keys::{self, Outcome, RateWindow}; use crate::auth::jwt; +use crate::mcp_server::{self, McpCaller}; use crate::models::{ApiKeyRef, Claims}; use crate::openapi; use crate::permissions::{self, Access, Capability}; @@ -32,6 +33,12 @@ pub async fn require_auth( mut req: Request, next: Next, ) -> Result { + // A tool call of a connected app (mcp_server::call): set only by the + // gateway on the requests it makes itself, never from outside. + if let Some(caller) = req.extensions().get::().cloned() { + return Ok(app_request(&state, req, next, caller).await); + } + // A team API key: its own path, and never a session's (no cookies, no // support view, no sliding refresh). if let Some(token) = api_keys::bearer_key(req.headers()).map(str::to_string) { @@ -179,6 +186,51 @@ pub async fn require_auth( Ok(response) } +/// A connected app's request, as the person who connected it: the same +/// checks a session of theirs gets on every request (still on the team, no +/// session ended since they connected the app, the team's two-factor rule, +/// their role's capabilities, custom roles included), plus the connection's +/// scopes and the routes the tools may call (`mcp_server::decide`). No +/// support view, no cookies, no sliding refresh. +async fn app_request( + state: &Arc, + mut req: Request, + next: Next, + caller: McpCaller, +) -> Response { + let handler = req + .extensions() + .get::() + .and_then(|m| permissions::routed_handler(req.method().as_str(), m.as_str())); + let mut claims = caller.claims.clone(); + claims.support_view = None; + claims.api_key = None; + if let Err(ended) = sign_in::check_member_session(state, &claims).await { + return ended; + } + let proof = jwt::SignInProof { + mfa: caller.grant.mfa, + via: caller.grant.via.clone(), + }; + if let Err(held) = sign_in::check_session(state, &claims.team_id, &proof, handler).await { + return held; + } + let holder = roles::holder_for(state, &claims).await; + match mcp_server::decide(&caller.scopes, caller.tool_handlers, &holder, handler) { + Err(refusal) => return refusal.response(), + Ok(effective_role) => { + if holder.custom.is_some() { + claims.role = effective_role.to_string(); + claims.custom = Some(holder); + } + } + } + note_activity(state, &claims.team_id, &claims.sub).await; + req.extensions_mut().insert(claims); + req.extensions_mut().insert(proof); + next.run(req).await +} + /// A request made with a team API key. The key is checked and counted /// against its rate limit; only the public routes are open to it; and what it /// may do there is decided by `permissions::resolve_access` from its scopes, diff --git a/services/gateway/src/middleware/cors.rs b/services/gateway/src/middleware/cors.rs index 978fc8ac5..4ebd9376f 100644 --- a/services/gateway/src/middleware/cors.rs +++ b/services/gateway/src/middleware/cors.rs @@ -46,6 +46,17 @@ pub fn public_methods(path: &str) -> Option<&'static str> { if path == "/openapi.json" || path == "/api/setup/status" { return Some("GET"); } + // The MCP server and how its clients sign in: a browser-based MCP + // client calls them with a bearer token, never with cookies. + if path == "/mcp" { + return Some("GET, POST, DELETE"); + } + if path.starts_with("/.well-known/oauth-") { + return Some("GET"); + } + if crate::routes::mcp_oauth::is_public_oauth_path(path) { + return Some("POST"); + } if let Some(name) = path.strip_prefix("/hybrid/names/") { // GET /hybrid/names/:name only; /hybrid/names/records is for installs. if !name.is_empty() && !name.contains('/') && name != "records" { @@ -68,6 +79,19 @@ pub fn public_methods(path: &str) -> Option<&'static str> { None } +/// The request headers any origin may send on a public path. +fn public_headers(path: &str) -> &'static str { + if path == "/mcp" { + "Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID" + } else { + "Content-Type" + } +} + +/// The MCP server's answers a browser-based client must read: where to sign +/// in, on a refusal. +const MCP_EXPOSED: &str = "WWW-Authenticate, Mcp-Session-Id"; + /// The middleware, with the origins from `CORS_ORIGINS`. pub async fn cors(req: Request, next: Next) -> Response { apply(origins_from_env(), req, next).await @@ -116,7 +140,7 @@ pub async fn apply(credentialed: &[String], req: Request, next: Next) -> Respons ); h.insert( header::ACCESS_CONTROL_ALLOW_HEADERS, - HeaderValue::from_static("Content-Type"), + HeaderValue::from_static(public_headers(&path)), ); } if trusted.is_some() || public.is_some() { @@ -151,6 +175,12 @@ pub async fn apply(credentialed: &[String], req: Request, next: Next) -> Respons header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"), ); + if path == "/mcp" || path.starts_with("/.well-known/") { + h.insert( + header::ACCESS_CONTROL_EXPOSE_HEADERS, + HeaderValue::from_static(MCP_EXPOSED), + ); + } } } res @@ -355,6 +385,48 @@ mod tests { } } + #[tokio::test] + async fn a_browser_based_mcp_client_may_call_the_mcp_server_and_sign_in() { + let app = Router::new() + .route("/mcp", post(|| async { "{}" })) + .route("/oauth/token", post(|| async { "{}" })) + .route("/oauth/authorize", get(|| async { "" })) + .layer(axum::middleware::from_fn(|req, next| async move { + apply(&[], req, next).await + })); + let pre = Request::builder() + .method("OPTIONS") + .uri("/mcp") + .header(header::ORIGIN, "http://localhost:6274") + .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST") + .body(Body::empty()) + .unwrap(); + let r = app.clone().oneshot(pre).await.unwrap(); + assert_eq!(get_h(&r, header::ACCESS_CONTROL_ALLOW_ORIGIN), Some("*")); + assert!(get_h(&r, header::ACCESS_CONTROL_ALLOW_HEADERS) + .unwrap() + .contains("Authorization")); + assert_eq!(get_h(&r, header::ACCESS_CONTROL_ALLOW_CREDENTIALS), None); + let call = Request::builder() + .method("POST") + .uri("/mcp") + .header(header::ORIGIN, "http://localhost:6274") + .body(Body::empty()) + .unwrap(); + let r = app.clone().oneshot(call).await.unwrap(); + assert_eq!( + get_h(&r, header::ACCESS_CONTROL_EXPOSE_HEADERS), + Some(MCP_EXPOSED) + ); + assert_eq!(public_methods("/oauth/token"), Some("POST")); + assert_eq!( + public_methods("/.well-known/oauth-authorization-server"), + Some("GET") + ); + // The consent step is a page in the browser, not a cross-origin call. + assert_eq!(public_methods("/oauth/authorize"), None); + } + async fn post_with(origin: Option<&str>, fetch_site: Option<&str>, cookie: bool) -> StatusCode { let mut b = Request::builder() .method("POST") diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index df44c6fff..5ca32612f 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -241,11 +241,12 @@ pub const CAPABILITIES: &[Capability] = &[ }, Capability { key: "runs", - label: "Retry, re-run, re-review, cancel, close or reopen runs", + label: "Start, retry, re-run, re-review, cancel, close or reopen runs", - short_label: "Retry and cancel runs", + short_label: "Start, retry and cancel runs", min_role: "member", handlers: &[ + "run_start::start_run", "api::retry_run", "decisions::export_decisions", "run_answer::answer_run", diff --git a/services/gateway/src/routes/mcp_oauth.rs b/services/gateway/src/routes/mcp_oauth.rs new file mode 100644 index 000000000..3cae0968f --- /dev/null +++ b/services/gateway/src/routes/mcp_oauth.rs @@ -0,0 +1,641 @@ +//! The HTTP side of signing in to CoderHelm's MCP server (`crate::mcp_oauth` +//! has the rules): +//! +//! - public, for MCP clients: the two metadata documents, `POST +//! /oauth/register`, `GET /oauth/authorize`, `POST /oauth/token` and `POST +//! /oauth/revoke`; +//! - for the dashboard, with the person's session: the consent page's +//! `POST /api/mcp/authorize/describe` and `POST /api/mcp/authorize`, and +//! the Connected apps page's `GET /api/mcp/connections` and +//! `DELETE /api/mcp/connections/:id`. +//! +//! Everyone on a team may connect an app as themselves: what the app can do +//! is what they can do, checked on every call. Each person sees and revokes +//! their own connections; people who manage the team's API keys see and +//! revoke everyone's. + +use axum::{ + extract::{Extension, Path, Query, State}, + http::{header, HeaderValue, StatusCode}, + response::{IntoResponse, Redirect, Response}, + Form, Json, +}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::sync::Arc; +use tracing::{error, info}; + +use crate::auth::jwt::SignInProof; +use crate::mcp_oauth::{self as oauth, OAuthStore, StoredGrant, READ_SCOPE, SCOPES}; +use crate::middleware::rate_limit::{self, ClientIp}; +use crate::models::Claims; +use crate::routes::roles::{self, AuditEntry}; +use crate::AppState; + +type ApiError = (StatusCode, Json); + +fn fail(code: StatusCode, msg: &str) -> ApiError { + (code, Json(json!({ "error": msg }))) +} + +fn internal(context: &str, e: impl std::fmt::Display) -> ApiError { + error!("{context}: {e}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +fn oauth_error(status: StatusCode, error: &str, description: &str) -> Response { + ( + status, + Json(json!({ "error": error, "error_description": description })), + ) + .into_response() +} + +fn unavailable() -> Response { + oauth_error( + StatusCode::SERVICE_UNAVAILABLE, + "temporarily_unavailable", + "CoderHelm couldn't answer just now. Try again shortly.", + ) +} + +fn too_many() -> Response { + let mut r = oauth_error( + StatusCode::TOO_MANY_REQUESTS, + "slow_down", + "Too many requests from this address. Try again in a few minutes.", + ); + r.headers_mut() + .insert(header::RETRY_AFTER, HeaderValue::from_static("300")); + r +} + +// ── Metadata ──────────────────────────────────────────────────────── + +/// The protected resource metadata (RFC 9728), for `/mcp`. +pub fn resource_metadata(issuer: &str) -> Value { + json!({ + "resource": oauth::resource_for(issuer), + "authorization_servers": [issuer], + "scopes_supported": SCOPES, + "bearer_methods_supported": ["header"], + "resource_name": "CoderHelm", + "resource_documentation": "https://docs.coderhelm.com/mcp", + }) +} + +/// The authorization server metadata (RFC 8414). +pub fn server_metadata(issuer: &str) -> Value { + json!({ + "issuer": issuer, + "authorization_endpoint": format!("{issuer}/oauth/authorize"), + "token_endpoint": format!("{issuer}/oauth/token"), + "registration_endpoint": format!("{issuer}/oauth/register"), + "revocation_endpoint": format!("{issuer}/oauth/revoke"), + "response_types_supported": ["code"], + "response_modes_supported": ["query"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": ["none"], + "revocation_endpoint_auth_methods_supported": ["none"], + "scopes_supported": SCOPES, + "authorization_response_iss_parameter_supported": true, + "service_documentation": "https://docs.coderhelm.com/mcp", + }) +} + +/// GET /.well-known/oauth-protected-resource and .../mcp +pub async fn protected_resource() -> Json { + Json(resource_metadata(&oauth::issuer())) +} + +/// GET /.well-known/oauth-authorization-server +pub async fn authorization_server() -> Json { + Json(server_metadata(&oauth::issuer())) +} + +// ── Registration ──────────────────────────────────────────────────── + +/// POST /oauth/register — dynamic client registration (RFC 7591). Open to +/// anyone, as MCP clients need; 20 a day per address, and a registration +/// alone can do nothing: every sign-in still asks the person. +pub async fn register( + State(state): State>, + ip: ClientIp, + body: axum::body::Bytes, +) -> Response { + if rate_limit::allow_shared(&state, "mcp_register", &ip.0, 20, 86_400) + .await + .is_err() + { + return too_many(); + } + let Ok(reg) = serde_json::from_slice::(&body) else { + return oauth_error( + StatusCode::BAD_REQUEST, + "invalid_client_metadata", + "The body must be a JSON object (RFC 7591).", + ); + }; + let now = chrono::Utc::now(); + let client = match oauth::register(®, now) { + Ok(c) => c, + Err((code, msg)) => return oauth_error(StatusCode::BAD_REQUEST, code, &msg), + }; + if let Err(e) = oauth::store(&state).put_client(&client).await { + error!(error = %e, "MCP client not registered"); + return unavailable(); + } + info!(client_id = %client.client_id, client_name = %client.client_name, "MCP client registered"); + ( + StatusCode::CREATED, + Json(oauth::registration_answer(&client, now.timestamp())), + ) + .into_response() +} + +// ── Authorization ─────────────────────────────────────────────────── + +/// A refusal shown to the person, when the app can't be trusted with it. +fn refusal_page(message: &str) -> Response { + let escaped = message + .replace('&', "&") + .replace('<', "<") + .replace('>', ">"); + let html = format!( + "CoderHelm\ + \ +

CoderHelm couldn't connect this app

{escaped}

" + ); + let mut r = (StatusCode::BAD_REQUEST, html).into_response(); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + r +} + +/// GET /oauth/authorize — checks the app's request and sends the person to +/// the dashboard's consent page, with the request signed into the link. +pub async fn authorize( + State(state): State>, + ip: ClientIp, + Query(p): Query, +) -> Response { + if rate_limit::allow(&ip, "mcp_authorize", 60, 300).is_err() { + return refusal_page( + "Too many sign-in attempts from this address. Try again in a few minutes.", + ); + } + let client = match p.client_id.as_deref() { + Some(id) => match oauth::store(&state).get_client(id).await { + Ok(c) => c, + Err(e) => { + error!(error = %e, "MCP client not read"); + return refusal_page("CoderHelm couldn't answer just now. Try again shortly."); + } + }, + None => None, + }; + let issuer = oauth::issuer(); + let req = match oauth::check_authorize(&p, client.as_ref(), &oauth::resource_for(&issuer)) { + Ok(r) => r, + Err(e) => { + return match oauth::error_redirect(&e, &issuer) { + Some(url) => Redirect::to(&url).into_response(), + None => match e { + oauth::AuthorizeError::Page(m) => refusal_page(&m), + _ => refusal_page("The app's request is not valid."), + }, + } + } + }; + let now = chrono::Utc::now().timestamp().max(0) as u64; + let Ok(signed) = oauth::sign_request(&req, &state.secrets.jwt_secret, now) else { + return refusal_page("CoderHelm couldn't answer just now. Try again shortly."); + }; + let app = common::public_urls::app_url_from_env(); + Redirect::to(&format!( + "{app}/authorize/?request={}", + urlencoding::encode(&signed) + )) + .into_response() +} + +// ── Tokens ────────────────────────────────────────────────────────── + +/// POST /oauth/token (form-encoded, RFC 6749 3.2). +pub async fn token( + State(state): State>, + ip: ClientIp, + Form(form): Form, +) -> Response { + if rate_limit::allow_shared(&state, "mcp_token", &ip.0, 120, 300) + .await + .is_err() + { + return too_many(); + } + let store = oauth::store(&state); + match oauth::token( + &store, + &form, + &oauth::issuer(), + &state.secrets.jwt_secret, + chrono::Utc::now(), + ) + .await + { + Ok(Ok(t)) => { + let mut r = Json(t).into_response(); + r.headers_mut() + .insert(header::PRAGMA, HeaderValue::from_static("no-cache")); + r + } + Ok(Err(e)) => oauth_error(StatusCode::BAD_REQUEST, e.error, &e.description), + Err(e) => { + error!(error = %e, "MCP token request failed"); + unavailable() + } + } +} + +#[derive(Deserialize, Default)] +pub struct RevokeForm { + #[serde(default)] + token: String, +} + +/// POST /oauth/revoke (RFC 7009): always `200`, whatever the token was. +pub async fn revoke( + State(state): State>, + ip: ClientIp, + Form(form): Form, +) -> Response { + if rate_limit::allow_shared(&state, "mcp_token", &ip.0, 120, 300) + .await + .is_err() + { + return too_many(); + } + match oauth::revoke_token( + &oauth::store(&state), + form.token.trim(), + &state.secrets.jwt_secret, + chrono::Utc::now(), + ) + .await + { + Ok(()) => StatusCode::OK.into_response(), + Err(e) => { + error!(error = %e, "MCP token not revoked"); + unavailable() + } + } +} + +// ── The consent page (dashboard, signed in) ───────────────────────── + +#[derive(Deserialize)] +pub struct RequestBody { + request: String, +} + +/// The request and its app, when the link is ours, current, and the app is +/// still registered. +async fn pending( + state: &AppState, + signed: &str, +) -> Result<(oauth::PendingRequest, oauth::StoredClient), ApiError> { + let now = chrono::Utc::now().timestamp().max(0) as u64; + let req = oauth::read_request(signed, &state.secrets.jwt_secret, now).ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + "This link has expired or isn't valid. Go back to the app and connect again.", + ) + })?; + let client = oauth::store(state) + .get_client(&req.client_id) + .await + .map_err(|e| internal("MCP client not read", e))? + .ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + "This app's registration has expired. Go back to the app and connect again.", + ) + })?; + Ok((req, client)) +} + +/// Only a person's own session decides: never a support view or an API key. +fn own_session(claims: &Claims) -> Result<(), ApiError> { + if claims.support_view.is_some() || claims.api_key.is_some() { + return Err(fail( + StatusCode::FORBIDDEN, + "Only the person signing in can connect an app.", + )); + } + Ok(()) +} + +/// POST /api/mcp/authorize/describe — what the consent page shows. +pub async fn describe_request( + State(state): State>, + Extension(claims): Extension, + Json(body): Json, +) -> Result, ApiError> { + own_session(&claims)?; + let (req, client) = pending(&state, &body.request).await?; + let holder = claims.holder(); + let scopes: Vec = SCOPES + .iter() + .map(|s| { + json!({ + "key": s, + "label": oauth::scope_label(s), + "requested": req.scopes.iter().any(|r| r == s), + "always": *s == READ_SCOPE, + }) + }) + .collect(); + Ok(Json(json!({ + "client_id": client.client_id, + "client_name": client.client_name, + "client_uri": client.client_uri, + "redirect_host": oauth::redirect_host(&req.redirect_uri), + "registered_at": client.created_at, + "scopes": scopes, + "email": claims.email, + "team_id": claims.team_id, + // Acting needs a role that can act; the page says so instead of + // letting someone grant what they can't use. + "can_act": holder.holds("runs") || holder.holds("plans") || holder.holds("reviews"), + "mcp_url": oauth::resource(), + }))) +} + +#[derive(Deserialize)] +pub struct DecisionBody { + request: String, + approve: bool, + #[serde(default)] + allow_write: bool, +} + +/// POST /api/mcp/authorize — the person's answer. Gives back where to send +/// their browser: the app, with a code or with `access_denied`. +pub async fn decide_request( + State(state): State>, + Extension(claims): Extension, + proof: Option>, + Json(body): Json, +) -> Result, ApiError> { + own_session(&claims)?; + let (req, client) = pending(&state, &body.request).await?; + let issuer = oauth::issuer(); + let mut params: Vec<(&str, String)> = Vec::new(); + if !body.approve { + params.push(("error", "access_denied".into())); + params.push(( + "error_description", + "The person said no in CoderHelm.".into(), + )); + } else { + let proof = proof.map(|p| p.0).unwrap_or_default(); + let who = oauth::Consent { + team_id: claims.team_id.clone(), + user_id: claims.sub.clone(), + email: claims.email.clone(), + mfa: proof.mfa, + via: proof.via.clone(), + allow_write: body.allow_write, + }; + let (code, stored) = oauth::approve(&req, &client, &who, chrono::Utc::now()); + // Written before the code goes out: no connection without a record. + roles::record( + &state, + &claims, + AuditEntry { + action: "mcp_connected", + role_id: &client.client_id, + role_name: &client.client_name, + detail: format!( + "Connected {} ({}) to use CoderHelm as them: {}.", + client.client_name, + oauth::redirect_host(&req.redirect_uri), + stored + .scopes + .iter() + .map(|s| oauth::scope_label(s).to_lowercase()) + .collect::>() + .join("; ") + ), + }, + ) + .await?; + oauth::store(&state) + .put_code(&stored) + .await + .map_err(|e| internal("MCP code not saved", e))?; + params.push(("code", code)); + } + if let Some(s) = &req.state { + params.push(("state", s.clone())); + } + params.push(("iss", issuer)); + let pairs: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect(); + Ok(Json(json!({ + "redirect_to": oauth::redirect_with(&req.redirect_uri, &pairs), + }))) +} + +// ── Connected apps (dashboard, signed in) ─────────────────────────── + +/// Sees and revokes everyone's connections: the people who manage the +/// team's API keys. +fn manages_all(claims: &Claims) -> bool { + claims.support_view.is_none() && claims.holder().holds("api_keys") +} + +/// A connection as the page shows it. Never a token or its hash. +pub fn connection_view(g: &StoredGrant, me: &str, now: chrono::DateTime) -> Value { + let expired = + chrono::DateTime::parse_from_rfc3339(&g.refresh_expires_at).is_ok_and(|t| t <= now); + let status = if g.revoked_at.is_some() { + "revoked" + } else if expired { + "expired" + } else { + "active" + }; + json!({ + "id": g.id, + "client_name": g.client_name, + "redirect_host": g.redirect_host, + "scopes": g.scopes, + "email": g.email, + "mine": g.user_id == me, + "created_at": g.created_at, + "last_used_at": g.last_used_at, + "revoked_at": g.revoked_at, + "status": status, + }) +} + +/// GET /api/mcp/connections — this person's connected apps (everyone's, for +/// people who manage API keys), and the address to add. +pub async fn list_connections( + State(state): State>, + Extension(claims): Extension, +) -> Result, ApiError> { + let all = manages_all(&claims); + let now = chrono::Utc::now(); + let grants = oauth::store(&state) + .list_grants(&claims.team_id) + .await + .map_err(|e| internal("Connected apps not listed", e))?; + let connections: Vec = grants + .iter() + .filter(|g| all || g.user_id == claims.sub) + .map(|g| connection_view(g, &claims.sub, now)) + .collect(); + Ok(Json(json!({ + "connections": connections, + "team_wide": all, + "mcp_url": oauth::resource(), + "scopes": SCOPES.iter().map(|s| json!({ "key": s, "label": oauth::scope_label(s) })).collect::>(), + }))) +} + +/// DELETE /api/mcp/connections/:id — ends a connection: its tokens stop at +/// once. Your own, or anyone's for people who manage API keys. +pub async fn revoke_connection( + State(state): State>, + Extension(claims): Extension, + Path(id): Path, +) -> Result, ApiError> { + own_session(&claims)?; + let store = oauth::store(&state); + let grant = store + .get_grant(&id) + .await + .map_err(|e| internal("Connected app not read", e))? + .filter(|g| g.team_id == claims.team_id && g.revoked_at.is_none()) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "That app isn't connected."))?; + if grant.user_id != claims.sub && !manages_all(&claims) { + return Err(fail( + StatusCode::FORBIDDEN, + "You can remove only the apps you connected. Ask an admin to remove someone else's.", + )); + } + roles::record( + &state, + &claims, + AuditEntry { + action: "mcp_revoked", + role_id: &grant.id, + role_name: &grant.client_name, + detail: format!( + "Removed {} ({}), connected by {}.", + grant.client_name, grant.redirect_host, grant.email + ), + }, + ) + .await?; + let at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + let done = store + .revoke_grant(&claims.team_id, &id, &claims.display_name(), &at) + .await + .map_err(|e| internal("Connected app not removed", e))?; + if !done { + return Err(fail(StatusCode::NOT_FOUND, "That app isn't connected.")); + } + Ok(Json(json!({ "status": "revoked", "id": id }))) +} + +/// Is this request headed for one of the public sign-in routes? (For CORS.) +pub fn is_public_oauth_path(path: &str) -> bool { + matches!(path, "/oauth/register" | "/oauth/token" | "/oauth/revoke") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mcp_oauth::tests::{connect, Mem}; + + #[test] + fn the_metadata_points_clients_at_this_install() { + let r = resource_metadata("https://ch.example.org"); + assert_eq!(r["resource"], "https://ch.example.org/mcp"); + assert_eq!(r["authorization_servers"][0], "https://ch.example.org"); + assert_eq!(r["scopes_supported"], json!(["runs:read", "runs:write"])); + let s = server_metadata("https://ch.example.org"); + assert_eq!(s["issuer"], "https://ch.example.org"); + assert_eq!( + s["registration_endpoint"], + "https://ch.example.org/oauth/register" + ); + assert_eq!(s["code_challenge_methods_supported"], json!(["S256"])); + assert_eq!(s["token_endpoint_auth_methods_supported"], json!(["none"])); + } + + #[tokio::test] + async fn a_connection_shows_no_token_and_its_status() { + let mem = Mem::default(); + connect(&mem, "TEAM#a", "USER#ann", true).await; + let g = mem.list_grants("TEAM#a").await.unwrap().remove(0); + let v = connection_view(&g, "USER#ann", chrono::Utc::now()); + assert_eq!(v["status"], "active"); + assert_eq!(v["mine"], true); + assert!(v.get("refresh_hash").is_none()); + let text = v.to_string(); + assert!(!text.contains(&g.refresh_hash)); + let v = connection_view( + &g, + "USER#bob", + chrono::Utc::now() + chrono::Duration::days(31), + ); + assert_eq!(v["status"], "expired"); + assert_eq!(v["mine"], false); + } + + fn claims(role: &str) -> Claims { + Claims { + sub: "USER#me".into(), + team_id: "TEAM#a".into(), + email: "me@example.com".into(), + role: role.into(), + github_login: None, + aud: "coderhelm-dashboard".into(), + exp: 0, + iat: 0, + support_view: None, + custom: None, + api_key: None, + } + } + + #[test] + fn only_key_managers_see_everyones_connections() { + assert!(manages_all(&claims("admin"))); + assert!(manages_all(&claims("owner"))); + assert!(!manages_all(&claims("member"))); + assert!(!manages_all(&claims("viewer"))); + assert!(own_session(&claims("member")).is_ok()); + let mut c = claims("admin"); + c.api_key = Some(crate::models::ApiKeyRef { + id: "k".into(), + name: "k".into(), + scopes: vec![], + rate_limit_per_minute: 1, + expires_at: None, + created_by: String::new(), + }); + assert!(own_session(&c).is_err(), "an API key never connects apps"); + assert!(is_public_oauth_path("/oauth/token")); + assert!(!is_public_oauth_path("/oauth/authorize")); + } +} diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 800e0256b..4125813ab 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -44,6 +44,7 @@ pub mod knowledge_tokens; pub mod learning; pub mod log_analyzer; pub mod log_findings; +pub mod mcp_oauth; pub mod mcp_servers; pub mod memory; pub mod merge_control; @@ -60,6 +61,7 @@ pub mod roles; pub mod run_answer; pub mod run_close; pub mod run_search; +pub mod run_start; pub mod run_trigger; pub mod search; pub mod setup; diff --git a/services/gateway/src/routes/run_start.rs b/services/gateway/src/routes/run_start.rs new file mode 100644 index 000000000..e42c250b5 --- /dev/null +++ b/services/gateway/src/routes/run_start.rs @@ -0,0 +1,325 @@ +//! POST /api/runs/start — a person starts CoderHelm on a ticket from outside +//! its tracker (a connected app's `start_run`, or a script). +//! +//! - A GitHub issue (its URL or `owner/name#N`): read from GitHub with the +//! team's app, and queued exactly as labeling it `coderhelm` would queue +//! it, with the person as the one who asked. +//! - A Jira key: Jira sends CoderHelm its tickets (CoderHelm can't read Jira +//! itself), so a key CoderHelm has seen starts again from its latest run, +//! as Retry does; one it hasn't seen is refused with how to start it. +//! +//! Like any person's start: the team's token limit applies, and a run +//! already working on the ticket blocks a second one (`trigger_gate`, as an +//! explicit ask). + +use crate::models::{TicketMessage, TicketSource, WorkerMessage}; +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{ + extract::{Extension, State}, + http::StatusCode, + Json, +}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::sync::Arc; +use tracing::{error, info}; + +use super::trigger_gate::{self, TicketGate}; +use crate::models::Claims; +use crate::AppState; + +type ApiError = (StatusCode, Json); + +fn fail(code: StatusCode, msg: &str) -> ApiError { + (code, Json(json!({ "error": msg }))) +} + +fn internal(context: &str, e: impl std::fmt::Display) -> ApiError { + error!("{context}: {e}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +/// A ticket, as a person names it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TicketRef { + Github { repo: String, number: u64 }, + Jira(String), +} + +/// A Jira key: a project key (a letter, then letters, digits or `_`) and a +/// number, `WEB-42`. +fn jira_key(raw: &str) -> Option { + let key = raw.trim().to_ascii_uppercase(); + let (project, number) = key.rsplit_once('-')?; + let mut chars = project.chars(); + let project_ok = chars.next().is_some_and(|c| c.is_ascii_uppercase()) + && project.len() <= 20 + && chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'); + let number_ok = + !number.is_empty() && number.len() <= 9 && number.chars().all(|c| c.is_ascii_digit()); + (project_ok && number_ok).then_some(key) +} + +pub fn parse_ticket(raw: &str) -> Option { + if let Some((repo, number)) = crate::mcp_server::parse_github_ref(raw, "issues") { + return Some(TicketRef::Github { repo, number }); + } + jira_key(raw).map(TicketRef::Jira) +} + +#[derive(Deserialize)] +pub struct StartBody { + ticket: String, +} + +/// What the gate's answer means for a person asking. +fn gate_refusal(gate: &TicketGate) -> Option { + match gate { + TicketGate::Enqueue => None, + TicketGate::SkipInFlight => Some(fail( + StatusCode::CONFLICT, + "A run is already working on this ticket. Follow it in the runs list.", + )), + TicketGate::OpenPr(pr) => Some(fail( + StatusCode::CONFLICT, + &format!( + "This ticket's pull request #{} is still open. Comment there to change it.", + pr.pr_number + ), + )), + TicketGate::SkipUnchanged => Some(fail( + StatusCode::CONFLICT, + "CoderHelm already finished this ticket and it hasn't changed since.", + )), + } +} + +/// POST /api/runs/start +pub async fn start_run( + State(state): State>, + Extension(claims): Extension, + Json(body): Json, +) -> Result, ApiError> { + // member+ + if claims.require_role(1).is_err() { + return Err(fail( + StatusCode::FORBIDDEN, + "Your role doesn't allow starting runs.", + )); + } + let Some(ticket) = parse_ticket(&body.ticket) else { + return Err(fail( + StatusCode::BAD_REQUEST, + "Give a GitHub issue (https://github.com/owner/name/issues/42 or owner/name#42) or a Jira key such as WEB-42.", + )); + }; + if let Some(reason) = super::github_webhook::check_run_budget(&state, &claims.team_id).await { + return Err(fail(StatusCode::TOO_MANY_REQUESTS, &reason)); + } + let (message, ticket_id) = match ticket { + TicketRef::Github { repo, number } => github_ticket(&state, &claims, &repo, number).await?, + TicketRef::Jira(key) => jira_ticket(&state, &claims, &key).await?, + }; + super::github_webhook::send_to_queue( + &state, + &state.config.ticket_queue_url, + &WorkerMessage::Ticket(message), + ) + .await + .map_err(|s| fail(s, "CoderHelm couldn't queue the run. Try again."))?; + info!(team_id = %claims.team_id, ticket_id = %ticket_id, "Run started by a person from outside the tracker"); + Ok(Json(json!({ + "status": "queued", + "ticket_id": ticket_id, + "message": format!("CoderHelm queued a run for {ticket_id}. It shows in the runs list within a minute."), + }))) +} + +async fn github_ticket( + state: &AppState, + claims: &Claims, + repo: &str, + number: u64, +) -> Result<(TicketMessage, String), ApiError> { + let installation_id = super::api::get_team_installation_id(state, &claims.team_id) + .await + .map_err(|_| { + fail( + StatusCode::BAD_REQUEST, + "Connect GitHub to CoderHelm first (Settings, GitHub).", + ) + })?; + let token = crate::auth::github_app::get_installation_token(state, installation_id) + .await + .map_err(|e| internal("GitHub token for a start", e))?; + let res = state + .http + .get(format!( + "https://api.github.com/repos/{repo}/issues/{number}" + )) + .bearer_auth(token) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "coderhelm") + .header("X-GitHub-Api-Version", "2022-11-28") + .send() + .await + .map_err(|e| internal("GitHub issue not read", e))?; + if matches!(res.status().as_u16(), 403 | 404 | 410) { + return Err(fail( + StatusCode::NOT_FOUND, + "CoderHelm can't see that issue. Check the address, and that the repository is connected to CoderHelm.", + )); + } + if !res.status().is_success() { + return Err(internal("GitHub issue not read", res.status())); + } + let issue: Value = res + .json() + .await + .map_err(|e| internal("GitHub issue not readable", e))?; + if issue["pull_request"].is_object() { + return Err(fail( + StatusCode::BAD_REQUEST, + "That's a pull request, not an issue. Ask for a review of it instead.", + )); + } + let (owner, name) = repo.split_once('/').unwrap_or((repo, "")); + let ticket_id = format!("GH-{number}"); + let title = issue["title"].as_str().unwrap_or(""); + let body = issue["body"].as_str().unwrap_or(""); + let hash = common::ticket_context_hash(title, body, &[]); + let gate = trigger_gate::gate_ticket_trigger( + state, + &claims.team_id, + &ticket_id, + Some(&hash), + true, + false, + ) + .await; + if let Some(refused) = gate_refusal(&gate) { + return Err(refused); + } + Ok(( + TicketMessage { + team_id: claims.team_id.clone(), + installation_id, + source: TicketSource::Github, + ticket_id: ticket_id.clone(), + title: title.to_string(), + body: body.to_string(), + repo_owner: owner.to_string(), + repo_name: name.to_string(), + issue_number: number, + sender: claims + .github_login + .clone() + .unwrap_or_else(|| claims.email.clone()), + requester: common::requester::Requester::member( + claims.github_login.as_deref(), + &claims.email, + ), + image_attachments: vec![], + ticket_type: common::messages::ticket_type_of_github(&issue), + ..Default::default() + }, + ticket_id, + )) +} + +async fn jira_ticket( + state: &AppState, + claims: &Claims, + key: &str, +) -> Result<(TicketMessage, String), ApiError> { + let runs = common::log_findings::runs_for_ticket( + &state.dynamo, + &state.config.runs_table_name, + &claims.team_id, + key, + ) + .await + .map_err(|e| internal("Runs of a ticket not read", e))?; + let Some(latest) = runs.iter().max_by(|a, b| a.run_id.cmp(&b.run_id)) else { + return Err(fail( + StatusCode::NOT_FOUND, + &format!("CoderHelm hasn't received {key} from Jira yet. Start it from Jira the way your team does, or give a task and a repository instead."), + )); + }; + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(claims.team_id.clone())) + .key("run_id", AttributeValue::S(latest.run_id.clone())) + .send() + .await + .map_err(|e| internal("Run not read", e))? + .item + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "That ticket's last run is gone."))?; + let gate = + trigger_gate::gate_ticket_trigger(state, &claims.team_id, key, None, true, false).await; + if let Some(refused) = gate_refusal(&gate) { + return Err(refused); + } + let message = super::api::retry_message(state, claims, &item) + .await + .map_err(|s| fail(s, "CoderHelm couldn't start that ticket again."))?; + // A person asked: a stale lock from an earlier run never holds it back. + super::api::delete_ticket_lock(state, &claims.team_id, key).await; + Ok((message, key.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tickets_are_github_issues_or_jira_keys() { + assert_eq!( + parse_ticket("https://github.com/acme/web/issues/42"), + Some(TicketRef::Github { + repo: "acme/web".into(), + number: 42 + }) + ); + assert_eq!( + parse_ticket("acme/web#42"), + Some(TicketRef::Github { + repo: "acme/web".into(), + number: 42 + }) + ); + assert_eq!( + parse_ticket("web-42"), + Some(TicketRef::Jira("WEB-42".into())) + ); + assert_eq!( + parse_ticket("OPS_2-7"), + Some(TicketRef::Jira("OPS_2-7".into())) + ); + for bad in [ + "", + "42", + "WEB-", + "-42", + "2WEB-4", + "WEB-4x", + "https://github.com/acme/web/pull/42", + "https://gitlab.com/acme/web/issues/42", + ] { + assert_eq!(parse_ticket(bad), None, "{bad}"); + } + } + + #[test] + fn a_blocked_ticket_says_why() { + assert!(gate_refusal(&TicketGate::Enqueue).is_none()); + let (code, body) = gate_refusal(&TicketGate::SkipInFlight).unwrap(); + assert_eq!(code, StatusCode::CONFLICT); + assert!(body["error"].as_str().unwrap().contains("already working")); + } +}