diff --git a/apps/auth-service/src/oidc/mod.rs b/apps/auth-service/src/oidc/mod.rs index 1ac27aae5..242ddf32d 100644 --- a/apps/auth-service/src/oidc/mod.rs +++ b/apps/auth-service/src/oidc/mod.rs @@ -43,6 +43,7 @@ use sourceorigin_common::{ clients::ClientKind, config::Origin, protocol::{ + challenge::AuthScheme, claims::{Acr, ProfileClaims}, jwt::{Algorithm, Claim, TokenType}, metadata::ServerMetadata, @@ -93,28 +94,6 @@ pub struct OidcApplication { metadata: PublicDocument, } -sourceorigin_common::str_enum! { - /// HTTP authentication schemes accepted by the protocol endpoints. - enum AuthScheme { - /// Client ID and secret, used by confidential clients at the token endpoint. - Basic = "Basic", - /// An access token, used at `UserInfo`. - Bearer = "Bearer", - } -} - -impl AuthScheme { - /// Returns the credentials of an `Authorization` value using this scheme. - /// Scheme names are case-insensitive, and one or more spaces separate them - /// from the credentials (RFC 9110 §11.4); credentials are otherwise untouched. - fn credentials(self, value: &str) -> Option<&str> { - let (scheme, credentials) = value.split_once(' ')?; - scheme - .eq_ignore_ascii_case(self.as_str()) - .then(|| credentials.trim_start_matches(' ')) - } -} - sourceorigin_common::str_enum! { /// Opaque token prefixes; each binds a token to one purpose so it cannot be used for another. enum TokenPrefix { diff --git a/apps/auth-service/src/oidc/tests/protocol.rs b/apps/auth-service/src/oidc/tests/protocol.rs index 65e591144..0115d563f 100644 --- a/apps/auth-service/src/oidc/tests/protocol.rs +++ b/apps/auth-service/src/oidc/tests/protocol.rs @@ -153,22 +153,6 @@ async fn post_protocol_endpoints_and_error_contracts() { ); } -/// Checks case-insensitive scheme matching without changing credential bytes. -#[test] -fn authentication_schemes_are_case_insensitive() { - assert_eq!(AuthScheme::Bearer.credentials("bEaReR a.B"), Some("a.B")); - assert_eq!(AuthScheme::Basic.credentials("BASIC Zm9v"), Some("Zm9v")); - assert_eq!(AuthScheme::Basic.credentials("Bearer Zm9v"), None); - assert_eq!(AuthScheme::Bearer.credentials("Bearer"), None); -} - -/// Checks that credentials may follow the scheme after more than one space (RFC 9110 §11.4). -#[test] -fn authentication_schemes_allow_several_spaces() { - assert_eq!(AuthScheme::Bearer.credentials("Bearer a.B"), Some("a.B")); - assert_eq!(AuthScheme::Basic.credentials("Basic Zm9v"), Some("Zm9v")); -} - /// Checks deduplication, lexical ordering and preservation of registered extension scopes. #[test] fn scope_sets_preserve_existing_wire_semantics() { diff --git a/crates/auth-sdk/src/axum/bearer.rs b/crates/auth-sdk/src/axum/bearer.rs index f25a649fd..065422399 100644 --- a/crates/auth-sdk/src/axum/bearer.rs +++ b/crates/auth-sdk/src/axum/bearer.rs @@ -11,7 +11,7 @@ use axum::{ use serde::de::DeserializeOwned; use sourceorigin_common::{ ErrorChain, - protocol::challenge::{BearerChallenge, BearerError}, + protocol::challenge::{AuthScheme, BearerChallenge, BearerError}, }; use std::{ future::Future, @@ -151,8 +151,8 @@ where Err(_) => Outcome::Malformed, Ok(value) => { let (scheme, credentials) = value.split_once(' ').unwrap_or((value, "")); - match scheme - .eq_ignore_ascii_case("Bearer") + match AuthScheme::Bearer + .matches(scheme) .then(|| credentials.trim()) { None => Outcome::Missing, diff --git a/crates/auth-sdk/src/client.rs b/crates/auth-sdk/src/client.rs index e0f4fb5fb..31557834e 100644 --- a/crates/auth-sdk/src/client.rs +++ b/crates/auth-sdk/src/client.rs @@ -12,6 +12,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwn use sourceorigin_common::{ ClientId, protocol::{ + challenge::AuthScheme, claims::{IdTokenClaims, LogoutTokenClaims, UserInfo}, jwt::TokenType, oauth::{ @@ -1038,7 +1039,7 @@ impl Client { nonce: Option<&str>, max_age: Option, ) -> Result { - if !response.token_type.eq_ignore_ascii_case("Bearer") { + if !AuthScheme::Bearer.matches(&response.token_type) { return Err(OAuthError::UnexpectedResponse { endpoint: "token", status: StatusCode::OK.as_u16(), diff --git a/crates/auth-sdk/src/http.rs b/crates/auth-sdk/src/http.rs index a501792d1..457ca3c95 100644 --- a/crates/auth-sdk/src/http.rs +++ b/crates/auth-sdk/src/http.rs @@ -8,7 +8,10 @@ use reqwest::{ }; use sourceorigin_common::{ SendTraced, - protocol::constants::{MAX_RESPONSE_BYTES, REQUEST_DEADLINE}, + protocol::{ + challenge::AuthScheme, + constants::{MAX_RESPONSE_BYTES, REQUEST_DEADLINE}, + }, }; use thiserror::Error; use url::Url; @@ -199,7 +202,10 @@ impl Http { url::form_urlencoded::byte_serialize(value.as_bytes()).collect::() }; let credentials = STANDARD.encode(format!("{}:{}", encode(id), encode(secret))); - request.header(header::AUTHORIZATION, format!("Basic {credentials}")) + request.header( + header::AUTHORIZATION, + format!("{} {credentials}", AuthScheme::Basic), + ) } }; tokio::time::timeout(REQUEST_DEADLINE, Self::read(url, request)) diff --git a/crates/common/src/protocol/challenge/mod.rs b/crates/common/src/protocol/challenge/mod.rs index bb04f0b82..887571248 100644 --- a/crates/common/src/protocol/challenge/mod.rs +++ b/crates/common/src/protocol/challenge/mod.rs @@ -1,5 +1,6 @@ //! `WWW-Authenticate: Bearer` challenges (RFC 6750 §3, RFC 9470 §3, RFC 9728 §5.1), -//! produced by resource servers and parsed by clients. +//! produced by resource servers and parsed by clients, and the authentication +//! schemes (`AuthScheme`) `Authorization` headers name. //! //! Parameters are written in one fixed order (`error`, `error_description`, `scope`, //! `acr_values`, `max_age`, `resource_metadata`) with every value quoted, so every SDK @@ -69,8 +70,46 @@ impl BearerError { } } -/// The authentication scheme of every challenge here. -const SCHEME: &str = "Bearer"; +crate::str_enum! { + /// HTTP authentication schemes (RFC 9110 §11): `Bearer` for access tokens, the + /// scheme of every challenge here, and `Basic` for a confidential client's ID + /// and secret at the token endpoint. Parsing reads only the canonical spelling; + /// compare a header's scheme with [`AuthScheme::matches`] or + /// [`AuthScheme::credentials`], which ignore case as HTTP does. + pub enum AuthScheme { + /// Client ID and secret, used by confidential clients at the token endpoint. + Basic = "Basic", + /// An access token (RFC 6750). + Bearer = "Bearer", + } +} + +impl AuthScheme { + /// Whether `scheme` names this scheme. Scheme names are case-insensitive + /// (RFC 9110 §11.1). + #[must_use] + pub fn matches(self, scheme: &str) -> bool { + scheme.eq_ignore_ascii_case(self.as_str()) + } + + /// Returns the credentials of an `Authorization` value using this scheme, or + /// `None` for another scheme or a value without credentials. One or more + /// spaces separate the scheme from the credentials (RFC 9110 §11.4), which are + /// otherwise untouched. + /// + /// ``` + /// use sourceorigin_common::protocol::challenge::AuthScheme; + /// + /// assert_eq!(AuthScheme::Bearer.credentials("bearer a.B"), Some("a.B")); + /// assert_eq!(AuthScheme::Basic.credentials("Bearer Zm9v"), None); + /// ``` + #[must_use] + pub fn credentials(self, value: &str) -> Option<&str> { + let (scheme, credentials) = value.split_once(' ')?; + self.matches(scheme) + .then(|| credentials.trim_start_matches(' ')) + } +} /// One `Bearer` challenge. Without `error` it means no token was sent (RFC 6750 §3.1). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -217,7 +256,7 @@ impl BearerChallenge { impl fmt::Display for BearerChallenge { /// Writes the header value, parameters in their fixed order. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str(SCHEME)?; + formatter.write_str(AuthScheme::Bearer.as_str())?; let mut first = true; if let Some(error) = &self.error { Self::write_parameter(formatter, &mut first, "error", error.as_str())?; @@ -250,7 +289,7 @@ impl FromStr for BearerChallenge { Parser::new(value) .challenges()? .into_iter() - .find(|challenge| challenge.scheme.eq_ignore_ascii_case(SCHEME)) + .find(|challenge| AuthScheme::Bearer.matches(&challenge.scheme)) .ok_or(ChallengeError::NotBearer) .and_then(|challenge| Self::from_parameters(challenge.parameters)) } diff --git a/crates/common/src/protocol/challenge/tests.rs b/crates/common/src/protocol/challenge/tests.rs index 67382dd27..cc5e120db 100644 --- a/crates/common/src/protocol/challenge/tests.rs +++ b/crates/common/src/protocol/challenge/tests.rs @@ -63,3 +63,19 @@ fn rejects_invalid_headers() { assert_eq!(header.parse::(), Err(expected), "{header}"); } } + +/// Checks case-insensitive scheme matching without changing credential bytes. +#[test] +fn authentication_schemes_are_case_insensitive() { + assert_eq!(AuthScheme::Bearer.credentials("bEaReR a.B"), Some("a.B")); + assert_eq!(AuthScheme::Basic.credentials("BASIC Zm9v"), Some("Zm9v")); + assert_eq!(AuthScheme::Basic.credentials("Bearer Zm9v"), None); + assert_eq!(AuthScheme::Bearer.credentials("Bearer"), None); +} + +/// Checks that credentials may follow the scheme after more than one space (RFC 9110 §11.4). +#[test] +fn authentication_schemes_allow_several_spaces() { + assert_eq!(AuthScheme::Bearer.credentials("Bearer a.B"), Some("a.B")); + assert_eq!(AuthScheme::Basic.credentials("Basic Zm9v"), Some("Zm9v")); +}