Skip to main content

ppoppo_token/
jwks.rs

1//! JWKS (JSON Web Key Set) — RFC 7517 + RFC 8037 OKP/Ed25519 publication.
2//!
3//! Phase 6/8 (RFC_2026-05-04_jwt-full-adoption §6.7 + §6.9). PAS publishes
4//! its trusted Ed25519 verification keys at `/.well-known/jwks.json`;
5//! consumers (chat-auth, ppoppo-pas-external SDK) fetch + cache to populate
6//! `KeySet`.
7//!
8//! ── Pure RFC 7517 design (no extension fields) ─────────────────────────
9//!
10//! No `status`, no `cache_ttl_seconds`. The rotation lifecycle is "key in
11//! JWKS = trusted; key removed = revoked", and TTL is communicated via
12//! the `Cache-Control: max-age=N` HTTP header. The result is consumable
13//! by any RFC 7517 library (`jsonwebtoken::jwk::JwkSet`, jose-jwk,
14//! python-jose, ...) — no ppoppo-specific knowledge required.
15//!
16//! ── Shape (RFC 8037 §2 for Ed25519) ─────────────────────────────────────
17//!
18//! ```json
19//! {
20//!   "keys": [
21//!     {"kty":"OKP","crv":"Ed25519","use":"sig","alg":"EdDSA","kid":"...","x":"<b64url(32B pubkey)>"}
22//!   ]
23//! }
24//! ```
25//!
26//! `kty=OKP` (Octet Key Pair, RFC 8037), `crv=Ed25519`, `alg=EdDSA`. The
27//! 32-byte public key is base64url-encoded without padding into `x`.
28//! `use=sig` (signature; RFC 7517 §4.2).
29
30use base64::Engine;
31use jsonwebtoken::DecodingKey;
32use serde::{Deserialize, Serialize};
33
34use crate::{Algorithm, KeySet};
35
36/// ASN.1 DER prefix for an Ed25519 SubjectPublicKeyInfo (RFC 8410 §4).
37/// Prepended to the raw 32-byte public key to form a 44-byte SPKI DER
38/// blob that `jsonwebtoken::DecodingKey::from_ed_der` consumes directly.
39///
40/// Bytes in plain English:
41/// - `30 2a` SEQUENCE, length 42
42/// - `30 05` SEQUENCE, length 5 (AlgorithmIdentifier)
43/// - `06 03 2b 65 70` OID 1.3.101.112 = id-Ed25519
44/// - `03 21 00` BIT STRING length 33, 0 unused bits
45const ED25519_SPKI_PREFIX: [u8; 12] = [
46    0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
47];
48
49/// JSON Web Key Set — collection of trusted public keys per RFC 7517 §5.
50///
51/// Equality + Clone derive enables ergonomic Arc-wrapping at the wiring
52/// site without polluting the public surface.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Jwks {
55    pub keys: Vec<Jwk>,
56}
57
58impl Jwks {
59    /// Build a JWKS from a slice of (kid, 32-byte Ed25519 public key)
60    /// tuples. Keys land in the order supplied — callers control which
61    /// keys appear (typically: filter Revoked at the call site, supply
62    /// Active + Retiring to the builder).
63    #[must_use]
64    pub fn from_ed25519_keys(keys: &[(&str, &[u8; 32])]) -> Self {
65        Self {
66            keys: keys.iter().map(|(kid, pk)| Jwk::ed25519(kid, pk)).collect(),
67        }
68    }
69
70    /// Find the key with the matching kid that satisfies `use=sig`.
71    /// Returns the 32-byte Ed25519 public key bytes when present and
72    /// well-formed; `None` for missing kid or wrong key type. Used by
73    /// consumer-side verification flows to bind a token's `kid` header
74    /// to a trusted public key.
75    #[must_use]
76    pub fn find_ed25519(&self, kid: &str) -> Option<[u8; 32]> {
77        let jwk = self.keys.iter().find(|k| k.kid == kid)?;
78        jwk.ed25519_bytes()
79    }
80
81    /// Convert the JWKS into the engine's `KeySet`. Every well-formed
82    /// `kty=OKP / crv=Ed25519` entry becomes a `(kid, DecodingKey)`
83    /// binding; entries with any other shape are silently skipped (the
84    /// engine cannot verify them anyway, and a future JWKS may legitimately
85    /// carry mixed key types — RSA for legacy clients, EC for some federated
86    /// IdP). The skip-or-fail tradeoff favours skip: a single malformed
87    /// entry must not break key rotation for the well-formed siblings.
88    ///
89    /// Returns `Err(JwksError::DuplicateKid)` only if two entries share a
90    /// kid — that is a control-plane bug (every kid is supposed to be
91    /// globally unique), and admitting both would create non-determinism
92    /// in `KeySet::get`.
93    pub fn into_key_set(self) -> Result<KeySet, JwksError> {
94        let mut key_set = KeySet::new();
95        let mut seen: std::collections::HashSet<String> = Default::default();
96        for jwk in self.keys {
97            let Some(pk_bytes) = jwk.ed25519_bytes() else {
98                continue;
99            };
100            if !seen.insert(jwk.kid.clone()) {
101                return Err(JwksError::DuplicateKid(jwk.kid));
102            }
103            let mut der = Vec::with_capacity(ED25519_SPKI_PREFIX.len() + pk_bytes.len());
104            der.extend_from_slice(&ED25519_SPKI_PREFIX);
105            der.extend_from_slice(&pk_bytes);
106            key_set.insert(jwk.kid, DecodingKey::from_ed_der(&der));
107        }
108        Ok(key_set)
109    }
110}
111
112/// JWKS-side errors surfaced to consumers of `into_key_set`.
113///
114/// Distinct from `AuthError` because this fires at *configuration* time
115/// (boot / cache refresh), not per-request verify time. Operators see
116/// these in startup logs; users never do.
117#[derive(Debug, thiserror::Error, PartialEq, Eq)]
118pub enum JwksError {
119    /// Two JWK entries share a kid. Engine refuses to insert both
120    /// because `KeySet::get` would be non-deterministic. Operator must
121    /// fix the upstream JWKS source.
122    #[error("duplicate kid in JWKS: '{0}'")]
123    DuplicateKid(String),
124}
125
126/// A single JWK entry. Pinned to the OKP/Ed25519/EdDSA shape — other
127/// `kty` values (`EC`, `RSA`, `oct`) deserialize but `ed25519_bytes()`
128/// returns `None` so the engine never accidentally accepts a non-Ed25519
129/// key.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct Jwk {
132    pub kty: String,
133    pub crv: String,
134    #[serde(rename = "use", default)]
135    pub use_: String,
136    pub alg: String,
137    pub kid: String,
138    pub x: String,
139}
140
141impl Jwk {
142    /// Construct an Ed25519 JWK from its raw 32-byte public key. The
143    /// `kty=OKP`, `crv=Ed25519`, `use=sig` fields are RFC 8037 §2 curve
144    /// facts (verbatim, independent of the JWS algorithm); `alg` projects
145    /// from [`Algorithm::as_jose_str`] so the JOSE `alg` string lives in one
146    /// place across the JWKS document and the discovery metadata.
147    #[must_use]
148    pub fn ed25519(kid: &str, public_key: &[u8; 32]) -> Self {
149        Self {
150            kty: "OKP".to_string(),
151            crv: "Ed25519".to_string(),
152            use_: "sig".to_string(),
153            alg: Algorithm::EdDSA.as_jose_str().to_string(),
154            kid: kid.to_string(),
155            x: base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public_key),
156        }
157    }
158
159    /// Decode the 32-byte Ed25519 public key carried in `x` when this
160    /// JWK is shaped as `kty=OKP / crv=Ed25519`. Returns `None` for any
161    /// other shape so consumers cannot accidentally feed a `kty=EC` or
162    /// `kty=RSA` key to an Ed25519 verifier.
163    #[must_use]
164    pub fn ed25519_bytes(&self) -> Option<[u8; 32]> {
165        if self.kty != "OKP" || self.crv != "Ed25519" {
166            return None;
167        }
168        let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
169            .decode(self.x.as_bytes())
170            .ok()?;
171        decoded.try_into().ok()
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
178    use super::*;
179
180    fn sample_pubkey() -> [u8; 32] {
181        // Deterministic test vector — first 32 bytes of a known Ed25519
182        // public key. Value is irrelevant to the codec test; we only
183        // care about round-trip fidelity.
184        let mut bytes = [0u8; 32];
185        for (i, b) in bytes.iter_mut().enumerate() {
186            *b = i as u8;
187        }
188        bytes
189    }
190
191    #[test]
192    fn ed25519_jwk_carries_rfc_8037_shape() {
193        let jwk = Jwk::ed25519("k4.pid.test", &sample_pubkey());
194        assert_eq!(jwk.kty, "OKP", "RFC 8037 §2: kty MUST be OKP for Ed25519");
195        assert_eq!(jwk.crv, "Ed25519");
196        assert_eq!(jwk.use_, "sig", "RFC 7517 §4.2: signature key");
197        assert_eq!(jwk.alg, "EdDSA", "RFC 8037 §3.1: alg = EdDSA");
198        assert_eq!(jwk.kid, "k4.pid.test");
199    }
200
201    #[test]
202    fn ed25519_x_round_trips_through_base64url() {
203        let pk = sample_pubkey();
204        let jwk = Jwk::ed25519("kid-1", &pk);
205        let recovered = jwk.ed25519_bytes().expect("must decode");
206        assert_eq!(recovered, pk, "x must round-trip the raw public key bytes");
207    }
208
209    #[test]
210    fn ed25519_x_is_base64url_no_pad() {
211        // RFC 7515 §2 + RFC 7518: JWK fields use base64url without
212        // padding. A `=` in the encoded form would be a wire-shape bug.
213        let jwk = Jwk::ed25519("k", &sample_pubkey());
214        assert!(
215            !jwk.x.contains('='),
216            "base64url MUST NOT carry padding: {}",
217            jwk.x
218        );
219        assert!(
220            !jwk.x.contains('+') && !jwk.x.contains('/'),
221            "base64url MUST NOT use std-b64 chars: {}",
222            jwk.x
223        );
224    }
225
226    #[test]
227    fn non_ed25519_kty_returns_none_from_bytes() {
228        // Belt-and-suspenders for the engine: even if a JWKS publishes
229        // an EC key with `x` carrying 32 bytes, ed25519_bytes refuses.
230        let mut jwk = Jwk::ed25519("kid", &sample_pubkey());
231        jwk.kty = "EC".to_string();
232        assert!(jwk.ed25519_bytes().is_none(), "non-OKP must return None");
233    }
234
235    #[test]
236    fn non_ed25519_crv_returns_none_from_bytes() {
237        let mut jwk = Jwk::ed25519("kid", &sample_pubkey());
238        jwk.crv = "X25519".to_string(); // OKP-but-key-agreement (RFC 8037 §3.2)
239        assert!(
240            jwk.ed25519_bytes().is_none(),
241            "X25519 is OKP but for ECDH, not signing — must return None",
242        );
243    }
244
245    #[test]
246    fn jwks_round_trips_through_json() {
247        let original =
248            Jwks::from_ed25519_keys(&[("kid-a", &sample_pubkey()), ("kid-b", &sample_pubkey())]);
249        let json = serde_json::to_string(&original).unwrap();
250        let parsed: Jwks = serde_json::from_str(&json).unwrap();
251        assert_eq!(parsed, original, "JWKS must serde round-trip");
252    }
253
254    #[test]
255    fn jwks_find_returns_matching_key() {
256        let pk = sample_pubkey();
257        let jwks = Jwks::from_ed25519_keys(&[("active-kid", &pk)]);
258        let found = jwks
259            .find_ed25519("active-kid")
260            .expect("active-kid must be findable");
261        assert_eq!(found, pk);
262    }
263
264    #[test]
265    fn jwks_find_returns_none_for_unknown_kid() {
266        let jwks = Jwks::from_ed25519_keys(&[("only-kid", &sample_pubkey())]);
267        assert!(jwks.find_ed25519("missing-kid").is_none());
268    }
269
270    #[test]
271    fn into_key_set_admits_well_formed_ed25519_entries() {
272        let jwks =
273            Jwks::from_ed25519_keys(&[("kid-a", &sample_pubkey()), ("kid-b", &sample_pubkey())]);
274        let key_set = jwks.into_key_set().expect("well-formed JWKS must convert");
275        // KeySet::get is pub(crate); we don't have direct visibility into
276        // its contents from here, but the absence of an error and the
277        // duplicate-kid guard fires only when entries land — so success
278        // here implies both entries inserted.
279        let _ = key_set;
280    }
281
282    #[test]
283    fn into_key_set_skips_non_ed25519_entries() {
284        // A JWKS legitimately may carry other key types in a federation
285        // scenario. ed25519_bytes returns None for them, so they get
286        // silently skipped. Test by hand-constructing an EC-shaped entry
287        // alongside a valid Ed25519 entry.
288        let pk = sample_pubkey();
289        let mut jwks = Jwks {
290            keys: vec![
291                Jwk::ed25519("ed-kid", &pk),
292                Jwk {
293                    kty: "EC".to_string(),
294                    crv: "P-256".to_string(),
295                    use_: "sig".to_string(),
296                    alg: "ES256".to_string(),
297                    kid: "ec-kid".to_string(),
298                    x: "irrelevant".to_string(),
299                },
300            ],
301        };
302        // Sanity: the EC entry would fail Ed25519 decode.
303        assert!(jwks.keys[1].ed25519_bytes().is_none());
304        // Conversion succeeds — only the Ed25519 entry lands in KeySet.
305        // (Non-Ed25519 silently skipped, no error.)
306        let _ = jwks.into_key_set().expect("mixed-type JWKS must convert");
307        // Add a duplicate to prove the dup-kid path is reachable.
308        jwks = Jwks::from_ed25519_keys(&[("dup", &pk), ("dup", &pk)]);
309        // KeySet doesn't impl Debug/PartialEq (it carries opaque
310        // DecodingKey values from jsonwebtoken), so we assert on the
311        // Err variant directly instead of through Result equality.
312        let err = jwks
313            .into_key_set()
314            .expect_err("duplicate kid must surface as Err");
315        assert_eq!(err, JwksError::DuplicateKid("dup".to_string()));
316    }
317
318    #[test]
319    fn into_key_set_round_trips_through_jwks_json_for_engine_verify() {
320        // End-to-end smoke: a real signing key's public half goes into a
321        // Jwks document, then comes back out as a KeySet that the engine
322        // can use to verify a token signed by the matching private half.
323        // This is the integration that 8.3 / 6.4 rely on.
324        use crate::SigningKey;
325        let (signer, _direct_key_set) = SigningKey::test_pair();
326
327        // Reach into the test_pair PEM constants and re-derive the public
328        // key bytes for the JWKS path. We use the documented test_pair
329        // public-key PEM (from signing_key.rs) — base64 of the SPKI DER's
330        // last 32 bytes.
331        const TEST_PUBLIC_KEY_DER_B64: &str =
332            "MCowBQYDK2VwAyEAh//e6j3It3xhjghg8Kpn2pM0jMCH/cvemGu4vv7D1Q4=";
333        use base64::Engine as _;
334        let der = base64::engine::general_purpose::STANDARD
335            .decode(TEST_PUBLIC_KEY_DER_B64)
336            .unwrap();
337        // Last 32 bytes of the 44-byte SPKI are the raw public key.
338        let pk_bytes: [u8; 32] = der[12..].try_into().unwrap();
339
340        let jwks = Jwks::from_ed25519_keys(&[(signer.kid(), &pk_bytes)]);
341        let _key_set = jwks.into_key_set().expect("well-formed JWKS must convert");
342        // A full sign-then-verify round-trip lives in tests/keyset_jwks.rs;
343        // here we only verify the conversion path itself.
344    }
345
346    #[test]
347    fn jwks_json_shape_is_rfc_7517_compliant() {
348        // Snapshot test — locks in the wire shape so a future refactor
349        // (e.g. swapping to a different serde struct) cannot silently
350        // drift to a non-standard shape.
351        let pk = sample_pubkey();
352        let jwks = Jwks::from_ed25519_keys(&[("test-kid", &pk)]);
353        let value: serde_json::Value = serde_json::to_value(&jwks).unwrap();
354        let key = &value["keys"][0];
355        assert_eq!(key["kty"], "OKP");
356        assert_eq!(key["crv"], "Ed25519");
357        assert_eq!(key["use"], "sig");
358        assert_eq!(key["alg"], "EdDSA");
359        assert_eq!(key["kid"], "test-kid");
360        assert!(key["x"].is_string());
361        // No status, no cache_ttl_seconds — those are out (deliberate).
362        assert!(value.get("cache_ttl_seconds").is_none());
363        assert!(key.get("status").is_none());
364    }
365}