Skip to main content

id_effect_auth/
jwt.rs

1//! JSON Web Tokens (feature `jwt`): [`JwtVerifier`] turns a bearer token into an
2//! [`AuthPrincipal`], [`JwtIssuer`] signs first-party tokens.
3//!
4//! Signatures, `iss` and `aud` are checked by [jsonwebtoken]; `exp` and `nbf` are checked here,
5//! against a [`WallClock`], so expiry runs in virtual time under a `TestExecutor` or an anchored
6//! clock. A verifier needs:
7//!
8//! - **keys** — [`JwtKey`]s given up front (an HMAC secret, PEM public keys, JWKs), or with
9//!   feature `jwks` a [`JwksClient`](crate::jwks::JwksClient) that fetches the issuer's key set and
10//!   refetches it when a token names an unknown `kid` (key rotation). A key only verifies the
11//!   algorithms of its own family, so an RSA public key can never be used as an HMAC secret;
12//! - **expectations** — accepted issuers and audiences, required claims, clock leeway (60 s by
13//!   default), and whether `exp` is required (yes by default). A verifier with neither an
14//!   issuer nor an audience rejects every token with [`AuthError::Config`]: it would accept
15//!   tokens minted for any service by anyone holding a key it trusts. Opt out with both
16//!   [`dangerous_any_issuer`](JwtVerifier::dangerous_any_issuer) and
17//!   [`dangerous_any_audience`](JwtVerifier::dangerous_any_audience);
18//! - a **[`ClaimMapping`]** — which claims hold the subject, roles, permissions and tenant
19//!   (`sub`, `roles`, `permissions` / `scope` / `scp` and `tenant` by default; dotted paths such
20//!   as `realm_access.roles` reach into objects).
21//!
22//! HMAC secrets shorter than [`MIN_HMAC_KEY_LEN`] (32) bytes are refused (RFC 7518 §3.2): a
23//! verifier with one rejects the tokens it would check and an issuer with one issues nothing,
24//! both with [`AuthError::Key`].
25//!
26//! ```
27//! use id_effect::{Cause, Exit};
28//! use id_effect_auth::{AuthError, AuthPrincipal, JwtIssuer, JwtKey, JwtVerifier};
29//! use id_effect_authz::Principal;
30//!
31//! let secret = b"a 256-bit secret for HS256 tokens";
32//! let issuer = JwtIssuer::hs256(secret).issuer("https://id.example.com").audience("ledger");
33//! let verifier = JwtVerifier::new([JwtKey::hmac(secret)])
34//!   .issuer("https://id.example.com")
35//!   .audience("ledger");
36//!
37//! let alice = AuthPrincipal::new("alice").with_role("accountant");
38//! let Exit::Success(token) = issuer.issue(&alice).block_on() else { panic!() };
39//! let Exit::Success(p) = verifier.verify(&token).block_on() else { panic!() };
40//! assert_eq!((p.id(), p.roles()), ("alice", &["accountant".to_owned()][..]));
41//!
42//! let other = JwtVerifier::new([JwtKey::hmac(b"another 256-bit secret for HS256 tokens")])
43//!   .issuer("https://id.example.com")
44//!   .audience("ledger");
45//! let rejected = other.verify(&token).block_on();
46//! assert!(matches!(rejected, Exit::Failure(Cause::Fail(AuthError::InvalidCredentials))));
47//! ```
48//!
49//! [jsonwebtoken]: https://docs.rs/jsonwebtoken
50
51use std::collections::HashSet;
52use std::fmt;
53use std::sync::Arc;
54use std::time::Duration;
55
56use id_effect::{Effect, UtcDateTime, WallClock, fail, succeed};
57use jsonwebtoken::errors::{Error as JwtLibError, ErrorKind};
58use jsonwebtoken::jwk::{CommonParameters, KeyAlgorithm, PublicKeyUse};
59pub use jsonwebtoken::jwk::{Jwk, JwkSet};
60pub use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey};
61use jsonwebtoken::{AlgorithmFamily, Header, Validation, decode, decode_header, encode};
62use serde_json::{Map, Value};
63
64use crate::error::AuthError;
65use crate::principal::{AuthPrincipal, AuthScheme, split_list};
66
67/// Default clock-skew allowance for `exp` and `nbf`.
68pub const DEFAULT_LEEWAY: Duration = Duration::from_secs(60);
69
70/// Default lifetime of an issued token.
71pub const DEFAULT_TTL: Duration = Duration::from_secs(15 * 60);
72
73/// The shortest HMAC secret a [`JwtKey`] or [`JwtIssuer`] accepts, in bytes (RFC 7518 §3.2: at
74/// least the hash output, 256 bits for HS256).
75pub const MIN_HMAC_KEY_LEN: usize = 32;
76
77/// Posture id of [`JwtVerifier::dangerous_any_issuer`] (and the deprecated
78/// [`JwtVerifier::any_issuer_dangerous`]).
79pub const DANGEROUS_ANY_ISSUER: &str = "id_effect_auth::jwt::JwtVerifier::dangerous_any_issuer";
80
81/// Posture id of [`JwtVerifier::dangerous_any_audience`] (and the deprecated
82/// [`JwtVerifier::any_audience_dangerous`]).
83pub const DANGEROUS_ANY_AUDIENCE: &str = "id_effect_auth::jwt::JwtVerifier::dangerous_any_audience";
84
85/// [`AuthError::Key`] for an HMAC secret of `len` bytes, when it is too short.
86fn check_hmac_len(len: usize) -> Result<(), AuthError> {
87  if len < MIN_HMAC_KEY_LEN {
88    return Err(AuthError::Key(format!(
89      "an HMAC secret needs at least {MIN_HMAC_KEY_LEN} bytes, this one has {len}"
90    )));
91  }
92  Ok(())
93}
94
95impl From<JwtLibError> for AuthError {
96  fn from(e: JwtLibError) -> Self {
97    match e.kind() {
98      ErrorKind::InvalidSignature | ErrorKind::InvalidAlgorithm => Self::InvalidCredentials,
99      ErrorKind::ExpiredSignature => Self::Expired,
100      ErrorKind::ImmatureSignature => Self::NotYetValid,
101      ErrorKind::InvalidIssuer => Self::InvalidClaims("iss is not accepted".into()),
102      ErrorKind::InvalidAudience => Self::InvalidClaims("aud is not accepted".into()),
103      ErrorKind::InvalidSubject => Self::InvalidClaims("sub is not accepted".into()),
104      ErrorKind::MissingRequiredClaim(c) => Self::InvalidClaims(format!("missing claim {c}")),
105      ErrorKind::InvalidClaimFormat(c) => Self::InvalidClaims(format!("claim {c} is malformed")),
106      ErrorKind::InvalidToken | ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
107        Self::Malformed("not a well-formed JWT".into())
108      }
109      _ => Self::Key(e.to_string()),
110    }
111  }
112}
113
114/// A verification key: the key, the algorithms it may verify, and its `kid`.
115#[derive(Clone)]
116pub struct JwtKey {
117  kid: Option<String>,
118  algorithms: Vec<Algorithm>,
119  key: DecodingKey,
120}
121
122impl fmt::Debug for JwtKey {
123  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124    f.debug_struct("JwtKey")
125      .field("kid", &self.kid)
126      .field("algorithms", &self.algorithms)
127      .finish_non_exhaustive()
128  }
129}
130
131impl JwtKey {
132  /// `key`, verifying `algorithms` (those outside the key's family are dropped).
133  pub fn new(key: DecodingKey, algorithms: impl IntoIterator<Item = Algorithm>) -> Self {
134    let family = key.family();
135    Self {
136      kid: None,
137      algorithms: algorithms
138        .into_iter()
139        .filter(|a| family.algorithms().contains(a))
140        .collect(),
141      key,
142    }
143  }
144
145  /// `key`, verifying every algorithm of its family.
146  fn family(key: DecodingKey) -> Self {
147    let algorithms = key.family().algorithms().to_vec();
148    Self::new(key, algorithms)
149  }
150
151  /// An HMAC secret (HS256, HS384, HS512). A secret shorter than [`MIN_HMAC_KEY_LEN`] bytes
152  /// makes every verification with it fail with [`AuthError::Key`].
153  pub fn hmac(secret: &[u8]) -> Self {
154    Self::family(DecodingKey::from_secret(secret))
155  }
156
157  /// An RSA public key in PEM (RS256/384/512, PS256/384/512).
158  ///
159  /// # Errors
160  ///
161  /// [`AuthError::Key`] when `pem` is not an RSA public key.
162  pub fn rsa_pem(pem: &[u8]) -> Result<Self, AuthError> {
163    DecodingKey::from_rsa_pem(pem)
164      .map(Self::family)
165      .map_err(|e| AuthError::Key(e.to_string()))
166  }
167
168  /// An elliptic-curve public key in PEM (ES256, ES384).
169  ///
170  /// # Errors
171  ///
172  /// [`AuthError::Key`] when `pem` is not an EC public key.
173  pub fn ec_pem(pem: &[u8]) -> Result<Self, AuthError> {
174    DecodingKey::from_ec_pem(pem)
175      .map(Self::family)
176      .map_err(|e| AuthError::Key(e.to_string()))
177  }
178
179  /// An Ed25519 public key in PEM (EdDSA).
180  ///
181  /// # Errors
182  ///
183  /// [`AuthError::Key`] when `pem` is not an Ed25519 public key.
184  pub fn ed_pem(pem: &[u8]) -> Result<Self, AuthError> {
185    DecodingKey::from_ed_pem(pem)
186      .map(Self::family)
187      .map_err(|e| AuthError::Key(e.to_string()))
188  }
189
190  /// A key from a JSON Web Key: its `kid`, and its `alg` when set (else every algorithm of its
191  /// family).
192  ///
193  /// # Errors
194  ///
195  /// [`AuthError::Key`] for a key type or algorithm jsonwebtoken does not support.
196  pub fn from_jwk(jwk: &Jwk) -> Result<Self, AuthError> {
197    let key = DecodingKey::from_jwk(jwk).map_err(|e| AuthError::Key(e.to_string()))?;
198    let mut out = match jwk.common.key_algorithm {
199      Some(alg) => Self::new(key, [signing_algorithm(alg)?]),
200      None => Self::family(key),
201    };
202    out.kid = jwk.common.key_id.clone();
203    Ok(out)
204  }
205
206  /// The same key with `kid`.
207  #[must_use]
208  pub fn with_kid(mut self, kid: impl Into<String>) -> Self {
209    self.kid = Some(kid.into());
210    self
211  }
212
213  /// The key id, if any.
214  #[inline]
215  pub fn kid(&self) -> Option<&str> {
216    self.kid.as_deref()
217  }
218
219  /// The algorithms this key verifies.
220  #[inline]
221  pub fn algorithms(&self) -> &[Algorithm] {
222    &self.algorithms
223  }
224
225  fn allows(&self, alg: Algorithm) -> bool {
226    self.algorithms.contains(&alg)
227  }
228
229  /// [`AuthError::Key`] when this is an HMAC secret shorter than [`MIN_HMAC_KEY_LEN`].
230  fn check_strength(&self) -> Result<(), AuthError> {
231    if self.key.family() != AlgorithmFamily::Hmac {
232      return Ok(());
233    }
234    check_hmac_len(self.key.try_get_as_bytes().map_or(0, <[u8]>::len))
235  }
236}
237
238/// The JWS algorithm a JWK's `alg` names (`RSA-OAEP` and other encryption algorithms are not).
239fn signing_algorithm(alg: KeyAlgorithm) -> Result<Algorithm, AuthError> {
240  let name = serde_json::to_value(alg)
241    .ok()
242    .and_then(|v| v.as_str().map(str::to_owned))
243    .unwrap_or_default();
244  name
245    .parse()
246    .map_err(|_| AuthError::Key(format!("{name} is not a JWS signing algorithm")))
247}
248
249/// The key in `keys` for a token with `kid` and `alg`: the key with that `kid`, else a key
250/// without a `kid`; for a token without `kid`, a key without one, else the only candidate.
251pub(crate) fn select_key(
252  keys: &[JwtKey],
253  kid: Option<&str>,
254  alg: Algorithm,
255) -> Result<JwtKey, AuthError> {
256  let candidates: Vec<&JwtKey> = keys.iter().filter(|k| k.allows(alg)).collect();
257  let by_kid = kid.and_then(|kid| candidates.iter().find(|k| k.kid() == Some(kid)));
258  let unnamed = || candidates.iter().find(|k| k.kid.is_none());
259  let only = || (candidates.len() == 1 && kid.is_none()).then(|| &candidates[0]);
260  by_kid
261    .or_else(unnamed)
262    .or_else(only)
263    .map(|k| (*k).clone())
264    .ok_or_else(|| {
265      AuthError::UnknownKey(match kid {
266        Some(kid) => format!("kid {kid:?} ({alg:?})"),
267        None => format!("no key for {alg:?}"),
268      })
269    })
270}
271
272/// Which claims make up the principal of a verified token.
273#[derive(Clone, Debug, PartialEq, Eq)]
274pub struct ClaimMapping {
275  /// The principal id (default `sub`). It must be a string.
276  pub subject: String,
277  /// Claims whose values become roles (default `roles`).
278  pub roles: Vec<String>,
279  /// Claims whose values become direct permissions (default `permissions`, `scope`, `scp`).
280  pub permissions: Vec<String>,
281  /// The tenant claim (default `tenant`).
282  pub tenant: Option<String>,
283}
284
285impl Default for ClaimMapping {
286  fn default() -> Self {
287    Self {
288      subject: "sub".into(),
289      roles: vec!["roles".into()],
290      permissions: vec!["permissions".into(), "scope".into(), "scp".into()],
291      tenant: Some("tenant".into()),
292    }
293  }
294}
295
296impl ClaimMapping {
297  /// Read roles from `claims` instead (`["realm_access.roles"]` for Keycloak, `["groups"]`, …).
298  #[must_use]
299  pub fn roles<S: Into<String>>(mut self, claims: impl IntoIterator<Item = S>) -> Self {
300    self.roles = claims.into_iter().map(Into::into).collect();
301    self
302  }
303
304  /// Read permissions from `claims` instead.
305  #[must_use]
306  pub fn permissions<S: Into<String>>(mut self, claims: impl IntoIterator<Item = S>) -> Self {
307    self.permissions = claims.into_iter().map(Into::into).collect();
308    self
309  }
310
311  /// Read the principal id from `claim` instead of `sub`.
312  #[must_use]
313  pub fn subject(mut self, claim: impl Into<String>) -> Self {
314    self.subject = claim.into();
315    self
316  }
317
318  /// Read the tenant from `claim` (or nowhere, with `None`).
319  #[must_use]
320  pub fn tenant(mut self, claim: Option<&str>) -> Self {
321    self.tenant = claim.map(str::to_owned);
322    self
323  }
324
325  /// The principal of verified `claims` (every claim is kept on it).
326  ///
327  /// # Errors
328  ///
329  /// [`AuthError::InvalidClaims`] when the subject claim is missing or not a string.
330  pub fn principal(&self, claims: Map<String, Value>) -> Result<AuthPrincipal, AuthError> {
331    let subject = match lookup(&claims, &self.subject) {
332      Some(Value::String(s)) if !s.is_empty() => s.clone(),
333      _ => {
334        return Err(AuthError::InvalidClaims(format!(
335          "claim {} must be a non-empty string",
336          self.subject
337        )));
338      }
339    };
340    let list = |names: &[String]| {
341      let mut out: Vec<String> = Vec::new();
342      for value in names.iter().filter_map(|n| lookup(&claims, n)) {
343        for item in string_items(value) {
344          if !out.contains(&item) {
345            out.push(item);
346          }
347        }
348      }
349      out
350    };
351    let mut principal = AuthPrincipal::new(subject)
352      .with_roles(list(&self.roles))
353      .with_permissions(list(&self.permissions))
354      .with_scheme(AuthScheme::Bearer);
355    if let Some(tenant) = self
356      .tenant
357      .as_deref()
358      .and_then(|t| lookup(&claims, t))
359      .and_then(Value::as_str)
360    {
361      principal = principal.with_tenant(tenant);
362    }
363    Ok(
364      claims
365        .into_iter()
366        .fold(principal, |p, (name, value)| p.with_claim(name, value)),
367    )
368  }
369}
370
371/// The claim `name`: a top-level claim of that exact name (namespaced claims contain dots),
372/// else a dotted path into nested objects.
373fn lookup<'c>(claims: &'c Map<String, Value>, name: &str) -> Option<&'c Value> {
374  if let Some(v) = claims.get(name) {
375    return Some(v);
376  }
377  let mut parts = name.split('.');
378  let first = claims.get(parts.next()?)?;
379  parts.try_fold(first, |v, part| v.get(part))
380}
381
382/// Strings in a claim value: an array's string items, or a space/comma-separated string.
383fn string_items(value: &Value) -> Vec<String> {
384  match value {
385    Value::String(s) => split_list(s),
386    Value::Array(items) => items
387      .iter()
388      .filter_map(Value::as_str)
389      .map(str::to_owned)
390      .collect(),
391    _ => Vec::new(),
392  }
393}
394
395/// Where a verifier's keys come from.
396#[derive(Clone)]
397enum Keys {
398  Static(Arc<[JwtKey]>),
399  #[cfg(feature = "jwks")]
400  Jwks(crate::jwks::JwksClient),
401}
402
403/// Verifies bearer tokens and maps their claims to an [`AuthPrincipal`]. Cheap to clone.
404///
405/// See the [module documentation](self).
406#[derive(Clone)]
407pub struct JwtVerifier {
408  keys: Keys,
409  algorithms: Option<Vec<Algorithm>>,
410  issuers: Vec<String>,
411  audiences: Vec<String>,
412  required: Vec<String>,
413  require_exp: bool,
414  leeway: Duration,
415  mapping: ClaimMapping,
416  clock: WallClock,
417  any_issuer: bool,
418  any_audience: bool,
419}
420
421impl fmt::Debug for JwtVerifier {
422  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423    let keys = match &self.keys {
424      Keys::Static(keys) => format!("{} static", keys.len()),
425      #[cfg(feature = "jwks")]
426      Keys::Jwks(client) => format!("JWKS {}", client.url()),
427    };
428    f.debug_struct("JwtVerifier")
429      .field("keys", &keys)
430      .field("issuers", &self.issuers)
431      .field("audiences", &self.audiences)
432      .field("leeway", &self.leeway)
433      .finish_non_exhaustive()
434  }
435}
436
437impl JwtVerifier {
438  fn with_keys(keys: Keys) -> Self {
439    Self {
440      keys,
441      algorithms: None,
442      issuers: Vec::new(),
443      audiences: Vec::new(),
444      required: Vec::new(),
445      require_exp: true,
446      leeway: DEFAULT_LEEWAY,
447      mapping: ClaimMapping::default(),
448      clock: WallClock::system(),
449      any_issuer: false,
450      any_audience: false,
451    }
452  }
453
454  /// A verifier over fixed `keys`.
455  pub fn new(keys: impl IntoIterator<Item = JwtKey>) -> Self {
456    Self::with_keys(Keys::Static(keys.into_iter().collect()))
457  }
458
459  /// A verifier over the key set `jwks` fetches (and refetches on an unknown `kid`).
460  #[cfg(feature = "jwks")]
461  pub fn jwks(jwks: crate::jwks::JwksClient) -> Self {
462    Self::with_keys(Keys::Jwks(jwks))
463  }
464
465  /// Accept tokens whose `iss` is `issuer` (repeat for several). Once set, `iss` is required.
466  #[must_use]
467  pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
468    self.issuers.push(issuer.into());
469    self
470  }
471
472  /// Accept tokens whose `aud` contains `audience` (repeat for several). Once set, `aud` is
473  /// required. Set it: without an audience a token minted for another service is accepted.
474  /// A verifier with neither an issuer nor an audience rejects every token (see
475  /// [`dangerous_any_issuer`](Self::dangerous_any_issuer)).
476  #[must_use]
477  pub fn audience(mut self, audience: impl Into<String>) -> Self {
478    self.audiences.push(audience.into());
479    self
480  }
481
482  /// Accept tokens from any issuer even though no [`issuer`](Self::issuer) is set. Records
483  /// [`DANGEROUS_ANY_ISSUER`] in the posture registry.
484  ///
485  /// **Dangerous.** A verifier with neither an issuer nor an audience fails every verification
486  /// with [`AuthError::Config`]; calling both this and
487  /// [`dangerous_any_audience`](Self::dangerous_any_audience) re-opens the 0.10.0 behaviour:
488  /// any token signed by a trusted key is accepted, whoever minted it and for whichever service.
489  /// Only for keys that sign tokens for this service alone (a test, a single-service secret).
490  #[must_use]
491  pub fn dangerous_any_issuer(mut self) -> Self {
492    id_effect::observability::posture::record_dangerous(
493      DANGEROUS_ANY_ISSUER,
494      "H7: a JwtVerifier may accept tokens from any issuer",
495    );
496    self.any_issuer = true;
497    self
498  }
499
500  /// Accept tokens from any issuer.
501  #[deprecated(
502    since = "0.11.0",
503    note = "renamed to dangerous_any_issuer (ADR 0013 naming)"
504  )]
505  #[must_use]
506  pub fn any_issuer_dangerous(self) -> Self {
507    self.dangerous_any_issuer()
508  }
509
510  /// Accept tokens for any audience even though no [`audience`](Self::audience) is set. Records
511  /// [`DANGEROUS_ANY_AUDIENCE`] in the posture registry.
512  ///
513  /// **Dangerous**: see [`dangerous_any_issuer`](Self::dangerous_any_issuer); a token minted for
514  /// another service of the same issuer is accepted.
515  #[must_use]
516  pub fn dangerous_any_audience(mut self) -> Self {
517    id_effect::observability::posture::record_dangerous(
518      DANGEROUS_ANY_AUDIENCE,
519      "H7: a JwtVerifier may accept tokens minted for any audience",
520    );
521    self.any_audience = true;
522    self
523  }
524
525  /// Accept tokens for any audience.
526  #[deprecated(
527    since = "0.11.0",
528    note = "renamed to dangerous_any_audience (ADR 0013 naming)"
529  )]
530  #[must_use]
531  pub fn any_audience_dangerous(self) -> Self {
532    self.dangerous_any_audience()
533  }
534
535  /// [`AuthError::Config`] unless the verifier pins an issuer or an audience, or opted out of
536  /// both.
537  fn check_expectations(&self) -> Result<(), AuthError> {
538    let pinned = !self.issuers.is_empty() || !self.audiences.is_empty();
539    if pinned || (self.any_issuer && self.any_audience) {
540      return Ok(());
541    }
542    Err(AuthError::Config(
543      "a JwtVerifier needs an issuer or an audience (or both dangerous_any_issuer() and \
544       dangerous_any_audience())"
545        .into(),
546    ))
547  }
548
549  /// Only accept these algorithms (default: whatever the matching key's family allows).
550  #[must_use]
551  pub fn algorithms(mut self, algorithms: impl IntoIterator<Item = Algorithm>) -> Self {
552    self.algorithms = Some(algorithms.into_iter().collect());
553    self
554  }
555
556  /// Reject tokens without the claim `claim`.
557  #[must_use]
558  pub fn require_claim(mut self, claim: impl Into<String>) -> Self {
559    self.required.push(claim.into());
560    self
561  }
562
563  /// Whether `exp` must be present (default `true`). An `exp` that is present is always checked.
564  #[must_use]
565  pub fn require_exp(mut self, require: bool) -> Self {
566    self.require_exp = require;
567    self
568  }
569
570  /// Clock-skew allowance for `exp` and `nbf` (default [`DEFAULT_LEEWAY`]).
571  #[must_use]
572  pub fn leeway(mut self, leeway: Duration) -> Self {
573    self.leeway = leeway;
574    self
575  }
576
577  /// Map claims to the principal with `mapping`.
578  #[must_use]
579  pub fn claims(mut self, mapping: ClaimMapping) -> Self {
580    self.mapping = mapping;
581    self
582  }
583
584  /// Read the time from `clock` (an anchored clock follows a `TestExecutor`'s virtual time).
585  #[must_use]
586  pub fn with_clock(mut self, clock: WallClock) -> Self {
587    self.clock = clock;
588    self
589  }
590
591  /// The principal `token` stands for, or why it is rejected: [`AuthError::Malformed`] (not a
592  /// JWT), [`AuthError::InvalidCredentials`] (signature, algorithm),
593  /// [`AuthError::UnknownKey`], [`AuthError::Expired`], [`AuthError::NotYetValid`],
594  /// [`AuthError::InvalidClaims`]; [`AuthError::Unavailable`] when the JWKS cannot be fetched;
595  /// [`AuthError::Config`] when neither an issuer nor an audience is set, and
596  /// [`AuthError::Key`] for an HMAC secret that is too short.
597  pub fn verify(&self, token: &str) -> Effect<AuthPrincipal, AuthError> {
598    let mapping = self.mapping.clone();
599    self
600      .verify_claims(token)
601      .flat_map(move |claims| match mapping.principal(claims) {
602        Ok(p) => succeed(p),
603        Err(e) => fail(e),
604      })
605  }
606
607  /// The verified claims of `token` (see [`verify`](Self::verify)).
608  pub fn verify_claims(&self, token: &str) -> Effect<Map<String, Value>, AuthError> {
609    if let Err(e) = self.check_expectations() {
610      return fail(e);
611    }
612    let header = match decode_header(token) {
613      Ok(h) => h,
614      Err(_) => return fail(AuthError::Malformed("not a well-formed JWT".into())),
615    };
616    if let Some(allowed) = &self.algorithms
617      && !allowed.contains(&header.alg)
618    {
619      return fail(AuthError::InvalidCredentials);
620    }
621    let (this, token) = (self.clone(), token.to_owned());
622    let alg = header.alg;
623    self.key(header.kid, alg).flat_map(move |key| {
624      if let Err(e) = key.check_strength() {
625        return fail(e);
626      }
627      let claims = match decode::<Map<String, Value>>(&token, &key.key, &this.validation(alg)) {
628        Ok(data) => data.claims,
629        Err(e) => return fail(AuthError::from(e)),
630      };
631      this
632        .clock
633        .now()
634        .flat_map(move |now| match this.check(&claims, now) {
635          Ok(()) => succeed(claims),
636          Err(e) => fail(e),
637        })
638    })
639  }
640
641  fn key(&self, kid: Option<String>, alg: Algorithm) -> Effect<JwtKey, AuthError> {
642    match &self.keys {
643      Keys::Static(keys) => match select_key(keys, kid.as_deref(), alg) {
644        Ok(k) => succeed(k),
645        Err(e) => fail(e),
646      },
647      #[cfg(feature = "jwks")]
648      Keys::Jwks(client) => client.key(kid, alg),
649    }
650  }
651
652  fn validation(&self, alg: Algorithm) -> Validation {
653    let mut v = Validation::new(alg);
654    v.validate_exp = false;
655    v.validate_nbf = false;
656    v.leeway = 0;
657    v.required_spec_claims = HashSet::new();
658    if !self.issuers.is_empty() {
659      v.set_issuer(&self.issuers);
660      v.required_spec_claims.insert("iss".into());
661    }
662    v.validate_aud = !self.audiences.is_empty();
663    if v.validate_aud {
664      v.set_audience(&self.audiences);
665      v.required_spec_claims.insert("aud".into());
666    }
667    v
668  }
669
670  /// Time and required-claim checks on signature-verified `claims`.
671  fn check(&self, claims: &Map<String, Value>, now: UtcDateTime) -> Result<(), AuthError> {
672    let now = now.0.as_second();
673    let leeway = i64::try_from(self.leeway.as_secs()).unwrap_or(i64::MAX);
674    let time = |name: &str| -> Result<Option<i64>, AuthError> {
675      match claims.get(name) {
676        None => Ok(None),
677        Some(v) => v
678          .as_i64()
679          .or_else(|| v.as_f64().map(|f| f as i64))
680          .map(Some)
681          .ok_or_else(|| AuthError::InvalidClaims(format!("claim {name} must be a number"))),
682      }
683    };
684    match time("exp")? {
685      Some(exp) if now >= exp.saturating_add(leeway) => return Err(AuthError::Expired),
686      None if self.require_exp => return Err(AuthError::InvalidClaims("missing claim exp".into())),
687      _ => {}
688    }
689    if let Some(nbf) = time("nbf")?
690      && now.saturating_add(leeway) < nbf
691    {
692      return Err(AuthError::NotYetValid);
693    }
694    match self.required.iter().find(|c| lookup(claims, c).is_none()) {
695      Some(missing) => Err(AuthError::InvalidClaims(format!("missing claim {missing}"))),
696      None => Ok(()),
697    }
698  }
699}
700
701/// Signs tokens: first-party access tokens and test fixtures. Cheap to clone.
702///
703/// [`issue`](Self::issue) writes the principal's id as `sub`, its roles, permissions and tenant
704/// under the [`ClaimMapping`] default names (`roles`, `permissions`, `tenant`), its other claims
705/// as they are, then `iss`, `aud`, `iat`, `exp` (now + [`ttl`](Self::ttl)) and a random `jti`.
706#[derive(Clone)]
707pub struct JwtIssuer {
708  key: EncodingKey,
709  alg: Algorithm,
710  kid: Option<String>,
711  issuer: Option<String>,
712  audience: Option<String>,
713  ttl: Duration,
714  clock: WallClock,
715}
716
717impl fmt::Debug for JwtIssuer {
718  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719    f.debug_struct("JwtIssuer")
720      .field("alg", &self.alg)
721      .field("kid", &self.kid)
722      .field("issuer", &self.issuer)
723      .field("audience", &self.audience)
724      .field("ttl", &self.ttl)
725      .finish_non_exhaustive()
726  }
727}
728
729impl JwtIssuer {
730  /// Sign with `key` using `alg`.
731  ///
732  /// # Errors
733  ///
734  /// [`AuthError::Key`] when `alg` does not belong to the key's family.
735  pub fn new(alg: Algorithm, key: EncodingKey) -> Result<Self, AuthError> {
736    if !key.family().algorithms().contains(&alg) {
737      return Err(AuthError::Key(format!(
738        "{alg:?} cannot sign with a {:?} key",
739        key.family()
740      )));
741    }
742    Ok(Self {
743      key,
744      alg,
745      kid: None,
746      issuer: None,
747      audience: None,
748      ttl: DEFAULT_TTL,
749      clock: WallClock::system(),
750    })
751  }
752
753  /// HS256 with `secret` (at least [`MIN_HMAC_KEY_LEN`] random bytes: with a shorter one
754  /// [`issue`](Self::issue) fails with [`AuthError::Key`]).
755  pub fn hs256(secret: &[u8]) -> Self {
756    Self {
757      key: EncodingKey::from_secret(secret),
758      alg: Algorithm::HS256,
759      kid: None,
760      issuer: None,
761      audience: None,
762      ttl: DEFAULT_TTL,
763      clock: WallClock::system(),
764    }
765  }
766
767  /// An RSA private key in PEM (PKCS#1 or PKCS#8), signing with `alg` (RS* or PS*).
768  ///
769  /// # Errors
770  ///
771  /// [`AuthError::Key`] when `pem` is not an RSA private key or `alg` is not an RSA algorithm.
772  pub fn rsa_pem(alg: Algorithm, pem: &[u8]) -> Result<Self, AuthError> {
773    let key = EncodingKey::from_rsa_pem(pem).map_err(|e| AuthError::Key(e.to_string()))?;
774    Self::new(alg, key)
775  }
776
777  /// An EC private key in PKCS#8 PEM, signing with `alg` (ES256 or ES384).
778  ///
779  /// # Errors
780  ///
781  /// [`AuthError::Key`] when `pem` is not an EC private key or `alg` is not an EC algorithm.
782  pub fn ec_pem(alg: Algorithm, pem: &[u8]) -> Result<Self, AuthError> {
783    let key = EncodingKey::from_ec_pem(pem).map_err(|e| AuthError::Key(e.to_string()))?;
784    Self::new(alg, key)
785  }
786
787  /// Name the key `kid` in every token header (and in [`jwk`](Self::jwk)).
788  #[must_use]
789  pub fn kid(mut self, kid: impl Into<String>) -> Self {
790    self.kid = Some(kid.into());
791    self
792  }
793
794  /// Write `iss: issuer`.
795  #[must_use]
796  pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
797    self.issuer = Some(issuer.into());
798    self
799  }
800
801  /// Write `aud: audience`.
802  #[must_use]
803  pub fn audience(mut self, audience: impl Into<String>) -> Self {
804    self.audience = Some(audience.into());
805    self
806  }
807
808  /// Tokens live `ttl` (default [`DEFAULT_TTL`]).
809  #[must_use]
810  pub fn ttl(mut self, ttl: Duration) -> Self {
811    self.ttl = ttl;
812    self
813  }
814
815  /// Read the time from `clock`.
816  #[must_use]
817  pub fn with_clock(mut self, clock: WallClock) -> Self {
818    self.clock = clock;
819    self
820  }
821
822  /// The signing algorithm.
823  #[inline]
824  pub fn algorithm(&self) -> Algorithm {
825    self.alg
826  }
827
828  /// A signed token for `principal` (see the type documentation for the claims).
829  pub fn issue(&self, principal: &AuthPrincipal) -> Effect<String, AuthError> {
830    use id_effect_authz::Principal as _;
831    let mut claims: Map<String, Value> = principal
832      .claims()
833      .iter()
834      .map(|(k, v)| (k.clone(), v.clone()))
835      .collect();
836    claims.insert("sub".into(), principal.id().into());
837    if !principal.roles().is_empty() {
838      claims.insert("roles".into(), principal.roles().into());
839    }
840    if !principal.permissions().is_empty() {
841      claims.insert("permissions".into(), principal.permissions().into());
842    }
843    if let Some(tenant) = principal.tenant() {
844      claims.insert("tenant".into(), tenant.into());
845    }
846    self.issue_claims(claims)
847  }
848
849  /// A signed token carrying `claims`, plus `iss`, `aud`, `iat`, `exp` and `jti` unless
850  /// `claims` already sets them.
851  pub fn issue_claims(&self, claims: Map<String, Value>) -> Effect<String, AuthError> {
852    if self.key.family() == AlgorithmFamily::Hmac
853      && let Err(e) = check_hmac_len(self.key.as_bytes().len())
854    {
855      return fail(e);
856    }
857    let this = self.clone();
858    self.clock.now().flat_map(move |now| {
859      let now = now.0.as_second();
860      let ttl = i64::try_from(this.ttl.as_secs()).unwrap_or(i64::MAX);
861      let mut claims = claims;
862      let mut default = |name: &str, value: Value| {
863        claims.entry(name.to_owned()).or_insert(value);
864      };
865      if let Some(iss) = &this.issuer {
866        default("iss", iss.as_str().into());
867      }
868      if let Some(aud) = &this.audience {
869        default("aud", aud.as_str().into());
870      }
871      default("iat", now.into());
872      default("exp", now.saturating_add(ttl).into());
873      match crate::apikey::random_hex(16) {
874        Ok(jti) => default("jti", jti.into()),
875        Err(e) => return fail(e),
876      }
877      let mut header = Header::new(this.alg);
878      header.kid.clone_from(&this.kid);
879      match encode(&header, &claims, &this.key) {
880        Ok(token) => succeed(token),
881        Err(e) => fail(AuthError::Key(e.to_string())),
882      }
883    })
884  }
885
886  /// The public JSON Web Key of an asymmetric issuer (with its `kid`, `alg` and `use: sig`), to
887  /// publish in a JWKS document.
888  ///
889  /// # Errors
890  ///
891  /// [`AuthError::Key`] for an HMAC issuer: its secret must never be published.
892  pub fn jwk(&self) -> Result<Jwk, AuthError> {
893    if self.key.family() == AlgorithmFamily::Hmac {
894      return Err(AuthError::Key("an HMAC secret has no public key".into()));
895    }
896    let mut jwk =
897      Jwk::from_encoding_key(&self.key, self.alg).map_err(|e| AuthError::Key(e.to_string()))?;
898    jwk.common = CommonParameters {
899      public_key_use: Some(PublicKeyUse::Signature),
900      key_algorithm: Some(KeyAlgorithm::from(self.alg)),
901      key_id: self.kid.clone(),
902      ..CommonParameters::default()
903    };
904    Ok(jwk)
905  }
906
907  /// The key that verifies this issuer's tokens (the public key, or the HMAC secret).
908  ///
909  /// # Errors
910  ///
911  /// [`AuthError::Key`] when the public key cannot be derived.
912  pub fn verification_key(&self) -> Result<JwtKey, AuthError> {
913    let key = if self.key.family() == AlgorithmFamily::Hmac {
914      JwtKey::new(DecodingKey::from_secret(self.key.as_bytes()), [self.alg])
915    } else {
916      JwtKey::from_jwk(&self.jwk()?)?
917    };
918    Ok(match &self.kid {
919      Some(kid) => key.with_kid(kid.clone()),
920      None => key,
921    })
922  }
923}
924
925#[cfg(test)]
926mod tests {
927  use std::time::Instant;
928
929  use id_effect::{Cause, Exit};
930  use id_effect_authz::Principal;
931  use serde_json::json;
932
933  use super::*;
934
935  const SECRET: &[u8] = b"0123456789abcdef0123456789abcdef";
936
937  fn run<A: Send + 'static>(eff: Effect<A, AuthError>) -> Result<A, AuthError> {
938    match eff.block_on() {
939      Exit::Success(a) => Ok(a),
940      Exit::Failure(Cause::Fail(e)) => Err(e),
941      Exit::Failure(c) => panic!("unexpected cause: {c:?}"),
942    }
943  }
944
945  fn clock_at(secs: i64) -> WallClock {
946    WallClock::anchored(Instant::now(), UtcDateTime::unsafe_make(secs * 1000))
947  }
948
949  fn claims(v: Value) -> Map<String, Value> {
950    match v {
951      Value::Object(m) => m,
952      _ => unreachable!(),
953    }
954  }
955
956  fn hs(claims_v: Value) -> String {
957    let issuer = JwtIssuer::hs256(SECRET).with_clock(clock_at(1_000));
958    run(issuer.issue_claims(claims(claims_v))).unwrap()
959  }
960
961  /// A verifier that pins nothing (these tests are not about `iss` / `aud`).
962  fn verifier() -> JwtVerifier {
963    JwtVerifier::new([JwtKey::hmac(SECRET)])
964      .with_clock(clock_at(1_000))
965      .dangerous_any_issuer()
966      .dangerous_any_audience()
967  }
968
969  #[test]
970  fn issued_tokens_round_trip_with_mapped_claims() {
971    let issuer = JwtIssuer::hs256(SECRET)
972      .issuer("iss-a")
973      .audience("aud-a")
974      .kid("k1")
975      .ttl(Duration::from_secs(60))
976      .with_clock(clock_at(1_000));
977    assert_eq!(issuer.algorithm(), Algorithm::HS256);
978    let alice = AuthPrincipal::new("alice")
979      .with_role("viewer")
980      .with_permission("ledger:read")
981      .with_tenant("acme")
982      .with_claim("email", "a@example.com");
983    let token = run(issuer.issue(&alice)).unwrap();
984    let v = verifier().issuer("iss-a").audience("aud-a");
985    let p = run(v.verify(&token)).unwrap();
986    assert_eq!(p.id(), "alice");
987    assert_eq!(p.roles(), ["viewer"]);
988    assert_eq!(p.permissions(), ["ledger:read"]);
989    assert_eq!(Principal::tenant(&p), Some("acme"));
990    assert_eq!(p.claim("email"), Some(&json!("a@example.com")));
991    assert_eq!(p.claim("exp"), Some(&json!(1_060)));
992    assert_eq!(p.claim("iat"), Some(&json!(1_000)));
993    assert!(p.claim("jti").is_some());
994    assert_eq!(p.scheme(), Some(AuthScheme::Bearer));
995    let header = decode_header(&token).unwrap();
996    assert_eq!(header.kid.as_deref(), Some("k1"));
997    let vk = issuer.verification_key().unwrap();
998    assert_eq!(vk.kid(), Some("k1"));
999    assert!(
1000      run(
1001        JwtVerifier::new([vk])
1002          .issuer("iss-a")
1003          .with_clock(clock_at(1_000))
1004          .verify(&token)
1005      )
1006      .is_ok()
1007    );
1008    assert!(issuer.jwk().is_err(), "HMAC secrets are never published");
1009  }
1010
1011  #[test]
1012  fn time_checks_use_the_clock_and_leeway() {
1013    let token = hs(json!({"sub": "a", "exp": 1_100, "nbf": 900}));
1014    let at = |secs| verifier().with_clock(clock_at(secs));
1015    assert!(run(at(1_000).verify(&token)).is_ok());
1016    assert!(run(at(1_159).verify(&token)).is_ok(), "within leeway");
1017    assert_eq!(run(at(1_160).verify(&token)), Err(AuthError::Expired));
1018    assert_eq!(
1019      run(at(1_100).leeway(Duration::ZERO).verify(&token)),
1020      Err(AuthError::Expired)
1021    );
1022    assert!(run(at(840).verify(&token)).is_ok(), "nbf within leeway");
1023    assert_eq!(run(at(839).verify(&token)), Err(AuthError::NotYetValid));
1024    let float_exp = hs(json!({"sub": "a", "exp": 1_100.5}));
1025    assert!(run(verifier().verify(&float_exp)).is_ok());
1026    let bad_exp = hs(json!({"sub": "a", "exp": "soon"}));
1027    assert!(matches!(
1028      run(verifier().verify(&bad_exp)),
1029      Err(AuthError::InvalidClaims(_))
1030    ));
1031  }
1032
1033  #[test]
1034  fn exp_and_other_claims_can_be_required() {
1035    let no_exp = {
1036      let mut m = claims(json!({"sub": "a"}));
1037      m.insert("exp".into(), Value::Null);
1038      let mut header = Header::new(Algorithm::HS256);
1039      header.kid = None;
1040      m.remove("exp");
1041      encode(&header, &m, &EncodingKey::from_secret(SECRET)).unwrap()
1042    };
1043    assert_eq!(
1044      run(verifier().verify(&no_exp)),
1045      Err(AuthError::InvalidClaims("missing claim exp".into()))
1046    );
1047    assert!(run(verifier().require_exp(false).verify(&no_exp)).is_ok());
1048    let token = hs(json!({"sub": "a", "org": {"id": 7}}));
1049    assert!(run(verifier().require_claim("org.id").verify(&token)).is_ok());
1050    assert_eq!(
1051      run(verifier().require_claim("email").verify(&token)),
1052      Err(AuthError::InvalidClaims("missing claim email".into()))
1053    );
1054  }
1055
1056  #[test]
1057  fn issuer_audience_and_signature_are_enforced() {
1058    let token = hs(json!({"sub": "a", "iss": "iss-a", "aud": ["aud-a", "aud-b"]}));
1059    assert!(run(verifier().issuer("iss-a").audience("aud-b").verify(&token)).is_ok());
1060    assert!(matches!(
1061      run(verifier().issuer("iss-x").verify(&token)),
1062      Err(AuthError::InvalidClaims(m)) if m.contains("iss")
1063    ));
1064    assert!(matches!(
1065      run(verifier().audience("aud-x").verify(&token)),
1066      Err(AuthError::InvalidClaims(m)) if m.contains("aud")
1067    ));
1068    let bare = hs(json!({"sub": "a"}));
1069    assert!(matches!(
1070      run(verifier().audience("aud-a").verify(&bare)),
1071      Err(AuthError::InvalidClaims(m)) if m.contains("aud")
1072    ));
1073    let wrong = JwtVerifier::new([JwtKey::hmac(b"another secret of at least 32 bytes")])
1074      .with_clock(clock_at(1_000))
1075      .dangerous_any_issuer()
1076      .dangerous_any_audience();
1077    assert_eq!(run(wrong.verify(&bare)), Err(AuthError::InvalidCredentials));
1078    // Flip the signature's first character (every base64url character there is significant).
1079    let at = bare.rfind('.').unwrap() + 1;
1080    let flipped = if bare[at..].starts_with('A') {
1081      "B"
1082    } else {
1083      "A"
1084    };
1085    let tampered = format!("{}{flipped}{}", &bare[..at], &bare[at + 1..]);
1086    assert_eq!(
1087      run(verifier().verify(&tampered)),
1088      Err(AuthError::InvalidCredentials)
1089    );
1090    assert!(matches!(
1091      run(verifier().verify("not.a.jwt")),
1092      Err(AuthError::Malformed(_))
1093    ));
1094    assert_eq!(
1095      run(verifier().algorithms([Algorithm::HS512]).verify(&bare)),
1096      Err(AuthError::InvalidCredentials)
1097    );
1098    assert!(run(verifier().algorithms([Algorithm::HS256]).verify(&bare)).is_ok());
1099  }
1100
1101  #[test]
1102  fn claim_mapping_reads_nested_namespaced_and_scope_claims() {
1103    let token = hs(json!({
1104      "sub": "a",
1105      "uid": "u-9",
1106      "realm_access": {"roles": ["admin", "viewer"]},
1107      "https://example.com/roles": ["x"],
1108      "scope": "read write",
1109      "scp": ["read", "audit"],
1110      "org": "acme"
1111    }));
1112    let mapping = ClaimMapping::default()
1113      .roles(["realm_access.roles", "https://example.com/roles"])
1114      .subject("uid")
1115      .tenant(Some("org"));
1116    let p = run(verifier().claims(mapping).verify(&token)).unwrap();
1117    assert_eq!(p.id(), "u-9");
1118    assert_eq!(p.roles(), ["admin", "viewer", "x"]);
1119    assert_eq!(p.permissions(), ["read", "write", "audit"]);
1120    assert_eq!(Principal::tenant(&p), Some("acme"));
1121    let none = ClaimMapping::default().permissions(["nope"]).tenant(None);
1122    let p = run(verifier().claims(none).verify(&token)).unwrap();
1123    assert!(p.permissions().is_empty());
1124    assert_eq!(Principal::tenant(&p), None);
1125    let no_sub = hs(json!({"name": "a"}));
1126    assert!(matches!(
1127      run(verifier().verify(&no_sub)),
1128      Err(AuthError::InvalidClaims(m)) if m.contains("sub")
1129    ));
1130    assert!(string_items(&json!(7)).is_empty());
1131  }
1132
1133  #[test]
1134  fn key_selection_by_kid_and_family() {
1135    let a = JwtKey::hmac(b"a").with_kid("a");
1136    let b = JwtKey::hmac(b"b").with_kid("b");
1137    let unnamed = JwtKey::hmac(b"u");
1138    let keys = [a.clone(), b.clone()];
1139    assert_eq!(
1140      select_key(&keys, Some("b"), Algorithm::HS256)
1141        .unwrap()
1142        .kid(),
1143      Some("b")
1144    );
1145    assert!(matches!(
1146      select_key(&keys, Some("c"), Algorithm::HS256),
1147      Err(AuthError::UnknownKey(m)) if m.contains("\"c\"")
1148    ));
1149    assert!(matches!(
1150      select_key(&keys, None, Algorithm::HS256),
1151      Err(AuthError::UnknownKey(m)) if m.contains("HS256")
1152    ));
1153    assert_eq!(
1154      select_key(std::slice::from_ref(&a), None, Algorithm::HS256)
1155        .unwrap()
1156        .kid(),
1157      Some("a")
1158    );
1159    let with_unnamed = [a, unnamed];
1160    assert_eq!(
1161      select_key(&with_unnamed, Some("zz"), Algorithm::HS256)
1162        .unwrap()
1163        .kid(),
1164      None
1165    );
1166    assert!(select_key(&keys, Some("a"), Algorithm::RS256).is_err());
1167    let narrowed = JwtKey::new(
1168      DecodingKey::from_secret(b"s"),
1169      [Algorithm::HS512, Algorithm::RS256],
1170    );
1171    assert_eq!(narrowed.algorithms(), [Algorithm::HS512]);
1172    assert!(format!("{narrowed:?}").contains("HS512"));
1173  }
1174
1175  #[test]
1176  fn key_material_errors() {
1177    assert!(matches!(JwtKey::rsa_pem(b"nope"), Err(AuthError::Key(_))));
1178    assert!(matches!(JwtKey::ec_pem(b"nope"), Err(AuthError::Key(_))));
1179    assert!(matches!(JwtKey::ed_pem(b"nope"), Err(AuthError::Key(_))));
1180    assert!(matches!(
1181      JwtIssuer::rsa_pem(Algorithm::RS256, b"nope"),
1182      Err(AuthError::Key(_))
1183    ));
1184    assert!(matches!(
1185      JwtIssuer::ec_pem(Algorithm::ES256, b"nope"),
1186      Err(AuthError::Key(_))
1187    ));
1188    assert!(matches!(
1189      JwtIssuer::new(Algorithm::RS256, EncodingKey::from_secret(b"s")),
1190      Err(AuthError::Key(_))
1191    ));
1192    let issuer = JwtIssuer::new(Algorithm::HS384, EncodingKey::from_secret(b"s")).unwrap();
1193    assert!(format!("{issuer:?}").contains("HS384"));
1194    let verifier = verifier().issuer("i").audience("a");
1195    let dbg = format!("{verifier:?}");
1196    assert!(dbg.contains("1 static") && dbg.contains("\"i\""), "{dbg}");
1197  }
1198
1199  #[test]
1200  fn h7_jwt_without_issuer_or_audience_is_rejected() {
1201    let token = hs(json!({"sub": "a", "iss": "iss-a", "aud": "aud-a"}));
1202    let lax = JwtVerifier::new([JwtKey::hmac(SECRET)]).with_clock(clock_at(1_000));
1203    let Err(AuthError::Config(m)) = run(lax.verify(&token)) else {
1204      panic!("a verifier pinning neither iss nor aud must not accept tokens")
1205    };
1206    assert!(m.contains("issuer or an audience"), "{m}");
1207    assert_eq!(AuthError::Config(m).http_status(), 500);
1208    // Pinning either is enough.
1209    assert!(run(lax.clone().issuer("iss-a").verify(&token)).is_ok());
1210    assert!(run(lax.clone().audience("aud-a").verify(&token)).is_ok());
1211    // A token for another audience of the same issuer is still refused once aud is pinned.
1212    assert!(matches!(
1213      run(lax.audience("aud-b").verify(&token)),
1214      Err(AuthError::InvalidClaims(m)) if m.contains("aud")
1215    ));
1216  }
1217
1218  #[test]
1219  fn h7_dangerous_opt_out_is_explicit() {
1220    let token = hs(json!({"sub": "a"}));
1221    let lax = JwtVerifier::new([JwtKey::hmac(SECRET)]).with_clock(clock_at(1_000));
1222    // One opt-out alone does not re-open the lax default.
1223    for half in [
1224      lax.clone().dangerous_any_issuer(),
1225      lax.clone().dangerous_any_audience(),
1226    ] {
1227      assert!(matches!(
1228        run(half.verify(&token)),
1229        Err(AuthError::Config(_))
1230      ));
1231    }
1232    let both = lax.dangerous_any_issuer().dangerous_any_audience();
1233    assert_eq!(run(both.verify(&token)).unwrap().id(), "a");
1234  }
1235
1236  #[test]
1237  fn h7_dangerous_any_issuer_and_audience_are_recorded() {
1238    let token = hs(json!({"sub": "a"}));
1239    let lax = JwtVerifier::new([JwtKey::hmac(SECRET)]).with_clock(clock_at(1_000));
1240    #[allow(deprecated)]
1241    let shim = lax.clone().any_issuer_dangerous().any_audience_dangerous();
1242    assert_eq!(run(shim.verify(&token)).unwrap().id(), "a");
1243    let _ = lax.dangerous_any_issuer().dangerous_any_audience();
1244    let recorded = id_effect::observability::posture::dangerous_opt_outs();
1245    for id in [DANGEROUS_ANY_ISSUER, DANGEROUS_ANY_AUDIENCE] {
1246      let (_, reopens) = recorded
1247        .iter()
1248        .find(|(found, _)| *found == id)
1249        .expect("recorded");
1250      assert!(reopens.starts_with("H7:"), "{id}: {reopens}");
1251    }
1252  }
1253
1254  #[test]
1255  fn m15_short_hmac_key_rejected() {
1256    let short = b"31 bytes, one short of HS256 ok";
1257    assert_eq!(short.len(), MIN_HMAC_KEY_LEN - 1);
1258    // A short secret issues nothing ...
1259    let issued = run(JwtIssuer::hs256(short).issue(&AuthPrincipal::new("a")));
1260    assert!(
1261      matches!(&issued, Err(AuthError::Key(m)) if m.contains("at least 32 bytes")),
1262      "{issued:?}"
1263    );
1264    let other_route = JwtIssuer::new(Algorithm::HS384, EncodingKey::from_secret(short)).unwrap();
1265    assert!(matches!(
1266      run(other_route.issue(&AuthPrincipal::new("a"))),
1267      Err(AuthError::Key(_))
1268    ));
1269    // ... and verifies nothing, even a token its bytes did sign.
1270    let mut header = Header::new(Algorithm::HS256);
1271    header.kid = None;
1272    let forged = encode(
1273      &header,
1274      &claims(json!({"sub": "a", "exp": 2_000})),
1275      &EncodingKey::from_secret(short),
1276    )
1277    .unwrap();
1278    let weak = JwtVerifier::new([JwtKey::hmac(short)])
1279      .with_clock(clock_at(1_000))
1280      .dangerous_any_issuer()
1281      .dangerous_any_audience();
1282    assert!(matches!(
1283      run(weak.verify(&forged)),
1284      Err(AuthError::Key(m)) if m.contains("has 31")
1285    ));
1286    // 32 bytes are accepted.
1287    assert!(run(JwtIssuer::hs256(SECRET).issue(&AuthPrincipal::new("a"))).is_ok());
1288  }
1289
1290  #[test]
1291  fn library_errors_map_to_auth_errors() {
1292    let cases = [
1293      (ErrorKind::InvalidSignature, AuthError::InvalidCredentials),
1294      (ErrorKind::ExpiredSignature, AuthError::Expired),
1295      (ErrorKind::ImmatureSignature, AuthError::NotYetValid),
1296      (
1297        ErrorKind::InvalidSubject,
1298        AuthError::InvalidClaims("sub is not accepted".into()),
1299      ),
1300      (
1301        ErrorKind::MissingRequiredClaim("x".into()),
1302        AuthError::InvalidClaims("missing claim x".into()),
1303      ),
1304      (
1305        ErrorKind::InvalidClaimFormat("x".into()),
1306        AuthError::InvalidClaims("claim x is malformed".into()),
1307      ),
1308    ];
1309    for (kind, expected) in cases {
1310      assert_eq!(AuthError::from(JwtLibError::from(kind)), expected);
1311    }
1312    assert!(matches!(
1313      AuthError::from(JwtLibError::from(ErrorKind::InvalidKeyFormat)),
1314      AuthError::Key(_)
1315    ));
1316  }
1317}