|
| 1 | +// Copyright (c) 2025 Ronan LE MEILLAT, SCTG Development |
| 2 | +// This file is part of the rust-photoacoustic project and is licensed under the |
| 3 | +// SCTG Development Non-Commercial License v1.0 (see LICENSE.md for details). |
| 4 | + |
| 5 | +//! Rocket request guard for validating Bearer tokens using JwtValidator (HS256/RS256) |
| 6 | +
|
| 7 | +use rocket::http::Status; |
| 8 | +use rocket::request::{FromRequest, Outcome, Request}; |
| 9 | +use rocket::State; |
| 10 | +use crate::visualization::jwt::jwt_validator::{JwtValidator, UserInfo}; |
| 11 | +use crate::visualization::oidc_auth::OxideState; |
| 12 | +use base64::Engine; |
| 13 | + |
| 14 | +/// Request guard for extracting and validating a Bearer JWT from the Authorization header |
| 15 | +pub struct OAuthBearer(pub UserInfo); |
| 16 | + |
| 17 | +#[rocket::async_trait] |
| 18 | +impl<'r> FromRequest<'r> for OAuthBearer { |
| 19 | + type Error = (Status, &'static str); |
| 20 | + |
| 21 | + async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> { |
| 22 | + // Get the Authorization header |
| 23 | + let auth_header = request.headers().get_one("Authorization"); |
| 24 | + |
| 25 | + if let Some(header) = auth_header { |
| 26 | + if let Some(token) = header.strip_prefix("Bearer ") { |
| 27 | + // Get the OxideState from Rocket state |
| 28 | + let state = match request.guard::<&State<OxideState>>().await { |
| 29 | + Outcome::Success(state) => state, |
| 30 | + _ => return Outcome::Error((Status::InternalServerError,(Status::InternalServerError, "Missing state"))), |
| 31 | + }; |
| 32 | + // Build JwtValidator from state (supporting both HS256 and RS256) |
| 33 | + let hmac_secret = state.hmac_secret.as_bytes(); |
| 34 | + let rs256_public_key = if !state.rs256_public_key.is_empty() { |
| 35 | + base64::engine::general_purpose::STANDARD.decode(&state.rs256_public_key).ok() |
| 36 | + } else { |
| 37 | + None |
| 38 | + }; |
| 39 | + |
| 40 | + let mut validator = match rs256_public_key { |
| 41 | + Some(ref pem) => JwtValidator::new(Some(hmac_secret), Some(pem)), |
| 42 | + None => JwtValidator::new(Some(hmac_secret), None), |
| 43 | + }; |
| 44 | + match validator { |
| 45 | + Ok(validator) => { |
| 46 | + match validator.get_user_info(token) { |
| 47 | + Ok(user_info) => Outcome::Success(OAuthBearer(user_info)), |
| 48 | + Err(_) => Outcome::Error((Status::Unauthorized,(Status::Unauthorized, "Invalid token"))), |
| 49 | + } |
| 50 | + } |
| 51 | + Err(_) => Outcome::Error((Status::InternalServerError,(Status::InternalServerError, "Validator error"))), |
| 52 | + } |
| 53 | + } else { |
| 54 | + Outcome::Error((Status::Unauthorized,(Status::Unauthorized, "Missing Bearer token"))) |
| 55 | + } |
| 56 | + } else { |
| 57 | + Outcome::Error((Status::Unauthorized,(Status::Unauthorized, "Missing Authorization header"))) |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments