Over engineered bearer token extraction (although it's not perfect yet).

This commit is contained in:
2026-10-10 12:15:00 +02:00
parent 1655becf39
commit 30efddbc20
6 changed files with 320 additions and 130 deletions
+178
View File
@@ -0,0 +1,178 @@
use axum::{
extract::FromRequestParts,
http::header::{AUTHORIZATION, ToStrError},
response::IntoResponse,
};
use crate::routes::extractors::auth::AuthError;
#[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<S> FromRequestParts<S> for AuthHeader
where
S: Send + Sync,
{
type Rejection = AuthHeaderError;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
_state: &S,
) -> Result<Self, Self::Rejection> {
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 IntoResponse for AuthHeaderError {
fn into_response(self) -> axum::response::Response {
Into::<AuthError>::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
));
}
}