Line data Source code
1 : use anyhow::{Result, anyhow};
2 : use axum::{RequestExt, body::Body};
3 : use axum_extra::{
4 : TypedHeader,
5 : headers::{Authorization, authorization::Bearer},
6 : };
7 : use compute_api::requests::{COMPUTE_AUDIENCE, ComputeClaims, ComputeClaimsScope};
8 : use futures::future::BoxFuture;
9 : use http::{Request, Response, StatusCode};
10 : use jsonwebtoken::{Algorithm, DecodingKey, TokenData, Validation, jwk::JwkSet};
11 : use tower_http::auth::AsyncAuthorizeRequest;
12 : use tracing::{debug, warn};
13 :
14 : use crate::http::JsonResponse;
15 :
16 : #[derive(Clone, Debug)]
17 : pub(in crate::http) struct Authorize {
18 : compute_id: String,
19 : jwks: JwkSet,
20 : validation: Validation,
21 : }
22 :
23 : impl Authorize {
24 0 : pub fn new(compute_id: String, jwks: JwkSet) -> Self {
25 0 : let mut validation = Validation::new(Algorithm::EdDSA);
26 0 : validation.validate_exp = true;
27 : // Unused by the control plane
28 0 : validation.validate_nbf = false;
29 : // Unused by the control plane
30 0 : validation.validate_aud = false;
31 0 : validation.set_audience(&[COMPUTE_AUDIENCE]);
32 : // Nothing is currently required
33 0 : validation.set_required_spec_claims(&[] as &[&str; 0]);
34 :
35 0 : Self {
36 0 : compute_id,
37 0 : jwks,
38 0 : validation,
39 0 : }
40 0 : }
41 : }
42 :
43 : impl AsyncAuthorizeRequest<Body> for Authorize {
44 : type RequestBody = Body;
45 : type ResponseBody = Body;
46 : type Future = BoxFuture<'static, Result<Request<Body>, Response<Self::ResponseBody>>>;
47 :
48 0 : fn authorize(&mut self, mut request: Request<Body>) -> Self::Future {
49 0 : let compute_id = self.compute_id.clone();
50 0 : let jwks = self.jwks.clone();
51 0 : let validation = self.validation.clone();
52 :
53 0 : Box::pin(async move {
54 0 : let TypedHeader(Authorization(bearer)) = request
55 0 : .extract_parts::<TypedHeader<Authorization<Bearer>>>()
56 0 : .await
57 0 : .map_err(|_| {
58 0 : JsonResponse::error(StatusCode::BAD_REQUEST, "invalid authorization token")
59 0 : })?;
60 :
61 0 : let data = match Self::verify(&jwks, bearer.token(), &validation) {
62 0 : Ok(claims) => claims,
63 0 : Err(e) => return Err(JsonResponse::error(StatusCode::UNAUTHORIZED, e)),
64 : };
65 :
66 0 : match data.claims.scope {
67 : // TODO: We should validate audience for every token, but
68 : // instead of this ad-hoc validation, we should turn
69 : // [`Validation::validate_aud`] on. This is merely a stopgap
70 : // while we roll out `aud` deployment. We return a 401
71 : // Unauthorized because when we eventually do use
72 : // [`Validation`], we will hit the above `Err` match arm which
73 : // returns 401 Unauthorized.
74 : Some(ComputeClaimsScope::Admin) => {
75 0 : let Some(ref audience) = data.claims.audience else {
76 0 : return Err(JsonResponse::error(
77 0 : StatusCode::UNAUTHORIZED,
78 0 : "missing audience in authorization token claims",
79 0 : ));
80 : };
81 :
82 0 : if !audience.iter().any(|a| a == COMPUTE_AUDIENCE) {
83 0 : return Err(JsonResponse::error(
84 0 : StatusCode::UNAUTHORIZED,
85 0 : "invalid audience in authorization token claims",
86 0 : ));
87 0 : }
88 : }
89 :
90 : // If the scope is not [`ComputeClaimsScope::Admin`], then we
91 : // must validate the compute_id
92 : _ => {
93 0 : let Some(ref claimed_compute_id) = data.claims.compute_id else {
94 0 : return Err(JsonResponse::error(
95 0 : StatusCode::FORBIDDEN,
96 0 : "missing compute_id in authorization token claims",
97 0 : ));
98 : };
99 :
100 0 : if *claimed_compute_id != compute_id {
101 0 : return Err(JsonResponse::error(
102 0 : StatusCode::FORBIDDEN,
103 0 : "invalid compute ID in authorization token claims",
104 0 : ));
105 0 : }
106 : }
107 : }
108 :
109 : // Make claims available to any subsequent middleware or request
110 : // handlers
111 0 : request.extensions_mut().insert(data.claims);
112 :
113 0 : Ok(request)
114 0 : })
115 0 : }
116 : }
117 :
118 : impl Authorize {
119 : /// Verify the token using the JSON Web Key set and return the token data.
120 0 : fn verify(
121 0 : jwks: &JwkSet,
122 0 : token: &str,
123 0 : validation: &Validation,
124 0 : ) -> Result<TokenData<ComputeClaims>> {
125 0 : debug_assert!(!jwks.keys.is_empty());
126 :
127 0 : debug!("verifying token {}", token);
128 :
129 0 : for jwk in jwks.keys.iter() {
130 0 : let decoding_key = match DecodingKey::from_jwk(jwk) {
131 0 : Ok(key) => key,
132 0 : Err(e) => {
133 0 : warn!(
134 0 : "failed to construct decoding key from {}: {}",
135 0 : jwk.common.key_id.as_ref().unwrap(),
136 : e
137 : );
138 :
139 0 : continue;
140 : }
141 : };
142 :
143 0 : match jsonwebtoken::decode::<ComputeClaims>(token, &decoding_key, validation) {
144 0 : Ok(data) => return Ok(data),
145 0 : Err(e) => {
146 0 : warn!(
147 0 : "failed to decode authorization token using {}: {}",
148 0 : jwk.common.key_id.as_ref().unwrap(),
149 : e
150 : );
151 :
152 0 : continue;
153 : }
154 : }
155 : }
156 :
157 0 : Err(anyhow!("failed to verify authorization token"))
158 0 : }
159 : }
|