mod authorize;
mod metadata;
mod middleware;
mod register;
mod token;
pub use authorize::client_ip;
pub use middleware::require_bearer;
pub use register::{
MAX_CLIENT_NAME_CHARS, MAX_REDIRECT_URI_LEN, MAX_REDIRECT_URIS, validate_redirect_uri,
};
use crate::credential::{CheckCache, CheckRunner, CredentialVerifier, Sealer};
use crate::guards::{Ceiling, LoginLimiter, ReplayGuard};
use crate::jwt::Jwt;
use axum::Router;
use axum::routing::{get, post};
use secrecy::{ExposeSecret, SecretString};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone)]
pub struct OAuthSettings {
pub public_url: String,
pub signing_key: SecretString,
pub trusted_proxies: Vec<IpAddr>,
pub static_token: Option<SecretString>,
}
impl std::fmt::Debug for OAuthSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OAuthSettings")
.field("public_url", &self.public_url)
.field("trusted_proxies", &self.trusted_proxies)
.field("static_token", &self.static_token.as_ref().map(|_| ".."))
.finish_non_exhaustive()
}
}
pub const BEARER_VALID_FOR: Duration = Duration::from_secs(600);
pub const BEARER_INVALID_FOR: Duration = Duration::from_secs(60);
const BEARER_CACHE_ENTRIES: usize = 10_000;
pub const MAX_RUNNING_CHECKS: usize = 16;
pub const MAX_GRANT_AGE: Duration = Duration::from_secs(90 * 24 * 3600);
pub const CHECK_TIMEOUT: Duration = Duration::from_secs(15);
pub const CHECK_SLOT_WAIT: Duration = Duration::from_secs(5);
pub const LOGIN_ATTEMPTS: usize = 5;
pub const LOGIN_WINDOW: Duration = Duration::from_secs(60);
pub struct AuthState {
pub(crate) settings: OAuthSettings,
pub(crate) jwt: Jwt,
pub(crate) limiter: LoginLimiter,
pub(crate) replay: ReplayGuard,
pub(crate) verifier: Arc<dyn CredentialVerifier>,
pub(crate) sealer: Sealer,
pub(crate) bearer_checks: CheckCache,
pub(crate) checks: CheckRunner,
services: Vec<String>,
sign_in_version: String,
subject_key: ring::hmac::Key,
}
pub(crate) fn static_token_problem(
token: &str,
verifier: &dyn CredentialVerifier,
) -> Option<String> {
static_token_verifier_problem(verifier).or_else(|| static_token_shape_problem(token))
}
pub(crate) fn static_token_verifier_problem(verifier: &dyn CredentialVerifier) -> Option<String> {
(verifier.carried() || verifier.accepts_bearer()).then(|| {
format!(
"MCP_AUTH_TOKEN cannot be used when people sign in with their own {}",
verifier.label()
)
})
}
pub(crate) fn static_token_shape_problem(token: &str) -> Option<String> {
(token.split('.').count() == 3).then(|| {
"MCP_AUTH_TOKEN must not have the shape of a JWT (three dot-separated parts)".into()
})
}
pub fn sign_in_version(signing_key: &[u8], verifier: &dyn CredentialVerifier) -> String {
use base64::Engine as _;
use ring::hmac;
let key = hmac::Key::new(hmac::HMAC_SHA256, signing_key);
let mut ctx = hmac::Context::with_key(&key);
ctx.update(b"mcp-server-core sign-in v1\0");
ctx.update(if verifier.carried() {
b"carried\0"
} else {
b"password\0"
});
for part in [verifier.label().as_bytes(), verifier.generation()] {
ctx.update(&(part.len() as u64).to_be_bytes());
ctx.update(part);
}
let tag = ctx.sign();
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&tag.as_ref()[..16])
}
impl AuthState {
pub fn new(
settings: OAuthSettings,
services: &[&str],
verifier: Arc<dyn CredentialVerifier>,
) -> Arc<Self> {
if let Some(token) = &settings.static_token
&& let Some(problem) = static_token_problem(token.expose_secret(), verifier.as_ref())
{
panic!("{problem}");
}
let key = settings.signing_key.expose_secret().as_bytes();
let jwt = Jwt::new(
key,
settings.public_url.clone(),
settings.public_url.clone(),
);
let sealer = Sealer::new(key);
let sign_in_version = sign_in_version(key, verifier.as_ref());
let subject_key = {
let mut ctx =
ring::hmac::Context::with_key(&ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key));
ctx.update(b"mcp-server-core subject v1");
ring::hmac::Key::new(ring::hmac::HMAC_SHA256, ctx.sign().as_ref())
};
let ceiling = if verifier.carried() {
Ceiling::BlockFailing
} else {
Ceiling::BlockEveryone
};
Arc::new(Self {
settings,
jwt,
limiter: LoginLimiter::new(LOGIN_ATTEMPTS, LOGIN_WINDOW, ceiling),
replay: ReplayGuard::new(),
verifier,
sealer,
bearer_checks: CheckCache::new(
BEARER_VALID_FOR,
BEARER_INVALID_FOR,
BEARER_CACHE_ENTRIES,
),
checks: CheckRunner::new(MAX_RUNNING_CHECKS, CHECK_TIMEOUT, CHECK_SLOT_WAIT),
services: services.iter().map(|s| s.to_string()).collect(),
sign_in_version,
subject_key,
})
}
pub fn sign_in_version(&self) -> &str {
&self.sign_in_version
}
pub(crate) fn grant_is_current(&self, claims: &crate::jwt::Claims) -> bool {
let p = &claims.payload;
let version_ok = p
.ver
.as_deref()
.is_some_and(|v| crate::pkce::ct_eq(v, &self.sign_in_version));
let mode_ok = p.credential.is_some() == self.verifier.carried();
let now = jsonwebtoken::get_current_timestamp();
let fresh = p
.auth_time
.is_some_and(|t| now.saturating_sub(t) < MAX_GRANT_AGE.as_secs());
version_ok && mode_ok && fresh
}
pub fn subject_of(&self, credential: &str) -> String {
if let Some(subject) = self.verifier.subject(credential) {
return subject;
}
if !self.verifier.carried() {
return "owner".into();
}
let tag = ring::hmac::sign(&self.subject_key, credential.as_bytes());
let hex: String = tag.as_ref()[..8]
.iter()
.map(|b| format!("{b:02x}"))
.collect();
format!("key:{hex}")
}
pub fn settings(&self) -> &OAuthSettings {
&self.settings
}
pub fn jwt(&self) -> &Jwt {
&self.jwt
}
pub fn sealer(&self) -> &Sealer {
&self.sealer
}
pub fn verifier(&self) -> &dyn CredentialVerifier {
self.verifier.as_ref()
}
pub fn services(&self) -> &[String] {
&self.services
}
pub fn has_service(&self, service: &str) -> bool {
self.services.iter().any(|s| s == service)
}
pub fn resource(&self, service: &str) -> String {
format!("{}/{service}", self.settings.public_url)
}
pub fn resource_metadata_url(&self, service: &str) -> String {
format!(
"{}/.well-known/oauth-protected-resource/{service}",
self.settings.public_url
)
}
pub fn service_for_resource(&self, resource: &str) -> Option<&str> {
self.services
.iter()
.find(|s| self.resource(s) == resource)
.map(String::as_str)
}
}
pub fn oauth_router(state: Arc<AuthState>) -> Router {
Router::new()
.route(
"/.well-known/oauth-protected-resource/{service}",
get(metadata::protected_resource),
)
.route(
"/.well-known/oauth-authorization-server",
get(metadata::authorization_server),
)
.route("/register", post(register::register))
.route("/token", post(token::token))
.route(
"/authorize",
get(authorize::get_authorize).post(authorize::post_authorize),
)
.with_state(state)
}