1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
6use reqwest::Client;
7use serde::Deserialize;
8use tokio::sync::RwLock;
9use tracing::debug;
10
11use crate::config::Issuer;
12use crate::error::{Result, ServerError};
13
14const ALGORITHM_TABLE: &[(&str, Algorithm)] = &[
19 ("RS256", Algorithm::RS256),
20 ("RS384", Algorithm::RS384),
21 ("RS512", Algorithm::RS512),
22 ("PS256", Algorithm::PS256),
23 ("PS384", Algorithm::PS384),
24 ("PS512", Algorithm::PS512),
25 ("ES256", Algorithm::ES256),
26 ("ES384", Algorithm::ES384),
27 ("HS256", Algorithm::HS256),
28 ("HS384", Algorithm::HS384),
29 ("HS512", Algorithm::HS512),
30];
31
32fn parse_algorithm(s: &str) -> Option<Algorithm> {
33 ALGORITHM_TABLE
34 .iter()
35 .find(|(name, _)| *name == s)
36 .map(|(_, alg)| *alg)
37}
38
39#[derive(Debug, Clone)]
44pub struct Identity {
45 pub issuer: String,
46 pub org: String,
47 pub service: String,
48 pub env: String,
49 pub action: String,
50 pub branch: String,
51 pub actor: String,
52 pub groups: Vec<String>,
53 pub claims: HashMap<String, serde_json::Value>,
54}
55
56#[derive(Deserialize)]
61struct RawClaims {
62 iss: Option<String>,
63 sub: Option<String>,
64 aud: Option<Audience>,
65 exp: Option<u64>,
66 #[serde(flatten)]
67 extra: HashMap<String, serde_json::Value>,
68}
69
70#[derive(Deserialize, Clone)]
71#[serde(untagged)]
72enum Audience {
73 Single(String),
74 Multiple(Vec<String>),
75}
76
77impl RawClaims {
78 fn into_flat_map(self) -> HashMap<String, serde_json::Value> {
80 let mut m = self.extra;
81 if let Some(iss) = self.iss {
82 m.insert("iss".into(), serde_json::Value::String(iss));
83 }
84 if let Some(sub) = self.sub {
85 m.insert("sub".into(), serde_json::Value::String(sub));
86 }
87 if let Some(aud) = self.aud {
88 match aud {
89 Audience::Single(s) => {
90 m.insert("aud".into(), serde_json::Value::String(s));
91 }
92 Audience::Multiple(v) => {
93 m.insert(
94 "aud".into(),
95 serde_json::Value::Array(
96 v.into_iter().map(serde_json::Value::String).collect(),
97 ),
98 );
99 }
100 }
101 }
102 if let Some(exp) = self.exp {
103 m.insert(
104 "exp".into(),
105 serde_json::Value::Number(serde_json::Number::from(exp)),
106 );
107 }
108 m
109 }
110}
111
112#[derive(Clone)]
117struct CachedJwks {
118 keys: Vec<JwksKey>,
119 fetched_at: Instant,
120}
121
122#[derive(Deserialize, Clone)]
123#[allow(dead_code)]
124struct JwksKey {
125 kid: Option<String>,
126 kty: String,
127 alg: Option<String>,
128 n: Option<String>,
129 e: Option<String>,
130 x: Option<String>,
131 y: Option<String>,
132 crv: Option<String>,
133}
134
135#[derive(Deserialize)]
136struct JwksResponse {
137 keys: Vec<JwksKey>,
138}
139
140type JwksCache = Arc<RwLock<HashMap<String, CachedJwks>>>;
141
142const JWKS_TTL: Duration = Duration::from_secs(3600);
143
144async fn get_jwks_key(
145 cache: &JwksCache,
146 jwks_url: &str,
147 kid: &str,
148) -> Result<Option<(DecodingKey, Algorithm)>> {
149 {
151 let c = cache.read().await;
152 if let Some(cached) = c.get(jwks_url) {
153 if cached.fetched_at.elapsed() < JWKS_TTL {
154 if let Some(result) = find_key_in_jwks(&cached.keys, kid) {
155 return Ok(Some(result));
156 }
157 return Ok(None);
158 }
159 }
160 }
161
162 let client = Client::new();
164 let resp: JwksResponse = client
165 .get(jwks_url)
166 .send()
167 .await?
168 .json()
169 .await
170 .map_err(|e| ServerError::Jwt(format!("failed to parse JWKS: {e}")))?;
171
172 let result = find_key_in_jwks(&resp.keys, kid);
173
174 {
176 let mut c = cache.write().await;
177 c.insert(
178 jwks_url.to_string(),
179 CachedJwks {
180 keys: resp.keys,
181 fetched_at: Instant::now(),
182 },
183 );
184 }
185
186 Ok(result)
187}
188
189fn find_key_in_jwks(keys: &[JwksKey], kid: &str) -> Option<(DecodingKey, Algorithm)> {
190 let key = keys
191 .iter()
192 .find(|k| k.kid.as_deref() == Some(kid))?;
193
194 let alg = key
195 .alg
196 .as_deref()
197 .and_then(parse_algorithm)
198 .unwrap_or(Algorithm::RS256);
199
200 let decoding_key = match key.kty.as_str() {
201 "RSA" => {
202 let n = key.n.as_ref()?;
203 let e = key.e.as_ref()?;
204 DecodingKey::from_rsa_components(n, e).ok()?
205 }
206 "EC" => {
207 let x = key.x.as_ref()?;
208 let y = key.y.as_ref()?;
209 DecodingKey::from_ec_components(x, y).ok()?
210 }
211 _ => return None,
212 };
213
214 Some((decoding_key, alg))
215}
216
217pub struct JwtVerifier {
222 issuers: Vec<Issuer>,
223 jwks_cache: JwksCache,
224}
225
226impl JwtVerifier {
227 pub fn new(issuers: Vec<Issuer>) -> Self {
228 Self {
229 issuers,
230 jwks_cache: Arc::new(RwLock::new(HashMap::new())),
231 }
232 }
233
234 pub async fn verify(&self, token: &str) -> Result<Identity> {
235 let header = decode_header(token)?;
236 let kid = header.kid.unwrap_or_default();
237 let header_alg = header.alg;
238
239 for issuer in &self.issuers {
240 match self
241 .try_issuer(token, issuer, &kid, header_alg)
242 .await
243 {
244 Ok(Some(identity)) => return Ok(identity),
245 Ok(None) => continue,
246 Err(e) => return Err(e),
247 }
248 }
249
250 Err(ServerError::Jwt("no matching issuer found".into()))
251 }
252
253 async fn try_issuer(
254 &self,
255 token: &str,
256 issuer: &Issuer,
257 kid: &str,
258 header_alg: Algorithm,
259 ) -> Result<Option<Identity>> {
260 if let Some(static_keys) = &issuer.static_keys {
262 for sk in static_keys {
263 if sk.kid != kid {
264 continue;
265 }
266 let alg = match parse_algorithm(&sk.alg) {
267 Some(a) => a,
268 None => continue,
269 };
270 if alg != header_alg {
271 continue;
272 }
273 let dk = decoding_key_from_pem(&sk.pem, alg)?;
274 match try_decode(token, &dk, alg, issuer) {
275 Ok(Some(claims)) => return Ok(Some(normalize(issuer, claims))),
276 Ok(None) => return Ok(None),
277 Err(e) => return Err(e),
278 }
279 }
280 }
281
282 if let Some(jwks_url) = &issuer.jwks_url {
284 if let Some((dk, alg)) =
285 get_jwks_key(&self.jwks_cache, jwks_url, kid).await?
286 {
287 match try_decode(token, &dk, alg, issuer) {
288 Ok(Some(claims)) => return Ok(Some(normalize(issuer, claims))),
289 Ok(None) => return Ok(None),
290 Err(e) => return Err(e),
291 }
292 }
293 }
294
295 Ok(None)
296 }
297}
298
299fn decoding_key_from_pem(pem: &str, alg: Algorithm) -> Result<DecodingKey> {
304 let pem_bytes = pem.as_bytes();
305 match alg {
306 Algorithm::ES256 | Algorithm::ES384 => DecodingKey::from_ec_pem(pem_bytes)
307 .map_err(|e| ServerError::Jwt(format!("invalid EC PEM: {e}"))),
308 Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
309 Ok(DecodingKey::from_secret(pem_bytes))
310 }
311 _ => DecodingKey::from_rsa_pem(pem_bytes)
312 .map_err(|e| ServerError::Jwt(format!("invalid RSA PEM: {e}"))),
313 }
314}
315
316fn try_decode(
323 token: &str,
324 key: &DecodingKey,
325 alg: Algorithm,
326 issuer: &Issuer,
327) -> Result<Option<HashMap<String, serde_json::Value>>> {
328 let mut validation = Validation::new(alg);
329 validation.validate_exp = true;
330 validation.set_issuer(&[&issuer.issuer_url]);
331
332 if let Some(ref aud) = issuer.audience {
333 validation.set_audience(&[aud]);
334 } else {
335 validation.validate_aud = false;
336 }
337
338 match decode::<RawClaims>(token, key, &validation) {
339 Ok(token_data) => Ok(Some(token_data.claims.into_flat_map())),
340 Err(e) => {
341 use jsonwebtoken::errors::ErrorKind;
342 match e.kind() {
343 ErrorKind::InvalidIssuer | ErrorKind::InvalidAudience => {
344 debug!(
345 issuer = issuer.name,
346 "issuer/audience mismatch, skipping"
347 );
348 Ok(None)
349 }
350 _ => Err(ServerError::Jwt(e.to_string())),
351 }
352 }
353 }
354}
355
356fn normalize(issuer: &Issuer, claims: HashMap<String, serde_json::Value>) -> Identity {
357 let map = issuer.effective_map();
358
359 let get_str = |field: &str| -> String {
360 map.get(field)
361 .and_then(|claim_name| claims.get(claim_name))
362 .and_then(|v| v.as_str())
363 .unwrap_or("")
364 .to_string()
365 };
366
367 let groups = map
368 .get("groups")
369 .and_then(|claim_name| claims.get(claim_name))
370 .map(|v| match v {
371 serde_json::Value::Array(arr) => arr
372 .iter()
373 .filter_map(|item| item.as_str().map(String::from))
374 .collect(),
375 serde_json::Value::String(s) => vec![s.clone()],
376 _ => vec![],
377 })
378 .unwrap_or_default();
379
380 Identity {
381 issuer: issuer.name.clone(),
382 org: get_str("org"),
383 service: get_str("service"),
384 env: get_str("env"),
385 action: get_str("action"),
386 branch: get_str("branch"),
387 actor: get_str("actor"),
388 groups,
389 claims,
390 }
391}