Skip to main content

mcp_server_core/oauth/
mod.rs

1//! The OAuth 2.1 authorization server and the bearer guard in front of every service.
2//!
3//! Endpoints, all at the root of `PUBLIC_URL`:
4//!
5//! | Path | |
6//! |---|---|
7//! | `GET /.well-known/oauth-protected-resource/<service>` | Protected-resource metadata (RFC 9728) |
8//! | `GET /.well-known/oauth-authorization-server` | Authorization-server metadata (RFC 8414) |
9//! | `POST /register` | Dynamic client registration (RFC 7591), public clients only |
10//! | `GET, POST /authorize` | The sign-in page; authorization code with PKCE S256 only |
11//! | `POST /token` | `authorization_code` and `refresh_token` grants |
12//! | `GET /callback` | Where an upstream provider sends people back, when they sign in through one ([`crate::upstream`]) |
13//!
14//! Every service `<name>` is its own protected resource, `PUBLIC_URL/<name>`, and access tokens
15//! are bound to it (RFC 8707): a token for one service is refused by every other.
16//!
17//! Nothing is stored. Clients, CSRF tokens, codes, access and refresh tokens are all JWTs signed
18//! with `OAUTH_SIGNING_KEY` (HS256); only the one-time use of authorization codes is remembered in
19//! memory until they expire. Rotating the key signs everyone out.
20
21mod authorize;
22mod callback;
23mod metadata;
24mod middleware;
25mod register;
26mod token;
27
28pub use authorize::client_ip;
29pub use middleware::require_bearer;
30pub use register::{
31    MAX_CLIENT_NAME_CHARS, MAX_REDIRECT_URI_LEN, MAX_REDIRECT_URIS, validate_redirect_uri,
32};
33
34use crate::credential::{CheckCache, CheckRunner, CredentialVerifier, Sealer};
35use crate::guards::{Ceiling, LoginLimiter, ReplayGuard};
36use crate::jwt::Jwt;
37use axum::Router;
38use axum::routing::{get, post};
39use secrecy::{ExposeSecret, SecretString};
40use std::net::IpAddr;
41use std::sync::Arc;
42use std::time::Duration;
43
44/// What the authorization server needs from the core configuration.
45#[derive(Clone)]
46pub struct OAuthSettings {
47    /// External base URL without a trailing slash: the issuer, and the prefix of every resource.
48    pub public_url: String,
49    /// Signs every token (HS256) and derives the key that seals credentials. At least 32 bytes.
50    pub signing_key: SecretString,
51    /// Reverse proxies whose `X-Forwarded-For` is believed when limiting sign-in attempts.
52    pub trusted_proxies: Vec<IpAddr>,
53    /// A fixed bearer token accepted on every service (`MCP_AUTH_TOKEN`), for clients that
54    /// cannot do OAuth. Only for sign-in that does not carry credentials: requests made with it
55    /// have no [`Credential`](crate::credential::Credential).
56    pub static_token: Option<SecretString>,
57}
58
59impl std::fmt::Debug for OAuthSettings {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.debug_struct("OAuthSettings")
62            .field("public_url", &self.public_url)
63            .field("trusted_proxies", &self.trusted_proxies)
64            .field("static_token", &self.static_token.as_ref().map(|_| ".."))
65            .finish_non_exhaustive()
66    }
67}
68
69/// How long a bearer credential found valid upstream is trusted before it is checked again.
70pub const BEARER_VALID_FOR: Duration = Duration::from_secs(600);
71/// How long a rejected bearer credential is remembered.
72pub const BEARER_INVALID_FOR: Duration = Duration::from_secs(60);
73const BEARER_CACHE_ENTRIES: usize = 10_000;
74/// Credential checks allowed to run at once, across sign-ins and bearer credentials.
75pub const MAX_RUNNING_CHECKS: usize = 16;
76/// Longest a grant lasts after the person signed in, however often it is refreshed. Then they
77/// sign in again.
78pub const MAX_GRANT_AGE: Duration = Duration::from_secs(90 * 24 * 3600);
79/// Longest a credential check may take before it counts as unavailable.
80pub const CHECK_TIMEOUT: Duration = Duration::from_secs(15);
81/// Longest a check waits for a free slot when [`MAX_RUNNING_CHECKS`] are already running.
82pub const CHECK_SLOT_WAIT: Duration = Duration::from_secs(5);
83/// Failed sign-in attempts one address may make per [`LOGIN_WINDOW`]. Failures across all
84/// addresses are capped too (see [`crate::guards::Ceiling`]): with a credential that is not
85/// carried, such as the owner's password, reaching that cap blocks everyone for the window.
86pub const LOGIN_ATTEMPTS: usize = 5;
87/// The window [`LOGIN_ATTEMPTS`] counts over.
88pub const LOGIN_WINDOW: Duration = Duration::from_secs(60);
89
90/// The authorization server's state, shared by its routes and every service's bearer guard.
91pub struct AuthState {
92    pub(crate) settings: OAuthSettings,
93    pub(crate) jwt: Jwt,
94    pub(crate) limiter: LoginLimiter,
95    pub(crate) replay: ReplayGuard,
96    pub(crate) verifier: Arc<dyn CredentialVerifier>,
97    pub(crate) sealer: Sealer,
98    /// Recent verdicts on credentials sent directly as bearer tokens.
99    pub(crate) bearer_checks: CheckCache,
100    /// Runs credential checks: shared per credential, capped and timed out.
101    pub(crate) checks: CheckRunner,
102    /// Seals sign-ins waiting for an upstream provider into the browser's cookie.
103    pub(crate) pending: Sealer,
104    /// Upstream code exchanges allowed to run at once.
105    pub(crate) exchanges: Arc<tokio::sync::Semaphore>,
106    services: Vec<String>,
107    sign_in_version: String,
108    /// Keys the default subject of carried credentials, so a subject cannot be used to guess
109    /// the credential offline.
110    subject_key: ring::hmac::Key,
111}
112
113/// Why the static token cannot be used with a verifier, if it cannot.
114pub(crate) fn static_token_problem(
115    token: &str,
116    verifier: &dyn CredentialVerifier,
117) -> Option<String> {
118    static_token_verifier_problem(verifier).or_else(|| static_token_shape_problem(token))
119}
120
121/// Why no static token can be used next to `verifier`, if none can.
122pub(crate) fn static_token_verifier_problem(verifier: &dyn CredentialVerifier) -> Option<String> {
123    (verifier.carried() || verifier.accepts_bearer()).then(|| {
124        format!(
125            "MCP_AUTH_TOKEN cannot be used when people sign in with their own {}",
126            verifier.label()
127        )
128    })
129}
130
131/// Why `token` cannot be a static token whatever the verifier, if it cannot.
132pub(crate) fn static_token_shape_problem(token: &str) -> Option<String> {
133    (token.split('.').count() == 3).then(|| {
134        "MCP_AUTH_TOKEN must not have the shape of a JWT (three dot-separated parts)".into()
135    })
136}
137
138/// The sign-in version tokens carry as `ver`: a keyed hash of the sign-in mode, the verifier's
139/// [label](CredentialVerifier::label) and its [generation](CredentialVerifier::generation) under
140/// `signing_key`. The same as [`AuthState::sign_in_version`]; useful for minting tokens in tests.
141pub fn sign_in_version(signing_key: &[u8], verifier: &dyn CredentialVerifier) -> String {
142    use base64::Engine as _;
143    use ring::hmac;
144    let key = hmac::Key::new(hmac::HMAC_SHA256, signing_key);
145    let mut ctx = hmac::Context::with_key(&key);
146    ctx.update(b"mcp-server-core sign-in v1\0");
147    ctx.update(if verifier.carried() {
148        b"carried\0"
149    } else {
150        b"password\0"
151    });
152    for part in [verifier.label().as_bytes(), verifier.generation()] {
153        ctx.update(&(part.len() as u64).to_be_bytes());
154        ctx.update(part);
155    }
156    let tag = ctx.sign();
157    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&tag.as_ref()[..16])
158}
159
160impl AuthState {
161    /// `services` are the enabled service names; each is the protected resource
162    /// `PUBLIC_URL/<name>`. Tokens the authorization server keeps for itself (client, CSRF, code,
163    /// refresh) use the public URL as audience; access tokens use their resource. `verifier`
164    /// decides who may sign in.
165    ///
166    /// # Panics
167    ///
168    /// If `settings.static_token` is set while `verifier` carries credentials or accepts them as
169    /// bearer tokens (requests made with it would lack the credential tools expect, and wrong
170    /// tokens could be tried as credentials without limit), or when the static token has the shape
171    /// of a JWT. [`Server::load`](crate::app::Server::load) reports these as configuration errors.
172    pub fn new(
173        settings: OAuthSettings,
174        services: &[&str],
175        verifier: Arc<dyn CredentialVerifier>,
176    ) -> Arc<Self> {
177        if let Some(token) = &settings.static_token
178            && let Some(problem) = static_token_problem(token.expose_secret(), verifier.as_ref())
179        {
180            panic!("{problem}");
181        }
182        let key = settings.signing_key.expose_secret().as_bytes();
183        let jwt = Jwt::new(
184            key,
185            settings.public_url.clone(),
186            settings.public_url.clone(),
187        );
188        let sealer = Sealer::new(key);
189        let pending = Sealer::for_purpose(
190            key,
191            b"upstream pending v1",
192            b"mcp-server-core upstream pending v1",
193        );
194        let sign_in_version = sign_in_version(key, verifier.as_ref());
195        let subject_key = {
196            let mut ctx =
197                ring::hmac::Context::with_key(&ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key));
198            ctx.update(b"mcp-server-core subject v1");
199            ring::hmac::Key::new(ring::hmac::HMAC_SHA256, ctx.sign().as_ref())
200        };
201        // One shared secret (the owner's password, the static token) is worth a lockout of
202        // everyone during a distributed attack; with per-person credentials it is not.
203        let ceiling = if verifier.carried() {
204            Ceiling::BlockFailing
205        } else {
206            Ceiling::BlockEveryone
207        };
208        Arc::new(Self {
209            settings,
210            jwt,
211            limiter: LoginLimiter::new(LOGIN_ATTEMPTS, LOGIN_WINDOW, ceiling),
212            replay: ReplayGuard::new(),
213            verifier,
214            sealer,
215            bearer_checks: CheckCache::new(
216                BEARER_VALID_FOR,
217                BEARER_INVALID_FOR,
218                BEARER_CACHE_ENTRIES,
219            ),
220            checks: CheckRunner::new(MAX_RUNNING_CHECKS, CHECK_TIMEOUT, CHECK_SLOT_WAIT),
221            pending,
222            exchanges: Arc::new(tokio::sync::Semaphore::new(MAX_RUNNING_CHECKS)),
223            services: services.iter().map(|s| s.to_string()).collect(),
224            sign_in_version,
225            subject_key,
226        })
227    }
228
229    /// The `ver` every code, access and refresh token must carry: a keyed hash of the sign-in
230    /// mode, the verifier's [label](CredentialVerifier::label) and its
231    /// [generation](CredentialVerifier::generation). Changing the owner's password, switching
232    /// sign-in mode or verifier, or rotating `OAUTH_SIGNING_KEY` changes it and so ends every
233    /// earlier grant.
234    pub fn sign_in_version(&self) -> &str {
235        &self.sign_in_version
236    }
237
238    /// Whether a code, access or refresh token's grant still holds: same sign-in version, a
239    /// sealed credential exactly when credentials are carried, and signed in less than
240    /// [`MAX_GRANT_AGE`] ago.
241    pub(crate) fn grant_is_current(&self, claims: &crate::jwt::Claims) -> bool {
242        let p = &claims.payload;
243        let version_ok = p
244            .ver
245            .as_deref()
246            .is_some_and(|v| crate::pkce::ct_eq(v, &self.sign_in_version));
247        let mode_ok = p.credential.is_some() == self.verifier.carried();
248        let now = jsonwebtoken::get_current_timestamp();
249        // auth_time is signed, so only its age needs checking; a time slightly ahead is another
250        // replica's clock.
251        let fresh = p
252            .auth_time
253            .is_some_and(|t| now.saturating_sub(t) < MAX_GRANT_AGE.as_secs());
254        version_ok && mode_ok && fresh
255    }
256
257    /// Who signed in with `credential`: what the verifier names
258    /// ([`CredentialVerifier::subject`]), else `key:` and 16 hex digits of a keyed hash of the
259    /// credential when credentials are carried, and `owner` otherwise.
260    pub fn subject_of(&self, credential: &str) -> String {
261        if let Some(subject) = self.verifier.subject(credential) {
262            return subject;
263        }
264        if !self.verifier.carried() {
265            return "owner".into();
266        }
267        let tag = ring::hmac::sign(&self.subject_key, credential.as_bytes());
268        let hex: String = tag.as_ref()[..8]
269            .iter()
270            .map(|b| format!("{b:02x}"))
271            .collect();
272        format!("key:{hex}")
273    }
274
275    /// The settings this server was built with.
276    pub fn settings(&self) -> &OAuthSettings {
277        &self.settings
278    }
279
280    /// Issues and verifies this server's tokens, e.g. to mint one in a test.
281    pub fn jwt(&self) -> &Jwt {
282        &self.jwt
283    }
284
285    /// Seals and opens the credentials carried in tokens.
286    pub fn sealer(&self) -> &Sealer {
287        &self.sealer
288    }
289
290    /// Who may sign in.
291    pub fn verifier(&self) -> &dyn CredentialVerifier {
292        self.verifier.as_ref()
293    }
294
295    /// The enabled service names, each a protected resource.
296    pub fn services(&self) -> &[String] {
297        &self.services
298    }
299
300    /// Whether `service` is one of them.
301    pub fn has_service(&self, service: &str) -> bool {
302        self.services.iter().any(|s| s == service)
303    }
304
305    /// Where an upstream provider sends people back: `PUBLIC_URL/callback`. Register it with the
306    /// provider as a redirect URI.
307    pub fn callback_url(&self) -> String {
308        format!(
309            "{}{}",
310            self.settings.public_url,
311            crate::upstream::CALLBACK_PATH
312        )
313    }
314
315    /// The resource URL of `service`: `PUBLIC_URL/<service>`.
316    pub fn resource(&self, service: &str) -> String {
317        format!("{}/{service}", self.settings.public_url)
318    }
319
320    /// Where `service`'s protected-resource metadata is served.
321    pub fn resource_metadata_url(&self, service: &str) -> String {
322        format!(
323            "{}/.well-known/oauth-protected-resource/{service}",
324            self.settings.public_url
325        )
326    }
327
328    /// The enabled service whose resource URL is exactly `resource`.
329    pub fn service_for_resource(&self, resource: &str) -> Option<&str> {
330        self.services
331            .iter()
332            .find(|s| self.resource(s) == resource)
333            .map(String::as_str)
334    }
335}
336
337/// The authorization server's routes: metadata, registration, sign-in and token endpoints.
338/// [`crate::server::build_app`] merges them for you.
339pub fn oauth_router(state: Arc<AuthState>) -> Router {
340    let router = if state.verifier.upstream().is_some() {
341        Router::new().route(crate::upstream::CALLBACK_PATH, get(callback::get_callback))
342    } else {
343        Router::new()
344    };
345    router
346        .route(
347            "/.well-known/oauth-protected-resource/{service}",
348            get(metadata::protected_resource),
349        )
350        .route(
351            "/.well-known/oauth-authorization-server",
352            get(metadata::authorization_server),
353        )
354        .route("/register", post(register::register))
355        .route("/token", post(token::token))
356        .route(
357            "/authorize",
358            get(authorize::get_authorize).post(authorize::post_authorize),
359        )
360        .with_state(state)
361}