Skip to main content

hyprstream_core/services/oauth/
client_auth.rs

1//! OAuth 2.1 client authentication at the token endpoint.
2//!
3//! Currently supports:
4//!   - `none` — public client; PKCE substitutes for client auth
5//!   - `private_key_jwt` — RFC 7521 / RFC 7523 §2.2 client assertion
6//!
7//! The client assertion is a JWT signed by one of the keys in the
8//! registered client's `jwks` field (inline) or via `jwks_uri`
9//! (deferred). Claim requirements per RFC 7523 §3 + the atproto OAuth
10//! profile (#1146 T1.2/T3.3):
11//!   iss == sub == client_id
12//!   aud == the AS issuer. The atproto OAuth profile mandates this form;
13//!          RFC 7523 §3 permits the token endpoint URL too, but this AS
14//!          accepts the issuer ALONE at every endpoint (PAR and token) —
15//!          see #1146 T1.2.
16//!   exp > now
17//!   iat present and not in the future (beyond 60s clock skew)
18//!   jti present and unique per client until exp (replay registry in
19//!       `OAuthState::assertion_jti_seen`)
20//!   alg per the JWKS key kty/crv (RS256, ES256, EdDSA)
21//!
22//! Spec reference: MCP 2025-11-25 § Client ID Metadata Documents lists
23//! `private_key_jwt` as a MAY for clients (CIMD §6.2). Servers honoring
24//! the `token_endpoint_auth_method` field in a CIMD/DCR registration
25//! MUST validate the assertion before issuing tokens.
26
27use serde_json::Value;
28use std::time::{Duration, Instant};
29
30use super::state::{OAuthState, RegisteredClient};
31use crate::auth::id_token_verify::{algorithm_for_key_pub, build_decoding_key};
32use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
33use jsonwebtoken::{decode, DecodingKey, Validation};
34use sha2::{Digest as _, Sha256};
35
36/// HTTP fetch timeout for jwks_uri. Same as CIMD document fetch.
37const JWKS_URI_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
38
39/// Client authentication failure.
40#[derive(Debug, Clone)]
41pub enum ClientAuthError {
42    /// The client is configured for `private_key_jwt` but no assertion
43    /// was presented at the token endpoint.
44    MissingAssertion,
45    /// The presented `client_assertion_type` is not the RFC 7523 jwt-bearer
46    /// type. We accept exactly:
47    /// `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`.
48    UnsupportedAssertionType(String),
49    /// The client has no usable JWKS (inline or via `jwks_uri`) to verify
50    /// against.
51    NoKeys,
52    /// jwks_uri fetch failed (network error, non-2xx status, parse error,
53    /// or SSRF-blocked URL).
54    JwksUriFetchFailed(String),
55    /// Trust-policy denied this CIMD origin between PAR/authorize and
56    /// the token-endpoint client-assertion verification.
57    TrustPolicyDenied(String),
58    /// JWT structural / decoding error (malformed parts, base64, JSON).
59    Malformed(String),
60    /// Signature verification failed against every candidate key.
61    InvalidSignature,
62    /// One of the iss/sub/aud/exp claims failed validation. The string
63    /// describes which.
64    InvalidClaim(String),
65}
66
67impl std::fmt::Display for ClientAuthError {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            Self::MissingAssertion => write!(f, "client_assertion required for private_key_jwt"),
71            Self::UnsupportedAssertionType(t) => {
72                write!(f, "unsupported client_assertion_type: {t}")
73            }
74            Self::NoKeys => write!(f, "client has no jwks/jwks_uri for private_key_jwt"),
75            Self::JwksUriFetchFailed(e) => write!(f, "jwks_uri fetch failed: {e}"),
76            Self::TrustPolicyDenied(e) => write!(f, "CIMD trust policy denied: {e}"),
77            Self::Malformed(e) => write!(f, "malformed client_assertion: {e}"),
78            Self::InvalidSignature => write!(f, "client_assertion signature did not verify"),
79            Self::InvalidClaim(c) => write!(f, "invalid client_assertion claim: {c}"),
80        }
81    }
82}
83
84impl std::error::Error for ClientAuthError {}
85
86pub const JWT_BEARER_ASSERTION_TYPE: &str =
87    "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
88
89/// Bounds replay-barrier residency for client assertions and follows the
90/// short-lived private_key_jwt profile expected by OAuth clients.
91const MAX_CLIENT_ASSERTION_LIFETIME_SECS: i64 = 300;
92
93/// A successfully verified client assertion.
94#[derive(Debug, Clone)]
95pub struct VerifiedAssertion {
96    /// The verified JWT claims (caller-side use: logging, `jti` audits).
97    pub claims: Value,
98    /// RFC 7638 thumbprint (SHA-256, base64url) of the JWKS key that
99    /// verified the signature. Callers bind sessions to this so a later
100    /// request cannot switch to another registered key (#1146 T3.3).
101    pub key_jkt: String,
102}
103
104/// Decide whether a registered client requires `private_key_jwt`. Default
105/// is "no" — i.e. public client / PKCE-only — unless the registration
106/// explicitly set `token_endpoint_auth_method=private_key_jwt`.
107pub fn requires_private_key_jwt(client: &RegisteredClient) -> bool {
108    matches!(
109        client.token_endpoint_auth_method.as_deref(),
110        Some("private_key_jwt")
111    )
112}
113
114/// Verify an RFC 7523 client_assertion against the registered client's
115/// JWKS — inline `jwks` if present, otherwise fetched from `jwks_uri`
116/// (cached for `state.client_jwks_uri_cache_ttl`). `expected_audiences`
117/// is the accepted `aud` set — on every profile path this is the AS
118/// issuer alone (atproto mandate, #1146 T1.2).
119///
120/// On success, records the assertion's `jti` in the replay registry
121/// (single-use per client until `exp`) and returns the verified claims
122/// plus the verifying key's thumbprint for session binding.
123pub async fn verify_client_assertion(
124    state: &OAuthState,
125    client: &RegisteredClient,
126    assertion_type: &str,
127    assertion: &str,
128    expected_audiences: &[String],
129) -> Result<VerifiedAssertion, ClientAuthError> {
130    if assertion_type != JWT_BEARER_ASSERTION_TYPE {
131        return Err(ClientAuthError::UnsupportedAssertionType(
132            assertion_type.to_owned(),
133        ));
134    }
135    let keys = resolve_keys(state, client).await?;
136    let verified =
137        verify_assertion_with_keys(&keys, &client.client_id, assertion, expected_audiences)?;
138
139    // Replay registry (RFC 7523 §3: the AS MUST NOT accept the same jti
140    // more than once). check_claims already required jti/exp, so the
141    // lookups below are defensive-only.
142    let jti = verified
143        .claims
144        .get("jti")
145        .and_then(Value::as_str)
146        .ok_or_else(|| ClientAuthError::InvalidClaim("missing jti".to_owned()))?;
147    let exp = verified
148        .claims
149        .get("exp")
150        .and_then(Value::as_i64)
151        .ok_or_else(|| ClientAuthError::InvalidClaim("missing exp".to_owned()))?;
152    if !state.check_and_record_assertion_jti(&client.client_id, jti, exp) {
153        return Err(ClientAuthError::InvalidClaim(
154            "jti already used (assertion replay)".to_owned(),
155        ));
156    }
157    Ok(verified)
158}
159
160/// Pure-sync core verification: given a set of candidate keys, verify
161/// the JWT's signature and claims. Used both by the async public entry
162/// point and directly by unit tests.
163pub fn verify_assertion_with_keys(
164    keys: &[Value],
165    client_id: &str,
166    assertion: &str,
167    expected_audiences: &[String],
168) -> Result<VerifiedAssertion, ClientAuthError> {
169    let keys = keys.to_vec();
170
171    // Parse the header to learn alg + (optional) kid before iterating keys.
172    let header = jsonwebtoken::decode_header(assertion)
173        .map_err(|e| ClientAuthError::Malformed(format!("header decode: {e}")))?;
174    let kid = header.kid.as_deref();
175
176    // Filter by kid first when present — avoids futile signature attempts.
177    let candidates: Vec<&Value> = keys
178        .iter()
179        .filter(|k| match kid {
180            Some(want) => k.get("kid").and_then(Value::as_str) == Some(want),
181            None => true,
182        })
183        .collect();
184
185    if candidates.is_empty() {
186        return Err(ClientAuthError::InvalidClaim(
187            "no JWKS key matches assertion header kid".to_owned(),
188        ));
189    }
190
191    // Try each candidate. jsonwebtoken::decode validates exp and aud
192    // when set in Validation. We disable aud-via-validation and check it
193    // manually so we can produce a precise error.
194    //
195    // Per-key failures log at `debug!` — this loop is expected to
196    // discard non-matching candidates in the happy path (a JWKS may
197    // hold many keys and only the kid-matched one is the right
198    // verifier). Promoting to warn would flood logs. The final
199    // `InvalidSignature` carries an aggregate warn-level summary so
200    // operators can correlate a verification failure with the keys
201    // that were considered.
202    let mut attempts = 0u32;
203    for jwk in &candidates {
204        let kid_for_log = jwk.get("kid").and_then(Value::as_str);
205        let alg = match algorithm_for_key_pub(jwk) {
206            Ok(a) => a,
207            Err(e) => {
208                tracing::debug!(
209                    kid = ?kid_for_log,
210                    error = %e,
211                    "client_assertion: skipping JWKS key (unsupported algorithm)"
212                );
213                continue;
214            }
215        };
216        let mut validation = Validation::new(alg);
217        validation.validate_exp = true;
218        validation.validate_aud = false; // checked manually below
219        validation.required_spec_claims = ["exp"].into_iter().map(str::to_owned).collect();
220
221        let decoding_key: DecodingKey = match build_decoding_key(jwk) {
222            Ok(k) => k,
223            Err(e) => {
224                tracing::debug!(
225                    kid = ?kid_for_log,
226                    error = %e,
227                    "client_assertion: skipping JWKS key (invalid key material)"
228                );
229                continue;
230            }
231        };
232
233        attempts += 1;
234        match decode::<Value>(assertion, &decoding_key, &validation) {
235            Ok(data) => {
236                let claims = data.claims;
237                check_claims(&claims, client_id, expected_audiences)?;
238                let key_jkt = jwk_thumbprint_sha256(jwk).ok_or_else(|| {
239                    ClientAuthError::InvalidClaim(
240                        "cannot compute thumbprint of verifying JWK".to_owned(),
241                    )
242                })?;
243                return Ok(VerifiedAssertion { claims, key_jkt });
244            }
245            Err(e) => {
246                tracing::debug!(
247                    kid = ?kid_for_log,
248                    error = %e,
249                    "client_assertion: signature/claims verification failed for this key"
250                );
251                continue;
252            }
253        }
254    }
255
256    // Aggregate summary at warn level: emits once per failed assertion
257    // with the kid the assertion was *signed for*, helping operators
258    // pinpoint a misconfigured client.
259    let header_kid = jsonwebtoken::decode_header(assertion)
260        .ok()
261        .and_then(|h| h.kid);
262    tracing::warn!(
263        client_id = %client_id,
264        header_kid = ?header_kid,
265        candidates = candidates.len(),
266        actual_verify_attempts = attempts,
267        "client_assertion verification failed against every candidate key"
268    );
269    Err(ClientAuthError::InvalidSignature)
270}
271
272/// Resolve a registered client's signing keys: inline `jwks` first,
273/// then `jwks_uri` (cached). The two are RFC 7591 §2.1 mutually
274/// exclusive, but defensive prefer-inline is harmless.
275async fn resolve_keys(
276    state: &OAuthState,
277    client: &RegisteredClient,
278) -> Result<Vec<Value>, ClientAuthError> {
279    // Defense in depth: re-check the unified federation:register policy
280    // at the token endpoint. The cimd_cache entry was admitted at
281    // PAR/authorize time, but operators may have flipped policy in the
282    // interim (the cache TTL bounds the window). Fail-closed on RPC
283    // error, matching resolve_cimd_client.
284    if client.is_cimd {
285        if let Some(origin) = super::registration::extract_origin(&client.client_id) {
286            if let Err(e) =
287                super::registration::check_federation_register_for_client_auth(state, &origin).await
288            {
289                return Err(ClientAuthError::TrustPolicyDenied(e));
290            }
291        }
292    }
293
294    if let Some(jwks) = client.jwks.as_ref() {
295        return extract_keys_array(jwks);
296    }
297    if let Some(uri) = client.jwks_uri.as_deref() {
298        let jwks = fetch_jwks_uri(state, uri).await?;
299        return extract_keys_array(&jwks);
300    }
301    Err(ClientAuthError::NoKeys)
302}
303
304/// Extract the `keys` array from a JWKS document. Accepts both the
305/// canonical `{"keys": [...]}` (RFC 7517) and a bare array.
306fn extract_keys_array(jwks: &Value) -> Result<Vec<Value>, ClientAuthError> {
307    if let Some(keys) = jwks.get("keys").and_then(Value::as_array) {
308        return Ok(keys.clone());
309    }
310    if let Some(keys) = jwks.as_array() {
311        return Ok(keys.clone());
312    }
313    Err(ClientAuthError::NoKeys)
314}
315
316/// SSRF + scheme check for jwks_uri. Same policy as CIMD document fetch:
317/// HTTPS only, no private / loopback / RFC 1918 hosts.
318fn validate_jwks_uri(url: &str) -> Result<(), ClientAuthError> {
319    if !url.starts_with("https://") {
320        return Err(ClientAuthError::JwksUriFetchFailed(
321            "jwks_uri must use https://".to_owned(),
322        ));
323    }
324    let parsed = url::Url::parse(url)
325        .map_err(|e| ClientAuthError::JwksUriFetchFailed(format!("invalid jwks_uri: {e}")))?;
326    if let Some(host) = parsed.host_str() {
327        if super::registration::is_private_host_for_jwks(host) {
328            return Err(ClientAuthError::JwksUriFetchFailed(
329                "jwks_uri must not point to private/loopback addresses".to_owned(),
330            ));
331        }
332    }
333    Ok(())
334}
335
336/// Fetch a jwks_uri (or return a fresh-enough cached entry). Lazy
337/// expiry: stale entries in the map are detected here and re-fetched
338/// before being used.
339async fn fetch_jwks_uri(state: &OAuthState, url: &str) -> Result<Value, ClientAuthError> {
340    // Cache check (read lock).
341    {
342        let cache = state.jwks_uri_cache.read().await;
343        if let Some((jwks, fetched_at)) = cache.get(url) {
344            if fetched_at.elapsed() < state.client_jwks_uri_cache_ttl {
345                return Ok(jwks.clone());
346            }
347        }
348    }
349
350    validate_jwks_uri(url)?;
351
352    let client = reqwest::Client::builder()
353        .timeout(JWKS_URI_FETCH_TIMEOUT)
354        .build()
355        .map_err(|e| ClientAuthError::JwksUriFetchFailed(format!("http client init: {e}")))?;
356    let response = client
357        .get(url)
358        .header("Accept", "application/json")
359        .send()
360        .await
361        .map_err(|e| ClientAuthError::JwksUriFetchFailed(format!("network: {e}")))?;
362    if !response.status().is_success() {
363        return Err(ClientAuthError::JwksUriFetchFailed(format!(
364            "HTTP {}",
365            response.status()
366        )));
367    }
368    let jwks: Value = response
369        .json()
370        .await
371        .map_err(|e| ClientAuthError::JwksUriFetchFailed(format!("parse: {e}")))?;
372
373    // Validate JWKS shape: must have `keys` array OR be a bare array.
374    let _ = extract_keys_array(&jwks)?;
375
376    // Cache (write lock).
377    state
378        .jwks_uri_cache
379        .write()
380        .await
381        .insert(url.to_owned(), (jwks.clone(), Instant::now()));
382    Ok(jwks)
383}
384
385/// RFC 7638 JWK thumbprint (SHA-256, base64url) over the required
386/// members of an OKP/EC/RSA key. Used to bind a session to the exact
387/// assertion key that verified — switching to another registered key
388/// changes the thumbprint (#1146 T3.3).
389///
390/// The member lists are already in lexicographic order as required by
391/// RFC 7638 §3.2. JWK key material is base64url by construction, so the
392/// canonical JSON needs no string escaping. Any other `kty` returns
393/// `None`, which the caller treats as an authentication failure — unknown
394/// key types fail closed rather than falling back to a weaker binding.
395fn jwk_thumbprint_sha256(jwk: &Value) -> Option<String> {
396    let get = |name: &str| jwk.get(name).and_then(Value::as_str);
397    let kty = get("kty")?;
398    let members: Vec<(&str, &str)> = match kty {
399        "OKP" => vec![("crv", get("crv")?), ("kty", kty), ("x", get("x")?)],
400        "EC" => vec![
401            ("crv", get("crv")?),
402            ("kty", kty),
403            ("x", get("x")?),
404            ("y", get("y")?),
405        ],
406        "RSA" => vec![("e", get("e")?), ("kty", kty), ("n", get("n")?)],
407        _ => return None,
408    };
409    let canonical = format!(
410        "{{{}}}",
411        members
412            .iter()
413            .map(|(k, v)| format!("\"{k}\":\"{v}\""))
414            .collect::<Vec<_>>()
415            .join(",")
416    );
417    Some(URL_SAFE_NO_PAD.encode(Sha256::digest(canonical.as_bytes())))
418}
419
420fn check_claims(
421    claims: &Value,
422    client_id: &str,
423    expected_audiences: &[String],
424) -> Result<(), ClientAuthError> {
425    let iss = claims
426        .get("iss")
427        .and_then(Value::as_str)
428        .ok_or_else(|| ClientAuthError::InvalidClaim("missing iss".to_owned()))?;
429    let sub = claims
430        .get("sub")
431        .and_then(Value::as_str)
432        .ok_or_else(|| ClientAuthError::InvalidClaim("missing sub".to_owned()))?;
433    if iss != client_id {
434        return Err(ClientAuthError::InvalidClaim(format!(
435            "iss '{iss}' does not match client_id"
436        )));
437    }
438    if sub != client_id {
439        return Err(ClientAuthError::InvalidClaim(format!(
440            "sub '{sub}' does not match client_id"
441        )));
442    }
443
444    let now = chrono::Utc::now().timestamp();
445
446    // iat is REQUIRED (#1146 T3.3): together with the mandatory jti it
447    // bounds the replay window and gives operators an issuance-time
448    // audit anchor. Reject assertions dated beyond a 60s clock skew.
449    let iat = claims
450        .get("iat")
451        .and_then(Value::as_i64)
452        .ok_or_else(|| ClientAuthError::InvalidClaim("missing iat".to_owned()))?;
453    if iat > now.saturating_add(60) {
454        return Err(ClientAuthError::InvalidClaim(format!(
455            "iat {iat} is in the future (now={now})"
456        )));
457    }
458
459    // jti is REQUIRED (#1146 T3.3): it keys the replay registry. RFC 7523
460    // §3 makes it optional, but this AS mandates it — without a unique
461    // jti there is no replay protection for a bearer assertion.
462    match claims.get("jti").and_then(Value::as_str) {
463        Some(jti) if !jti.is_empty() => {}
464        _ => return Err(ClientAuthError::InvalidClaim("missing jti".to_owned())),
465    }
466
467    // Explicit exp check — defend against jsonwebtoken's
468    // Validation::validate_exp behaviour quirks across versions.
469    let exp = claims
470        .get("exp")
471        .and_then(Value::as_i64)
472        .ok_or_else(|| ClientAuthError::InvalidClaim("missing exp".to_owned()))?;
473    if exp <= now {
474        return Err(ClientAuthError::InvalidClaim(format!(
475            "exp {exp} is not in the future (now={now})"
476        )));
477    }
478    let _lifetime = exp
479        .checked_sub(iat)
480        .filter(|lifetime| *lifetime > 0 && *lifetime <= MAX_CLIENT_ASSERTION_LIFETIME_SECS)
481        .ok_or_else(|| ClientAuthError::InvalidClaim("assertion lifetime is invalid".to_owned()))?;
482
483    // aud may be a string or an array of strings (RFC 7519 §4.1.3). It
484    // must include one of the accepted audiences — on all profile paths
485    // that is the AS issuer alone (#1146 T1.2).
486    let aud_matches = |candidate: &str| expected_audiences.iter().any(|e| e == candidate);
487    let aud_ok = match claims.get("aud") {
488        Some(Value::String(s)) => aud_matches(s),
489        Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).any(aud_matches),
490        _ => false,
491    };
492    if !aud_ok {
493        return Err(ClientAuthError::InvalidClaim(format!(
494            "aud does not include any of {expected_audiences:?}"
495        )));
496    }
497
498    Ok(())
499}
500
501#[cfg(test)]
502#[allow(clippy::unwrap_used, clippy::expect_used)]
503mod tests {
504    use super::*;
505    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
506    use ed25519_dalek::{Signer, SigningKey};
507    use std::time::Instant;
508
509    fn make_client(
510        client_id: &str,
511        jwks: serde_json::Value,
512        auth_method: &str,
513    ) -> RegisteredClient {
514        RegisteredClient {
515            client_id: client_id.to_owned(),
516            redirect_uris: vec!["http://localhost/cb".to_owned()],
517            client_name: None,
518            client_uri: None,
519            logo_uri: None,
520            grant_types: vec![],
521            response_types: vec![],
522            token_endpoint_auth_method: Some(auth_method.to_owned()),
523            jwks: Some(jwks),
524            jwks_uri: None,
525            hyprstream_node_did: None,
526            scope: None,
527            dpop_bound_access_tokens: None,
528            is_cimd: true,
529            registered_at: Instant::now(),
530        }
531    }
532
533    fn ed25519_keypair_and_jwk() -> (SigningKey, serde_json::Value) {
534        let mut rng = rand::rngs::OsRng;
535        let sk = SigningKey::generate(&mut rng);
536        let vk = sk.verifying_key();
537        let x = URL_SAFE_NO_PAD.encode(vk.to_bytes());
538        let jwk = serde_json::json!({
539            "kty": "OKP",
540            "crv": "Ed25519",
541            "x": x,
542            "kid": "k1",
543        });
544        (sk, jwk)
545    }
546
547    /// Sign a JWT manually with ed25519-dalek — avoids needing a PKCS#8
548    /// DER encoding just for tests.
549    fn make_ed_assertion(sk: &SigningKey, claims: serde_json::Value) -> String {
550        let header = serde_json::json!({"alg": "EdDSA", "typ": "JWT", "kid": "k1"});
551        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
552        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
553        let signing_input = format!("{header_b64}.{payload_b64}");
554        let sig = sk.sign(signing_input.as_bytes());
555        let sig_b64 = URL_SAFE_NO_PAD.encode(sig.to_bytes());
556        format!("{signing_input}.{sig_b64}")
557    }
558
559    fn keys_array(jwk: serde_json::Value) -> Vec<serde_json::Value> {
560        vec![jwk]
561    }
562
563    /// The accepted audience set used by BOTH the PAR and token endpoints
564    /// (#1146 T1.2 rev): the AS issuer alone.
565    fn issuer_audiences() -> Vec<String> {
566        vec!["https://hs.test".to_owned()]
567    }
568
569    /// Baseline valid claims: iss/sub, issuer-form aud, iat, jti, exp.
570    fn valid_claims() -> serde_json::Value {
571        serde_json::json!({
572            "iss": "https://app.test/c",
573            "sub": "https://app.test/c",
574            "aud": "https://hs.test",
575            "iat": chrono::Utc::now().timestamp(),
576            "exp": chrono::Utc::now().timestamp() + 60,
577            "jti": "j1",
578        })
579    }
580
581    #[test]
582    fn valid_assertion_round_trip() {
583        // #1146 T1.2: the atproto-mandated audience is the AS ISSUER.
584        let (sk, jwk) = ed25519_keypair_and_jwk();
585        let assertion = make_ed_assertion(&sk, valid_claims());
586        let got = verify_assertion_with_keys(
587            &keys_array(jwk),
588            "https://app.test/c",
589            &assertion,
590            &issuer_audiences(),
591        );
592        assert!(got.is_ok(), "verify failed: {:?}", got.err());
593    }
594
595    #[test]
596    fn rejects_token_endpoint_audience() {
597        // #1146 T1.2 (rev): RFC 7523 §3 permits the token endpoint URL as
598        // aud, but the atproto OAuth profile mandates the issuer ALONE.
599        // Accepting the endpoint form would leave it valid as an assertion
600        // target — it must be rejected at the token endpoint too.
601        let (sk, jwk) = ed25519_keypair_and_jwk();
602        let mut claims = valid_claims();
603        claims["aud"] = serde_json::json!("https://hs.test/oauth/token");
604        let assertion = make_ed_assertion(&sk, claims);
605        let got = verify_assertion_with_keys(
606            &keys_array(jwk),
607            "https://app.test/c",
608            &assertion,
609            &issuer_audiences(),
610        );
611        assert!(
612            matches!(got, Err(ClientAuthError::InvalidClaim(_))),
613            "token-endpoint aud must be rejected (issuer-only): {got:?}"
614        );
615    }
616
617    #[test]
618    fn rejects_missing_iat() {
619        let (sk, jwk) = ed25519_keypair_and_jwk();
620        let mut claims = valid_claims();
621        claims.as_object_mut().unwrap().remove("iat");
622        let assertion = make_ed_assertion(&sk, claims);
623        let got = verify_assertion_with_keys(
624            &keys_array(jwk),
625            "https://app.test/c",
626            &assertion,
627            &issuer_audiences(),
628        );
629        assert!(
630            matches!(&got, Err(ClientAuthError::InvalidClaim(c)) if c.contains("iat")),
631            "missing iat must be rejected: {got:?}"
632        );
633    }
634
635    #[test]
636    fn rejects_future_iat() {
637        let (sk, jwk) = ed25519_keypair_and_jwk();
638        let mut claims = valid_claims();
639        claims["iat"] = serde_json::json!(chrono::Utc::now().timestamp() + 3600);
640        let assertion = make_ed_assertion(&sk, claims);
641        let got = verify_assertion_with_keys(
642            &keys_array(jwk),
643            "https://app.test/c",
644            &assertion,
645            &issuer_audiences(),
646        );
647        assert!(
648            matches!(&got, Err(ClientAuthError::InvalidClaim(c)) if c.contains("iat")),
649            "future iat must be rejected: {got:?}"
650        );
651    }
652
653    #[test]
654    fn rejects_extreme_timestamp_interval_without_overflow() {
655        let mut claims = valid_claims();
656        claims["iat"] = serde_json::json!(i64::MIN);
657        claims["exp"] = serde_json::json!(i64::MAX);
658        let got = check_claims(&claims, "https://app.test/c", &issuer_audiences());
659        assert!(matches!(got, Err(ClientAuthError::InvalidClaim(_))));
660    }
661
662    #[test]
663    fn accepts_maximum_admitted_future_skew_and_lifetime() {
664        let mut claims = valid_claims();
665        let now = chrono::Utc::now().timestamp();
666        let iat = now + 60;
667        claims["iat"] = serde_json::json!(iat);
668        claims["exp"] = serde_json::json!(iat + MAX_CLIENT_ASSERTION_LIFETIME_SECS);
669        assert!(check_claims(&claims, "https://app.test/c", &issuer_audiences()).is_ok());
670    }
671
672    #[test]
673    fn rejects_missing_jti() {
674        let (sk, jwk) = ed25519_keypair_and_jwk();
675        let mut claims = valid_claims();
676        claims.as_object_mut().unwrap().remove("jti");
677        let assertion = make_ed_assertion(&sk, claims);
678        let got = verify_assertion_with_keys(
679            &keys_array(jwk),
680            "https://app.test/c",
681            &assertion,
682            &issuer_audiences(),
683        );
684        assert!(
685            matches!(&got, Err(ClientAuthError::InvalidClaim(c)) if c.contains("jti")),
686            "missing jti must be rejected: {got:?}"
687        );
688    }
689
690    #[test]
691    fn rejects_wrong_audience() {
692        let (sk, jwk) = ed25519_keypair_and_jwk();
693        let mut claims = valid_claims();
694        claims["aud"] = serde_json::json!("https://attacker.test/oauth/token");
695        let assertion = make_ed_assertion(&sk, claims);
696        let got = verify_assertion_with_keys(
697            &keys_array(jwk),
698            "https://app.test/c",
699            &assertion,
700            &issuer_audiences(),
701        );
702        assert!(matches!(got, Err(ClientAuthError::InvalidClaim(_))));
703    }
704
705    #[test]
706    fn rejects_wrong_iss() {
707        let (sk, jwk) = ed25519_keypair_and_jwk();
708        let mut claims = valid_claims();
709        claims["iss"] = serde_json::json!("https://impostor.test/c");
710        claims["sub"] = serde_json::json!("https://impostor.test/c");
711        let assertion = make_ed_assertion(&sk, claims);
712        let got = verify_assertion_with_keys(
713            &keys_array(jwk),
714            "https://app.test/c",
715            &assertion,
716            &issuer_audiences(),
717        );
718        assert!(matches!(got, Err(ClientAuthError::InvalidClaim(_))));
719    }
720
721    #[test]
722    fn rejects_expired_assertion() {
723        let (sk, jwk) = ed25519_keypair_and_jwk();
724        let mut claims = valid_claims();
725        claims["exp"] = serde_json::json!(chrono::Utc::now().timestamp() - 60);
726        let assertion = make_ed_assertion(&sk, claims);
727        let got = verify_assertion_with_keys(
728            &keys_array(jwk),
729            "https://app.test/c",
730            &assertion,
731            &issuer_audiences(),
732        );
733        assert!(got.is_err(), "expired assertion should not verify: {got:?}");
734    }
735
736    #[test]
737    fn rejects_client_assertion_lifetime_over_replay_barrier_window() {
738        let mut claims = valid_claims();
739        let now = chrono::Utc::now().timestamp();
740        claims["iat"] = serde_json::json!(now);
741        claims["exp"] = serde_json::json!(now + MAX_CLIENT_ASSERTION_LIFETIME_SECS + 1);
742        let got = check_claims(&claims, "https://app.test/c", &issuer_audiences());
743        assert!(
744            matches!(got, Err(ClientAuthError::InvalidClaim(message)) if message.contains("lifetime"))
745        );
746    }
747
748    #[test]
749    fn rejects_empty_keys_set() {
750        let got = verify_assertion_with_keys(
751            &[],
752            "https://app.test/c",
753            "irrelevant",
754            &issuer_audiences(),
755        );
756        assert!(got.is_err(), "empty key set must not verify");
757    }
758
759    #[test]
760    fn extract_keys_supports_bare_array_and_keys_wrapper() {
761        let jwk = serde_json::json!({"kty": "OKP", "crv": "Ed25519", "x": "abc"});
762        let wrapped = serde_json::json!({"keys": [jwk.clone()]});
763        let bare = serde_json::json!([jwk]);
764        assert_eq!(extract_keys_array(&wrapped).unwrap().len(), 1);
765        assert_eq!(extract_keys_array(&bare).unwrap().len(), 1);
766        assert!(extract_keys_array(&serde_json::json!({"other": 1})).is_err());
767    }
768
769    #[test]
770    fn jwks_uri_blocks_non_https() {
771        let got = validate_jwks_uri("http://app.test/jwks.json");
772        assert!(matches!(got, Err(ClientAuthError::JwksUriFetchFailed(_))));
773    }
774
775    #[test]
776    fn jwks_uri_blocks_private_hosts() {
777        for url in &[
778            "https://localhost/jwks.json",
779            "https://127.0.0.1/jwks.json",
780            "https://10.0.0.1/jwks.json",
781            "https://192.168.1.1/jwks.json",
782        ] {
783            let got = validate_jwks_uri(url);
784            assert!(
785                matches!(got, Err(ClientAuthError::JwksUriFetchFailed(_))),
786                "expected SSRF rejection for {url}"
787            );
788        }
789    }
790
791    #[test]
792    fn alg_confusion_hs256_header_against_rsa_jwk_is_rejected() {
793        // Canonical alg-confusion attack: a malicious assertion declares
794        // alg=HS256 in the header, hoping the verifier will HMAC-verify
795        // the JWT using the RSA public key (as bytes) — which the client
796        // also knows. Our defense: alg is derived from JWK kty (RSA →
797        // RS256), not from the header. The signature verify must use
798        // RS256 against the HMAC-signed payload and fail.
799        //
800        // Build a JWS structure with alg=HS256 in the header and a
801        // bogus signature, against an RSA JWK. verify must reject.
802        let rsa_jwk = serde_json::json!({
803            "kty": "RSA",
804            "n": "u1SU1LfVLPHCozMxH2Mo4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0_IzW7yWR7QkrmBL7jTKEn5u-qKhbwKfBstIs-bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyehkd3qqGElvW_VDL5AaWTg0nLVkjRo9z-40RQzuVaE8AkAFmxZzow3x-VJYKdjykkJ0iT9wCS0DRTXu269V264Vf_3jvredZiKRkgwlL9xNAwxXFg0x_XFw005UWVRIkdgcKWTjpBP2dPwVZ4WWC-9aGVd-Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbcmw",
805            "e": "AQAB",
806            "kid": "rsa1",
807        });
808        // A header with alg=HS256 (attacker-controlled), body, and
809        // signature computed by HMAC-SHA256 with the public-RSA bytes
810        // as key. We don't need to actually compute it — the structural
811        // claim is that decoding will fail because:
812        //   - algorithm_for_key_pub returns RS256 (from kty=RSA)
813        //   - decode<>(token, key, validation_with_RS256_alg) checks
814        //     the header alg matches the Validation's allowed algs
815        //     (jsonwebtoken rejects HS256 token with RS256 validation)
816        let bogus_assertion = format!(
817            "{}.{}.{}",
818            URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","typ":"JWT","kid":"rsa1"}"#),
819            URL_SAFE_NO_PAD.encode(br#"{"iss":"https://app.test/c","sub":"https://app.test/c","aud":"https://hs.test/oauth/token","exp":9999999999}"#),
820            URL_SAFE_NO_PAD.encode([0u8; 32]),
821        );
822        let got = verify_assertion_with_keys(
823            &[rsa_jwk],
824            "https://app.test/c",
825            &bogus_assertion,
826            &issuer_audiences(),
827        );
828        assert!(
829            matches!(got, Err(ClientAuthError::InvalidSignature)),
830            "HS256 header against RSA JWK MUST be rejected; got {got:?}"
831        );
832    }
833
834    #[test]
835    fn jwks_uri_accepts_public_https() {
836        // We can't fetch in a unit test; just verify the SSRF + scheme
837        // gate lets a plausible URL through.
838        let got = validate_jwks_uri("https://app.example.com/jwks.json");
839        assert!(got.is_ok());
840    }
841
842    #[test]
843    fn requires_private_key_jwt_only_when_configured() {
844        let (_, jwk) = ed25519_keypair_and_jwk();
845        let jwks = serde_json::json!({"keys": [jwk]});
846        let mut client = make_client("https://app.test/c", jwks, "private_key_jwt");
847        assert!(requires_private_key_jwt(&client));
848        client.token_endpoint_auth_method = Some("none".to_owned());
849        assert!(!requires_private_key_jwt(&client));
850        client.token_endpoint_auth_method = None;
851        assert!(!requires_private_key_jwt(&client));
852    }
853}