1use std::collections::HashMap;
14use std::future::Future;
15use std::pin::Pin;
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::Arc;
18use std::sync::Mutex as StdMutex;
19use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
20
21use base64::Engine as _;
22use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
23use serde::{Deserialize, Serialize};
24use serde_json::{Map, Value};
25use tokio::sync::{Mutex, RwLock};
26
27use crate::error::AuthError;
28use crate::logout::{
29 check_logout_claims, is_logout_typ, LogoutFailure, LogoutToken,
30 DEFAULT_LOGOUT_TOKEN_MAX_AGE_SECONDS,
31};
32use crate::policy::{validate_claims, validate_typ_header, ValidationPolicy};
33
34pub const DEFAULT_MIN_FETCH_INTERVAL: Duration = Duration::from_secs(10);
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct Claims {
42 pub sub: String,
43 pub iss: Option<String>,
44 pub aud: Option<serde_json::Value>,
45 pub exp: i64,
46 pub iat: i64,
47 #[serde(rename = "type")]
48 pub typ: String,
49 pub jti: Option<String>,
50 pub client_id: Option<String>,
51 pub session_id: Option<String>,
52 pub central_user_id: Option<String>,
53 pub auth_user_id: Option<String>,
54 pub scopes: Option<Vec<String>>,
55 pub scope: Option<String>,
56 pub app: Option<String>,
57 pub email: Option<String>,
58 pub token_version: Option<i64>,
59 pub permissions_version: Option<i64>,
60 pub is_system_admin: Option<bool>,
61 pub identity_class: Option<String>,
62}
63
64#[derive(Debug, Clone)]
72pub struct CurrentUser {
73 pub id: String,
74 pub issuer: Option<String>,
76 pub email: String,
77 pub scopes: Vec<String>,
78 pub firm_id: Option<String>,
79 pub auth_user_id: Option<String>,
80 pub session_id: Option<String>,
81 pub app: Option<String>,
82 pub token_version: i64,
83 pub permissions_version: i64,
84 pub is_system_admin: bool,
85 pub identity_class: Option<String>,
86}
87
88impl CurrentUser {
89 pub fn central_identity_id(&self) -> &str {
90 self.auth_user_id.as_deref().unwrap_or(&self.id)
91 }
92 pub fn has_scope(&self, scope: &str) -> bool {
93 let requires_admin = scope == "admin:*" || scope.starts_with("admin:");
94 if requires_admin && !self.is_system_admin {
95 return false;
96 }
97 if (self.scopes.contains(&"admin:*".to_string()) && self.is_system_admin)
98 || self.scopes.contains(&scope.to_string())
99 {
100 return true;
101 }
102 if let Some((ns, _)) = scope.split_once(':') {
103 return self.scopes.contains(&format!("{ns}:*"));
104 }
105 false
106 }
107 pub fn is_admin(&self) -> bool {
108 self.scopes.contains(&"admin:*".to_string()) && self.is_system_admin
109 }
110}
111
112fn claims_to_user(map: Map<String, Value>) -> Result<CurrentUser, AuthError> {
113 let c: Claims = serde_json::from_value(Value::Object(map))
114 .map_err(|e| AuthError::jwt(e.to_string(), "invalid"))?;
115 if c.sub.is_empty() {
116 return Err(AuthError::jwt("Missing sub", "invalid"));
117 }
118 let scopes = c.scopes.clone().unwrap_or_else(|| {
119 c.scope
120 .as_deref()
121 .unwrap_or("")
122 .split_whitespace()
123 .map(String::from)
124 .collect()
125 });
126 let is_system_admin =
127 c.is_system_admin.unwrap_or(false) || c.identity_class.as_deref() == Some("system_admin");
128 Ok(CurrentUser {
129 id: c.sub.clone(),
130 issuer: c.iss.clone().filter(|iss| !iss.is_empty()),
131 email: c.email.clone().unwrap_or_default(),
132 scopes,
133 firm_id: None,
134 auth_user_id: c.central_user_id.clone().or(c.auth_user_id.clone()),
135 session_id: c.session_id.clone(),
136 app: c.app.clone(),
137 token_version: c.token_version.unwrap_or(0),
138 permissions_version: c.permissions_version.unwrap_or(0),
139 is_system_admin,
140 identity_class: c.identity_class.clone(),
141 })
142}
143
144fn normalize_issuer(url: &str) -> String {
145 url.trim_end_matches('/').to_string()
146}
147
148#[derive(Debug, Clone)]
151pub struct IssuerConfig {
152 pub issuer_url: String,
153 pub jwks_uri: Option<String>,
154}
155
156impl IssuerConfig {
157 pub fn new(issuer_url: impl Into<String>) -> Self {
158 Self {
159 issuer_url: issuer_url.into(),
160 jwks_uri: None,
161 }
162 }
163 pub fn with_jwks_uri(mut self, uri: impl Into<String>) -> Self {
164 self.jwks_uri = Some(uri.into());
165 self
166 }
167}
168
169impl From<&str> for IssuerConfig {
170 fn from(issuer_url: &str) -> Self {
171 Self::new(issuer_url)
172 }
173}
174impl From<String> for IssuerConfig {
175 fn from(issuer_url: String) -> Self {
176 Self::new(issuer_url)
177 }
178}
179
180#[derive(Debug, Clone, Deserialize)]
181struct Jwks {
182 keys: Vec<Jwk>,
183}
184#[derive(Debug, Clone, Deserialize)]
188struct Jwk {
189 kty: String,
190 #[serde(rename = "use")]
191 use_: Option<String>,
192 alg: Option<String>,
193 kid: Option<String>,
194 n: Option<String>,
195 e: Option<String>,
196}
197
198fn key_algorithm(k: &Jwk) -> Option<Algorithm> {
202 if k.kty != "RSA" || k.use_.as_deref().is_some_and(|usage| usage != "sig") {
203 return None;
204 }
205 match k.alg.as_deref() {
206 None | Some("RS256") => Some(Algorithm::RS256),
207 Some(_) => None,
208 }
209}
210
211fn algorithm_name(alg: Algorithm) -> &'static str {
213 match alg {
214 Algorithm::RS256 => "RS256",
215 _ => "unsupported",
216 }
217}
218
219#[derive(Clone)]
221struct VerificationKey {
222 key: DecodingKey,
223 alg: Algorithm,
224}
225
226struct Cached {
227 fetched_at: Instant,
228 keys: HashMap<String, VerificationKey>,
229}
230
231struct IssuerState {
234 issuer: String,
235 jwks_uri: Option<String>,
236 cache: RwLock<Option<Cached>>,
237 last_attempt: StdMutex<Option<Instant>>,
240 fetch_lock: Mutex<()>,
242 generation: AtomicU64,
244}
245
246impl IssuerState {
247 fn new(issuer: String, jwks_uri: Option<String>) -> Self {
248 Self {
249 issuer,
250 jwks_uri,
251 cache: RwLock::new(None),
252 last_attempt: StdMutex::new(None),
253 fetch_lock: Mutex::new(()),
254 generation: AtomicU64::new(0),
255 }
256 }
257
258 fn jwks_uri_resolved(&self) -> String {
259 self.jwks_uri
260 .clone()
261 .unwrap_or_else(|| format!("{}/.well-known/jwks.json", self.issuer))
262 }
263}
264
265pub struct MultiIssuerVerifier {
271 issuers: HashMap<String, IssuerState>,
273 order: Vec<String>,
275 audience: Vec<String>,
278 ttl: Duration,
279 min_fetch_interval: Duration,
280 clock_skew: Duration,
282 require_at_jwt: bool,
284 http: reqwest::Client,
285}
286
287impl MultiIssuerVerifier {
288 pub fn new(audience: impl Into<String>) -> Self {
295 let audience = audience.into();
296 Self {
297 issuers: HashMap::new(),
298 order: Vec::new(),
299 audience: if audience.trim().is_empty() {
300 Vec::new()
301 } else {
302 vec![audience]
303 },
304 ttl: Duration::from_secs(300),
305 min_fetch_interval: DEFAULT_MIN_FETCH_INTERVAL,
306 clock_skew: Duration::ZERO,
307 require_at_jwt: true,
308 http: reqwest::Client::builder()
309 .timeout(Duration::from_secs(10))
310 .build()
311 .unwrap_or_else(|_| reqwest::Client::new()),
312 }
313 }
314 pub fn with_issuer(mut self, issuer: impl Into<IssuerConfig>) -> Self {
318 let IssuerConfig {
319 issuer_url,
320 jwks_uri,
321 } = issuer.into();
322 let issuer = normalize_issuer(&issuer_url);
323 if issuer.trim().is_empty() {
324 return self;
325 }
326 match self.issuers.get_mut(&issuer) {
327 Some(existing) => {
328 if existing.jwks_uri.is_none() {
329 existing.jwks_uri = jwks_uri;
330 }
331 }
332 None => {
333 self.order.push(issuer.clone());
334 self.issuers
335 .insert(issuer.clone(), IssuerState::new(issuer, jwks_uri));
336 }
337 }
338 self
339 }
340 pub fn with_audience(mut self, aud: impl Into<String>) -> Self {
343 let a = aud.into();
344 if !a.trim().is_empty() && !self.audience.contains(&a) {
345 self.audience.push(a);
346 }
347 self
348 }
349 pub fn with_audiences(mut self, auds: Vec<String>) -> Self {
351 for aud in auds {
352 self = self.with_audience(aud);
353 }
354 self
355 }
356 pub fn with_ttl(mut self, ttl: Duration) -> Self {
357 self.ttl = ttl;
358 self
359 }
360 pub fn with_min_fetch_interval(mut self, interval: Duration) -> Self {
364 self.min_fetch_interval = interval;
365 self
366 }
367 pub fn allow_legacy_typ(mut self) -> Self {
371 self.require_at_jwt = false;
372 self
373 }
374 pub fn with_clock_skew(mut self, skew: Duration) -> Self {
378 self.clock_skew = skew;
379 self
380 }
381
382 pub fn issuers(&self) -> Vec<String> {
384 self.order.clone()
385 }
386
387 async fn fetch_jwks(&self, state: &IssuerState) -> Result<Jwks, AuthError> {
388 let uri = state.jwks_uri_resolved();
389 let resp = self
390 .http
391 .get(&uri)
392 .send()
393 .await
394 .map_err(|e| AuthError::Network(e.to_string()))?;
395 if !resp.status().is_success() {
396 return Err(AuthError::Network(format!(
397 "JWKS fetch failed: {}",
398 resp.status()
399 )));
400 }
401 resp.json::<Jwks>()
402 .await
403 .map_err(|e| AuthError::Network(e.to_string()))
404 }
405
406 fn fetch_allowed(&self, state: &IssuerState) -> bool {
410 if self.min_fetch_interval.is_zero() {
411 return true;
412 }
413 match *state.last_attempt.lock().expect("last_attempt lock") {
414 None => true,
415 Some(at) => at.elapsed() >= self.min_fetch_interval,
416 }
417 }
418
419 async fn refresh(&self, state: &IssuerState, seen: u64) -> Result<bool, AuthError> {
424 let _flight = state.fetch_lock.lock().await;
425 if state.generation.load(Ordering::Acquire) != seen {
426 return Ok(true);
427 }
428 if !self.fetch_allowed(state) {
429 return Ok(false);
430 }
431 *state.last_attempt.lock().expect("last_attempt lock") = Some(Instant::now());
434 let jwks = self.fetch_jwks(state).await?;
435 let mut keys = HashMap::new();
436 for k in &jwks.keys {
437 let (Some(kid), Some(n), Some(e), Some(alg)) = (
438 k.kid.as_deref(),
439 k.n.as_deref(),
440 k.e.as_deref(),
441 key_algorithm(k),
442 ) else {
443 continue;
444 };
445 if kid.is_empty() {
446 continue;
447 }
448 if let Ok(pem) = crate::jwk::jwk_to_pem(n, e) {
449 if let Ok(key) = DecodingKey::from_rsa_pem(pem.as_bytes()) {
450 keys.insert(kid.to_string(), VerificationKey { key, alg });
451 }
452 }
453 }
454 *state.cache.write().await = Some(Cached {
455 fetched_at: Instant::now(),
456 keys,
457 });
458 state.generation.fetch_add(1, Ordering::Release);
459 Ok(true)
460 }
461
462 async fn cache_stale(&self, state: &IssuerState) -> bool {
463 match &*state.cache.read().await {
464 None => true,
465 Some(c) => c.fetched_at.elapsed() > self.ttl,
466 }
467 }
468
469 async fn lookup(&self, state: &IssuerState, kid: &str) -> Result<VerificationKey, bool> {
472 let g = state.cache.read().await;
473 let Some(c) = &*g else { return Err(false) };
474 let hit = if !kid.is_empty() {
475 c.keys.get(kid)
476 } else if c.keys.len() == 1 {
477 c.keys.values().next()
479 } else {
480 None
481 };
482 hit.cloned().ok_or(!c.keys.is_empty())
483 }
484
485 async fn key_for_kid(
488 &self,
489 state: &IssuerState,
490 kid: &str,
491 ) -> Result<VerificationKey, AuthError> {
492 let seen = state.generation.load(Ordering::Acquire);
493 let mut refreshed = false;
496 if self.cache_stale(state).await {
497 refreshed = self.refresh(state, seen).await?;
499 }
500 let mut miss = match self.lookup(state, kid).await {
501 Ok(key) => return Ok(key),
502 Err(has_keys) => has_keys,
503 };
504 if !refreshed {
505 if !self.refresh(state, seen).await? {
506 return Err(AuthError::jwt(
507 format!("Unknown kid: {kid} (JWKS refresh bounded)"),
508 "kid_mismatch",
509 ));
510 }
511 miss = match self.lookup(state, kid).await {
512 Ok(key) => return Ok(key),
513 Err(has_keys) => has_keys,
514 };
515 }
516 Err(if !miss {
517 AuthError::jwt("No RSA signing key in JWKS", "missing_key")
518 } else if kid.is_empty() {
519 AuthError::jwt("missing kid in a multi-key JWKS", "kid_mismatch")
520 } else {
521 AuthError::jwt(format!("Unknown kid: {kid}"), "kid_mismatch")
522 })
523 }
524
525 fn decode_claims(
526 &self,
527 token: &str,
528 key: &VerificationKey,
529 ) -> Result<Map<String, Value>, AuthError> {
530 let mut validation = Validation::new(key.alg);
533 validation.validate_aud = false; validation.validate_exp = true;
535 validation.required_spec_claims.insert("exp".to_string());
536 validation.leeway = leeway_seconds(self.clock_skew);
537 decode::<Map<String, Value>>(token, &key.key, &validation)
538 .map(|d| d.claims)
539 .map_err(|e| {
540 let msg = e.to_string();
541 if msg.contains("ExpiredSignature") || msg.to_lowercase().contains("expired") {
542 AuthError::jwt(msg, "expired")
543 } else if msg.contains("InvalidIssuer") {
544 AuthError::jwt(msg, "issuer_mismatch")
545 } else {
546 AuthError::jwt(msg, "invalid")
547 }
548 })
549 }
550
551 fn route(&self, token: &str, policy: &ValidationPolicy) -> Result<&IssuerState, AuthError> {
556 let payload = token
557 .split('.')
558 .nth(1)
559 .ok_or_else(|| AuthError::jwt("Invalid token payload", "invalid"))?;
560 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
561 .decode(payload.trim_end_matches('='))
562 .map_err(|e| AuthError::jwt(format!("Invalid token payload: {e}"), "invalid"))?;
563 let unverified: Value = serde_json::from_slice(&bytes)
564 .map_err(|e| AuthError::jwt(format!("Invalid token payload: {e}"), "invalid"))?;
565 match unverified.get("iss") {
566 None | Some(Value::Null) => {
567 if self.order.len() == 1 {
572 return Ok(&self.issuers[&self.order[0]]);
573 }
574 Err(AuthError::jwt(
575 "token has no iss claim to select an allow-listed issuer",
576 "issuer_mismatch",
577 ))
578 }
579 Some(iss) => {
580 let state = iss.as_str().and_then(|iss| self.issuers.get(iss));
581 match state {
582 Some(state)
583 if policy.trusted_issuers.is_empty()
584 || policy.trusted_issuers.contains(&state.issuer) =>
585 {
586 Ok(state)
587 }
588 _ => Err(AuthError::jwt(
589 format!("untrusted issuer {iss}"),
590 "issuer_mismatch",
591 )),
592 }
593 }
594 }
595 }
596
597 pub async fn verify_claims(
604 &self,
605 token: &str,
606 policy: &ValidationPolicy,
607 ) -> Result<Map<String, Value>, AuthError> {
608 let header = jsonwebtoken::decode_header(token)
609 .map_err(|e| AuthError::jwt(e.to_string(), "invalid"))?;
610 validate_typ_header(header.typ.as_deref(), policy)?;
611 if self.order.is_empty() {
612 return Err(AuthError::jwt(
613 "verifier issuer allow-list is empty: list the exact issuers this resource server trusts",
614 "issuer_mismatch",
615 ));
616 }
617 let state = self.route(token, policy)?;
618 let kid = header.kid.clone().unwrap_or_default();
619 let key = self.key_for_kid(state, &kid).await?;
620 let claims = self.decode_claims(token, &key)?;
621 validate_claims(&claims, policy)?;
622 Ok(claims)
623 }
624
625 pub async fn verify_logout_token(
643 &self,
644 token: &str,
645 options: &LogoutTokenOptions,
646 ) -> Result<LogoutToken, AuthError> {
647 if options.client_ids.is_empty() || options.client_ids.iter().any(|id| id.trim().is_empty())
648 {
649 return Err(AuthError::Config(
650 "client_id is required: the client id(s) this relying party is".into(),
651 ));
652 }
653 let max_age = options
654 .max_age
655 .unwrap_or(Duration::from_secs(DEFAULT_LOGOUT_TOKEN_MAX_AGE_SECONDS));
656 if max_age.is_zero() {
657 return Err(AuthError::Config(
658 "max_age must be a positive duration".into(),
659 ));
660 }
661 let now = options.now.unwrap_or_else(|| {
662 SystemTime::now()
663 .duration_since(UNIX_EPOCH)
664 .map(|d| d.as_secs_f64())
665 .unwrap_or(0.0)
666 });
667 let reject = |reason: LogoutFailure| AuthError::from(reason);
668 let parts: Vec<&str> = token.split('.').collect();
669 if token.len() > 16_384 || parts.len() != 3 {
670 return Err(reject(LogoutFailure::Signature));
671 }
672 let object = |segment: &str| -> Option<Map<String, Value>> {
673 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
674 .decode(segment.trim_end_matches('='))
675 .ok()?;
676 match serde_json::from_slice::<Value>(&bytes).ok()? {
677 Value::Object(map) => Some(map),
678 _ => None,
679 }
680 };
681 let (Some(header), Some(unverified)) = (object(parts[0]), object(parts[1])) else {
682 return Err(reject(LogoutFailure::Signature));
683 };
684 if !is_logout_typ(header.get("typ").and_then(Value::as_str)) {
685 return Err(reject(LogoutFailure::Typ));
686 }
687 let state = unverified
689 .get("iss")
690 .and_then(Value::as_str)
691 .and_then(|iss| self.issuers.get(iss))
692 .ok_or_else(|| reject(LogoutFailure::Issuer))?;
693 let kid = header.get("kid").and_then(Value::as_str).unwrap_or("");
694 let key = match self.key_for_kid(state, kid).await {
695 Ok(key) => key,
696 Err(AuthError::Jwt { .. }) => return Err(reject(LogoutFailure::Key)),
697 Err(other) => return Err(other),
698 };
699 if header.get("alg").and_then(Value::as_str) != Some(algorithm_name(key.alg)) {
703 return Err(reject(LogoutFailure::Signature));
704 }
705 let signed = format!("{}.{}", parts[0], parts[1]);
706 if !jsonwebtoken::crypto::verify(parts[2], signed.as_bytes(), &key.key, key.alg)
707 .unwrap_or(false)
708 {
709 return Err(reject(LogoutFailure::Signature));
710 }
711 let claims = unverified;
712 let skew = self.clock_skew.as_secs_f64();
713 for name in ["exp", "nbf", "iat"] {
714 if claims.contains_key(name)
715 && !claims
716 .get(name)
717 .and_then(Value::as_f64)
718 .is_some_and(f64::is_finite)
719 {
720 return Err(reject(LogoutFailure::Claims));
721 }
722 }
723 let number = |name: &str| claims.get(name).and_then(Value::as_f64);
724 if number("exp").is_some_and(|exp| exp <= now - skew) {
725 return Err(reject(LogoutFailure::Expired));
726 }
727 if number("nbf").is_some_and(|nbf| nbf > now + skew) {
728 return Err(reject(LogoutFailure::Claims));
729 }
730 let result = check_logout_claims(
731 &claims,
732 &options.client_ids,
733 now,
734 max_age.as_secs_f64(),
735 skew,
736 )
737 .map_err(AuthError::LogoutToken)?;
738 if let Some(consume) = &options.consume_jti {
739 if !consume(&result.jti, result.expires_at).await {
740 return Err(reject(LogoutFailure::Replay));
741 }
742 }
743 Ok(result)
744 }
745
746 pub async fn verify(&self, token: &str) -> Result<CurrentUser, AuthError> {
752 self.verify_with(token, Some(self.audience.clone()), None)
753 .await
754 }
755
756 pub async fn verify_with(
758 &self,
759 token: &str,
760 audience: Option<Vec<String>>,
761 issuer: Option<String>,
762 ) -> Result<CurrentUser, AuthError> {
763 let trusted: Vec<String> = match issuer {
764 Some(issuer) => vec![normalize_issuer(&issuer)],
765 None => self.order.clone(),
766 };
767 let aud = audience
768 .filter(|auds| auds.iter().any(|a| !a.trim().is_empty()))
769 .unwrap_or_else(|| self.audience.clone());
770 if trusted.is_empty() || trusted.iter().any(|iss| iss.trim().is_empty()) {
772 return Err(AuthError::jwt(
773 "verifier issuer pin is empty: pass the exact issuer",
774 "issuer_mismatch",
775 ));
776 }
777 if let Some(unlisted) = trusted.iter().find(|iss| !self.issuers.contains_key(*iss)) {
778 return Err(AuthError::jwt(
779 format!("{unlisted} is not an allow-listed issuer"),
780 "issuer_mismatch",
781 ));
782 }
783 if aud.is_empty() {
784 return Err(AuthError::jwt(
785 "verifier audience pin is empty: pass the audience this resource server accepts",
786 "audience_mismatch",
787 ));
788 }
789 let mut policy = ValidationPolicy::access().with_trusted_issuers(trusted.clone());
790 policy = policy.with_expected_audiences(aud);
791 if !self.require_at_jwt {
792 policy = policy.allow_legacy_typ();
793 }
794 let claims = self.verify_claims(token, &policy).await?;
795 match claims.get("iss").and_then(Value::as_str) {
798 Some(iss) if trusted.iter().any(|t| t == iss) => {}
799 Some(iss) => {
800 return Err(AuthError::jwt(
801 format!("Issuer mismatch: {iss} is not in {trusted:?}"),
802 "issuer_mismatch",
803 ))
804 }
805 None => {
806 return Err(AuthError::jwt(
807 "missing required claim iss",
808 "issuer_mismatch",
809 ))
810 }
811 }
812 claims_to_user(claims)
813 }
814}
815
816pub type ConsumeJti =
819 Arc<dyn Fn(&str, f64) -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
820
821#[derive(Clone)]
823pub struct LogoutTokenOptions {
824 client_ids: Vec<String>,
825 now: Option<f64>,
826 max_age: Option<Duration>,
827 consume_jti: Option<ConsumeJti>,
828}
829
830impl std::fmt::Debug for LogoutTokenOptions {
831 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
832 f.debug_struct("LogoutTokenOptions")
833 .field("client_ids", &self.client_ids)
834 .field("now", &self.now)
835 .field("max_age", &self.max_age)
836 .field("consume_jti", &self.consume_jti.is_some())
837 .finish()
838 }
839}
840
841impl LogoutTokenOptions {
842 pub fn new(client_id: impl Into<String>) -> Self {
844 Self {
845 client_ids: vec![client_id.into()],
846 now: None,
847 max_age: None,
848 consume_jti: None,
849 }
850 }
851 pub fn with_client_ids(ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
853 Self {
854 client_ids: ids.into_iter().map(Into::into).collect(),
855 now: None,
856 max_age: None,
857 consume_jti: None,
858 }
859 }
860 pub fn with_now(mut self, unix_seconds: f64) -> Self {
862 self.now = Some(unix_seconds);
863 self
864 }
865 pub fn with_max_age(mut self, max_age: Duration) -> Self {
867 self.max_age = Some(max_age);
868 self
869 }
870 pub fn with_consume_jti(
872 mut self,
873 consume: impl Fn(&str, f64) -> bool + Send + Sync + 'static,
874 ) -> Self {
875 self.consume_jti = Some(Arc::new(move |jti, expires_at| {
876 let seen_before = !consume(jti, expires_at);
877 Box::pin(async move { !seen_before })
878 }));
879 self
880 }
881 pub fn with_consume_jti_async(mut self, consume: ConsumeJti) -> Self {
883 self.consume_jti = Some(consume);
884 self
885 }
886}
887
888pub struct Verifier {
892 inner: MultiIssuerVerifier,
893 issuer: String,
894}
895
896impl Verifier {
897 pub fn new(issuer_url: impl Into<String>, audience: impl Into<String>) -> Self {
903 let issuer = normalize_issuer(&issuer_url.into());
904 Self {
905 inner: MultiIssuerVerifier::new(audience).with_issuer(issuer.clone()),
906 issuer,
907 }
908 }
909 pub fn with_audience(mut self, aud: impl Into<String>) -> Self {
912 self.inner = self.inner.with_audience(aud);
913 self
914 }
915 pub fn with_audiences(mut self, auds: Vec<String>) -> Self {
917 self.inner = self.inner.with_audiences(auds);
918 self
919 }
920 pub fn with_jwks_uri(mut self, uri: impl Into<String>) -> Self {
921 if let Some(state) = self.inner.issuers.get_mut(&self.issuer) {
922 state.jwks_uri = Some(uri.into());
923 }
924 self
925 }
926 pub fn with_ttl(mut self, ttl: Duration) -> Self {
927 self.inner = self.inner.with_ttl(ttl);
928 self
929 }
930 pub fn with_min_fetch_interval(mut self, interval: Duration) -> Self {
933 self.inner = self.inner.with_min_fetch_interval(interval);
934 self
935 }
936 pub fn allow_legacy_typ(mut self) -> Self {
940 self.inner = self.inner.allow_legacy_typ();
941 self
942 }
943 pub fn with_clock_skew(mut self, skew: Duration) -> Self {
945 self.inner = self.inner.with_clock_skew(skew);
946 self
947 }
948 pub fn issuers(&self) -> Vec<String> {
950 self.inner.issuers()
951 }
952 pub async fn verify_logout_token(
954 &self,
955 token: &str,
956 options: &LogoutTokenOptions,
957 ) -> Result<LogoutToken, AuthError> {
958 self.inner.verify_logout_token(token, options).await
959 }
960 pub async fn verify_claims(
962 &self,
963 token: &str,
964 policy: &ValidationPolicy,
965 ) -> Result<Map<String, Value>, AuthError> {
966 self.inner.verify_claims(token, policy).await
967 }
968 pub async fn verify(&self, token: &str) -> Result<CurrentUser, AuthError> {
970 self.inner.verify(token).await
971 }
972 pub async fn verify_with(
975 &self,
976 token: &str,
977 audience: Option<Vec<String>>,
978 issuer: Option<String>,
979 ) -> Result<CurrentUser, AuthError> {
980 self.inner.verify_with(token, audience, issuer).await
981 }
982}
983
984pub fn create_multi_issuer_verifier(audience: impl Into<String>) -> MultiIssuerVerifier {
985 MultiIssuerVerifier::new(audience)
986}
987
988pub fn create_verifier(issuer_url: impl Into<String>, audience: impl Into<String>) -> Verifier {
989 Verifier::new(issuer_url, audience)
990}
991
992pub fn generate_code_verifier() -> String {
994 use rand::RngCore;
995 let mut buf = [0u8; 32];
996 rand::thread_rng().fill_bytes(&mut buf);
997 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
998}
999pub fn generate_code_challenge(verifier: &str) -> String {
1000 use sha2::Digest;
1001 let hash = sha2::Sha256::digest(verifier.as_bytes());
1002 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash)
1003}
1004
1005fn leeway_seconds(skew: Duration) -> u64 {
1008 skew.as_secs()
1009 .saturating_add(u64::from(skew.subsec_nanos() > 0))
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014 use super::leeway_seconds;
1015 use std::time::Duration;
1016
1017 #[test]
1018 fn a_sub_second_skew_rounds_up_so_it_is_never_silently_zero() {
1019 assert_eq!(leeway_seconds(Duration::ZERO), 0);
1020 assert_eq!(leeway_seconds(Duration::from_millis(1)), 1);
1021 assert_eq!(leeway_seconds(Duration::from_millis(500)), 1);
1022 assert_eq!(leeway_seconds(Duration::from_secs(5)), 5);
1023 assert_eq!(leeway_seconds(Duration::from_millis(5_001)), 6);
1024 assert_eq!(leeway_seconds(Duration::MAX), u64::MAX);
1025 }
1026}