1#[cfg(feature = "seal")]
5use aws_lc_rs::rsa::PublicKeyComponents;
6#[cfg(feature = "seal")]
7use aws_lc_rs::signature::{
8 ECDSA_P256_SHA256_FIXED, ED25519, RSA_PKCS1_2048_8192_SHA256, UnparsedPublicKey,
9};
10use base64::Engine;
11use base64::engine::general_purpose::URL_SAFE_NO_PAD;
12use oxabl_cache_format::audience::{Claim, issued_to};
13use serde_json::{Map, Value};
14
15pub const MAX_TOKEN_BYTES: usize = 16 * 1024;
17const MAX_KEYS: usize = 64;
19const MAX_MEMBERS: usize = 256;
21const SKEW_SECS: i64 = 60;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25enum Algorithm {
26 Rs256,
27 Es256,
28 EdDsa,
29}
30
31impl Algorithm {
32 fn parse(name: &str) -> Option<Self> {
33 match name {
34 "RS256" => Some(Self::Rs256),
35 "ES256" => Some(Self::Es256),
36 "EdDSA" => Some(Self::EdDsa),
37 _ => None,
38 }
39 }
40}
41
42#[derive(Debug, Clone)]
43enum Material {
44 Rsa { n: Vec<u8>, e: Vec<u8> },
45 Ec { point: Vec<u8> },
46 Ed { key: Vec<u8> },
47}
48
49#[derive(Debug, Clone)]
50struct Jwk {
51 kid: Option<String>,
52 alg: Option<String>,
53 material: Material,
54}
55
56#[derive(Debug, Clone)]
58pub struct KeySet(Vec<Jwk>);
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct SignedIn {
63 pub issuer: String,
64 pub subject: String,
65 pub claims: Vec<(String, String)>,
67 pub members: Vec<(String, String)>,
69}
70
71impl SignedIn {
72 pub fn claim(&self, name: &str) -> Option<&str> {
74 self.claims
75 .iter()
76 .find(|(claim, _)| claim == name)
77 .map(|(_, value)| value.as_str())
78 }
79
80 pub fn holds(&self, claim: &str, value: &str) -> bool {
82 self.claims
83 .iter()
84 .chain(&self.members)
85 .any(|(name, held)| name == claim && held == value)
86 }
87}
88
89fn b64(value: &Value, field: &str) -> Option<Vec<u8>> {
90 URL_SAFE_NO_PAD.decode(value.get(field)?.as_str()?).ok()
91}
92
93fn padded(bytes: Vec<u8>, width: usize) -> Option<Vec<u8>> {
94 (bytes.len() <= width).then(|| {
95 let mut out = vec![0u8; width - bytes.len()];
96 out.extend(bytes);
97 out
98 })
99}
100
101impl Jwk {
102 fn parse(value: &Value) -> Option<Self> {
103 if value.get("use").is_some_and(|usage| usage != "sig") {
104 return None;
105 }
106 let material = match value.get("kty")?.as_str()? {
107 "RSA" => {
108 let n = b64(value, "n")?;
109 let bits = n.iter().skip_while(|b| **b == 0).count() * 8;
110 if !(2048..=8192).contains(&bits) {
111 return None;
112 }
113 Material::Rsa {
114 n,
115 e: b64(value, "e")?,
116 }
117 }
118 "EC" if value.get("crv")? == "P-256" => {
119 let x = padded(b64(value, "x")?, 32)?;
120 let y = padded(b64(value, "y")?, 32)?;
121 Material::Ec {
122 point: [&[4u8][..], &x, &y].concat(),
123 }
124 }
125 "OKP" if value.get("crv")? == "Ed25519" => {
126 let key = b64(value, "x")?;
127 (key.len() == 32).then_some(Material::Ed { key })?
128 }
129 _ => return None,
130 };
131 Some(Self {
132 kid: value.get("kid").and_then(Value::as_str).map(str::to_owned),
133 alg: value.get("alg").and_then(Value::as_str).map(str::to_owned),
134 material,
135 })
136 }
137
138 fn fits(&self, algorithm: Algorithm) -> bool {
139 let family = matches!(
140 (&self.material, algorithm),
141 (Material::Rsa { .. }, Algorithm::Rs256)
142 | (Material::Ec { .. }, Algorithm::Es256)
143 | (Material::Ed { .. }, Algorithm::EdDsa)
144 );
145 let named = match &self.alg {
146 None => true,
147 Some(name) => Algorithm::parse(name) == Some(algorithm),
148 };
149 family && named
150 }
151
152 #[cfg(feature = "seal")]
153 fn verify(&self, message: &[u8], signature: &[u8]) -> bool {
154 match &self.material {
155 Material::Rsa { n, e } => PublicKeyComponents {
156 n: n.as_slice(),
157 e: e.as_slice(),
158 }
159 .verify(&RSA_PKCS1_2048_8192_SHA256, message, signature)
160 .is_ok(),
161 Material::Ec { point } => UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, point)
162 .verify(message, signature)
163 .is_ok(),
164 Material::Ed { key } => UnparsedPublicKey::new(&ED25519, key)
165 .verify(message, signature)
166 .is_ok(),
167 }
168 }
169
170 #[cfg(not(feature = "seal"))]
172 fn verify(&self, message: &[u8], signature: &[u8]) -> bool {
173 match &self.material {
174 Material::Rsa { n, e } => {
175 use rsa::pkcs1v15::{Signature, VerifyingKey};
176 use rsa::signature::Verifier;
177 let Ok(key) = rsa::RsaPublicKey::new_with_max_size(
178 rsa::BigUint::from_bytes_be(n),
179 rsa::BigUint::from_bytes_be(e),
180 8192,
181 ) else {
182 return false;
183 };
184 let Ok(signature) = Signature::try_from(signature) else {
185 return false;
186 };
187 VerifyingKey::<rsa::sha2::Sha256>::new(key)
188 .verify(message, &signature)
189 .is_ok()
190 }
191 Material::Ec { point } => {
192 use p256::ecdsa::signature::Verifier;
193 use p256::ecdsa::{Signature, VerifyingKey};
194 let Ok(key) = VerifyingKey::from_sec1_bytes(point) else {
195 return false;
196 };
197 let Ok(signature) = Signature::from_slice(signature) else {
198 return false;
199 };
200 key.verify(message, &signature).is_ok()
201 }
202 Material::Ed { key } => {
203 let Ok(key) = <[u8; 32]>::try_from(key.as_slice()) else {
204 return false;
205 };
206 let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(&key) else {
207 return false;
208 };
209 let Ok(signature) = ed25519_dalek::Signature::from_slice(signature) else {
210 return false;
211 };
212 key.verify_strict(message, &signature).is_ok()
213 }
214 }
215 }
216}
217
218impl KeySet {
219 pub fn parse(bytes: &[u8]) -> Option<Self> {
222 let document: Value = serde_json::from_slice(bytes).ok()?;
223 let keys = document.get("keys")?.as_array()?;
224 Some(Self(
225 keys.iter().take(MAX_KEYS).filter_map(Jwk::parse).collect(),
226 ))
227 }
228}
229
230fn object(segment: &str) -> Option<Map<String, Value>> {
231 match serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).ok()?).ok()? {
232 Value::Object(map) => Some(map),
233 _ => None,
234 }
235}
236
237fn seconds(claims: &Map<String, Value>, name: &str) -> Option<Option<i64>> {
238 match claims.get(name) {
239 None => Some(None),
240 Some(value) => value.as_i64().map(Some),
241 }
242}
243
244fn claim(value: Option<&Value>) -> Claim<'_> {
245 match value {
246 None => Claim::Absent,
247 Some(Value::String(text)) => Claim::String(text),
248 Some(Value::Array(list)) => list
249 .iter()
250 .map(Value::as_str)
251 .collect::<Option<Vec<_>>>()
252 .map_or(Claim::Other, Claim::Strings),
253 Some(_) => Claim::Other,
254 }
255}
256
257fn audience_is(claims: &Map<String, Value>, audience: &str) -> bool {
260 issued_to(&claim(claims.get("aud")), &claim(claims.get("azp")), |id| {
261 id == audience
262 })
263 .is_some()
264}
265
266fn scalars(claims: &Map<String, Value>) -> Vec<(String, String)> {
267 claims
268 .iter()
269 .filter(|(name, _)| !matches!(name.as_str(), "exp" | "nbf" | "iat" | "aud"))
270 .filter_map(|(name, value)| {
271 let text = match value {
272 Value::String(text) => text.clone(),
273 Value::Bool(flag) => flag.to_string(),
274 Value::Number(number) if number.is_i64() || number.is_u64() => number.to_string(),
275 _ => return None,
276 };
277 Some((name.clone(), text))
278 })
279 .collect()
280}
281
282fn members(claims: &Map<String, Value>) -> Vec<(String, String)> {
283 claims
284 .iter()
285 .filter(|(name, _)| name.as_str() != "aud")
286 .filter_map(|(name, value)| value.as_array().map(|list| (name, list)))
287 .flat_map(|(name, list)| {
288 list.iter()
289 .filter_map(Value::as_str)
290 .map(move |member| (name.clone(), member.to_owned()))
291 })
292 .take(MAX_MEMBERS)
293 .collect()
294}
295
296pub fn verify(
302 token: &str,
303 keys: &KeySet,
304 issuer: &str,
305 audience: &str,
306 now: i64,
307 max_age_secs: i64,
308) -> Result<SignedIn, &'static str> {
309 if token.len() > MAX_TOKEN_BYTES {
310 return Err("the token is too large");
311 }
312 let mut parts = token.split('.');
313 let (Some(header), Some(payload), Some(signature), None) =
314 (parts.next(), parts.next(), parts.next(), parts.next())
315 else {
316 return Err("not a signed token");
317 };
318 let header = object(header).ok_or("the header does not parse")?;
319 if header.contains_key("crit") {
320 return Err("the header has critical extensions");
321 }
322 let algorithm = header
323 .get("alg")
324 .and_then(Value::as_str)
325 .and_then(Algorithm::parse)
326 .ok_or("the algorithm is not RS256, ES256 or EdDSA")?;
327 let kid = match header.get("kid") {
328 None => None,
329 Some(Value::String(kid)) => Some(kid.as_str()),
330 Some(_) => return Err("the key id is not a string"),
331 };
332 let claims = object(payload).ok_or("the claims do not parse")?;
333 let signature = URL_SAFE_NO_PAD
334 .decode(signature)
335 .map_err(|_| "the signature does not parse")?;
336 let signed = &token[..token.len() - token.rsplit('.').next().map_or(0, str::len) - 1];
337 let fitting: Vec<&Jwk> = keys.0.iter().filter(|key| key.fits(algorithm)).collect();
338 let chosen: Vec<&Jwk> = match kid {
339 Some(kid) => fitting
340 .into_iter()
341 .filter(|key| key.kid.as_deref() == Some(kid))
342 .collect(),
343 None if fitting.len() == 1 => fitting,
344 None => Vec::new(),
345 };
346 if !chosen
347 .iter()
348 .any(|key| key.verify(signed.as_bytes(), &signature))
349 {
350 return Err("no key of the issuer signed it");
351 }
352 if claims.get("iss").and_then(Value::as_str) != Some(issuer) {
353 return Err("another issuer");
354 }
355 if !audience_is(&claims, audience) {
356 return Err("another audience");
357 }
358 let (Some(Some(iat)), Some(nbf)) = (seconds(&claims, "iat"), seconds(&claims, "nbf")) else {
359 return Err("the times do not parse");
360 };
361 let fresh = iat <= now + SKEW_SECS
362 && iat >= now.saturating_sub(max_age_secs)
363 && nbf.is_none_or(|nbf| nbf <= now + SKEW_SECS);
364 if !fresh {
365 return Err("signed too long ago, or in the future");
366 }
367 let subject = claims
368 .get("sub")
369 .and_then(Value::as_str)
370 .filter(|sub| !sub.is_empty())
371 .ok_or("no subject")?
372 .to_owned();
373 Ok(SignedIn {
374 issuer: issuer.to_owned(),
375 subject,
376 claims: scalars(&claims),
377 members: members(&claims),
378 })
379}