diff --git a/server/src/domain.rs b/server/src/domain.rs index eaa25e9..e4d73f1 100644 --- a/server/src/domain.rs +++ b/server/src/domain.rs @@ -1,4 +1,5 @@ mod account; +mod authorization; mod cents; mod direction; mod recurring_transaction; @@ -10,6 +11,7 @@ mod user_app; mod user_app_secret; pub use account::*; +pub use authorization::*; pub use cents::*; pub use direction::*; pub use recurring_transaction::*; diff --git a/server/src/domain/authorization.rs b/server/src/domain/authorization.rs new file mode 100644 index 0000000..79c87d7 --- /dev/null +++ b/server/src/domain/authorization.rs @@ -0,0 +1,16 @@ +use uuid::Uuid; + +#[derive(Debug)] +pub struct Authorization { + user_id: Uuid, +} + +impl Authorization { + pub fn new(user_id: Uuid) -> Self { + Self { user_id } + } + + pub fn user_id(&self) -> Uuid { + self.user_id + } +} diff --git a/server/src/routes.rs b/server/src/routes.rs index 01e6b46..cce0f6b 100644 --- a/server/src/routes.rs +++ b/server/src/routes.rs @@ -6,7 +6,7 @@ mod accounts; mod auth_passkey; mod auth_token; mod dtos; -mod extractors; +pub mod extractors; mod scheduled_transactions; mod transactions; mod user_app_secrets; diff --git a/server/src/routes/extractors/auth.rs b/server/src/routes/extractors/auth.rs index e912891..8fe29db 100644 --- a/server/src/routes/extractors/auth.rs +++ b/server/src/routes/extractors/auth.rs @@ -1,158 +1,100 @@ -use axum::{ - extract::{FromRef, FromRequestParts}, - http::{ - HeaderMap, - header::{AUTHORIZATION, ToStrError}, - }, -}; -use sqlx::PgPool; -use uuid::Uuid; +use axum::{extract::FromRequestParts, response::IntoResponse}; -use crate::{crypto::hash_secret, error::AppError, repository}; +mod bearer; +mod header; + +pub use bearer::*; +pub use header::*; + +use crate::{domain::Authorization, error::AppError}; #[derive(Debug)] pub struct Auth(pub Authorization); impl FromRequestParts for Auth where - PgPool: FromRef, + Bearer: AuthScheme + Authorizer, S: Send + Sync, { - type Rejection = AppError; + type Rejection = AuthError; async fn from_request_parts( parts: &mut axum::http::request::Parts, state: &S, ) -> Result { - let pool = PgPool::from_ref(state); + let header = AuthHeader::from_request_parts(parts, state).await?; + if !header.scheme().eq_ignore_ascii_case(Bearer::SCHEME) { + return Err(AuthError::UnsupportedScheme); + } - 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()))?; + let credentials = Bearer::credentials(header.token()).map_err(Into::::into)?; + let authorization = Bearer::authorize(credentials, state) + .await + .map_err(Into::::into)?; - Ok(Auth(Authorization { - user_id: token.user_id, - })) + Ok(Self(authorization)) } } -#[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")] +pub enum AuthError { + #[error("unsupported scheme")] UnsupportedScheme, - #[error("Missing authorization token")] - EmptyToken, + #[error(transparent)] + Header(#[from] AuthHeaderError), + + #[error(transparent)] + Bearer(#[from] BearerError), } -impl From for AppError { - fn from(error: AuthorizationHeaderError) -> Self { - tracing::debug!(%error, "authorization header error"); - AppError::Unauthorized(error.to_string()) +impl From for AppError { + fn from(err: AuthError) -> Self { + match err { + AuthError::UnsupportedScheme => { + AppError::Unauthorized("Unsupported authorization scheme".into()) + } + AuthError::Header(AuthHeaderError::Missing) => { + AppError::Unauthorized("Missing authorization header".into()) + } + AuthError::Header(AuthHeaderError::NotAscii(_)) => { + AppError::Unauthorized("Invalid authorization header encoding".into()) + } + AuthError::Header(AuthHeaderError::MalformedValue) => { + AppError::Unauthorized("Malformed authorization header".into()) + } + AuthError::Header(AuthHeaderError::EmptyScheme) => { + AppError::Unauthorized("Empty authorization scheme".into()) + } + AuthError::Header(AuthHeaderError::EmptyToken) => { + AppError::Unauthorized("Empty token value".into()) + } + AuthError::Bearer(BearerError::InvalidCredentials) => { + AppError::Unauthorized("Unauthorized".into()) + } + AuthError::Bearer(BearerError::Repository(error)) => error.into(), + } } } -#[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)); +impl IntoResponse for AuthError { + fn into_response(self) -> axum::response::Response { + AppError::from(self).into_response() } } + +trait AuthScheme { + const SCHEME: &'static str; + + type Credentials: Send; + type Error: Into; + + fn credentials(token: &str) -> Result; +} + +trait Authorizer: AuthScheme { + fn authorize( + credentials: Self::Credentials, + state: &S, + ) -> impl Future> + Send; +} diff --git a/server/src/routes/extractors/auth/bearer.rs b/server/src/routes/extractors/auth/bearer.rs new file mode 100644 index 0000000..8b872f3 --- /dev/null +++ b/server/src/routes/extractors/auth/bearer.rs @@ -0,0 +1,52 @@ +use axum::extract::FromRef; +use sqlx::PgPool; + +use super::{AuthScheme, Authorizer}; +use crate::{ + crypto::hash_secret, + repository::{self, RepositoryError}, +}; + +#[derive(Debug)] +pub struct Bearer; + +impl AuthScheme for Bearer { + const SCHEME: &'static str = "Bearer"; + + type Credentials = String; + type Error = BearerError; + + fn credentials(token: &str) -> Result { + Ok(token.to_string()) + } +} + +impl Authorizer for Bearer +where + PgPool: FromRef, + S: Send + Sync, +{ + async fn authorize( + credentials: Self::Credentials, + state: &S, + ) -> Result { + let pool = PgPool::from_ref(state); + + let token_hash = hash_secret(&credentials); + let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash) + .await + .map_err(|error| BearerError::Repository(error))? + .ok_or(BearerError::InvalidCredentials)?; + + Ok(crate::domain::Authorization::new(token.user_id)) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum BearerError { + #[error("invalid credentials")] + InvalidCredentials, + + #[error(transparent)] + Repository(#[from] RepositoryError), +} diff --git a/server/src/routes/extractors/auth/header.rs b/server/src/routes/extractors/auth/header.rs new file mode 100644 index 0000000..531ba26 --- /dev/null +++ b/server/src/routes/extractors/auth/header.rs @@ -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 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 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 + )); + } +}