use base64::Engine; use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use jiff::{SignedDuration, Timestamp}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; use url::Url; use crate::clients::{ClientId, Clients, RegisteredClient}; use crate::identity::Identity; pub const AUTHORIZATION_PARAMETERS: [&str; 12] = [ "client_id", "redirect_uri", "response_type", "scope", "state", "nonce", "login_hint", "code_challenge", "code_challenge_method", "prompt", "max_age", "remember", ]; const TOKEN_PARAMETERS: [&str; 6] = [ "grant_type", "code", "redirect_uri", "code_verifier", "client_id", "client_secret", ]; pub fn lookup<'a>(params: &'a [(String, String)], key: &str) -> Option<&'a str> { params .iter() .find(|(name, _)| name == key) .map(|(_, value)| value.as_str()) .filter(|value| !value.is_empty()) } #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum Scope { OpenId, Profile, Email, Groups, } impl Scope { pub fn as_str(self) -> &'static str { match self { Self::OpenId => "openid", Self::Profile => "profile", Self::Email => "email", Self::Groups => "groups", } } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct AuthorizationTarget { pub client_id: ClientId, pub redirect_uri: Url, pub client_state: Option, pub nonce: Option, pub challenge: Option, #[serde(default)] pub scopes: Vec, } #[derive(Clone, Debug)] pub struct AuthorizationRequest { pub client: RegisteredClient, pub target: AuthorizationTarget, pub login_hint: Option, pub prompt: Prompt, pub max_age: Option, pub remember: bool, } #[derive(Clone, Debug, Eq, PartialEq)] pub enum AuthorizationFailure { Rejected(UnverifiedRequest), Redirected(Box), Storage(String), } #[derive(Clone, Debug, Eq, PartialEq)] pub struct RedirectedFailure { pub redirect_uri: Url, pub state: Option, pub error: AuthorizationError, } fn duplicated(params: &[(String, String)], key: &str) -> bool { params.iter().filter(|(name, _)| name == key).count() > 1 } impl AuthorizationRequest { pub fn parse( params: &[(String, String)], clients: &Clients, ) -> Result { for key in ["client_id", "redirect_uri", "state"] { if duplicated(params, key) { return Err(AuthorizationFailure::Rejected( UnverifiedRequest::Duplicate(key), )); } } let client_id = ClientId::new(lookup(params, "client_id").unwrap_or_default()); let client = clients .get(&client_id) .map_err(|error| AuthorizationFailure::Storage(error.to_string()))? .ok_or(AuthorizationFailure::Rejected( UnverifiedRequest::UnknownClient, ))?; let redirect_uri = lookup(params, "redirect_uri") .filter(|raw| client.permits_redirect(raw)) .and_then(|raw| Url::parse(raw).ok()) .ok_or(AuthorizationFailure::Rejected( UnverifiedRequest::UnregisteredRedirect, ))?; let state = lookup(params, "state").map(str::to_owned); let redirected = |error: AuthorizationError| { AuthorizationFailure::Redirected(Box::new(RedirectedFailure { redirect_uri: redirect_uri.clone(), state: state.clone(), error, })) }; for key in AUTHORIZATION_PARAMETERS { if duplicated(params, key) { return Err(redirected(AuthorizationError::Duplicate(key))); } } if lookup(params, "response_type") != Some("code") { return Err(redirected(AuthorizationError::UnsupportedResponseType)); } let scopes = parse_scopes( lookup(params, "scope").unwrap_or_default(), client.email_policy().discloses(), ) .map_err(redirected)?; let challenge = match ( lookup(params, "code_challenge"), lookup(params, "code_challenge_method"), ) { (None, None) => None, (challenge, method) => Some( PkceChallenge::parse(challenge.unwrap_or_default(), method.unwrap_or_default()) .map_err(redirected)?, ), }; let nonce = lookup(params, "nonce").map(str::to_owned); if challenge.is_none() && nonce.is_none() { return Err(redirected(AuthorizationError::MissingChallengeOrNonce)); } Ok(Self { client, target: AuthorizationTarget { client_id, redirect_uri, client_state: state, nonce, challenge, scopes, }, login_hint: lookup(params, "login_hint") .map(str::trim) .filter(|hint| !hint.is_empty()) .map(str::to_owned), prompt: Prompt::parse(lookup(params, "prompt")), max_age: parse_max_age(lookup(params, "max_age")), remember: lookup(params, "remember") == Some("1"), }) } } fn parse_scopes(raw: &str, email_allowed: bool) -> Result, AuthorizationError> { let names: Vec<&str> = raw.split_whitespace().collect(); if !names.contains(&"openid") { return Err(AuthorizationError::MissingOpenId); } names .into_iter() .map(|name| match name { "openid" => Ok(Scope::OpenId), "profile" => Ok(Scope::Profile), "groups" => Ok(Scope::Groups), "email" if email_allowed => Ok(Scope::Email), other => Err(AuthorizationError::UnsupportedScope(other.to_owned())), }) .collect() } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PkceChallenge(String); impl PkceChallenge { pub fn parse(challenge: &str, method: &str) -> Result { let decoded = URL_SAFE_NO_PAD.decode(challenge).ok(); let well_formed = method == "S256" && challenge.len() == 43 && decoded.is_some_and(|bytes| bytes.len() == 32); if !well_formed { return Err(AuthorizationError::InvalidChallenge); } Ok(Self(challenge.to_owned())) } pub fn verify(&self, verifier: &str) -> bool { if !(43..=128).contains(&verifier.len()) { return false; } let digest = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); digest.as_bytes().ct_eq(self.0.as_bytes()).into() } } #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum UnverifiedRequest { #[error("duplicate {0}")] Duplicate(&'static str), #[error("invalid client_id")] UnknownClient, #[error("redirect_uri not registered")] UnregisteredRedirect, } #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum AuthorizationError { #[error("duplicate {0}")] Duplicate(&'static str), #[error("only response_type=code is supported")] UnsupportedResponseType, #[error("openid scope required")] MissingOpenId, #[error("unsupported scope for this client")] UnsupportedScope(String), #[error("PKCE requires an S256 challenge")] InvalidChallenge, #[error("code_challenge or nonce is required")] MissingChallengeOrNonce, } impl AuthorizationError { pub fn code(&self) -> &'static str { match self { Self::Duplicate(_) | Self::InvalidChallenge | Self::MissingChallengeOrNonce => { "invalid_request" } Self::UnsupportedResponseType => "unsupported_response_type", Self::MissingOpenId | Self::UnsupportedScope(_) => "invalid_scope", } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct TokenRequest { pub client_id: ClientId, pub client_secret: Vec, pub grant_type: String, pub code: String, pub redirect_uri: String, pub code_verifier: Option, } impl TokenRequest { pub fn parse( authorization: Option<&str>, form: &[(String, String)], ) -> Result { for key in TOKEN_PARAMETERS { if duplicated(form, key) { return Err(TokenError::Duplicate(key)); } } let (client_id, client_secret) = match authorization.and_then(|h| h.strip_prefix("Basic ")) { Some(encoded) => { if lookup(form, "client_secret").is_some() { return Err(TokenError::TwoAuthenticationMethods); } let decoded = STANDARD .decode(encoded.trim()) .map_err(|_| TokenError::InvalidClient)?; let text = String::from_utf8(decoded).map_err(|_| TokenError::InvalidClient)?; let (id, secret) = text.split_once(':').ok_or(TokenError::InvalidClient)?; let id = percent_encoding::percent_decode_str(id) .decode_utf8() .map_err(|_| TokenError::InvalidClient)?; let secret = percent_encoding::percent_decode_str(secret).collect::>(); if lookup(form, "client_id").is_some_and(|body_id| body_id != id) { return Err(TokenError::ClientIdMismatch); } (id.into_owned(), secret) } None => ( lookup(form, "client_id") .ok_or(TokenError::InvalidClient)? .to_owned(), lookup(form, "client_secret") .ok_or(TokenError::InvalidClient)? .as_bytes() .to_vec(), ), }; Ok(Self { client_id: ClientId::new(client_id), client_secret, grant_type: lookup(form, "grant_type").unwrap_or_default().to_owned(), code: lookup(form, "code").unwrap_or_default().to_owned(), redirect_uri: lookup(form, "redirect_uri").unwrap_or_default().to_owned(), code_verifier: lookup(form, "code_verifier").map(str::to_owned), }) } } #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum TokenError { #[error("invalid client credentials")] InvalidClient, #[error("unsupported grant_type")] UnsupportedGrant, #[error("invalid or expired code")] InvalidCode, #[error("client_id mismatch")] ClientMismatch, #[error("redirect_uri mismatch")] RedirectMismatch, #[error("invalid PKCE verifier")] InvalidVerifier, #[error("code_verifier sent without a code_challenge")] UnexpectedVerifier, #[error("duplicate {0}")] Duplicate(&'static str), #[error("client credentials sent in both the header and the body")] TwoAuthenticationMethods, #[error("client_id in the body does not match the credentials")] ClientIdMismatch, } impl TokenError { pub fn status(&self) -> u16 { match self { Self::InvalidClient => 401, _ => 400, } } pub fn code(&self) -> &'static str { match self { Self::InvalidClient => "invalid_client", Self::UnsupportedGrant => "unsupported_grant_type", Self::UnexpectedVerifier | Self::Duplicate(_) | Self::TwoAuthenticationMethods | Self::ClientIdMismatch => "invalid_request", Self::InvalidCode | Self::ClientMismatch | Self::RedirectMismatch | Self::InvalidVerifier => "invalid_grant", } } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct IdTokenClaims { pub iss: String, pub sub: String, pub aud: String, pub exp: i64, pub iat: i64, pub name: String, pub preferred_username: String, pub auth_time: i64, #[serde(skip_serializing_if = "Option::is_none")] pub nonce: Option, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option, #[serde(skip_serializing_if = "Option::is_none")] pub email_verified: Option, pub groups: Vec, } impl IdTokenClaims { pub fn new( issuer: &str, client: &ClientId, identity: &Identity, nonce: Option, auth_time: Timestamp, issued_at: Timestamp, lifetime: SignedDuration, ) -> Self { Self { email_verified: None, email: None, groups: vec![identity.did.as_str().to_owned()], iss: issuer.to_owned(), sub: identity.did.as_str().to_owned(), aud: client.as_str().to_owned(), exp: (issued_at + lifetime).as_second(), iat: issued_at.as_second(), name: identity.handle.as_str().to_owned(), preferred_username: identity.handle.as_str().to_owned(), auth_time: auth_time.as_second(), nonce, } } pub fn with_email(mut self, email: Option) -> Self { self.email_verified = email.as_ref().map(|email| email.verified); self.email = email.map(|email| email.address); self } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct EmailClaim { pub address: String, pub verified: bool, } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct Prompt { pub none: bool, pub login: bool, pub select_account: bool, } impl Prompt { pub fn parse(value: Option<&str>) -> Self { let mut prompt = Self::default(); for word in value.unwrap_or_default().split_whitespace() { match word { "none" => prompt.none = true, "login" => prompt.login = true, "select_account" => prompt.select_account = true, _ => {} } } prompt } } pub fn parse_max_age(value: Option<&str>) -> Option { value.and_then(|raw| raw.parse().ok()) } #[cfg(test)] mod tests { use super::*; use crate::clients::{ClientPolicy, ClientRegistry, ClientSecret, ClientStore}; use crate::database::Database; const REDIRECT: &str = "https://client.example/cb"; fn clients() -> Clients { let client = RegisteredClient::new( ClientId::new("client"), ClientSecret::new(vec![b's'; 32]).expect("long enough"), vec![crate::clients::RedirectUri::parse(REDIRECT).expect("valid uri")], ClientPolicy::default(), ) .expect("valid client"); Clients::new( ClientRegistry::new([client]).expect("registry"), ClientStore::new(Database::in_memory().expect("database")), ) } fn authorize_query() -> Vec<(String, String)> { [ ("client_id", "client"), ("redirect_uri", REDIRECT), ("response_type", "code"), ("scope", "openid profile"), ("state", "caller-state"), ("nonce", "caller-nonce"), ] .into_iter() .map(|(key, value)| (key.to_owned(), value.to_owned())) .collect() } #[test] fn duplicate_parameters_are_rejected() { let mut query = authorize_query(); query.push(("client_id".to_owned(), "other".to_owned())); assert_eq!( AuthorizationRequest::parse(&query, &clients()).err(), Some(AuthorizationFailure::Rejected( UnverifiedRequest::Duplicate("client_id") )) ); let mut query = authorize_query(); query.push(("nonce".to_owned(), "first".to_owned())); query.push(("nonce".to_owned(), "second".to_owned())); assert_eq!( AuthorizationRequest::parse(&query, &clients()).err(), Some(AuthorizationFailure::Redirected(Box::new( RedirectedFailure { redirect_uri: Url::parse(REDIRECT).expect("valid url"), state: Some("caller-state".to_owned()), error: AuthorizationError::Duplicate("nonce"), } ))) ); } #[test] fn prompts_and_max_age_parse_leniently() { let prompt = Prompt::parse(Some("login select_account unknown")); assert!(prompt.login && prompt.select_account && !prompt.none); assert_eq!(Prompt::parse(None), Prompt::default()); assert_eq!(parse_max_age(Some("300")), Some(300)); assert_eq!(parse_max_age(Some("soon")), None); assert_eq!(parse_max_age(None), None); } }