Skip to main content

adk_auth/web_bot_auth/
keys.rs

1//! Ed25519 keys, JWK thumbprints and the key directory document. Spec 3.5 §7.3.
2//!
3//! A key directory is a JSON Web Key Set ([RFC 7517] §5) of OKP keys ([RFC 8037]) served at
4//! `/.well-known/http-message-signatures-directory` (draft-ietf-webbotauth-httpsig-protocol-00
5//! §5.5; draft-meunier-http-message-signatures-directory-05 §3). A signature's `keyid` is the key's
6//! JWK SHA-256 thumbprint ([RFC 7638] §3.2, [RFC 8037] Appendix A.3).
7//!
8//! [RFC 7517]: https://www.rfc-editor.org/rfc/rfc7517
9//! [RFC 7638]: https://www.rfc-editor.org/rfc/rfc7638
10//! [RFC 8037]: https://www.rfc-editor.org/rfc/rfc8037
11
12use 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
25/// The public half of the RFC 9421 Appendix B.1.4 test key, which verifiers reject by default
26/// (draft §6.8).
27pub(crate) const RFC9421_TEST_KEY_X: &str = "JrQLj5P_89iXES9-vFgrIy29clF9CC_oPPsw3c5D0bs";
28
29/// The JWK SHA-256 thumbprint of an Ed25519 public key (RFC 7638 §3.2, RFC 8037 Appendix A.3),
30/// base64url without padding. Web Bot Auth uses it as the signature's `keyid`.
31///
32/// # Example
33///
34/// ```rust
35/// use adk_auth::web_bot_auth::jwk_thumbprint;
36/// use base64::Engine;
37///
38/// // RFC 8037 Appendix A.3.
39/// let x = base64::engine::general_purpose::URL_SAFE_NO_PAD
40///     .decode("11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo")
41///     .unwrap();
42/// assert_eq!(jwk_thumbprint(&x.try_into().unwrap()), "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k");
43/// ```
44pub 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
50/// Verifies an Ed25519 signature (RFC 8032 §5.1.7, RFC 9421 §3.3.6).
51pub(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
55/// An Ed25519 signing key held in memory, its seed zeroised on drop.
56///
57/// Signing uses `aws-lc-rs`, as the signed audit log does. `Debug` never prints the seed.
58///
59/// # Example
60///
61/// ```rust
62/// use adk_auth::web_bot_auth::Ed25519SigningKey;
63///
64/// let key = Ed25519SigningKey::generate().unwrap();
65/// let restored = Ed25519SigningKey::from_jwk(&key.to_private_jwk()).unwrap();
66/// assert_eq!(restored.thumbprint(), key.thumbprint());
67/// assert!(!format!("{key:?}").contains(&*key.to_private_jwk()));
68/// ```
69pub 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    /// Creates a key from its 32-byte seed (the RFC 8032 private key).
86    ///
87    /// # Errors
88    ///
89    /// Returns [`WebBotAuthError::InvalidKey`] when the seed is rejected.
90    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    /// Generates a key from the system's secure random source.
102    ///
103    /// # Errors
104    ///
105    /// Returns [`WebBotAuthError::InvalidKey`] when no randomness is available.
106    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    /// Reads a private OKP JWK (`kty` `OKP`, `crv` `Ed25519`, `d`, and `x` when present).
114    ///
115    /// # Errors
116    ///
117    /// Returns [`WebBotAuthError::InvalidKey`] when the JWK is not an Ed25519 private key or its
118    /// `x` does not match `d`.
119    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    /// The private JWK, with `kid` set to the thumbprint. Store it as a secret.
150    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    /// The raw public key.
161    pub fn public_key(&self) -> &[u8; 32] {
162        &self.public_key
163    }
164
165    /// The JWK thumbprint, used as `keyid`.
166    pub fn thumbprint(&self) -> &str {
167        &self.thumbprint
168    }
169
170    /// The public JWK as a directory publishes it: `kid` is the thumbprint and `use` is `sig`.
171    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    /// Signs `message` with Ed25519 (RFC 9421 §3.3.6).
185    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/// One Ed25519 public key in a key directory: an OKP JWK (RFC 7517, RFC 8037).
193///
194/// `nbf` and `exp` bound the key's validity. They are read as Unix seconds; values of
195/// 10^11 and above are read as milliseconds, as deployed directories publish them.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct DirectoryKey {
198    /// Key type: `OKP`.
199    pub kty: String,
200    /// Curve: `Ed25519`.
201    pub crv: String,
202    /// Key id; when present it is the thumbprint (draft §5.5).
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub kid: Option<String>,
205    /// The public key, base64url.
206    pub x: String,
207    /// Intended use: `sig`.
208    #[serde(rename = "use", default, skip_serializing_if = "Option::is_none")]
209    pub key_use: Option<String>,
210    /// Algorithm, restricted to HTTP signature algorithm names.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub alg: Option<String>,
213    /// Not valid before.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub nbf: Option<i64>,
216    /// Not valid after.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub exp: Option<i64>,
219}
220
221impl DirectoryKey {
222    /// The raw public key.
223    ///
224    /// # Errors
225    ///
226    /// Returns [`WebBotAuthError::InvalidKey`] when this is not an Ed25519 key with a 32-byte `x`.
227    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    /// The key's JWK thumbprint, computed from `x` (never taken from `kid`).
242    ///
243    /// # Errors
244    ///
245    /// Returns [`WebBotAuthError::InvalidKey`] when the key is malformed.
246    pub fn thumbprint(&self) -> Result<String, WebBotAuthError> {
247        self.public_key().map(|key| jwk_thumbprint(&key))
248    }
249
250    /// Whether the key's `nbf`/`exp` window includes `now` (Unix seconds).
251    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/// A key directory document: a JWKS of Ed25519 keys (draft §5.5.1).
259///
260/// # Example
261///
262/// ```rust
263/// use adk_auth::web_bot_auth::{Ed25519SigningKey, KeyDirectory};
264///
265/// let key = Ed25519SigningKey::generate().unwrap();
266/// let directory = KeyDirectory::from_keys([&key]);
267/// let parsed = KeyDirectory::parse(directory.to_json().as_bytes(), 16).unwrap();
268/// assert_eq!(parsed.find(key.thumbprint()).unwrap().x, directory.keys[0].x);
269/// ```
270#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
271pub struct KeyDirectory {
272    /// The keys.
273    pub keys: Vec<DirectoryKey>,
274}
275
276impl KeyDirectory {
277    /// The directory a site publishes for its own signing keys (spec 3.5 §7.3 "Outbound").
278    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    /// Parses a directory, keeping its well-formed Ed25519 keys and skipping other entries
283    /// (draft §5.5.1: verifiers reject malformed entries).
284    ///
285    /// An entry is skipped when it is not an OKP/Ed25519 key, its `x` is not 32 bytes, it
286    /// carries private material (`d`), its `use` is not `sig`, or its `alg` is not Ed25519.
287    ///
288    /// # Errors
289    ///
290    /// Returns a reason when the document is not a JWKS or lists more than `max_keys` entries.
291    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    /// The key whose computed thumbprint is `thumbprint`.
326    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    /// The JSON document, compact, members in the order `kty`, `crv`, `kid`, `x`, `use`.
331    pub fn to_json(&self) -> String {
332        serde_json::to_string(self).unwrap_or_else(|_| String::from(r#"{"keys":[]}"#))
333    }
334
335    /// The directory response with headers that prove possession of each key (draft
336    /// Appendix B.1): one signature per key over `@authority;req` (the authority the directory
337    /// was fetched from) and `content-digest`, tagged `http-message-signatures-directory`.
338    ///
339    /// Labels are `binding` for one key and `binding0`, `binding1`, … for several.
340    ///
341    /// # Errors
342    ///
343    /// Returns [`WebBotAuthError::InvalidConfig`] when `keys` is empty or `expires` precedes
344    /// `created`.
345    ///
346    /// # Example
347    ///
348    /// ```rust
349    /// use adk_auth::web_bot_auth::{Ed25519SigningKey, KeyDirectory};
350    ///
351    /// let key = Ed25519SigningKey::generate().unwrap();
352    /// let directory = KeyDirectory::from_keys([&key]);
353    /// let response = directory
354    ///     .signed_response(&[&key], "bot.example", 1_735_689_600, 1_735_776_000)
355    ///     .unwrap();
356    /// assert!(response.content_digest.starts_with("sha-256=:"));
357    /// assert!(response.signature_input.starts_with("binding=(\"@authority\";req \"content-digest\")"));
358    /// ```
359    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/// A directory response with its possession proof (draft Appendix B.1).
415///
416/// Serve `body` as `application/http-message-signatures-directory+json` with the
417/// `Content-Digest`, `Signature-Input` and `Signature` header values below.
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct DirectoryResponse {
420    /// The response body: the directory's JSON document.
421    pub body: String,
422    /// The `Content-Digest` value (RFC 9530): `sha-256=:<base64>:`.
423    pub content_digest: String,
424    /// The `Signature-Input` value.
425    pub signature_input: String,
426    /// The `Signature` value.
427    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}