LCOV - code coverage report
Current view: top level - compute_tools/src/http/middleware - authorize.rs (source / functions) Coverage Total Hit
Test: aca806cab4756d7eb6a304846130f4a73a5d5393.info Lines: 0.0 % 69 0
Test Date: 2025-04-24 20:31:15 Functions: 0.0 % 5 0

            Line data    Source code
       1              : use std::collections::HashSet;
       2              : 
       3              : use anyhow::{Result, anyhow};
       4              : use axum::{RequestExt, body::Body};
       5              : use axum_extra::{
       6              :     TypedHeader,
       7              :     headers::{Authorization, authorization::Bearer},
       8              : };
       9              : use compute_api::requests::ComputeClaims;
      10              : use futures::future::BoxFuture;
      11              : use http::{Request, Response, StatusCode};
      12              : use jsonwebtoken::{Algorithm, DecodingKey, TokenData, Validation, jwk::JwkSet};
      13              : use tower_http::auth::AsyncAuthorizeRequest;
      14              : use tracing::{debug, warn};
      15              : 
      16              : use crate::http::JsonResponse;
      17              : 
      18              : #[derive(Clone, Debug)]
      19              : pub(in crate::http) struct Authorize {
      20              :     compute_id: String,
      21              :     jwks: JwkSet,
      22              :     validation: Validation,
      23              : }
      24              : 
      25              : impl Authorize {
      26            0 :     pub fn new(compute_id: String, jwks: JwkSet) -> Self {
      27            0 :         let mut validation = Validation::new(Algorithm::EdDSA);
      28            0 :         // Nothing is currently required
      29            0 :         validation.required_spec_claims = HashSet::new();
      30            0 :         validation.validate_exp = true;
      31            0 :         // Unused by the control plane
      32            0 :         validation.validate_aud = false;
      33            0 :         // Unused by the control plane
      34            0 :         validation.validate_nbf = false;
      35            0 : 
      36            0 :         Self {
      37            0 :             compute_id,
      38            0 :             jwks,
      39            0 :             validation,
      40            0 :         }
      41            0 :     }
      42              : }
      43              : 
      44              : impl AsyncAuthorizeRequest<Body> for Authorize {
      45              :     type RequestBody = Body;
      46              :     type ResponseBody = Body;
      47              :     type Future = BoxFuture<'static, Result<Request<Body>, Response<Self::ResponseBody>>>;
      48              : 
      49            0 :     fn authorize(&mut self, mut request: Request<Body>) -> Self::Future {
      50            0 :         let compute_id = self.compute_id.clone();
      51            0 :         let jwks = self.jwks.clone();
      52            0 :         let validation = self.validation.clone();
      53            0 : 
      54            0 :         Box::pin(async move {
      55            0 :             let TypedHeader(Authorization(bearer)) = request
      56            0 :                 .extract_parts::<TypedHeader<Authorization<Bearer>>>()
      57            0 :                 .await
      58            0 :                 .map_err(|_| {
      59            0 :                     JsonResponse::error(StatusCode::BAD_REQUEST, "invalid authorization token")
      60            0 :                 })?;
      61              : 
      62            0 :             let data = match Self::verify(&jwks, bearer.token(), &validation) {
      63            0 :                 Ok(claims) => claims,
      64            0 :                 Err(e) => return Err(JsonResponse::error(StatusCode::UNAUTHORIZED, e)),
      65              :             };
      66              : 
      67            0 :             if data.claims.compute_id != compute_id {
      68            0 :                 return Err(JsonResponse::error(
      69            0 :                     StatusCode::UNAUTHORIZED,
      70            0 :                     "invalid compute ID in authorization token claims",
      71            0 :                 ));
      72            0 :             }
      73            0 : 
      74            0 :             // Make claims available to any subsequent middleware or request
      75            0 :             // handlers
      76            0 :             request.extensions_mut().insert(data.claims);
      77            0 : 
      78            0 :             Ok(request)
      79            0 :         })
      80            0 :     }
      81              : }
      82              : 
      83              : impl Authorize {
      84              :     /// Verify the token using the JSON Web Key set and return the token data.
      85            0 :     fn verify(
      86            0 :         jwks: &JwkSet,
      87            0 :         token: &str,
      88            0 :         validation: &Validation,
      89            0 :     ) -> Result<TokenData<ComputeClaims>> {
      90            0 :         debug_assert!(!jwks.keys.is_empty());
      91              : 
      92            0 :         debug!("verifying token {}", token);
      93              : 
      94            0 :         for jwk in jwks.keys.iter() {
      95            0 :             let decoding_key = match DecodingKey::from_jwk(jwk) {
      96            0 :                 Ok(key) => key,
      97            0 :                 Err(e) => {
      98            0 :                     warn!(
      99            0 :                         "failed to construct decoding key from {}: {}",
     100            0 :                         jwk.common.key_id.as_ref().unwrap(),
     101              :                         e
     102              :                     );
     103              : 
     104            0 :                     continue;
     105              :                 }
     106              :             };
     107              : 
     108            0 :             match jsonwebtoken::decode::<ComputeClaims>(token, &decoding_key, validation) {
     109            0 :                 Ok(data) => return Ok(data),
     110            0 :                 Err(e) => {
     111            0 :                     warn!(
     112            0 :                         "failed to decode authorization token using {}: {}",
     113            0 :                         jwk.common.key_id.as_ref().unwrap(),
     114              :                         e
     115              :                     );
     116              : 
     117            0 :                     continue;
     118              :                 }
     119              :             }
     120              :         }
     121              : 
     122            0 :         Err(anyhow!("failed to verify authorization token"))
     123            0 :     }
     124              : }
        

Generated by: LCOV version 2.1-beta