Something went wrong. Try again.
An OIDC provider for AT Protocol OAuth. Rust port of apenwarr/atlogin.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528use 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<String>, pub nonce: Option<String>, pub challenge: Option<PkceChallenge>, #[serde(default)] pub scopes: Vec<Scope>,}
#[derive(Clone, Debug)]pub struct AuthorizationRequest { pub client: RegisteredClient, pub target: AuthorizationTarget, pub login_hint: Option<String>, pub prompt: Prompt, pub max_age: Option<u64>, pub remember: bool,}
#[derive(Clone, Debug, Eq, PartialEq)]pub enum AuthorizationFailure { Rejected(UnverifiedRequest), Redirected(Box<RedirectedFailure>), Storage(String),}
#[derive(Clone, Debug, Eq, PartialEq)]pub struct RedirectedFailure { pub redirect_uri: Url, pub state: Option<String>, 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<Self, AuthorizationFailure> { 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<Vec<Scope>, 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<Self, AuthorizationError> { 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<u8>, pub grant_type: String, pub code: String, pub redirect_uri: String, pub code_verifier: Option<String>,}
impl TokenRequest { pub fn parse( authorization: Option<&str>, form: &[(String, String)], ) -> Result<Self, TokenError> { 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::<Vec<u8>>(); 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<String>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub email_verified: Option<bool>, pub groups: Vec<String>,}
impl IdTokenClaims { pub fn new( issuer: &str, client: &ClientId, identity: &Identity, nonce: Option<String>, 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<EmailClaim>) -> 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<u64> { 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); }}