use axum::{ extract::FromRequestParts, http::header::{AUTHORIZATION, ToStrError}, response::IntoResponse, }; #[derive(Debug)] pub struct AuthHeader { scheme: String, token: String, } impl AuthHeader { pub fn scheme(&self) -> &str { &self.scheme } pub fn token(&self) -> &str { &self.token } } impl FromRequestParts for AuthHeader where S: Send + Sync, { type Rejection = AuthHeaderError; async fn from_request_parts( parts: &mut axum::http::request::Parts, _state: &S, ) -> Result { let value = parts .headers .get(AUTHORIZATION) .ok_or(AuthHeaderError::Missing)? .to_str() .map_err(AuthHeaderError::NotAscii)?; let (scheme, token) = value .split_once(' ') .map(|(s, t)| (s, t.trim())) .ok_or(AuthHeaderError::MalformedValue)?; if scheme.is_empty() { return Err(AuthHeaderError::EmptyScheme); } if token.is_empty() { return Err(AuthHeaderError::EmptyToken); } Ok(AuthHeader { scheme: scheme.to_string(), token: token.to_string(), }) } } #[derive(Debug, thiserror::Error)] pub enum AuthHeaderError { #[error("missing header")] Missing, #[error("invalid encoding")] NotAscii(#[source] ToStrError), #[error("malformed value")] MalformedValue, #[error("empty scheme")] EmptyScheme, #[error("empty token")] EmptyToken, } impl crate::error::ClientError for AuthHeaderError { fn client_error_message(&self) -> &'static str { match self { AuthHeaderError::Missing => "Missing authorization header", AuthHeaderError::NotAscii(_) => "Invalid authorization header encoding", AuthHeaderError::MalformedValue => "Malformed authorization header", AuthHeaderError::EmptyScheme => "Empty authorization scheme", AuthHeaderError::EmptyToken => "Empty authorization token", } } } impl IntoResponse for AuthHeaderError { fn into_response(self) -> axum::response::Response { Into::::into(self).into_response() } } #[cfg(test)] mod tests { use axum::http::{HeaderMap, HeaderValue, Request, request::Parts}; use super::*; fn headers(value: &[u8]) -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert(AUTHORIZATION, HeaderValue::from_bytes(value).unwrap()); headers } fn parts(headers: HeaderMap) -> Parts { let (mut parts, _) = Request::builder().body(()).unwrap().into_parts(); parts.headers = headers; parts } #[tokio::test] async fn extracts_scheme_and_token() { let mut parts = parts(headers(b"Bearer abc123")); let auth_header = AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap(); assert_eq!(auth_header.scheme(), "Bearer"); assert_eq!(auth_header.token(), "abc123"); } #[tokio::test] async fn trims_token() { let mut parts = parts(headers(b"bearer abc123 ")); let auth_header = AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap(); assert_eq!(auth_header.scheme(), "bearer"); assert_eq!(auth_header.token(), "abc123"); } #[tokio::test] async fn rejects_missing_header() { let mut parts = parts(HeaderMap::new()); assert!(matches!( AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap_err(), AuthHeaderError::Missing )); } #[tokio::test] async fn rejects_non_utf8_header() { let mut parts = parts(headers(&[b'B', b'e', b'a', b'r', b' ', 0xFF])); assert!(matches!( AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap_err(), AuthHeaderError::NotAscii(_) )); } #[tokio::test] async fn rejects_value_without_separator() { let mut parts = parts(headers(b"Bearer")); assert!(matches!( AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap_err(), AuthHeaderError::MalformedValue )); } #[tokio::test] async fn rejects_empty_scheme() { let mut parts = parts(headers(b" abc123")); assert!(matches!( AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap_err(), AuthHeaderError::EmptyScheme )); } #[tokio::test] async fn rejects_empty_token() { let mut parts = parts(headers(b"Bearer ")); assert!(matches!( AuthHeader::from_request_parts(&mut parts, &()) .await .unwrap_err(), AuthHeaderError::EmptyToken )); } }