1use std::fmt;
13
14use aws_lc_rs::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
15use base64::Engine;
16use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use zeroize::Zeroizing;
20
21use super::message::{ComponentId, SignatureInput, signature_base};
22use super::structured::{BareItem, Dictionary, ListEntry};
23use super::{DIRECTORY_TAG, WebBotAuthError};
24
25pub(crate) const RFC9421_TEST_KEY_X: &str = "JrQLj5P_89iXES9-vFgrIy29clF9CC_oPPsw3c5D0bs";
28
29pub fn jwk_thumbprint(public_key: &[u8; 32]) -> String {
45 let canonical =
46 format!(r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, URL_SAFE_NO_PAD.encode(public_key));
47 URL_SAFE_NO_PAD.encode(Sha256::digest(canonical.as_bytes()))
48}
49
50pub(crate) fn verify_ed25519(public_key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool {
52 UnparsedPublicKey::new(&ED25519, public_key).verify(message, signature).is_ok()
53}
54
55pub struct Ed25519SigningKey {
70 seed: Zeroizing<[u8; 32]>,
71 key_pair: Ed25519KeyPair,
72 public_key: [u8; 32],
73 thumbprint: String,
74}
75
76impl fmt::Debug for Ed25519SigningKey {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.debug_struct("Ed25519SigningKey")
79 .field("thumbprint", &self.thumbprint)
80 .finish_non_exhaustive()
81 }
82}
83
84impl Ed25519SigningKey {
85 pub fn from_seed(seed: [u8; 32]) -> Result<Self, WebBotAuthError> {
91 let seed = Zeroizing::new(seed);
92 let key_pair = Ed25519KeyPair::from_seed_unchecked(seed.as_ref())
93 .map_err(|e| WebBotAuthError::InvalidKey { reason: e.to_string() })?;
94 let public_key: [u8; 32] = key_pair.public_key().as_ref().try_into().map_err(|_| {
95 WebBotAuthError::InvalidKey { reason: "public key is not 32 bytes".into() }
96 })?;
97 let thumbprint = jwk_thumbprint(&public_key);
98 Ok(Self { seed, key_pair, public_key, thumbprint })
99 }
100
101 pub fn generate() -> Result<Self, WebBotAuthError> {
107 let mut seed = Zeroizing::new([0u8; 32]);
108 aws_lc_rs::rand::fill(seed.as_mut())
109 .map_err(|_| WebBotAuthError::InvalidKey { reason: "no secure randomness".into() })?;
110 Self::from_seed(*seed)
111 }
112
113 pub fn from_jwk(jwk: &str) -> Result<Self, WebBotAuthError> {
120 #[derive(Deserialize)]
121 struct PrivateJwk {
122 kty: String,
123 crv: String,
124 x: Option<String>,
125 d: Option<String>,
126 }
127 let invalid = |reason: &str| WebBotAuthError::InvalidKey { reason: reason.to_string() };
128 let parsed: PrivateJwk =
129 serde_json::from_str(jwk).map_err(|_| invalid("the JWK is not an OKP JSON object"))?;
130 let d = Zeroizing::new(parsed.d.unwrap_or_default());
131 if parsed.kty != "OKP" || parsed.crv != "Ed25519" {
132 return Err(invalid("the JWK is not an OKP Ed25519 key"));
133 }
134 if d.is_empty() {
135 return Err(invalid("the JWK has no private `d` member"));
136 }
137 let seed = Zeroizing::new(
138 URL_SAFE_NO_PAD.decode(d.as_bytes()).map_err(|_| invalid("`d` is not base64url"))?,
139 );
140 let seed: [u8; 32] =
141 seed.as_slice().try_into().map_err(|_| invalid("`d` is not 32 bytes"))?;
142 let key = Self::from_seed(seed)?;
143 if parsed.x.is_some_and(|x| x != URL_SAFE_NO_PAD.encode(key.public_key)) {
144 return Err(invalid("`x` does not match `d`"));
145 }
146 Ok(key)
147 }
148
149 pub fn to_private_jwk(&self) -> Zeroizing<String> {
151 let d = Zeroizing::new(URL_SAFE_NO_PAD.encode(self.seed.as_ref()));
152 Zeroizing::new(format!(
153 r#"{{"kty":"OKP","crv":"Ed25519","kid":"{}","x":"{}","d":"{}"}}"#,
154 self.thumbprint,
155 URL_SAFE_NO_PAD.encode(self.public_key),
156 d.as_str()
157 ))
158 }
159
160 pub fn public_key(&self) -> &[u8; 32] {
162 &self.public_key
163 }
164
165 pub fn thumbprint(&self) -> &str {
167 &self.thumbprint
168 }
169
170 pub fn public_jwk(&self) -> DirectoryKey {
172 DirectoryKey {
173 kty: "OKP".to_string(),
174 crv: "Ed25519".to_string(),
175 kid: Some(self.thumbprint.clone()),
176 x: URL_SAFE_NO_PAD.encode(self.public_key),
177 key_use: Some("sig".to_string()),
178 alg: None,
179 nbf: None,
180 exp: None,
181 }
182 }
183
184 pub fn sign(&self, message: &[u8]) -> [u8; 64] {
186 let mut out = [0u8; 64];
187 out.copy_from_slice(self.key_pair.sign(message).as_ref());
188 out
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct DirectoryKey {
198 pub kty: String,
200 pub crv: String,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub kid: Option<String>,
205 pub x: String,
207 #[serde(rename = "use", default, skip_serializing_if = "Option::is_none")]
209 pub key_use: Option<String>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub alg: Option<String>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub nbf: Option<i64>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub exp: Option<i64>,
219}
220
221impl DirectoryKey {
222 pub fn public_key(&self) -> Result<[u8; 32], WebBotAuthError> {
228 if self.kty != "OKP" || self.crv != "Ed25519" {
229 return Err(WebBotAuthError::InvalidKey {
230 reason: format!("key type {}/{} is not OKP/Ed25519", self.kty, self.crv),
231 });
232 }
233 let bytes = URL_SAFE_NO_PAD
234 .decode(&self.x)
235 .map_err(|_| WebBotAuthError::InvalidKey { reason: "`x` is not base64url".into() })?;
236 bytes
237 .try_into()
238 .map_err(|_| WebBotAuthError::InvalidKey { reason: "`x` is not 32 bytes".into() })
239 }
240
241 pub fn thumbprint(&self) -> Result<String, WebBotAuthError> {
247 self.public_key().map(|key| jwk_thumbprint(&key))
248 }
249
250 pub fn is_current(&self, now: i64) -> bool {
252 let seconds = |value: i64| if value >= 100_000_000_000 { value / 1000 } else { value };
253 self.nbf.is_none_or(|nbf| now >= seconds(nbf))
254 && self.exp.is_none_or(|exp| now < seconds(exp))
255 }
256}
257
258#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
271pub struct KeyDirectory {
272 pub keys: Vec<DirectoryKey>,
274}
275
276impl KeyDirectory {
277 pub fn from_keys<'a>(keys: impl IntoIterator<Item = &'a Ed25519SigningKey>) -> Self {
279 Self { keys: keys.into_iter().map(Ed25519SigningKey::public_jwk).collect() }
280 }
281
282 pub fn parse(bytes: &[u8], max_keys: usize) -> Result<Self, String> {
292 #[derive(Deserialize)]
293 struct Raw {
294 keys: Vec<serde_json::Value>,
295 }
296 let raw: Raw = serde_json::from_slice(bytes)
297 .map_err(|e| format!("the document is not a JWKS: {e}"))?;
298 if raw.keys.len() > max_keys {
299 return Err(format!(
300 "it lists {} keys, more than the limit of {max_keys}",
301 raw.keys.len()
302 ));
303 }
304 let keys = raw
305 .keys
306 .into_iter()
307 .filter_map(|entry| {
308 if entry.get("d").is_some() {
309 tracing::warn!("key directory entry carries private key material; skipped");
310 return None;
311 }
312 let key: DirectoryKey = serde_json::from_value(entry).ok()?;
313 let usable = key.public_key().is_ok()
314 && key.key_use.as_deref().is_none_or(|u| u == "sig")
315 && key.alg.as_deref().is_none_or(|a| matches!(a, "ed25519" | "Ed25519" | "EdDSA"));
316 if !usable {
317 tracing::debug!(key.kty = %key.kty, "key directory entry is not a usable Ed25519 key; skipped");
318 }
319 usable.then_some(key)
320 })
321 .collect();
322 Ok(Self { keys })
323 }
324
325 pub fn find(&self, thumbprint: &str) -> Option<&DirectoryKey> {
327 self.keys.iter().find(|key| key.thumbprint().is_ok_and(|t| t == thumbprint))
328 }
329
330 pub fn to_json(&self) -> String {
332 serde_json::to_string(self).unwrap_or_else(|_| String::from(r#"{"keys":[]}"#))
333 }
334
335 pub fn signed_response(
360 &self,
361 keys: &[&Ed25519SigningKey],
362 authority: &str,
363 created: i64,
364 expires: i64,
365 ) -> Result<DirectoryResponse, WebBotAuthError> {
366 if keys.is_empty() || expires < created {
367 return Err(WebBotAuthError::InvalidConfig {
368 reason: "a directory proof needs at least one key and expires at or after created"
369 .into(),
370 });
371 }
372 let body = self.to_json();
373 let content_digest =
374 format!("sha-256=:{}:", STANDARD.encode(Sha256::digest(body.as_bytes())));
375 let authority = authority.to_ascii_lowercase();
376 let mut inputs = Dictionary::new();
377 let mut signatures = Dictionary::new();
378 for (index, key) in keys.iter().enumerate() {
379 let label =
380 if keys.len() == 1 { "binding".to_string() } else { format!("binding{index}") };
381 let mut input = SignatureInput::new(vec![
382 ComponentId::new("@authority").with_param("req", BareItem::Boolean(true)),
383 ComponentId::new("content-digest"),
384 ]);
385 input.params.insert("created", BareItem::Integer(created));
386 input.params.insert("expires", BareItem::Integer(expires));
387 input.params.insert("keyid", BareItem::String(key.thumbprint().to_string()));
388 input.params.insert("tag", BareItem::String(DIRECTORY_TAG.to_string()));
389 let base = signature_base(&input, |component| match component.name() {
390 "@authority" => Ok(authority.clone()),
391 _ => Ok(content_digest.clone()),
392 })?;
393 let signature = key.sign(base.as_bytes());
394 inputs.insert(label.clone(), ListEntry::InnerList(input.to_inner_list()));
395 signatures.insert(
396 label,
397 ListEntry::Item(super::structured::Item::new(BareItem::ByteSequence(
398 signature.to_vec(),
399 ))),
400 );
401 }
402 let serialize = |dict: Dictionary| {
403 dict.serialize().map_err(|e| WebBotAuthError::InvalidConfig { reason: e.to_string() })
404 };
405 Ok(DirectoryResponse {
406 body,
407 content_digest,
408 signature_input: serialize(inputs)?,
409 signature: serialize(signatures)?,
410 })
411 }
412}
413
414#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct DirectoryResponse {
420 pub body: String,
422 pub content_digest: String,
424 pub signature_input: String,
426 pub signature: String,
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 #[test]
435 fn key_validity_reads_seconds_and_milliseconds() {
436 let mut key = Ed25519SigningKey::generate().unwrap().public_jwk();
437 key.nbf = Some(1_743_465_600_000);
438 assert!(key.is_current(1_743_465_600));
439 assert!(!key.is_current(1_743_465_599));
440 key.nbf = Some(1_700_000_000);
441 key.exp = Some(1_800_000_000);
442 assert!(key.is_current(1_750_000_000));
443 assert!(!key.is_current(1_800_000_000));
444 }
445
446 #[test]
447 fn parse_skips_unusable_entries() {
448 let good = Ed25519SigningKey::generate().unwrap();
449 let doc = serde_json::json!({
450 "keys": [
451 {"kty": "RSA", "n": "abc", "e": "AQAB"},
452 {"kty": "OKP", "crv": "Ed25519", "x": "short"},
453 {"kty": "OKP", "crv": "Ed25519", "x": good.public_jwk().x, "d": "secret"},
454 {"kty": "OKP", "crv": "Ed25519", "x": good.public_jwk().x, "use": "enc"},
455 {"kty": "OKP", "crv": "Ed25519", "x": good.public_jwk().x, "alg": "ES256"},
456 good.public_jwk(),
457 ],
458 "purpose": "rag"
459 });
460 let parsed = KeyDirectory::parse(doc.to_string().as_bytes(), 16).unwrap();
461 assert_eq!(parsed.keys, vec![good.public_jwk()]);
462 assert!(KeyDirectory::parse(doc.to_string().as_bytes(), 3).is_err());
463 assert!(KeyDirectory::parse(b"[]", 3).is_err());
464 }
465
466 #[test]
467 fn from_jwk_rejects_mismatched_public_key() {
468 let a = Ed25519SigningKey::generate().unwrap();
469 let b = Ed25519SigningKey::generate().unwrap();
470 let mut jwk: serde_json::Value = serde_json::from_str(&a.to_private_jwk()).unwrap();
471 jwk["x"] = serde_json::Value::String(b.public_jwk().x);
472 assert!(Ed25519SigningKey::from_jwk(&jwk.to_string()).is_err());
473 assert!(Ed25519SigningKey::from_jwk(r#"{"kty":"OKP","crv":"Ed25519"}"#).is_err());
474 }
475
476 #[test]
477 fn signatures_verify() {
478 let key = Ed25519SigningKey::generate().unwrap();
479 let signature = key.sign(b"message");
480 assert!(verify_ed25519(key.public_key(), b"message", &signature));
481 assert!(!verify_ed25519(key.public_key(), b"other", &signature));
482 }
483}