use std::sync::Arc;
use poem::{IntoResponse, Request, RequestBody, http::StatusCode};
use poem_openapi::{
ApiExtractor, ApiExtractorType, ExtractParamOptions, SecurityScheme, auth::Bearer,
payload::Json, registry::Registry,
};
use puerto_core::{AuthError, Authenticator, Principal};
use crate::ErrorResponse;
pub const UNAUTHENTICATED: &str = "auth.unauthenticated";
pub const FORBIDDEN: &str = "auth.forbidden";
pub const UNAVAILABLE: &str = "auth.unavailable";
pub const NOT_CONFIGURED: &str = "auth.not_configured";
pub struct BearerAuth(pub Principal);
#[derive(SecurityScheme)]
#[oai(rename = "BearerAuth", ty = "bearer", bearer_format = "opaque or JWT")]
struct BearerScheme(Bearer);
impl<'a> ApiExtractor<'a> for BearerAuth {
const TYPES: &'static [ApiExtractorType] = &[ApiExtractorType::SecurityScheme];
type ParamType = ();
type ParamRawType = ();
fn register(registry: &mut Registry) {
BearerScheme::register(registry);
}
fn security_schemes() -> Vec<&'static str> {
BearerScheme::security_schemes()
}
async fn from_request(
req: &'a Request,
body: &mut RequestBody,
param_opts: ExtractParamOptions<Self::ParamType>,
) -> poem::Result<Self> {
let token = BearerScheme::from_request(req, body, param_opts)
.await
.map_err(|_| {
error(
StatusCode::UNAUTHORIZED,
ErrorResponse::from_code(UNAUTHENTICATED),
)
})?
.0
.token;
let Some(authenticator) = req.data::<Arc<dyn Authenticator>>() else {
tracing::error!("BearerAuth: no Authenticator registered on the routes");
return Err(error(
StatusCode::INTERNAL_SERVER_ERROR,
ErrorResponse {
name: NOT_CONFIGURED.into(),
message: "no Authenticator is registered on the routes: bootstrap.rs must add \
`.data(authenticator)` with an `Arc<dyn Authenticator>`"
.into(),
},
));
};
authenticator
.authenticate(&token)
.await
.map(Self)
.map_err(|err| {
let (status, body) = rejection(err);
error(status, body.0)
})
}
}
pub fn rejection(err: AuthError) -> (StatusCode, Json<ErrorResponse>) {
match err {
AuthError::Unavailable => {
tracing::warn!(error = %err, "BearerAuth: the token could not be checked");
(
StatusCode::SERVICE_UNAVAILABLE,
Json(ErrorResponse::from_code(UNAVAILABLE)),
)
}
_ => (
StatusCode::UNAUTHORIZED,
Json(ErrorResponse::from_code(UNAUTHENTICATED)),
),
}
}
pub fn forbidden() -> (StatusCode, Json<ErrorResponse>) {
(
StatusCode::FORBIDDEN,
Json(ErrorResponse::from_code(FORBIDDEN)),
)
}
pub fn bearer_token(req: &poem::Request) -> Option<&str> {
let (scheme, token) = req.header("Authorization")?.split_once(' ')?;
let token = token.trim();
(scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token)
}
fn error(status: StatusCode, body: ErrorResponse) -> poem::Error {
let mut response = Json(body).into_response();
response.set_status(status);
poem::Error::from_response(response)
}
#[cfg(test)]
mod tests {
use super::*;
fn request(authorization: Option<&str>) -> poem::Request {
let builder = poem::Request::builder();
match authorization {
Some(value) => builder.header("Authorization", value).finish(),
None => builder.finish(),
}
}
#[test]
fn should_read_the_bearer_token_whatever_the_scheme_case() {
assert_eq!(bearer_token(&request(Some("Bearer abc"))), Some("abc"));
assert_eq!(bearer_token(&request(Some("bearer abc "))), Some("abc"));
}
#[test]
fn should_read_no_token_when_there_is_no_bearer_one() {
assert_eq!(bearer_token(&request(None)), None);
assert_eq!(bearer_token(&request(Some("Basic abc"))), None);
assert_eq!(bearer_token(&request(Some("Bearer "))), None);
assert_eq!(bearer_token(&request(Some("Bearer"))), None);
}
#[test]
fn should_answer_401_unauthenticated_when_the_token_is_invalid() {
let (status, body) = rejection(AuthError::Invalid);
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body.0.name, "auth.unauthenticated");
}
#[test]
fn should_answer_401_unauthenticated_when_the_token_expired() {
let (status, body) = rejection(AuthError::Expired);
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body.0.name, "auth.unauthenticated");
}
#[test]
fn should_answer_503_unavailable_when_the_token_cannot_be_checked() {
let (status, body) = rejection(AuthError::Unavailable);
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(body.0.name, "auth.unavailable");
}
#[test]
fn should_answer_403_forbidden_when_a_role_is_missing() {
let (status, body) = forbidden();
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body.0.name, "auth.forbidden");
assert_eq!(body.0.message, "auth.forbidden");
}
}