159 lines
4.1 KiB
Rust
159 lines
4.1 KiB
Rust
use axum::{
|
|
extract::{FromRef, FromRequestParts},
|
|
http::{
|
|
HeaderMap,
|
|
header::{AUTHORIZATION, ToStrError},
|
|
},
|
|
};
|
|
use sqlx::PgPool;
|
|
use uuid::Uuid;
|
|
|
|
use crate::{crypto::hash_secret, error::AppError, repository};
|
|
|
|
#[derive(Debug)]
|
|
pub struct Auth(pub Authorization);
|
|
|
|
impl<S> FromRequestParts<S> for Auth
|
|
where
|
|
PgPool: FromRef<S>,
|
|
S: Send + Sync,
|
|
{
|
|
type Rejection = AppError;
|
|
|
|
async fn from_request_parts(
|
|
parts: &mut axum::http::request::Parts,
|
|
state: &S,
|
|
) -> Result<Self, Self::Rejection> {
|
|
let pool = PgPool::from_ref(state);
|
|
|
|
let token = bearer_token(&parts.headers)?;
|
|
let token_hash = hash_secret(token);
|
|
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
|
|
.await?
|
|
.ok_or(AppError::Unauthorized("Invalid access token".to_string()))?;
|
|
|
|
Ok(Auth(Authorization {
|
|
user_id: token.user_id,
|
|
}))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Authorization {
|
|
user_id: Uuid,
|
|
}
|
|
|
|
impl Authorization {
|
|
pub fn user_id(&self) -> Uuid {
|
|
self.user_id
|
|
}
|
|
}
|
|
|
|
fn bearer_token(headers: &HeaderMap) -> Result<&str, AuthorizationHeaderError> {
|
|
let value = headers
|
|
.get(AUTHORIZATION)
|
|
.ok_or(AuthorizationHeaderError::Missing)?
|
|
.to_str()
|
|
.map_err(AuthorizationHeaderError::NotAscii)?;
|
|
|
|
let (scheme, token) = value
|
|
.split_once(' ')
|
|
.ok_or(AuthorizationHeaderError::MalformedValue)?;
|
|
|
|
if !scheme.eq_ignore_ascii_case("Bearer") {
|
|
return Err(AuthorizationHeaderError::UnsupportedScheme);
|
|
}
|
|
|
|
let token = token.trim();
|
|
if token.is_empty() {
|
|
return Err(AuthorizationHeaderError::EmptyToken);
|
|
}
|
|
|
|
Ok(token)
|
|
}
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
enum AuthorizationHeaderError {
|
|
#[error("Missing authorization header")]
|
|
Missing,
|
|
|
|
#[error("Invalid authorization header encoding")]
|
|
NotAscii(#[source] ToStrError),
|
|
|
|
#[error("Malformed authorization header")]
|
|
MalformedValue,
|
|
|
|
#[error("Unsupported authorization scheme")]
|
|
UnsupportedScheme,
|
|
|
|
#[error("Missing authorization token")]
|
|
EmptyToken,
|
|
}
|
|
|
|
impl From<AuthorizationHeaderError> for AppError {
|
|
fn from(error: AuthorizationHeaderError) -> Self {
|
|
tracing::debug!(%error, "authorization header error");
|
|
AppError::Unauthorized(error.to_string())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use axum::http::HeaderValue;
|
|
|
|
use super::*;
|
|
|
|
fn headers_with(value: &[u8]) -> HeaderMap {
|
|
let mut headers = HeaderMap::new();
|
|
headers.insert(AUTHORIZATION, HeaderValue::from_bytes(value).unwrap());
|
|
headers
|
|
}
|
|
|
|
#[test]
|
|
fn extracts_bearer_token() {
|
|
let headers = headers_with(b"Bearer abc123");
|
|
assert_eq!(bearer_token(&headers).unwrap(), "abc123");
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_case_insensitive_scheme_and_trims_token() {
|
|
let headers = headers_with(b"bearer abc123 ");
|
|
assert_eq!(bearer_token(&headers).unwrap(), "abc123");
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_missing_header() {
|
|
let headers = HeaderMap::new();
|
|
let error = bearer_token(&headers).unwrap_err();
|
|
assert!(matches!(error, AuthorizationHeaderError::Missing));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_non_utf8_header() {
|
|
let headers = headers_with(&[b'B', b'e', b'a', b'r', b' ', 0xFF]);
|
|
let error = bearer_token(&headers).unwrap_err();
|
|
assert!(matches!(error, AuthorizationHeaderError::NotAscii(_)));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_value_without_separator() {
|
|
let headers = headers_with(b"Bearer");
|
|
let error = bearer_token(&headers).unwrap_err();
|
|
assert!(matches!(error, AuthorizationHeaderError::MalformedValue));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_unsupported_scheme() {
|
|
let headers = headers_with(b"Basic abc123");
|
|
let error = bearer_token(&headers).unwrap_err();
|
|
assert!(matches!(error, AuthorizationHeaderError::UnsupportedScheme));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_empty_token() {
|
|
let headers = headers_with(b"Bearer ");
|
|
let error = bearer_token(&headers).unwrap_err();
|
|
assert!(matches!(error, AuthorizationHeaderError::EmptyToken));
|
|
}
|
|
}
|