1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! OIDC token validation: signature verification and claim extraction.
//!
//! JWKS fetching, caching, and key-selection logic lives in [`super::jwks`].
/// Maximum byte size for an OIDC discovery document.
///
/// A well-formed `.well-known/openid-configuration` response is a few `KiB`.
/// 64 `KiB` is generous while blocking allocation-bomb responses from
/// a malicious or misconfigured OIDC provider.
pub(super) const MAX_DISCOVERY_RESPONSE_BYTES: usize = 64 * 1024; // 64 KiB
use std::{sync::Arc, time::Duration};
use chrono::{DateTime, Utc};
use fraiseql_jwks::JwksSource;
use jsonwebtoken::{Algorithm, Validation, decode, decode_header};
use crate::security::{
auth_middleware::{
AuthenticatedUser,
types::{extract_claim_string, extract_name_string},
},
errors::{Result, SecurityError},
oidc::{
audience::JwtClaims,
providers::{MAX_CLOCK_SKEW_SECS, OidcConfig},
replay_cache::ReplayCache,
},
};
// ============================================================================
// OidcValidator struct and constructor
// ============================================================================
/// OIDC token validator with JWKS caching.
///
/// Validates JWT tokens against an OIDC provider's public keys.
/// Automatically fetches and caches the JWKS for efficiency.
///
/// JWKS fetch/cache/key-selection helpers are in `impl OidcValidator` blocks
/// defined in the `jwks` sub-module.
pub struct OidcValidator {
/// The configuration as given: the primary issuer and the settings every issuer
/// shares (`required`, `me`, the JWKS cache TTL).
pub(super) config: OidcConfig,
/// Every trusted issuer, the primary first, then `additional_issuers` in order
/// (#1400). A token is verified by exactly one of them, chosen by its `iss`.
pub(super) issuers: Vec<IssuerProfile>,
/// Optional JWT replay cache. When set, each validated token's `jti` is
/// checked against the cache and rejected if it has been seen before.
pub(super) replay_cache: Option<Arc<ReplayCache>>,
}
/// One trusted issuer: its settings and its own key set (#1400).
pub(super) struct IssuerProfile {
/// The issuer's settings, as a complete single-issuer configuration.
pub(super) config: OidcConfig,
/// The one bounded JWKS client (#1335), for this issuer's keys only. Not a cache
/// this type owns: a near-copy of it lived here and another in `fraiseql_auth`,
/// and the two had drifted on key types and on DNS pinning while agreeing on the
/// one thing that mattered — neither bounded a refetch.
pub(super) jwks: Arc<JwksSource>,
}
/// The one claim read from a token before its signature is checked: which issuer's
/// keys to check it with.
#[derive(serde::Deserialize)]
struct IssuerClaim {
iss: Option<String>,
}
impl OidcValidator {
/// Create a new OIDC validator.
///
/// This will perform OIDC discovery to find the JWKS URI
/// unless `jwks_uri` is explicitly set in config.
///
/// # Errors
///
/// Returns error if:
/// - Config validation fails
/// - OIDC discovery fails
/// - JWKS endpoint cannot be determined
pub async fn new(config: OidcConfig) -> Result<Self> {
config.validate()?;
// Redirects are disabled to prevent redirect-chain SSRF attacks.
// `https_only` is not set here because `OidcConfig::validate()` already
// requires HTTPS for the issuer URL (localhost HTTP is allowed for dev/test).
// Local to this call: the only request it makes is the discovery document.
// The key set is fetched by the shared JWKS client, which builds its own
// client per fetch so it can pin the connection to the addresses it
// validated — a long-lived client cannot do that.
let http_client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(30))
.build()
.map_err(|e| SecurityError::SecurityConfigError(format!("HTTP client error: {e}")))?;
let mut issuers = Vec::new();
for issuer_config in Self::issuer_configs(&config) {
let jwks_uri = Self::jwks_uri_for(&http_client, &issuer_config).await?;
// The URI is validated here, by the client that will fetch it: not a URL,
// or not https (bar a loopback host for development), and this validator
// is refused rather than built. Core used only to check that it parsed,
// while `fraiseql_auth` checked the scheme too — one client, one rule.
let jwks = Self::key_source(&issuer_config, &jwks_uri)?;
issuers.push(IssuerProfile {
config: issuer_config,
jwks,
});
}
Ok(Self {
config,
issuers,
replay_cache: None,
})
}
/// Every issuer's complete configuration: the primary, then each additional one.
fn issuer_configs(config: &OidcConfig) -> Vec<OidcConfig> {
std::iter::once(config.clone())
.chain(config.additional_issuers.iter().map(|extra| extra.as_config(config)))
.collect()
}
/// The JWKS endpoint of one issuer: pinned, or located by OIDC discovery.
async fn jwks_uri_for(http_client: &reqwest::Client, config: &OidcConfig) -> Result<String> {
use crate::security::oidc::jwks::OidcDiscoveryDocument;
if let Some(ref uri) = config.jwks_uri {
return Ok(uri.clone());
}
// No pinned JWKS URI: locate it via OIDC discovery from the issuer.
// `config.validate()` above guarantees `issuer` is set whenever
// `jwks_uri` is not, so this error is unreachable in practice —
// it keeps the discovery path total without an unwrap.
let issuer = config.issuer.as_deref().ok_or_else(|| {
SecurityError::SecurityConfigError(
"OIDC discovery requires an issuer when `jwks_uri` is not pinned".to_string(),
)
})?;
// Perform OIDC discovery
let discovery_url =
format!("{}/.well-known/openid-configuration", issuer.trim_end_matches('/'));
tracing::debug!(url = %discovery_url, "Performing OIDC discovery");
let response = http_client.get(&discovery_url).send().await.map_err(|e| {
SecurityError::SecurityConfigError(format!("OIDC discovery failed: {e}"))
})?;
if !response.status().is_success() {
return Err(SecurityError::SecurityConfigError(format!(
"OIDC discovery failed with status: {}",
response.status()
)));
}
let body_bytes = response.bytes().await.map_err(|e| {
SecurityError::SecurityConfigError(format!(
"Failed to read OIDC discovery response: {e}"
))
})?;
if body_bytes.len() > MAX_DISCOVERY_RESPONSE_BYTES {
return Err(SecurityError::SecurityConfigError(format!(
"OIDC discovery response too large ({} bytes, max {MAX_DISCOVERY_RESPONSE_BYTES})",
body_bytes.len()
)));
}
let discovery: OidcDiscoveryDocument =
serde_json::from_slice(&body_bytes).map_err(|e| {
SecurityError::SecurityConfigError(format!("Invalid OIDC discovery response: {e}"))
})?;
tracing::info!(
issuer = %discovery.issuer,
jwks_uri = %discovery.jwks_uri,
"OIDC discovery successful"
);
Ok(discovery.jwks_uri)
}
/// The bounded JWKS client for a configured `jwks_uri`.
///
/// `jwks_cache_ttl_secs` is how long a fetched key set is served for, and
/// therefore the maximum window in which a rotated-out key keeps validating.
/// The refetch bound is [`fraiseql_jwks::REFETCH_COOLDOWN`] and is not
/// configurable — see it for why.
fn key_source(config: &OidcConfig, jwks_uri: &str) -> Result<Arc<JwksSource>> {
JwksSource::new(jwks_uri, Duration::from_secs(config.jwks_cache_ttl_secs))
.map(Arc::new)
.map_err(|error| {
SecurityError::SecurityConfigError(format!(
"OIDC jwks_uri {jwks_uri:?} cannot be used: {error}"
))
})
}
/// Create a validator without performing discovery.
///
/// Use this when you have the JWKS URI directly, and in tests.
///
/// # Returns a `Result` now (#1335)
///
/// It used to store the URI unexamined, so `jwks_uri = "not a url"` — or a
/// plain-`http` one pointing anywhere — built a validator that refused every
/// token at its first delivery instead of refusing to exist. The sibling
/// cache in `fraiseql_auth` had always validated at construction; there is now
/// one client and one answer.
///
/// # Errors
///
/// `SecurityError::SecurityConfigError` when `jwks_uri` is not a URL, or is
/// not `https` — plain `http` is accepted only for a loopback host, which is
/// what a local fixture or a development `IdP` is.
/// With `additional_issuers`, `jwks_uri` is the primary issuer's endpoint and every
/// additional issuer must pin its own: this constructor performs no discovery.
pub fn with_jwks_uri(config: OidcConfig, jwks_uri: &str) -> Result<Self> {
let mut issuers = Vec::new();
for (index, issuer_config) in Self::issuer_configs(&config).into_iter().enumerate() {
let uri = if index == 0 {
jwks_uri.to_string()
} else {
issuer_config.jwks_uri.clone().ok_or_else(|| {
SecurityError::SecurityConfigError(format!(
"additional issuer {:?} needs a pinned `jwks_uri` when the validator \
is built without discovery",
issuer_config.issuer.as_deref().unwrap_or_default()
))
})?
};
let jwks = Self::key_source(&issuer_config, &uri)?;
issuers.push(IssuerProfile {
config: issuer_config,
jwks,
});
}
Ok(Self {
config,
issuers,
replay_cache: None,
})
}
/// Attach a JWT replay cache to this validator.
///
/// When set, every validated token's `jti` claim is checked against the
/// cache. A token whose `jti` has been seen before is rejected with
/// `SecurityError::TokenReplayed`, preventing stolen-token replay attacks.
///
/// If `require_jti` is `true` in [`OidcConfig`], tokens without a `jti`
/// are also rejected before the replay check is reached.
#[must_use]
pub fn with_replay_cache(mut self, cache: Arc<ReplayCache>) -> Self {
self.replay_cache = Some(cache);
self
}
/// Validate a JWT token and extract user information.
///
/// # Arguments
///
/// * `token` - The JWT token string (without "Bearer " prefix)
///
/// # Returns
///
/// `AuthenticatedUser` if token is valid, error otherwise.
///
/// # Errors
///
/// Returns error if:
/// - Token is malformed
/// - Signature verification fails
/// - Required claims are missing
/// - Token is expired
/// - Issuer/audience don't match
pub async fn validate_token(&self, token: &str) -> Result<AuthenticatedUser> {
// Which issuer's keys and rules apply, decided from `iss` before anything else
// (#1400). Everything below reads `issuer`, never another profile.
let issuer = self.issuer_for(token)?;
// Decode header to get kid
let header = decode_header(token).map_err(|e| {
tracing::debug!(error = %e, "Failed to decode JWT header");
SecurityError::InvalidToken
})?;
let kid = header.kid.as_ref().ok_or_else(|| {
tracing::debug!("JWT missing kid (key ID) in header");
SecurityError::InvalidToken
})?;
// The allow-list is checked BEFORE the key lookup, and that ordering is
// the fix, not an optimisation (#1335). It used to run after, so a token
// whose `alg` this server refuses on its header alone — an `HS256` against
// an RSA JWKS, the algorithm-confusion probe — still cost one outbound
// request to the IdP. Nothing here touches the network.
let algorithm = issuer.get_algorithm(&header)?;
// Only now: the key lookup, which may reach the provider (bounded).
let decoding_key = issuer.get_decoding_key(kid).await?;
// Build validation
let mut validation = Validation::new(algorithm);
// Validate the `iss` claim only when an issuer is configured.
//
// `set_issuer` alone checks `iss` *only if the claim is present*
// (jsonwebtoken's default `required_spec_claims` is just `{exp}`), so we
// also require `iss` — a configured issuer then means "iss must be
// present AND match", matching operator intent.
//
// In issuer-less mode both are skipped: tokens that omit `iss` (e.g.
// Hanko access tokens) are accepted, gated only by signature (against
// the pinned JWKS) and `audience`.
if let Some(ref expected) = issuer.config.issuer {
validation.set_issuer(&[expected]);
validation.set_required_spec_claims(&["exp", "iss"]);
}
// Set audience validation — always enabled when any audience is configured.
// The validate() call earlier guarantees at least one audience is set,
// so this else branch (validate_aud = false) is never reached in practice.
// It is kept as a defensive fallback; the real protection is the mandatory
// audience check in OidcConfig::validate().
if let Some(ref aud) = issuer.config.audience {
let mut audiences = vec![aud.clone()];
audiences.extend(issuer.config.additional_audiences.clone());
validation.set_audience(&audiences);
} else if !issuer.config.additional_audiences.is_empty() {
// Only additional_audiences configured (no primary audience):
// still validate against those.
validation.set_audience(&issuer.config.additional_audiences);
} else {
// Should be unreachable after OidcConfig::validate() — fail-closed.
validation.validate_aud = true;
}
// Set clock skew tolerance — capped to prevent accepting arbitrarily
// old expired tokens due to misconfiguration.
validation.leeway = issuer.config.clock_skew_secs.min(MAX_CLOCK_SKEW_SECS);
// Decode and validate token
let token_data = decode::<JwtClaims>(token, &decoding_key, &validation).map_err(|e| {
tracing::debug!(error = %e, "JWT validation failed");
match e.kind() {
jsonwebtoken::errors::ErrorKind::ExpiredSignature => SecurityError::TokenExpired {
expired_at: Utc::now(), // Approximate
},
// Invalid issuer, audience, signature, and all other errors map to InvalidToken
_ => SecurityError::InvalidToken,
}
})?;
let claims = token_data.claims;
// Validate jti claim if required by configuration.
if issuer.config.require_jti && claims.jti.is_none() {
tracing::debug!("JWT missing required jti (JWT ID) claim");
return Err(SecurityError::TokenMissingClaim {
claim: "jti".to_string(),
});
}
// Replay check: if a replay cache is configured and the token carries a jti,
// verify the jti has not been seen before and record it for future checks.
if let (Some(replay_cache), Some(ref jti)) = (&self.replay_cache, &claims.jti) {
use std::time::Duration;
// Compute the token's remaining TTL for the cache entry.
let ttl = claims
.exp
.and_then(|exp| {
let remaining = exp - chrono::Utc::now().timestamp();
if remaining > 0 {
Some(Duration::from_secs(remaining.cast_unsigned()))
} else {
None
}
})
.unwrap_or(Duration::from_mins(15)); // Fallback: 15-minute TTL
replay_cache.check_and_record(jti, ttl).await.map_err(|e| {
use crate::security::oidc::replay_cache::ReplayCacheError;
match e {
ReplayCacheError::Replayed => {
tracing::warn!(jti = %jti, "JWT replay detected");
SecurityError::TokenReplayed
},
ReplayCacheError::Backend(_) => {
// Backend error with fail-open is already handled inside
// ReplayCache::check_and_record(); reaching here means
// fail-closed is configured.
tracing::warn!(jti = %jti, error = %e, "Replay cache backend error");
SecurityError::InvalidToken
},
}
})?;
}
// Extract scopes first (before moving claims.sub)
let scopes = issuer.extract_scopes(&claims);
// Extract user ID (required)
let user_id_str = claims.sub.ok_or(SecurityError::TokenMissingClaim {
claim: "sub".to_string(),
})?;
let user_id = crate::types::UserId::new(user_id_str);
// Extract expiration (required)
let exp = claims.exp.ok_or(SecurityError::TokenMissingClaim {
claim: "exp".to_string(),
})?;
let expires_at =
DateTime::<Utc>::from_timestamp(exp, 0).ok_or(SecurityError::InvalidToken)?;
tracing::debug!(
user_id = %user_id,
scopes = ?scopes,
expires_at = %expires_at,
"Token validated successfully"
);
// Extract email and display name from dedicated fields or extra claims.
// Dedicated fields take priority; fall back to extra for providers that
// use non-standard claim names.
let email = claims
.email
.as_ref()
.and_then(extract_claim_string)
.or_else(|| claims.extra.get("email").and_then(extract_claim_string));
let display_name = claims
.name
.as_ref()
.and_then(extract_name_string)
.or_else(|| claims.extra.get("name").and_then(extract_name_string));
// `iss` is a registered claim, so the deserializer lifts it out of `extra`; it is
// put back so the principal records which issuer vouched for it (#1400) — the
// issuer `SecurityContext::issuer` and `$iss` enrichment bindings read.
let mut extra_claims = claims.extra;
if let Some(iss) = claims.iss {
extra_claims.insert("iss".to_string(), serde_json::Value::String(iss));
}
Ok(AuthenticatedUser {
user_id,
scopes,
expires_at,
email,
display_name,
extra_claims,
})
}
/// The one trusted issuer whose keys and rules apply to `token` (#1400).
///
/// Chosen by the token's `iss`, read from the payload **before** the signature is
/// checked — only to pick a key set; the signature is then verified against that
/// issuer's keys alone, and `iss` itself is re-checked by the validation. An `iss`
/// that names no configured issuer is refused, never tried against every key set.
/// A single issuer-less profile (an `IdP` whose tokens omit `iss`) takes every token,
/// as before.
fn issuer_for(&self, token: &str) -> Result<&IssuerProfile> {
if let [only] = self.issuers.as_slice() {
if only.config.issuer.is_none() {
return Ok(only);
}
}
let iss = jsonwebtoken::dangerous::insecure_decode::<IssuerClaim>(token)
.ok()
.and_then(|data| data.claims.iss);
let Some(iss) = iss else {
tracing::debug!("JWT carries no `iss`, so no trusted issuer can verify it");
return Err(SecurityError::InvalidToken);
};
self.issuers
.iter()
.find(|issuer| issuer.config.issuer.as_deref() == Some(iss.as_str()))
.ok_or_else(|| {
tracing::debug!(iss = %iss, "JWT names an issuer this server does not trust");
SecurityError::InvalidToken
})
}
/// Check if authentication is required.
#[must_use]
pub const fn is_required(&self) -> bool {
self.config.required
}
/// Get the configured issuer, if any.
///
/// Returns `None` in issuer-less mode (`IdPs` whose tokens omit the `iss`
/// claim, validated via a pinned `jwks_uri`).
#[must_use]
pub fn issuer(&self) -> Option<&str> {
self.config.issuer.as_deref()
}
}
impl IssuerProfile {
/// Get the algorithm from the JWT header.
///
/// # Errors
///
/// Returns `SecurityError::InvalidTokenAlgorithm` if the algorithm is not in the allow-list.
pub(super) fn get_algorithm(&self, header: &jsonwebtoken::Header) -> Result<Algorithm> {
let alg_str = format!("{:?}", header.alg);
// Check if algorithm is allowed
if !self.config.allowed_algorithms.contains(&alg_str) {
return Err(SecurityError::InvalidTokenAlgorithm { algorithm: alg_str });
}
Ok(header.alg)
}
/// Extract scopes from JWT claims.
///
/// Handles multiple formats:
/// - `scope`: space-separated string (Auth0, Okta)
/// - `scp`: array of strings (some providers)
/// - `permissions`: array of strings (Auth0 RBAC)
fn extract_scopes(&self, claims: &JwtClaims) -> Vec<String> {
// Try the configured scope claim first (default: "scope")
if self.config.scope_claim == "scope" {
if let Some(ref scope) = claims.scope {
return scope.split_whitespace().map(String::from).collect();
}
}
// Try scp (array format)
if let Some(ref scp) = claims.scp {
return scp.clone();
}
// Try permissions (Auth0 RBAC)
if let Some(ref perms) = claims.permissions {
return perms.clone();
}
// Try scope as space-separated string
if let Some(ref scope) = claims.scope {
return scope.split_whitespace().map(String::from).collect();
}
Vec::new()
}
}