Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 1 addition & 22 deletions apps/auth-service/src/oidc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use sourceorigin_common::{
clients::ClientKind,
config::Origin,
protocol::{
challenge::AuthScheme,
claims::{Acr, ProfileClaims},
jwt::{Algorithm, Claim, TokenType},
metadata::ServerMetadata,
Expand Down Expand Up @@ -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 {
Expand Down
16 changes: 0 additions & 16 deletions apps/auth-service/src/oidc/tests/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
6 changes: 3 additions & 3 deletions crates/auth-sdk/src/axum/bearer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion crates/auth-sdk/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -1038,7 +1039,7 @@ impl Client {
nonce: Option<&str>,
max_age: Option<u32>,
) -> Result<Tokens, OAuthError> {
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(),
Expand Down
10 changes: 8 additions & 2 deletions crates/auth-sdk/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -199,7 +202,10 @@ impl Http {
url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
};
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))
Expand Down
49 changes: 44 additions & 5 deletions crates/common/src/protocol/challenge/mod.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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())?;
Expand Down Expand Up @@ -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))
}
Expand Down
16 changes: 16 additions & 0 deletions crates/common/src/protocol/challenge/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,19 @@ fn rejects_invalid_headers() {
assert_eq!(header.parse::<BearerChallenge>(), 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"));
}