Skip to main content

hyprstream_rpc/auth/
jwt.rs

1//! JWT token implementation with Ed25519 (EdDSA) signatures.
2//!
3//! Implements a minimal JWT encoder/decoder for API authentication.
4//! Uses Ed25519 signatures for stateless token validation.
5//!
6//! # Token Format
7//!
8//! Standard RFC 7519 JWT:
9//! - Header: `{"alg":"EdDSA","typ":"JWT"}`
10//! - Payload: Claims (sub, exp, iat)
11//! - Signature: Ed25519 over `base64url(header).base64url(payload)`
12
13use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
14use chrono::Utc;
15use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
16use thiserror::Error;
17
18use super::Claims;
19
20/// The two exact access-token type forms resource servers must accept under
21/// RFC 9068 section 4. Matching is intentionally case- and whitespace-sensitive.
22pub const RFC9068_ACCESS_TOKEN_TYPES: &[&str] = &["at+jwt", "application/at+jwt"];
23
24/// Return whether `typ` is exactly one of the RFC 9068 access-token forms.
25pub fn is_rfc9068_access_token_type(typ: &str) -> bool {
26    RFC9068_ACCESS_TOKEN_TYPES.contains(&typ)
27}
28
29/// Duplicate-detecting, closed protected JOSE header used for security dispatch.
30#[derive(Clone, Debug, Eq, PartialEq)]
31pub struct ProtectedHeader {
32    pub alg: String,
33    pub typ: String,
34    pub kid: String,
35}
36
37/// Parser-produced dispatch for a composite JWT. Its fields are private so
38/// callers cannot supply metadata that disagrees with the signed header.
39#[derive(Clone, Debug)]
40pub struct CompositeJwtDispatch {
41    header: ProtectedHeader,
42    protected_b64: String,
43}
44
45impl CompositeJwtDispatch {
46    pub fn typ(&self) -> &str {
47        &self.header.typ
48    }
49    pub fn kid(&self) -> &str {
50        &self.header.kid
51    }
52}
53
54impl<'de> serde::Deserialize<'de> for ProtectedHeader {
55    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
56    where
57        D: serde::Deserializer<'de>,
58    {
59        use serde::de::{Error as _, MapAccess, Visitor};
60
61        struct HeaderVisitor;
62        impl<'de> Visitor<'de> for HeaderVisitor {
63            type Value = ProtectedHeader;
64
65            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66                formatter.write_str("a closed JOSE protected header")
67            }
68
69            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
70            where
71                A: MapAccess<'de>,
72            {
73                let (mut alg, mut typ, mut kid): (Option<String>, Option<String>, Option<String>) =
74                    (None, None, None);
75                let mut crit_seen = false;
76                while let Some(key) = map.next_key::<String>()? {
77                    match key.as_str() {
78                        "alg" => {
79                            if alg.is_some() {
80                                return Err(A::Error::duplicate_field("alg"));
81                            }
82                            alg = Some(map.next_value()?);
83                        }
84                        "typ" => {
85                            if typ.is_some() {
86                                return Err(A::Error::duplicate_field("typ"));
87                            }
88                            typ = Some(map.next_value()?);
89                        }
90                        "kid" => {
91                            if kid.is_some() {
92                                return Err(A::Error::duplicate_field("kid"));
93                            }
94                            kid = Some(map.next_value()?);
95                        }
96                        "crit" => {
97                            if crit_seen {
98                                return Err(A::Error::duplicate_field("crit"));
99                            }
100                            crit_seen = true;
101                            let crit: Vec<String> = map.next_value()?;
102                            if !crit.is_empty() {
103                                return Err(A::Error::custom(
104                                    "unsupported critical JOSE semantics",
105                                ));
106                            }
107                        }
108                        _ => {
109                            return Err(A::Error::unknown_field(
110                                &key,
111                                &["alg", "typ", "kid", "crit"],
112                            ));
113                        }
114                    }
115                }
116                let alg = alg.ok_or_else(|| A::Error::missing_field("alg"))?;
117                let typ = typ.ok_or_else(|| A::Error::missing_field("typ"))?;
118                let kid = kid.ok_or_else(|| A::Error::missing_field("kid"))?;
119                if kid.is_empty() {
120                    return Err(A::Error::custom("kid must not be empty"));
121                }
122                Ok(ProtectedHeader { alg, typ, kid })
123            }
124        }
125        deserializer.deserialize_map(HeaderVisitor)
126    }
127}
128
129/// Parse a JWT protected header exactly once for security dispatch.
130pub fn parse_protected_header(token: &str) -> Result<ProtectedHeader, JwtError> {
131    let mut parts = token.split('.');
132    let header_b64 = parts.next().ok_or(JwtError::InvalidFormat)?;
133    if header_b64.len() > 4096
134        || parts.next().is_none()
135        || parts.next().is_none()
136        || parts.next().is_some()
137    {
138        return Err(JwtError::InvalidFormat);
139    }
140    let header_bytes = URL_SAFE_NO_PAD
141        .decode(header_b64)
142        .map_err(|_| JwtError::InvalidBase64)?;
143    serde_json::from_slice(&header_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))
144}
145
146/// Parse composite dispatch exactly once and enforce the caller's allowed types.
147pub fn parse_composite_dispatch(
148    token: &str,
149    allowed_types: &[&str],
150) -> Result<CompositeJwtDispatch, JwtError> {
151    let header = parse_protected_header(token)?;
152    if header.alg != "ML-DSA-65-Ed25519" {
153        return Err(JwtError::UnsupportedAlgorithm(header.alg));
154    }
155    if !allowed_types.iter().any(|allowed| *allowed == header.typ) {
156        return Err(JwtError::UnsupportedType(header.typ));
157    }
158    let protected_b64 = token
159        .split_once('.')
160        .map(|(value, _)| value.to_owned())
161        .ok_or(JwtError::InvalidFormat)?;
162    Ok(CompositeJwtDispatch {
163        header,
164        protected_b64,
165    })
166}
167
168/// Input for RFC 7638 JWK Thumbprint computation.
169///
170/// Each variant carries the required members for its key type's canonical
171/// JSON representation (RFC 7638 §3.2: members sorted lexicographically).
172pub enum JwkThumbprintInput<'a> {
173    /// OKP / Ed25519: canonical `{"crv":"Ed25519","kty":"OKP","x":"..."}`
174    Ed25519 { x: &'a [u8; 32] },
175    /// EC / P-256 (ES256): canonical `{"crv":"P-256","kty":"EC","x":"...","y":"..."}`
176    Es256 { x: &'a [u8; 32], y: &'a [u8; 32] },
177    /// RSA: canonical `{"e":"...","kty":"RSA","n":"..."}` (n, e already base64url)
178    Rsa { n: &'a str, e: &'a str },
179    /// AKP / ML-DSA-65 (draft-ietf-cose-dilithium-11): canonical
180    /// `{"alg":"ML-DSA-65","kty":"AKP","pub":"<base64url>"}`
181    Akp { alg: &'a str, pub_bytes: &'a [u8] },
182}
183
184/// Compute the RFC 7638 JWK Thumbprint for any supported key type.
185///
186/// Returns `base64url(SHA-256(canonical_jwk_json))` — a 43-char string.
187pub fn jwk_thumbprint(input: &JwkThumbprintInput<'_>) -> String {
188    use sha2::{Digest, Sha256};
189    let canonical = match input {
190        JwkThumbprintInput::Ed25519 { x } => {
191            let x_b64 = URL_SAFE_NO_PAD.encode(x);
192            format!(r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, x_b64)
193        }
194        JwkThumbprintInput::Es256 { x, y } => {
195            let x_b64 = URL_SAFE_NO_PAD.encode(x);
196            let y_b64 = URL_SAFE_NO_PAD.encode(y);
197            format!(
198                r#"{{"crv":"P-256","kty":"EC","x":"{}","y":"{}"}}"#,
199                x_b64, y_b64
200            )
201        }
202        JwkThumbprintInput::Rsa { n, e } => {
203            format!(r#"{{"e":"{}","kty":"RSA","n":"{}"}}"#, e, n)
204        }
205        JwkThumbprintInput::Akp { alg, pub_bytes } => {
206            let pub_b64 = URL_SAFE_NO_PAD.encode(pub_bytes);
207            format!(r#"{{"alg":"{}","kty":"AKP","pub":"{}"}}"#, alg, pub_b64)
208        }
209    };
210    let hash = Sha256::digest(canonical.as_bytes());
211    URL_SAFE_NO_PAD.encode(hash)
212}
213
214/// Compute the RFC 7638 thumbprint for one exact composite public-key pair.
215pub fn composite_kid(
216    ml_dsa: &crate::crypto::pq::MlDsaVerifyingKey,
217    ed25519: &VerifyingKey,
218) -> String {
219    let mut public = crate::crypto::pq::ml_dsa_vk_bytes(ml_dsa);
220    public.extend_from_slice(ed25519.as_bytes());
221    jwk_thumbprint(&JwkThumbprintInput::Akp {
222        alg: "ML-DSA-65-Ed25519",
223        pub_bytes: &public,
224    })
225}
226
227/// Compute the JWT `kid` for an Ed25519 signing key using RFC 7638 JWK Thumbprint.
228pub fn kid_for_key(signing_key: &SigningKey) -> String {
229    jwk_thumbprint(&JwkThumbprintInput::Ed25519 {
230        x: signing_key.verifying_key().as_bytes(),
231    })
232}
233
234/// Extract the `alg` from a JWT's JOSE header without verifying the signature.
235///
236/// Returns `Ok(None)` if the header has no `alg` field.
237pub fn header_alg(token: &str) -> Result<Option<String>, JwtError> {
238    let header_b64 = token.split('.').next().ok_or(JwtError::InvalidFormat)?;
239    let header_bytes = URL_SAFE_NO_PAD
240        .decode(header_b64)
241        .map_err(|_| JwtError::InvalidBase64)?;
242    let header: serde_json::Value =
243        serde_json::from_slice(&header_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
244    Ok(header.get("alg").and_then(|v| v.as_str()).map(String::from))
245}
246
247/// Extract the `kid` from a JWT's JOSE header without verifying the signature.
248///
249/// Returns `Ok(None)` if the header has no `kid` field.
250pub fn header_kid(token: &str) -> Result<Option<String>, JwtError> {
251    let header_b64 = token.split('.').next().ok_or(JwtError::InvalidFormat)?;
252    let header_bytes = URL_SAFE_NO_PAD
253        .decode(header_b64)
254        .map_err(|_| JwtError::InvalidBase64)?;
255    let header: serde_json::Value =
256        serde_json::from_slice(&header_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
257    Ok(header.get("kid").and_then(|v| v.as_str()).map(String::from))
258}
259
260/// Errors from JWT operations
261#[derive(Error, Debug)]
262pub enum JwtError {
263    #[error("Invalid token format")]
264    InvalidFormat,
265
266    #[error("Invalid base64 encoding")]
267    InvalidBase64,
268
269    #[error("Invalid JSON: {0}")]
270    InvalidJson(String),
271
272    #[error("Invalid signature")]
273    InvalidSignature,
274
275    #[error("Token expired")]
276    Expired,
277
278    #[error("Token not yet valid")]
279    NotYetValid,
280
281    #[error("Missing required claim: {0}")]
282    MissingClaim(String),
283
284    #[error("Invalid audience")]
285    InvalidAudience,
286
287    #[error("Unsupported algorithm: {0}")]
288    UnsupportedAlgorithm(String),
289
290    #[error("Unsupported token type: {0}")]
291    UnsupportedType(String),
292}
293
294/// Encode and sign a JWT with a specific JOSE header.
295fn encode_with_header(claims: &Claims, signing_key: &SigningKey, header_json: &str) -> String {
296    let header_b64 = URL_SAFE_NO_PAD.encode(header_json);
297    let payload_json = serde_json::to_string(claims).unwrap_or_else(|_e| {
298        #[cfg(not(target_arch = "wasm32"))]
299        tracing::error!("JWT claims serialization failed: {}", _e);
300        "{}".to_owned()
301    });
302    let payload_b64 = URL_SAFE_NO_PAD.encode(&payload_json);
303    let signing_input = format!("{header_b64}.{payload_b64}");
304    let signature = signing_key.sign(signing_input.as_bytes());
305    let signature_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
306    format!("{signing_input}.{signature_b64}")
307}
308
309/// Encode a user/client OAuth 2.0 access token (`typ: "at+jwt"`, RFC 9068).
310/// Includes `kid` in the JOSE header for key rotation support.
311/// Automatically assigns a `jti` if the claims don't already have one.
312pub fn encode(claims: &Claims, signing_key: &SigningKey) -> String {
313    let kid = kid_for_key(signing_key);
314    let header = format!(r#"{{"alg":"EdDSA","typ":"at+jwt","kid":"{}"}}"#, kid);
315    let claims = ensure_jti(claims);
316    encode_with_header(&claims, signing_key, &header)
317}
318
319/// Encode a WIMSE Workload Identity Token (`typ: "wit+jwt"`) for service JWTs.
320/// Includes `kid` in the JOSE header for key rotation support.
321/// Automatically assigns a `jti` if the claims don't already have one.
322pub fn encode_service_jwt(claims: &Claims, signing_key: &SigningKey) -> String {
323    let kid = kid_for_key(signing_key);
324    let header = format!(r#"{{"alg":"EdDSA","typ":"wit+jwt","kid":"{}"}}"#, kid);
325    let claims = ensure_jti(claims);
326    encode_with_header(&claims, signing_key, &header)
327}
328
329/// Encode a composite ML-DSA-65-Ed25519 service WIT (`typ: "wit+jwt"`).
330///
331/// Per draft-ietf-jose-pq-composite-sigs, the signature is
332/// `ml_dsa_sig (3309 bytes) ∥ ed25519_sig (64 bytes)` over
333/// `base64url(header).base64url(payload)`, and the `kid` is the
334/// [`composite_kid`] thumbprint binding the exact key pair — the shape
335/// [`parse_composite_dispatch`] and [`decode_composite`] verify.
336/// Automatically assigns a `jti` if the claims don't already have one.
337pub fn encode_service_jwt_hybrid(
338    claims: &Claims,
339    ed: &SigningKey,
340    ml_dsa: &crate::crypto::pq::MlDsaSigningKey,
341    ml_dsa_vk: &crate::crypto::pq::MlDsaVerifyingKey,
342) -> String {
343    let kid = composite_kid(ml_dsa_vk, &ed.verifying_key());
344    let header = format!(
345        r#"{{"alg":"ML-DSA-65-Ed25519","typ":"wit+jwt","kid":"{}"}}"#,
346        kid
347    );
348    let claims = ensure_jti(claims);
349    let header_b64 = URL_SAFE_NO_PAD.encode(&header);
350    let payload_json = serde_json::to_string(claims.as_ref()).unwrap_or_else(|_e| {
351        #[cfg(not(target_arch = "wasm32"))]
352        tracing::error!("JWT claims serialization failed: {}", _e);
353        "{}".to_owned()
354    });
355    let payload_b64 = URL_SAFE_NO_PAD.encode(&payload_json);
356    let signing_input = format!("{header_b64}.{payload_b64}");
357    let mut signature = crate::crypto::pq::ml_dsa_sign(ml_dsa, signing_input.as_bytes());
358    signature.extend_from_slice(&ed.sign(signing_input.as_bytes()).to_bytes());
359    format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature))
360}
361
362fn ensure_jti(claims: &Claims) -> std::borrow::Cow<'_, Claims> {
363    if claims.jti.is_some() {
364        std::borrow::Cow::Borrowed(claims)
365    } else {
366        std::borrow::Cow::Owned(claims.clone().with_jti())
367    }
368}
369
370/// Encode and sign an OIDC ID Token (EdDSA with `kid` in header).
371///
372/// The header includes `kid` (SHA-256 of the public key, first 8 hex chars)
373/// and `typ: "JWT"` per OIDC convention.
374pub fn encode_id_token(claims: &super::IdTokenClaims, signing_key: &SigningKey) -> String {
375    let kid = kid_for_key(signing_key);
376    let header = serde_json::json!({
377        "alg": "EdDSA",
378        "typ": "JWT",
379        "kid": kid,
380    });
381    let header_b64 = URL_SAFE_NO_PAD.encode(header.to_string().as_bytes());
382    let payload_json = serde_json::to_string(claims).unwrap_or_else(|_e| {
383        #[cfg(not(target_arch = "wasm32"))]
384        tracing::error!("id_token claims serialization failed: {}", _e);
385        "{}".to_owned()
386    });
387    let payload_b64 = URL_SAFE_NO_PAD.encode(&payload_json);
388    let signing_input = format!("{header_b64}.{payload_b64}");
389    let signature = signing_key.sign(signing_input.as_bytes());
390    let signature_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
391    format!("{signing_input}.{signature_b64}")
392}
393
394/// Decode and verify a JWT token issued by the **local** node.
395///
396/// For tokens from foreign issuers (federation), use [`decode_with_key`]
397/// with the key obtained from `FederationKeyResolver::get_key`.
398///
399/// Uses strict audience validation: if `expected_aud` is `Some`, the token
400/// must have a matching `aud` claim (absent `aud` is rejected).
401pub fn decode(
402    token: &str,
403    verifying_key: &VerifyingKey,
404    expected_aud: Option<&str>,
405) -> Result<Claims, JwtError> {
406    decode_inner(token, verifying_key, expected_aud, false)
407}
408
409/// Decode a JWT using a caller-supplied verifying key (for multi-issuer support).
410///
411/// Uses lenient audience validation: if `expected_aud` is `Some`, a wrong `aud`
412/// is rejected but an absent `aud` is accepted. This allows federated tokens
413/// from issuers that don't set `aud` while still rejecting cross-node replay
414/// attacks from issuers that do.
415pub fn decode_with_key(
416    token: &str,
417    verifying_key: &VerifyingKey,
418    expected_aud: Option<&str>,
419) -> Result<Claims, JwtError> {
420    decode_inner(token, verifying_key, expected_aud, true)
421}
422
423/// Try every supplied Ed25519 key for a JWT that has no `kid`.
424///
425/// Candidate verification is intentionally unavailable to named tokens: under
426/// invariant I2, a token declaring `kid=X` must be resolved and verified only
427/// with key X. Each kid-less candidate receives a complete verification,
428/// including the pinned `EdDSA` algorithm and all claim checks.
429pub fn decode_with_any_key(
430    token: &str,
431    candidates: &[VerifyingKey],
432    expected_aud: Option<&str>,
433) -> Result<Claims, JwtError> {
434    decode_with_any_key_inner(token, candidates, expected_aud, false)
435}
436
437/// Lenient-audience twin of [`decode_with_any_key`]. This remains restricted
438/// to kid-less JWTs; only the absent-audience behavior differs.
439pub fn decode_with_any_key_lenient(
440    token: &str,
441    candidates: &[VerifyingKey],
442    expected_aud: Option<&str>,
443) -> Result<Claims, JwtError> {
444    decode_with_any_key_inner(token, candidates, expected_aud, true)
445}
446
447fn decode_with_any_key_inner(
448    token: &str,
449    candidates: &[VerifyingKey],
450    expected_aud: Option<&str>,
451    lenient_aud: bool,
452) -> Result<Claims, JwtError> {
453    if header_kid(token)?.is_some() || candidates.is_empty() {
454        return Err(JwtError::InvalidSignature);
455    }
456
457    let mut last_err = JwtError::InvalidSignature;
458    for key in candidates {
459        match decode_inner(token, key, expected_aud, lenient_aud) {
460            Ok(claims) => return Ok(claims),
461            Err(error) => {
462                #[cfg(not(target_arch = "wasm32"))]
463                tracing::debug!(%error, "kid-less JWT candidate did not verify");
464                last_err = error;
465            }
466        }
467    }
468    Err(last_err)
469}
470
471/// Verify a federation JWT without losing its JWKS `kid` binding.
472///
473/// A named token must have exactly one candidate carrying that name and is
474/// verified only with that key. A kid-less token may try every published
475/// Ed25519 candidate, each through full pinned-algorithm verification.
476#[cfg(not(target_arch = "wasm32"))]
477pub fn decode_with_federation_candidates(
478    token: &str,
479    candidates: &[super::FederationKey],
480    expected_aud: Option<&str>,
481) -> Result<Claims, JwtError> {
482    match header_kid(token)? {
483        Some(kid) => {
484            let mut named = candidates
485                .iter()
486                .filter(|candidate| candidate.kid.as_deref() == Some(kid.as_str()));
487            let key = named.next().ok_or(JwtError::InvalidSignature)?;
488            if named.next().is_some() {
489                return Err(JwtError::InvalidSignature);
490            }
491            decode_with_key(token, &key.verifying_key, expected_aud)
492        }
493        None => {
494            let keys: Vec<VerifyingKey> = candidates
495                .iter()
496                .map(|candidate| candidate.verifying_key)
497                .collect();
498            decode_with_any_key_lenient(token, &keys, expected_aud)
499        }
500    }
501}
502
503/// Internal decode implementation shared by `decode` and `decode_with_key`.
504///
505/// `lenient_aud`: when true, accepts tokens with no `aud` claim even when
506/// `expected_aud` is `Some`. Wrong `aud` is always rejected.
507fn decode_inner(
508    token: &str,
509    verifying_key: &VerifyingKey,
510    expected_aud: Option<&str>,
511    lenient_aud: bool,
512) -> Result<Claims, JwtError> {
513    // Split into parts
514    let parts: Vec<&str> = token.split('.').collect();
515    if parts.len() != 3 {
516        return Err(JwtError::InvalidFormat);
517    }
518
519    let header_b64 = parts[0];
520    let payload_b64 = parts[1];
521    let signature_b64 = parts[2];
522
523    // Verify signature first
524    let signing_input = format!("{header_b64}.{payload_b64}");
525    let signature_bytes = URL_SAFE_NO_PAD
526        .decode(signature_b64)
527        .map_err(|_| JwtError::InvalidBase64)?;
528
529    if signature_bytes.len() != 64 {
530        return Err(JwtError::InvalidSignature);
531    }
532
533    let mut sig_array = [0u8; 64];
534    sig_array.copy_from_slice(&signature_bytes);
535    let signature = Signature::from_bytes(&sig_array);
536
537    verifying_key
538        .verify(signing_input.as_bytes(), &signature)
539        .map_err(|_| JwtError::InvalidSignature)?;
540
541    // Validate the JWT header `alg` field to prevent algorithm-agility attacks.
542    // We only accept EdDSA tokens; any other alg value is rejected.
543    let header_bytes = URL_SAFE_NO_PAD
544        .decode(header_b64)
545        .map_err(|_| JwtError::InvalidBase64)?;
546    let header: serde_json::Value =
547        serde_json::from_slice(&header_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
548    if header.get("alg").and_then(|v| v.as_str()) != Some("EdDSA") {
549        return Err(JwtError::InvalidSignature);
550    }
551
552    // Decode payload
553    let payload_bytes = URL_SAFE_NO_PAD
554        .decode(payload_b64)
555        .map_err(|_| JwtError::InvalidBase64)?;
556
557    let claims: Claims =
558        serde_json::from_slice(&payload_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
559
560    // Check expiration
561    if claims.is_expired() {
562        return Err(JwtError::Expired);
563    }
564
565    // Check iat is not in the future (with small tolerance)
566    let now = Utc::now().timestamp();
567    if claims.iat > now + 60 {
568        return Err(JwtError::NotYetValid);
569    }
570
571    // Validate audience if expected (trailing-slash tolerant)
572    if let Some(expected) = expected_aud {
573        let expected_norm = expected.trim_end_matches('/');
574        match &claims.aud {
575            Some(aud) if aud.trim_end_matches('/') == expected_norm => {}
576            None if lenient_aud => {}
577            Some(_) | None => return Err(JwtError::InvalidAudience),
578        }
579    }
580
581    Ok(claims)
582}
583
584/// Decode a JWT without verifying the signature.
585///
586/// Used by `verify_claims()` to peek at the issuer field before selecting
587/// the appropriate verification key (local vs federated). The token is
588/// always fully verified after issuer routing.
589pub fn decode_unverified(token: &str) -> Result<Claims, JwtError> {
590    // Split into parts
591    let parts: Vec<&str> = token.split('.').collect();
592    if parts.len() != 3 {
593        return Err(JwtError::InvalidFormat);
594    }
595
596    // Decode payload only
597    let payload_bytes = URL_SAFE_NO_PAD
598        .decode(parts[1])
599        .map_err(|_| JwtError::InvalidBase64)?;
600
601    serde_json::from_slice(&payload_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))
602}
603
604/// Decode and verify a JWT signed with ML-DSA-65 (`alg: "ML-DSA-65"`).
605///
606/// Uses lenient audience validation (same as `decode_with_key`): if
607/// `expected_aud` is `Some`, a wrong `aud` is rejected but an absent
608/// `aud` is accepted.
609pub fn decode_ml_dsa_65(
610    token: &str,
611    vk: &crate::crypto::pq::MlDsaVerifyingKey,
612    expected_aud: Option<&str>,
613) -> Result<Claims, JwtError> {
614    let parts: Vec<&str> = token.split('.').collect();
615    if parts.len() != 3 {
616        return Err(JwtError::InvalidFormat);
617    }
618
619    let signing_input = format!("{}.{}", parts[0], parts[1]);
620    let sig_bytes = URL_SAFE_NO_PAD
621        .decode(parts[2])
622        .map_err(|_| JwtError::InvalidBase64)?;
623
624    crate::crypto::pq::ml_dsa_verify(vk, signing_input.as_bytes(), &sig_bytes)
625        .map_err(|_| JwtError::InvalidSignature)?;
626
627    let header_bytes = URL_SAFE_NO_PAD
628        .decode(parts[0])
629        .map_err(|_| JwtError::InvalidBase64)?;
630    let header: serde_json::Value =
631        serde_json::from_slice(&header_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
632    if header.get("alg").and_then(|v| v.as_str()) != Some("ML-DSA-65") {
633        return Err(JwtError::UnsupportedAlgorithm(
634            header
635                .get("alg")
636                .and_then(|v| v.as_str())
637                .unwrap_or("none")
638                .to_owned(),
639        ));
640    }
641
642    let payload_bytes = URL_SAFE_NO_PAD
643        .decode(parts[1])
644        .map_err(|_| JwtError::InvalidBase64)?;
645    let claims: Claims =
646        serde_json::from_slice(&payload_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
647
648    if claims.is_expired() {
649        return Err(JwtError::Expired);
650    }
651    let now = Utc::now().timestamp();
652    if claims.iat > now + 60 {
653        return Err(JwtError::NotYetValid);
654    }
655
656    if let Some(expected) = expected_aud {
657        match &claims.aud {
658            Some(aud) if aud == expected => {}
659            None => {} // lenient: absent aud accepted
660            Some(_) => return Err(JwtError::InvalidAudience), // wrong aud rejected
661        }
662    }
663
664    Ok(claims)
665}
666
667/// Decode and verify a composite ML-DSA-65-Ed25519 JWT.
668///
669/// Per draft-ietf-jose-pq-composite-sigs, the signature is
670/// `ml_dsa_sig (3309 bytes) ∥ ed25519_sig (64 bytes)`.
671pub fn decode_composite(
672    token: &str,
673    ml_dsa_vk: &crate::crypto::pq::MlDsaVerifyingKey,
674    ed25519_vk: &VerifyingKey,
675    expected_aud: Option<&str>,
676    dispatch: &CompositeJwtDispatch,
677) -> Result<Claims, JwtError> {
678    let header = &dispatch.header;
679    if header.alg != "ML-DSA-65-Ed25519" {
680        return Err(JwtError::UnsupportedAlgorithm(header.alg.clone()));
681    }
682    if header.kid != composite_kid(ml_dsa_vk, ed25519_vk) {
683        return Err(JwtError::InvalidSignature);
684    }
685    let parts: Vec<&str> = token.split('.').collect();
686    if parts.len() != 3 {
687        return Err(JwtError::InvalidFormat);
688    }
689    if parts[0] != dispatch.protected_b64 {
690        return Err(JwtError::InvalidSignature);
691    }
692
693    let signing_input = format!("{}.{}", parts[0], parts[1]);
694    let sig_bytes = URL_SAFE_NO_PAD
695        .decode(parts[2])
696        .map_err(|_| JwtError::InvalidBase64)?;
697
698    // Composite signature: ML-DSA-65 (3309 bytes) + Ed25519 (64 bytes) = 3373 bytes
699    if sig_bytes.len() != 3309 + 64 {
700        return Err(JwtError::InvalidSignature);
701    }
702
703    let (ml_dsa_sig, ed25519_sig) = sig_bytes.split_at(3309);
704
705    // Build message per draft-ietf-jose-pq-composite-sigs:
706    // Hash(header.payload) used as message for both algorithms
707    let message = signing_input.as_bytes();
708
709    // Verify ML-DSA-65
710    crate::crypto::pq::ml_dsa_verify(ml_dsa_vk, message, ml_dsa_sig)
711        .map_err(|_| JwtError::InvalidSignature)?;
712
713    // Verify Ed25519
714    if ed25519_sig.len() != 64 {
715        return Err(JwtError::InvalidSignature);
716    }
717    let mut ed_sig_arr = [0u8; 64];
718    ed_sig_arr.copy_from_slice(ed25519_sig);
719    let ed_signature = Signature::from_bytes(&ed_sig_arr);
720    ed25519_vk
721        .verify_strict(message, &ed_signature)
722        .map_err(|_| JwtError::InvalidSignature)?;
723
724    let payload_bytes = URL_SAFE_NO_PAD
725        .decode(parts[1])
726        .map_err(|_| JwtError::InvalidBase64)?;
727    let claims: Claims =
728        serde_json::from_slice(&payload_bytes).map_err(|e| JwtError::InvalidJson(e.to_string()))?;
729
730    if claims.is_expired() {
731        return Err(JwtError::Expired);
732    }
733    let now = Utc::now().timestamp();
734    if claims.iat > now + 60 {
735        return Err(JwtError::NotYetValid);
736    }
737
738    if let Some(expected) = expected_aud {
739        match claims.aud.as_deref() {
740            Some(aud) if aud.trim_end_matches('/') == expected.trim_end_matches('/') => {}
741            _ => return Err(JwtError::InvalidAudience),
742        }
743    }
744
745    Ok(claims)
746}
747
748#[cfg(test)]
749#[allow(clippy::unwrap_used, clippy::expect_used)]
750mod tests {
751    use super::*;
752    use crate::auth::{Claims, IssuerResolver, JwksFetcher, JwksKeySource, JwksMode, JwtKeySource};
753    use ed25519_dalek::SigningKey;
754
755    fn make_key(seed: u8) -> SigningKey {
756        SigningKey::from_bytes(&[seed; 32])
757    }
758
759    fn composite_token_with_type(
760        typ: &str,
761    ) -> (String, crate::crypto::pq::MlDsaVerifyingKey, VerifyingKey) {
762        let (pq, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
763        let ed = make_key(0x71);
764        let token = composite_token_with_keys(typ, &pq, &pq_vk, &ed);
765        (token, pq_vk, ed.verifying_key())
766    }
767
768    fn composite_token_with_keys(
769        typ: &str,
770        pq: &crate::crypto::pq::MlDsaSigningKey,
771        pq_vk: &crate::crypto::pq::MlDsaVerifyingKey,
772        ed: &SigningKey,
773    ) -> String {
774        let header = format!(
775            r#"{{"alg":"ML-DSA-65-Ed25519","typ":"{typ}","kid":"{}"}}"#,
776            composite_kid(pq_vk, &ed.verifying_key())
777        );
778        let claims = Claims::new("dispatch-test".to_owned(), 0, 9_999_999_999);
779        let input = format!(
780            "{}.{}",
781            URL_SAFE_NO_PAD.encode(header),
782            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap())
783        );
784        let mut signature = crate::crypto::pq::ml_dsa_sign(pq, input.as_bytes());
785        signature.extend_from_slice(&ed.sign(input.as_bytes()).to_bytes());
786        format!("{}.{}", input, URL_SAFE_NO_PAD.encode(signature))
787    }
788
789    #[test]
790    fn public_composite_dispatch_rejects_type_and_header_binding_bypasses() {
791        let (bad_type, _, _) = composite_token_with_type("JWT");
792        assert!(matches!(
793            parse_composite_dispatch(&bad_type, &["at+jwt"]),
794            Err(JwtError::UnsupportedType(_))
795        ));
796        let (pq_sk, pq) = crate::crypto::pq::ml_dsa_generate_keypair();
797        let ed_sk = make_key(0x72);
798        let ed = ed_sk.verifying_key();
799        let token = composite_token_with_keys("at+jwt", &pq_sk, &pq, &ed_sk);
800        let dispatch = parse_composite_dispatch(&token, &["at+jwt"]).unwrap();
801        let separately_valid = composite_token_with_keys("wit+jwt", &pq_sk, &pq, &ed_sk);
802        assert!(matches!(
803            decode_composite(&separately_valid, &pq, &ed, None, &dispatch),
804            Err(JwtError::InvalidSignature)
805        ));
806    }
807
808    /// A freshly minted hybrid service WIT carries the composite alg/typ/kid
809    /// shape the dispatch path verifies, and round-trips through the real
810    /// composite verification (`parse_composite_dispatch` + `decode_composite`).
811    #[test]
812    fn hybrid_service_jwt_round_trips_composite_dispatch() {
813        let (pq, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
814        let ed = make_key(0x51);
815        let claims = Claims::new("service:discovery".to_owned(), 0, 9_999_999_999);
816        let token = encode_service_jwt_hybrid(&claims, &ed, &pq, &pq_vk);
817
818        let header = parse_protected_header(&token).unwrap();
819        assert_eq!(header.alg, "ML-DSA-65-Ed25519");
820        assert_eq!(header.typ, "wit+jwt");
821        assert_eq!(header.kid, composite_kid(&pq_vk, &ed.verifying_key()));
822
823        let dispatch = parse_composite_dispatch(&token, &["wit+jwt"]).unwrap();
824        let verified =
825            decode_composite(&token, &pq_vk, &ed.verifying_key(), None, &dispatch).unwrap();
826        assert_eq!(verified.sub, "service:discovery");
827        assert!(verified.jti.is_some(), "a jti must be assigned when absent");
828
829        // Neither half alone verifies: a wrong Ed25519 or ML-DSA key fails closed.
830        let other_ed = make_key(0x52);
831        assert!(matches!(
832            decode_composite(&token, &pq_vk, &other_ed.verifying_key(), None, &dispatch),
833            Err(JwtError::InvalidSignature)
834        ));
835        let (_, other_pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
836        assert!(matches!(
837            decode_composite(&token, &other_pq_vk, &ed.verifying_key(), None, &dispatch),
838            Err(JwtError::InvalidSignature)
839        ));
840    }
841
842    #[test]
843    fn rfc9068_access_token_type_matching_is_exact() {
844        for allowed in RFC9068_ACCESS_TOKEN_TYPES {
845            assert!(is_rfc9068_access_token_type(allowed));
846        }
847        for rejected in [
848            "",
849            "AT+JWT",
850            "at+JWT",
851            " at+jwt",
852            "at+jwt ",
853            "Application/at+jwt",
854            "application/AT+JWT",
855            "application/at+jwt ",
856            "application/at+jwt; charset=utf-8",
857            "JWT",
858            "wit+jwt",
859        ] {
860            assert!(
861                !is_rfc9068_access_token_type(rejected),
862                "accepted {rejected:?}"
863            );
864        }
865    }
866
867    #[test]
868    fn test_decode_with_key_multi_issuer() {
869        // Simulate two nodes with separate signing keys.
870        let key_a = make_key(0xAA);
871        let key_b = make_key(0xBB);
872        let vk_a = key_a.verifying_key();
873
874        // Node A issues a JWT with iss = "https://node-a"
875        let claims = Claims::new("alice".to_owned(), 0, 9_999_999_999)
876            .with_issuer("https://node-a".to_owned());
877        let token = encode(&claims, &key_a);
878
879        // decode_with_key should accept the correct key
880        let decoded = decode_with_key(&token, &vk_a, None)
881            .expect("decode_with_key with correct key must succeed");
882        assert_eq!(decoded.iss, "https://node-a");
883        assert_eq!(decoded.sub, "alice");
884
885        // decode_with_key must reject the wrong key
886        let vk_b = key_b.verifying_key();
887        let result = decode_with_key(&token, &vk_b, None);
888        assert!(
889            matches!(result, Err(JwtError::InvalidSignature)),
890            "wrong key must yield InvalidSignature"
891        );
892    }
893
894    /// I2b / #1234: every JWKS-derived lookup is issuer-scoped. In
895    /// particular, preloading issuer A must not make an issuer-B token signed
896    /// by A acceptable merely because both JWKS documents reuse a `kid`.
897    #[tokio::test]
898    async fn cross_issuer_shared_kid_rejects_issuer_a_signature() -> anyhow::Result<()> {
899        use std::sync::{
900            atomic::{AtomicU32, Ordering},
901            Arc,
902        };
903
904        const ISSUER_A: &str = "https://issuer-a.example";
905        const ISSUER_B: &str = "https://issuer-b.example";
906        const SHARED_KID: &str = "shared-kid";
907        const METADATA_KID: &str = "shared-metadata-kid";
908
909        struct TestResolver;
910
911        #[async_trait::async_trait]
912        impl IssuerResolver for TestResolver {
913            async fn resolve(&self, issuer: &str) -> anyhow::Result<String> {
914                Ok(format!("{issuer}/jwks"))
915            }
916        }
917
918        fn ed25519_jwk(signing_key: &SigningKey, kid: &str) -> serde_json::Value {
919            serde_json::json!({
920                "kty": "OKP",
921                "crv": "Ed25519",
922                "use": "sig",
923                "alg": "EdDSA",
924                "kid": kid,
925                "x": URL_SAFE_NO_PAD.encode(signing_key.verifying_key().as_bytes()),
926            })
927        }
928
929        let issuer_a_key = make_key(0xA1);
930        let issuer_b_key = make_key(0xB2);
931        let issuer_a_jwks = serde_json::json!({
932            "keys": [
933                ed25519_jwk(&issuer_a_key, SHARED_KID),
934                {
935                    "kty": "AKP",
936                    "use": "sig",
937                    "alg": "ML-DSA-65-Ed25519",
938                    "kid": METADATA_KID,
939                    "pub": URL_SAFE_NO_PAD.encode([0u8; 16]),
940                },
941            ]
942        });
943        let issuer_b_jwks = serde_json::json!({
944            "keys": [
945                ed25519_jwk(&issuer_b_key, SHARED_KID),
946                {
947                    "kty": "AKP",
948                    "use": "sig",
949                    "alg": "ML-DSA-65",
950                    "kid": METADATA_KID,
951                    "pub": URL_SAFE_NO_PAD.encode([1u8; 16]),
952                },
953            ]
954        });
955
956        let issuer_a_fetches = Arc::new(AtomicU32::new(0));
957        let issuer_b_fetches = Arc::new(AtomicU32::new(0));
958        let fetcher: JwksFetcher = {
959            let issuer_a_fetches = issuer_a_fetches.clone();
960            let issuer_b_fetches = issuer_b_fetches.clone();
961            Arc::new(move |url| {
962                let jwks = if url == format!("{ISSUER_A}/jwks") {
963                    issuer_a_fetches.fetch_add(1, Ordering::Relaxed);
964                    issuer_a_jwks.clone()
965                } else if url == format!("{ISSUER_B}/jwks") {
966                    issuer_b_fetches.fetch_add(1, Ordering::Relaxed);
967                    issuer_b_jwks.clone()
968                } else {
969                    return Box::pin(async move { anyhow::bail!("unexpected JWKS URL: {url}") });
970                };
971                Box::pin(async move { Ok(jwks) })
972            })
973        };
974
975        let key_source = JwksKeySource::new(
976            JwksMode::Federated {
977                local_jwks_url: "https://local.example/jwks".to_owned(),
978                resolver: Arc::new(TestResolver),
979            },
980            "https://local.example".to_owned(),
981            fetcher,
982        );
983
984        // Prime issuer A's positive cache under the deliberately shared kid.
985        let selected_a = key_source.get_key(ISSUER_A, Some(SHARED_KID)).await?;
986        assert_eq!(selected_a, issuer_a_key.verifying_key());
987
988        let claims = Claims::new("issuer-b-subject".to_owned(), 0, 9_999_999_999)
989            .with_issuer(ISSUER_B.to_owned());
990        let header = format!(r#"{{"alg":"EdDSA","typ":"JWT","kid":"{SHARED_KID}"}}"#);
991        let forged = encode_with_header(&claims, &issuer_a_key, &header);
992
993        // Issuer B must resolve only B's key, so A's signature is rejected.
994        let selected_b = key_source.get_key(ISSUER_B, Some(SHARED_KID)).await?;
995        assert_eq!(selected_b, issuer_b_key.verifying_key());
996        assert!(matches!(
997            decode_with_key(&forged, &selected_b, None),
998            Err(JwtError::InvalidSignature)
999        ));
1000
1001        // Kid-less candidates and kid→alg metadata are issuer-scoped too.
1002        assert_eq!(
1003            key_source.get_keys(ISSUER_B, None).await?,
1004            vec![issuer_b_key.verifying_key()]
1005        );
1006        assert_eq!(
1007            key_source.kid_algs(ISSUER_A, METADATA_KID),
1008            vec!["ML-DSA-65-Ed25519".to_owned()]
1009        );
1010        assert_eq!(
1011            key_source.kid_algs(ISSUER_B, METADATA_KID),
1012            vec!["ML-DSA-65".to_owned()]
1013        );
1014
1015        // A negative hit for issuer A must not suppress issuer B's fetch.
1016        assert!(key_source
1017            .get_key(ISSUER_A, Some("missing-kid"))
1018            .await
1019            .is_err());
1020        assert!(key_source
1021            .get_key(ISSUER_A, Some("missing-kid"))
1022            .await
1023            .is_err());
1024        assert_eq!(issuer_a_fetches.load(Ordering::Relaxed), 2);
1025        assert!(key_source
1026            .get_key(ISSUER_B, Some("missing-kid"))
1027            .await
1028            .is_err());
1029        assert_eq!(issuer_b_fetches.load(Ordering::Relaxed), 2);
1030
1031        Ok(())
1032    }
1033
1034    #[test]
1035    fn test_decode_with_key_audience_validation() {
1036        let key = make_key(0x01);
1037        let vk = key.verifying_key();
1038        let claims = Claims::new("bob".to_owned(), 0, 9_999_999_999)
1039            .with_issuer("https://node-a".to_owned())
1040            .with_audience(Some("https://node-b".to_owned()));
1041        let token = encode(&claims, &key);
1042
1043        // Correct audience
1044        decode_with_key(&token, &vk, Some("https://node-b"))
1045            .expect("correct audience must succeed");
1046
1047        // Wrong audience
1048        let result = decode_with_key(&token, &vk, Some("https://wrong"));
1049        assert!(matches!(result, Err(JwtError::InvalidAudience)));
1050    }
1051
1052    #[test]
1053    fn test_decode_and_decode_with_key_are_equivalent() {
1054        let key = make_key(0x42);
1055        let vk = key.verifying_key();
1056        let claims = Claims::new("carol".to_owned(), 0, 9_999_999_999);
1057        let token = encode(&claims, &key);
1058
1059        let via_decode = decode(&token, &vk, None).unwrap();
1060        let via_decode_with_key = decode_with_key(&token, &vk, None).unwrap();
1061        assert_eq!(via_decode.sub, via_decode_with_key.sub);
1062        assert_eq!(via_decode.exp, via_decode_with_key.exp);
1063    }
1064
1065    #[test]
1066    fn test_decode_strict_rejects_absent_audience() {
1067        // Local tokens (via decode) must have aud present when expected
1068        let key = make_key(0x10);
1069        let vk = key.verifying_key();
1070        let claims = Claims::new("dave".to_owned(), 0, 9_999_999_999);
1071        let token = encode(&claims, &key);
1072
1073        let result = decode(&token, &vk, Some("http://localhost:6789"));
1074        assert!(
1075            matches!(result, Err(JwtError::InvalidAudience)),
1076            "strict mode must reject absent aud"
1077        );
1078    }
1079
1080    #[test]
1081    fn test_decode_with_key_lenient_accepts_absent_audience() {
1082        // Federated tokens (via decode_with_key) accept absent aud
1083        let key = make_key(0x20);
1084        let vk = key.verifying_key();
1085        let claims = Claims::new("eve".to_owned(), 0, 9_999_999_999)
1086            .with_issuer("https://remote-node".to_owned());
1087        let token = encode(&claims, &key);
1088
1089        // Lenient mode: absent aud is accepted
1090        decode_with_key(&token, &vk, Some("http://localhost:6789"))
1091            .expect("lenient mode must accept absent aud");
1092    }
1093
1094    #[test]
1095    fn test_decode_with_key_lenient_rejects_wrong_audience() {
1096        // Federated tokens with wrong aud must still be rejected
1097        let key = make_key(0x30);
1098        let vk = key.verifying_key();
1099        let claims = Claims::new("frank".to_owned(), 0, 9_999_999_999)
1100            .with_issuer("https://node-a".to_owned())
1101            .with_audience(Some("https://node-b".to_owned()));
1102        let token = encode(&claims, &key);
1103
1104        let result = decode_with_key(&token, &vk, Some("https://node-c"));
1105        assert!(
1106            matches!(result, Err(JwtError::InvalidAudience)),
1107            "lenient mode must reject wrong aud"
1108        );
1109    }
1110
1111    #[test]
1112    fn test_jwk_thumbprint_ed25519() {
1113        let key = make_key(0x01);
1114        let kid = kid_for_key(&key);
1115        // RFC 7638: base64url(SHA-256(...)) = 43 chars
1116        assert_eq!(kid.len(), 43);
1117        assert!(!kid.contains('='));
1118        // Deterministic
1119        assert_eq!(kid, kid_for_key(&key));
1120    }
1121
1122    #[test]
1123    fn test_jwk_thumbprint_rsa() {
1124        let kid = jwk_thumbprint(&JwkThumbprintInput::Rsa {
1125            n: "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
1126            e: "AQAB",
1127        });
1128        assert_eq!(kid.len(), 43);
1129        assert!(!kid.contains('='));
1130    }
1131
1132    #[test]
1133    fn test_jwk_thumbprint_es256() {
1134        let x = [1u8; 32];
1135        let y = [2u8; 32];
1136        let kid = jwk_thumbprint(&JwkThumbprintInput::Es256 { x: &x, y: &y });
1137        assert_eq!(kid.len(), 43);
1138        assert!(!kid.contains('='));
1139    }
1140
1141    #[test]
1142    fn test_jwk_thumbprint_different_algorithms_differ() {
1143        let bytes = [1u8; 32];
1144        let ed_kid = jwk_thumbprint(&JwkThumbprintInput::Ed25519 { x: &bytes });
1145        let es_kid = jwk_thumbprint(&JwkThumbprintInput::Es256 {
1146            x: &bytes,
1147            y: &[2u8; 32],
1148        });
1149        assert_ne!(ed_kid, es_kid);
1150    }
1151
1152    #[test]
1153    fn test_header_kid_extraction() {
1154        let key = make_key(0x42);
1155        let claims = Claims::new("test".to_owned(), 0, 9_999_999_999);
1156        let token = encode(&claims, &key);
1157
1158        let kid = header_kid(&token).unwrap();
1159        assert!(kid.is_some());
1160        assert_eq!(kid.unwrap(), kid_for_key(&key));
1161    }
1162
1163    #[test]
1164    fn test_header_kid_missing() {
1165        // Manually craft a JWT with no kid in header
1166        let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"EdDSA","typ":"JWT"}"#);
1167        let payload = URL_SAFE_NO_PAD.encode(r#"{"sub":"test","exp":9999999999,"iat":0}"#);
1168        let token = format!("{}.{}.AAAA", header, payload);
1169
1170        let kid = header_kid(&token).unwrap();
1171        assert!(kid.is_none());
1172    }
1173
1174    // #1184/I2 — candidate verification is permitted only when the JWT has no
1175    // kid. Each candidate gets a complete EdDSA + claims verification.
1176    #[test]
1177    fn decode_with_any_key_accepts_kid_less_non_first_published_key() {
1178        let key_a = make_key(0xA1);
1179        let key_b = make_key(0xB2);
1180        let claims = Claims::new("overlap-test".to_owned(), 0, 9_999_999_999);
1181        let header = r#"{"alg":"EdDSA","typ":"at+jwt"}"#;
1182        let token = encode_with_header(&claims, &key_b, header);
1183        let candidates = vec![key_a.verifying_key(), key_b.verifying_key()];
1184
1185        let decoded = decode_with_any_key_lenient(&token, &candidates, None)
1186            .expect("kid-less second key verifies");
1187        assert_eq!(decoded.sub, "overlap-test");
1188    }
1189
1190    #[test]
1191    fn decode_with_any_key_rejects_named_token_even_if_another_candidate_verifies() {
1192        let old = make_key(0xA1);
1193        let new = make_key(0xB2);
1194        let claims = Claims::new("kid-substitution".to_owned(), 0, 9_999_999_999);
1195        let header = format!(
1196            r#"{{"alg":"EdDSA","typ":"at+jwt","kid":"{}"}}"#,
1197            kid_for_key(&new)
1198        );
1199        let token = encode_with_header(&claims, &old, &header);
1200        let candidates = vec![new.verifying_key(), old.verifying_key()];
1201
1202        assert!(decode_with_any_key_lenient(&token, &candidates, None).is_err());
1203    }
1204
1205    #[test]
1206    fn decode_with_any_key_rejects_when_no_candidate_verifies() {
1207        let signer = make_key(0x11);
1208        let unrelated = make_key(0x99);
1209        let claims = Claims::new("no-match".to_owned(), 0, 9_999_999_999);
1210        let token = encode_with_header(&claims, &signer, r#"{"alg":"EdDSA","typ":"at+jwt"}"#);
1211        assert!(decode_with_any_key_lenient(&token, &[unrelated.verifying_key()], None).is_err());
1212    }
1213
1214    #[test]
1215    fn decode_with_any_key_empty_set_fails_closed() {
1216        let signer = make_key(0x22);
1217        let claims = Claims::new("empty".to_owned(), 0, 9_999_999_999);
1218        let token = encode_with_header(&claims, &signer, r#"{"alg":"EdDSA","typ":"at+jwt"}"#);
1219        assert!(decode_with_any_key_lenient(&token, &[], None).is_err());
1220    }
1221
1222    #[test]
1223    fn federation_candidates_reject_mismatched_named_key() {
1224        use crate::auth::FederationKey;
1225
1226        let old = make_key(0xA1);
1227        let new = make_key(0xB2);
1228        let claims = Claims::new("kid-binding".to_owned(), 0, 9_999_999_999);
1229        let token = encode(&claims, &old);
1230        let old_kid = kid_for_key(&old);
1231
1232        // The token names `old_kid`, but only a different co-published key is
1233        // attached to that name. The bare-key candidate loop would accept the
1234        // `old` entry below; the federation path must reject it.
1235        let candidates = vec![
1236            FederationKey {
1237                kid: Some(old_kid),
1238                verifying_key: new.verifying_key(),
1239            },
1240            FederationKey {
1241                kid: Some(kid_for_key(&new)),
1242                verifying_key: old.verifying_key(),
1243            },
1244        ];
1245        assert!(decode_with_federation_candidates(&token, &candidates, None).is_err());
1246    }
1247}