//! The token check in front of `/mcp`. The backend knows the tokens: it is //! asked once a minute per token (`/oauth/whoami`); the tools send the token //! on with every call, and the backend checks it again there, so a revoked //! connection stops at once whatever this cache says. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use axum::extract::{Request, State}; use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; use axum::http::{HeaderValue, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use sha2::{Digest, Sha256}; use crate::App; const CACHE_TTL: Duration = Duration::from_secs(60); const CACHE_MAX: usize = 1000; /// The caller's token, for the tools (in the HTTP request's extensions). #[derive(Clone)] pub struct Bearer(pub String); /// What the backend said about a token. #[derive(Debug, PartialEq, Eq)] pub enum Verdict { Valid, /// Unknown, expired, revoked, or for another server. Invalid, /// Valid, but its owner is no admin any more. Forbidden, /// The backend did not answer. Unavailable, } /// Tokens found valid in the last minute (by their hash). #[derive(Default)] pub struct TokenCache(Mutex>); impl TokenCache { fn fresh(&self, key: &[u8; 32]) -> bool { self.0.lock().expect("token cache").get(key).is_some_and(|at| at.elapsed() < CACHE_TTL) } fn remember(&self, key: [u8; 32]) { let mut map = self.0.lock().expect("token cache"); if map.len() >= CACHE_MAX { map.retain(|_, at| at.elapsed() < CACHE_TTL); } map.insert(key, Instant::now()); } /// The backend refused the token in a tool call: the next request asks again /// (and gets 401, so the client logs in again or refreshes). pub fn forget(&self, token: &str) { let key: [u8; 32] = Sha256::digest(token.as_bytes()).into(); self.0.lock().expect("token cache").remove(&key); } } /// Asks the backend (or the cache) about a token. pub async fn check(app: &App, token: &str) -> Verdict { let key: [u8; 32] = Sha256::digest(token.as_bytes()).into(); if app.tokens.fresh(&key) { return Verdict::Valid; } let verdict = match app.api.whoami(token).await { Ok(Some(who)) => { let resource = who["resource"].as_str(); let ours = |r: &str| r.trim_end_matches('/') == app.config.mcp_public_url.trim_end_matches('/'); if resource.is_none_or(ours) { Verdict::Valid } else { Verdict::Invalid } } Ok(None) => Verdict::Invalid, Err(status) if status == StatusCode::FORBIDDEN => Verdict::Forbidden, Err(status) if status == StatusCode::UNAUTHORIZED => Verdict::Invalid, Err(_) => Verdict::Unavailable, }; if verdict == Verdict::Valid { app.tokens.remember(key); } verdict } /// 401 (or 403) with where to find the OAuth metadata, as MCP clients expect. fn refuse(app: &App, status: StatusCode, error: Option<&str>) -> Response { let mut value = String::from("Bearer"); if let Some(error) = error { value.push_str(&format!(" error=\"{error}\",")); } value.push_str(&format!(" scope=\"admin\", resource_metadata=\"{}\"", app.config.resource_metadata_url())); let mut response = (status, axum::Json(serde_json::json!({ "error": error.unwrap_or("unauthorized") }))).into_response(); if let Ok(header) = HeaderValue::from_str(&value) { response.headers_mut().insert(WWW_AUTHENTICATE, header); } response } /// Middleware: only requests with a valid token reach the MCP service. pub async fn require_token(State(app): State>, mut request: Request, next: Next) -> Response { let token = request .headers() .get(AUTHORIZATION) .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) .map(|t| t.trim().to_string()) .filter(|t| !t.is_empty()); let Some(token) = token else { return refuse(&app, StatusCode::UNAUTHORIZED, None) }; match check(&app, &token).await { Verdict::Valid => { request.extensions_mut().insert(Bearer(token)); next.run(request).await } Verdict::Invalid => refuse(&app, StatusCode::UNAUTHORIZED, Some("invalid_token")), Verdict::Forbidden => refuse(&app, StatusCode::FORBIDDEN, Some("insufficient_scope")), Verdict::Unavailable => { (StatusCode::SERVICE_UNAVAILABLE, axum::Json(serde_json::json!({ "error": "backend_unavailable" }))) .into_response() } } }