1use 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
36const JWKS_URI_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
38
39#[derive(Debug, Clone)]
41pub enum ClientAuthError {
42 MissingAssertion,
45 UnsupportedAssertionType(String),
49 NoKeys,
52 JwksUriFetchFailed(String),
55 TrustPolicyDenied(String),
58 Malformed(String),
60 InvalidSignature,
62 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
89const MAX_CLIENT_ASSERTION_LIFETIME_SECS: i64 = 300;
92
93#[derive(Debug, Clone)]
95pub struct VerifiedAssertion {
96 pub claims: Value,
98 pub key_jkt: String,
102}
103
104pub 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
114pub 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 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
160pub 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 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 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 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; 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 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
272async fn resolve_keys(
276 state: &OAuthState,
277 client: &RegisteredClient,
278) -> Result<Vec<Value>, ClientAuthError> {
279 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
304fn 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
316fn 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
336async fn fetch_jwks_uri(state: &OAuthState, url: &str) -> Result<Value, ClientAuthError> {
340 {
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 let _ = extract_keys_array(&jwks)?;
375
376 state
378 .jwks_uri_cache
379 .write()
380 .await
381 .insert(url.to_owned(), (jwks.clone(), Instant::now()));
382 Ok(jwks)
383}
384
385fn 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 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 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 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 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 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 fn issuer_audiences() -> Vec<String> {
566 vec!["https://hs.test".to_owned()]
567 }
568
569 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 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 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 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 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 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}