1mod 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#[derive(Clone)]
46pub struct OAuthSettings {
47 pub public_url: String,
49 pub signing_key: SecretString,
51 pub trusted_proxies: Vec<IpAddr>,
53 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
69pub const BEARER_VALID_FOR: Duration = Duration::from_secs(600);
71pub const BEARER_INVALID_FOR: Duration = Duration::from_secs(60);
73const BEARER_CACHE_ENTRIES: usize = 10_000;
74pub const MAX_RUNNING_CHECKS: usize = 16;
76pub const MAX_GRANT_AGE: Duration = Duration::from_secs(90 * 24 * 3600);
79pub const CHECK_TIMEOUT: Duration = Duration::from_secs(15);
81pub const CHECK_SLOT_WAIT: Duration = Duration::from_secs(5);
83pub const LOGIN_ATTEMPTS: usize = 5;
87pub const LOGIN_WINDOW: Duration = Duration::from_secs(60);
89
90pub 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 pub(crate) bearer_checks: CheckCache,
100 pub(crate) checks: CheckRunner,
102 pub(crate) pending: Sealer,
104 pub(crate) exchanges: Arc<tokio::sync::Semaphore>,
106 services: Vec<String>,
107 sign_in_version: String,
108 subject_key: ring::hmac::Key,
111}
112
113pub(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
121pub(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
131pub(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
138pub 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 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 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 pub fn sign_in_version(&self) -> &str {
235 &self.sign_in_version
236 }
237
238 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 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 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 pub fn settings(&self) -> &OAuthSettings {
277 &self.settings
278 }
279
280 pub fn jwt(&self) -> &Jwt {
282 &self.jwt
283 }
284
285 pub fn sealer(&self) -> &Sealer {
287 &self.sealer
288 }
289
290 pub fn verifier(&self) -> &dyn CredentialVerifier {
292 self.verifier.as_ref()
293 }
294
295 pub fn services(&self) -> &[String] {
297 &self.services
298 }
299
300 pub fn has_service(&self, service: &str) -> bool {
302 self.services.iter().any(|s| s == service)
303 }
304
305 pub fn callback_url(&self) -> String {
308 format!(
309 "{}{}",
310 self.settings.public_url,
311 crate::upstream::CALLBACK_PATH
312 )
313 }
314
315 pub fn resource(&self, service: &str) -> String {
317 format!("{}/{service}", self.settings.public_url)
318 }
319
320 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 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
337pub 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}