566 lines
18 KiB
Rust
566 lines
18 KiB
Rust
//! Fixed RS256 OIDC browser and RFC 9068 MCP resource-server profiles.
|
|
//! Authentication only: persistent tenant memberships and interactive sessions belong to the server.
|
|
use async_trait::async_trait;
|
|
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
|
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
|
|
use secrecy::{ExposeSecret, SecretString};
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest, Sha256};
|
|
use std::{
|
|
collections::BTreeSet,
|
|
sync::Arc,
|
|
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
|
};
|
|
use subtle::ConstantTimeEq;
|
|
use tokio::sync::Mutex;
|
|
use url::Url;
|
|
|
|
#[cfg(feature = "postgres-state")]
|
|
pub mod postgres;
|
|
|
|
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
|
pub enum Error {
|
|
#[error("not_configured or invalid OIDC configuration")]
|
|
Configuration,
|
|
#[error("OIDC transport, TLS or bounded response failed")]
|
|
Transport,
|
|
#[error("untrusted or unsupported discovery metadata")]
|
|
Discovery,
|
|
#[error("invalid JWT")]
|
|
InvalidToken,
|
|
#[error("invalid issuer")]
|
|
InvalidIssuer,
|
|
#[error("invalid audience or authorized party")]
|
|
InvalidAudience,
|
|
#[error("expired token")]
|
|
Expired,
|
|
#[error("token not yet valid")]
|
|
NotYetValid,
|
|
#[error("unknown signing key")]
|
|
UnknownKid,
|
|
#[error("invalid nonce")]
|
|
Nonce,
|
|
#[error("invalid, expired, unbound or replayed login state")]
|
|
State,
|
|
#[error("authorization code exchange rejected (including PKCE failure)")]
|
|
CodeExchange,
|
|
#[error("missing required resource scope")]
|
|
MissingScope,
|
|
#[error("state store unavailable or capacity exceeded")]
|
|
Store,
|
|
#[error("client secret unavailable")]
|
|
Secret,
|
|
}
|
|
pub type Result<T> = std::result::Result<T, Error>;
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Config {
|
|
pub issuer: Url,
|
|
pub browser_client_id: String,
|
|
pub client_secret_ref: String,
|
|
pub redirect_uri: Url,
|
|
/// Dedicated resource audience; MUST differ from the browser client ID.
|
|
pub mcp_audience: String,
|
|
/// Explicit authorized OAuth client IDs for the RFC 9068 profile.
|
|
pub mcp_client_ids: BTreeSet<String>,
|
|
}
|
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
pub enum Profile {
|
|
Production,
|
|
DevTest,
|
|
}
|
|
|
|
#[async_trait]
|
|
pub trait SecretResolver: Send + Sync {
|
|
async fn resolve(&self, reference: &str) -> Result<SecretString>;
|
|
}
|
|
|
|
/// Store encrypted at rest. No Debug: verifier and nonce are sensitive.
|
|
#[derive(Serialize, Deserialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
|
|
pub struct PendingLogin {
|
|
pub binding_hash: String,
|
|
pub nonce: String,
|
|
pub pkce_verifier: String,
|
|
pub expires_at: u64,
|
|
}
|
|
#[async_trait]
|
|
pub trait StateStore: Send + Sync {
|
|
/// Production adapters must implement durable, shared, atomic storage.
|
|
fn is_persistent(&self) -> bool;
|
|
async fn insert(&self, state_hash: String, login: PendingLogin) -> Result<()>;
|
|
/// Atomically DELETE ... RETURNING only when binding matches and expiry > now.
|
|
/// Concurrent callbacks must return at most one record. Never restore on failure.
|
|
async fn consume(&self, state_hash: &str, binding_hash: &str, now: u64)
|
|
-> Result<PendingLogin>;
|
|
}
|
|
|
|
/// Sensitive URL and cookie: intentionally not Debug/Serialize.
|
|
pub struct LoginStart {
|
|
pub authorization_url: Url,
|
|
/// Set verbatim; Secure, HttpOnly, host-only Lax cookie permits the cross-site GET callback.
|
|
pub binding_set_cookie: String,
|
|
}
|
|
pub struct Callback<'a> {
|
|
pub code: &'a str,
|
|
pub state: &'a str,
|
|
/// Value of __Host-rmm_oidc_binding, NOT the entire Cookie header.
|
|
pub browser_binding: &'a str,
|
|
}
|
|
pub const CLEAR_BINDING_COOKIE: &str =
|
|
"__Host-rmm_oidc_binding=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0";
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct Identity {
|
|
pub issuer: String,
|
|
pub subject: String,
|
|
}
|
|
#[derive(Debug)]
|
|
pub struct BearerIdentity {
|
|
pub identity: Identity,
|
|
pub scopes: BTreeSet<String>,
|
|
pub client_id: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct Discovery {
|
|
issuer: String,
|
|
authorization_endpoint: Url,
|
|
token_endpoint: Url,
|
|
jwks_uri: Url,
|
|
response_types_supported: Vec<String>,
|
|
id_token_signing_alg_values_supported: Vec<String>,
|
|
code_challenge_methods_supported: Vec<String>,
|
|
token_endpoint_auth_methods_supported: Vec<String>,
|
|
}
|
|
#[derive(Deserialize)]
|
|
struct Jwk {
|
|
kid: String,
|
|
kty: String,
|
|
alg: String,
|
|
#[serde(rename = "use")]
|
|
usage: String,
|
|
n: String,
|
|
e: String,
|
|
}
|
|
#[derive(Deserialize)]
|
|
struct Jwks {
|
|
keys: Vec<Jwk>,
|
|
}
|
|
struct Cache {
|
|
keys: Vec<Jwk>,
|
|
fetched: Option<Instant>,
|
|
}
|
|
|
|
pub struct OidcAuth {
|
|
config: Config,
|
|
http: reqwest::Client,
|
|
discovery: Discovery,
|
|
keys: Mutex<Cache>,
|
|
store: Arc<dyn StateStore>,
|
|
secrets: Arc<dyn SecretResolver>,
|
|
}
|
|
|
|
fn https(url: &Url) -> bool {
|
|
url.scheme() == "https"
|
|
&& url.host_str().is_some()
|
|
&& url.username().is_empty()
|
|
&& url.password().is_none()
|
|
&& url.fragment().is_none()
|
|
}
|
|
fn now() -> u64 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap_or_default()
|
|
.as_secs()
|
|
}
|
|
fn random() -> String {
|
|
URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>())
|
|
}
|
|
fn hash(value: &str) -> String {
|
|
URL_SAFE_NO_PAD.encode(Sha256::digest(value.as_bytes()))
|
|
}
|
|
fn equal(a: &str, b: &str) -> bool {
|
|
bool::from(a.as_bytes().ct_eq(b.as_bytes()))
|
|
}
|
|
async fn bounded<T: serde::de::DeserializeOwned>(mut response: reqwest::Response) -> Result<T> {
|
|
if !response.status().is_success() || response.content_length().is_some_and(|n| n > 131072) {
|
|
return Err(Error::Transport);
|
|
}
|
|
let mut body = Vec::new();
|
|
while let Some(chunk) = response.chunk().await.map_err(|_| Error::Transport)? {
|
|
if body.len() + chunk.len() > 131072 {
|
|
return Err(Error::Transport);
|
|
}
|
|
body.extend_from_slice(&chunk);
|
|
}
|
|
serde_json::from_slice(&body).map_err(|_| Error::Transport)
|
|
}
|
|
|
|
impl OidcAuth {
|
|
/// Normal TLS roots; additional roots may be explicitly provisioned for a private IdP.
|
|
/// No arbitrary HTTP client injection, redirects, environment proxies or insecure TLS switches.
|
|
pub async fn discover(
|
|
config: Config,
|
|
profile: Profile,
|
|
store: Arc<dyn StateStore>,
|
|
secrets: Arc<dyn SecretResolver>,
|
|
extra_roots: Vec<reqwest::Certificate>,
|
|
) -> Result<Self> {
|
|
if !https(&config.issuer)
|
|
|| config.issuer.query().is_some()
|
|
|| !https(&config.redirect_uri)
|
|
|| config.redirect_uri.query().is_some()
|
|
|| config.browser_client_id.is_empty()
|
|
|| config.client_secret_ref.is_empty()
|
|
|| config.mcp_audience.is_empty()
|
|
|| config.mcp_audience == config.browser_client_id
|
|
|| config.mcp_client_ids.is_empty()
|
|
|| (profile == Profile::Production && !store.is_persistent())
|
|
{
|
|
return Err(Error::Configuration);
|
|
}
|
|
let mut builder = reqwest::Client::builder()
|
|
.https_only(true)
|
|
.no_proxy()
|
|
.redirect(reqwest::redirect::Policy::none())
|
|
.connect_timeout(Duration::from_secs(3))
|
|
.timeout(Duration::from_secs(10));
|
|
for root in extra_roots {
|
|
builder = builder.add_root_certificate(root);
|
|
}
|
|
let http = builder.build().map_err(|_| Error::Transport)?;
|
|
let discovery_url = format!(
|
|
"{}/.well-known/openid-configuration",
|
|
config.issuer.as_str().trim_end_matches('/')
|
|
);
|
|
let discovery: Discovery = bounded(
|
|
http.get(discovery_url)
|
|
.send()
|
|
.await
|
|
.map_err(|_| Error::Transport)?,
|
|
)
|
|
.await?;
|
|
if discovery.issuer != config.issuer.as_str()
|
|
|| [
|
|
&discovery.authorization_endpoint,
|
|
&discovery.token_endpoint,
|
|
&discovery.jwks_uri,
|
|
]
|
|
.iter()
|
|
.any(|u| !https(u) || u.origin() != config.issuer.origin() || u.query().is_some())
|
|
|| !discovery
|
|
.response_types_supported
|
|
.iter()
|
|
.any(|s| s == "code")
|
|
|| !discovery
|
|
.id_token_signing_alg_values_supported
|
|
.iter()
|
|
.any(|s| s == "RS256")
|
|
|| !discovery
|
|
.code_challenge_methods_supported
|
|
.iter()
|
|
.any(|s| s == "S256")
|
|
|| !discovery
|
|
.token_endpoint_auth_methods_supported
|
|
.iter()
|
|
.any(|s| s == "client_secret_post")
|
|
{
|
|
return Err(Error::Discovery);
|
|
}
|
|
Ok(Self {
|
|
config,
|
|
http,
|
|
discovery,
|
|
keys: Mutex::new(Cache {
|
|
keys: vec![],
|
|
fetched: None,
|
|
}),
|
|
store,
|
|
secrets,
|
|
})
|
|
}
|
|
|
|
pub async fn login_start(&self) -> Result<LoginStart> {
|
|
let state = random();
|
|
let binding = random();
|
|
let nonce = random();
|
|
let verifier = random();
|
|
let mut url = self.discovery.authorization_endpoint.clone();
|
|
url.query_pairs_mut().extend_pairs([
|
|
("response_type", "code"),
|
|
("client_id", &self.config.browser_client_id),
|
|
("redirect_uri", self.config.redirect_uri.as_str()),
|
|
("scope", "openid"),
|
|
("state", &state),
|
|
("nonce", &nonce),
|
|
("code_challenge", &hash(&verifier)),
|
|
("code_challenge_method", "S256"),
|
|
]);
|
|
self.store
|
|
.insert(
|
|
hash(&state),
|
|
PendingLogin {
|
|
binding_hash: hash(&binding),
|
|
nonce,
|
|
pkce_verifier: verifier,
|
|
expires_at: now() + 300,
|
|
},
|
|
)
|
|
.await?;
|
|
Ok(LoginStart {
|
|
authorization_url: url,
|
|
binding_set_cookie: format!(
|
|
"__Host-rmm_oidc_binding={binding}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=300"
|
|
),
|
|
})
|
|
}
|
|
|
|
pub async fn callback(&self, input: Callback<'_>) -> Result<Identity> {
|
|
if input.state.len() != 43
|
|
|| input.browser_binding.len() != 43
|
|
|| input.code.is_empty()
|
|
|| input.code.len() > 4096
|
|
{
|
|
return Err(Error::State);
|
|
}
|
|
let login = self
|
|
.store
|
|
.consume(&hash(input.state), &hash(input.browser_binding), now())
|
|
.await?;
|
|
if login.expires_at <= now() || !equal(&login.binding_hash, &hash(input.browser_binding)) {
|
|
return Err(Error::State);
|
|
}
|
|
let secret = self.secrets.resolve(&self.config.client_secret_ref).await?;
|
|
#[derive(Deserialize)]
|
|
struct Tokens {
|
|
id_token: String,
|
|
}
|
|
let response = self
|
|
.http
|
|
.post(self.discovery.token_endpoint.clone())
|
|
.form(&[
|
|
("grant_type", "authorization_code"),
|
|
("code", input.code),
|
|
("redirect_uri", self.config.redirect_uri.as_str()),
|
|
("client_id", &self.config.browser_client_id),
|
|
("client_secret", secret.expose_secret()),
|
|
("code_verifier", &login.pkce_verifier),
|
|
])
|
|
.send()
|
|
.await
|
|
.map_err(|_| Error::Transport)?;
|
|
if !response.status().is_success() {
|
|
return Err(Error::CodeExchange);
|
|
}
|
|
let tokens: Tokens = bounded(response).await?;
|
|
let claims = self
|
|
.verify(&tokens.id_token, &self.config.browser_client_id, false)
|
|
.await?;
|
|
if !claims
|
|
.nonce
|
|
.as_deref()
|
|
.is_some_and(|n| equal(n, &login.nonce))
|
|
{
|
|
return Err(Error::Nonce);
|
|
}
|
|
Ok(self.identity(claims))
|
|
}
|
|
|
|
pub async fn verify_mcp_bearer(
|
|
&self,
|
|
token: &str,
|
|
required_scopes: &[&str],
|
|
) -> Result<BearerIdentity> {
|
|
let claims = self.verify(token, &self.config.mcp_audience, true).await?;
|
|
let client_id = claims
|
|
.client_id
|
|
.clone()
|
|
.filter(|id| self.config.mcp_client_ids.contains(id))
|
|
.ok_or(Error::InvalidAudience)?;
|
|
let scopes: BTreeSet<String> = claims
|
|
.scope
|
|
.as_deref()
|
|
.unwrap_or_default()
|
|
.split_ascii_whitespace()
|
|
.map(str::to_owned)
|
|
.collect();
|
|
if required_scopes.iter().any(|s| !scopes.contains(*s)) {
|
|
return Err(Error::MissingScope);
|
|
}
|
|
Ok(BearerIdentity {
|
|
identity: self.identity(claims),
|
|
scopes,
|
|
client_id,
|
|
})
|
|
}
|
|
fn identity(&self, claims: Claims) -> Identity {
|
|
Identity {
|
|
issuer: self.config.issuer.to_string(),
|
|
subject: claims.sub,
|
|
}
|
|
}
|
|
|
|
async fn verify(&self, token: &str, audience: &str, access: bool) -> Result<Claims> {
|
|
if token.len() > 32768 {
|
|
return Err(Error::InvalidToken);
|
|
}
|
|
let header = decode_header(token).map_err(|_| Error::InvalidToken)?;
|
|
if header.alg != Algorithm::RS256 || (access && header.typ.as_deref() != Some("at+jwt")) {
|
|
return Err(Error::InvalidToken);
|
|
}
|
|
let kid = header
|
|
.kid
|
|
.filter(|s| !s.is_empty() && s.len() <= 256)
|
|
.ok_or(Error::UnknownKid)?;
|
|
// Header kid is only a selector within configured-issuer keys, never a URL/authority.
|
|
let mut cache = self.keys.lock().await;
|
|
let unknown = !cache.keys.iter().any(|k| k.kid == kid);
|
|
let stale = cache
|
|
.fetched
|
|
.is_none_or(|t| t.elapsed() >= Duration::from_secs(300));
|
|
if stale
|
|
|| (unknown
|
|
&& cache
|
|
.fetched
|
|
.is_some_and(|t| t.elapsed() >= Duration::from_secs(1)))
|
|
{
|
|
// Throttle even failed refreshes; one lock prevents concurrent refresh storms.
|
|
cache.fetched = Some(Instant::now());
|
|
cache.keys.clear();
|
|
let jwks: Jwks = bounded(
|
|
self.http
|
|
.get(self.discovery.jwks_uri.clone())
|
|
.send()
|
|
.await
|
|
.map_err(|_| Error::Transport)?,
|
|
)
|
|
.await?;
|
|
let mut ids = BTreeSet::new();
|
|
if jwks.keys.is_empty()
|
|
|| jwks.keys.len() > 64
|
|
|| jwks.keys.iter().any(|k| {
|
|
!ids.insert(&k.kid) || k.kty != "RSA" || k.alg != "RS256" || k.usage != "sig"
|
|
})
|
|
{
|
|
return Err(Error::InvalidToken);
|
|
}
|
|
cache.keys = jwks.keys;
|
|
}
|
|
let jwk = cache
|
|
.keys
|
|
.iter()
|
|
.find(|k| k.kid == kid)
|
|
.ok_or(Error::UnknownKid)?;
|
|
let key =
|
|
DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(|_| Error::InvalidToken)?;
|
|
drop(cache);
|
|
let mut validation = Validation::new(Algorithm::RS256);
|
|
validation.set_issuer(&[self.config.issuer.as_str()]);
|
|
validation.set_audience(&[audience]);
|
|
validation.set_required_spec_claims(&["exp", "iss", "aud", "sub", "iat"]);
|
|
validation.leeway = 0;
|
|
validation.validate_nbf = true;
|
|
let claims = decode::<Claims>(token, &key, &validation)
|
|
.map_err(|e| match e.kind() {
|
|
jsonwebtoken::errors::ErrorKind::InvalidIssuer => Error::InvalidIssuer,
|
|
jsonwebtoken::errors::ErrorKind::InvalidAudience => Error::InvalidAudience,
|
|
jsonwebtoken::errors::ErrorKind::ExpiredSignature => Error::Expired,
|
|
jsonwebtoken::errors::ErrorKind::ImmatureSignature => Error::NotYetValid,
|
|
_ => Error::InvalidToken,
|
|
})?
|
|
.claims;
|
|
if claims.sub.is_empty() || claims.sub.len() > 1024 || claims.iat > now() {
|
|
return Err(Error::InvalidToken);
|
|
}
|
|
if access
|
|
&& !claims
|
|
.jti
|
|
.as_deref()
|
|
.is_some_and(|jti| !jti.is_empty() && jti.len() <= 1024)
|
|
{
|
|
return Err(Error::InvalidToken);
|
|
}
|
|
if !access
|
|
&& ((claims.aud.len() > 1 && claims.azp.is_none())
|
|
|| claims
|
|
.azp
|
|
.as_deref()
|
|
.is_some_and(|a| a != self.config.browser_client_id))
|
|
{
|
|
return Err(Error::InvalidAudience);
|
|
}
|
|
Ok(claims)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Deserialize)]
|
|
struct Claims {
|
|
jti: Option<String>,
|
|
sub: String,
|
|
#[serde(deserialize_with = "audiences")]
|
|
aud: Vec<String>,
|
|
iat: u64,
|
|
azp: Option<String>,
|
|
nonce: Option<String>,
|
|
scope: Option<String>,
|
|
client_id: Option<String>,
|
|
}
|
|
fn audiences<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
|
#[derive(Deserialize)]
|
|
#[serde(untagged)]
|
|
enum Aud {
|
|
One(String),
|
|
Many(Vec<String>),
|
|
}
|
|
Ok(match Aud::deserialize(d)? {
|
|
Aud::One(s) => vec![s],
|
|
Aud::Many(v) => v,
|
|
})
|
|
}
|
|
|
|
#[cfg(any(test, feature = "dev-memory-store"))]
|
|
pub mod dev {
|
|
use super::*;
|
|
use std::collections::HashMap;
|
|
/// Explicit dev/test-only volatile adapter. Rejected by the production constructor.
|
|
pub struct InMemoryStateStore {
|
|
records: Mutex<HashMap<String, PendingLogin>>,
|
|
}
|
|
impl InMemoryStateStore {
|
|
pub fn new(_profile: DevTestOnly) -> Self {
|
|
Self {
|
|
records: Mutex::new(HashMap::new()),
|
|
}
|
|
}
|
|
}
|
|
pub struct DevTestOnly;
|
|
#[async_trait]
|
|
impl StateStore for InMemoryStateStore {
|
|
fn is_persistent(&self) -> bool {
|
|
false
|
|
}
|
|
async fn insert(&self, state: String, login: PendingLogin) -> Result<()> {
|
|
let mut records = self.records.lock().await;
|
|
records.retain(|_, v| v.expires_at > now());
|
|
if records.len() >= 1024 || records.contains_key(&state) {
|
|
return Err(Error::Store);
|
|
}
|
|
records.insert(state, login);
|
|
Ok(())
|
|
}
|
|
async fn consume(&self, state: &str, binding: &str, time: u64) -> Result<PendingLogin> {
|
|
let mut records = self.records.lock().await;
|
|
if !records
|
|
.get(state)
|
|
.is_some_and(|v| v.expires_at > time && equal(&v.binding_hash, binding))
|
|
{
|
|
return Err(Error::State);
|
|
}
|
|
records.remove(state).ok_or(Error::State)
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|