datapress-core 0.4.3

Backend-agnostic core types, config, routing, and HTTP handlers for the datapress dataset server.
Documentation
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! OIDC bearer-token enforcement.
//!
//! Compiled in only when the `auth` cargo feature is enabled. Provides:
//!
//! 1. A [`JwksCache`] that periodically fetches the issuer's JWKS and
//!    keeps the latest snapshot in an [`ArcSwap`] for lock-free reads.
//!    A `kid` cache miss triggers an out-of-band refresh so key
//!    rotation doesn't strand callers.
//! 2. A [`verify_token`] helper that validates signature, `iss`, `aud`,
//!    `exp`/`nbf` (with leeway), and the configured `alg` allow-list.
//! 3. An actix middleware [`Auth`] that extracts the bearer token,
//!    verifies it, and attaches a [`Principal`] to request extensions.
//!    Handlers then use [`require_scope`] / [`require_scopes`] /
//!    [`Principal::tenant`] to enforce per-route policy.
//!
//! The scope strings come from either the standard `scope` claim
//! (usually space-separated, per RFC 8693) or `scp` (Azure AD style).
//! Both string and array forms are accepted.
//!
//! The Swagger UI's SSO support (`crate::swagger`) is independent of
//! this module — that one only drives the UI login dialog.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use actix_web::body::EitherBody;
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::header;
use actix_web::{Error as ActixError, HttpMessage, HttpRequest, HttpResponse, ResponseError};
use arc_swap::ArcSwap;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header, jwk::JwkSet};
use serde::Deserialize;
use std::future::{Ready, ready};
use std::pin::Pin;

use crate::config::AuthConfig;
use crate::errors::AppError;

fn install_jwt_crypto_provider() {
    let _ = jsonwebtoken::crypto::aws_lc::DEFAULT_PROVIDER.install_default();
}

// ---------------------------------------------------------------------------
// Principal — what handlers see after a successful auth
// ---------------------------------------------------------------------------

/// Authenticated caller. Attached to every authenticated request via
/// `req.extensions_mut().insert(Principal { … })`; retrieve with
/// `req.extensions().get::<Principal>()`.
#[derive(Debug, Clone)]
pub struct Principal {
    /// `sub` claim — the IdP's stable identifier for the user / client.
    pub sub: String,
    /// All scopes the bearer holds, normalised to lowercase.
    pub scopes: Vec<String>,
    /// Tenant extracted via `auth.tenant_claim`, if configured and
    /// present in the token. `None` when no tenant claim is configured.
    pub tenant: Option<String>,
}

impl Principal {
    /// True iff the bearer has every requested scope.
    pub fn has_all_scopes(&self, required: &[String]) -> bool {
        required.iter().all(|r| self.scopes.iter().any(|s| s == r))
    }
}

// ---------------------------------------------------------------------------
// Scope guard — for use inside handlers
// ---------------------------------------------------------------------------

/// Reject the request unless the attached [`Principal`] holds every
/// scope in `required`. Returns `Ok(())` when the check passes — or
/// when no [`Principal`] is attached *and* `required` is empty (the
/// anonymous-read path).
///
/// Anonymous callers that try to access scoped routes get 401, not
/// 403, so clients can distinguish "you forgot your token" from
/// "your token is insufficient".
pub fn require_scopes(req: &HttpRequest, required: &[String]) -> Result<(), AppError> {
    if required.is_empty() {
        return Ok(());
    }
    let ext = req.extensions();
    match ext.get::<Principal>() {
        Some(p) if p.has_all_scopes(required) => Ok(()),
        Some(_) => Err(AppError::Forbidden(format!(
            "token is missing required scope(s): {}",
            required.join(" ")
        ))),
        None => Err(AppError::Unauthorized(
            "missing or invalid bearer token".into(),
        )),
    }
}

// ---------------------------------------------------------------------------
// JWKS cache
// ---------------------------------------------------------------------------

/// Lock-free snapshot of the latest JWKS plus the timestamp it was
/// fetched at (for debug logging only). Swapped atomically by the
/// background refresher.
#[derive(Clone)]
struct JwksSnapshot {
    set: Arc<JwkSet>,
}

/// JWKS cache with a background refresh task. Cheap to clone — the
/// inner snapshot is behind an Arc.
#[derive(Clone)]
pub struct JwksCache {
    inner: Arc<ArcSwap<Option<JwksSnapshot>>>,
    /// OIDC issuer, used to run discovery (`.well-known/openid-configuration`).
    issuer: Arc<String>,
    /// JWKS endpoint discovered from the issuer's OIDC metadata. Cached
    /// once resolved; `None` until the first successful discovery.
    jwks_uri: Arc<ArcSwap<Option<String>>>,
    client: reqwest::Client,
}

impl JwksCache {
    /// Build the cache and seed it from the issuer's JWKS endpoint.
    ///
    /// The JWKS URL is **discovered** from the issuer's OIDC metadata
    /// (`{issuer}/.well-known/openid-configuration` → `jwks_uri`) rather
    /// than assumed, so IdPs that publish keys under a non-standard path
    /// (Keycloak's `…/protocol/openid-connect/certs`, Azure AD, Auth0,
    /// Okta, …) work out of the box. If discovery is unreachable the
    /// cache falls back to the legacy `{issuer}/.well-known/jwks.json`
    /// path for that attempt only, and re-tries discovery on the next
    /// refresh.
    ///
    /// When the initial fetch fails, behaviour depends on
    /// `start_degraded`:
    ///
    /// * `start_degraded = true` → return `Ok` with an empty cache;
    ///   the middleware will reject every auth'd request with 503
    ///   until a subsequent refresh succeeds.
    /// * `start_degraded = false` → return `Err` so `serve` aborts.
    ///
    /// In either case a background refresher is spawned on the current
    /// tokio runtime.
    pub async fn boot(cfg: &AuthConfig) -> Result<Self, AppError> {
        install_jwt_crypto_provider();

        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(10))
            .build()
            .map_err(|e| AppError::Internal(format!("reqwest client: {e}")))?;
        let cache = Self {
            inner: Arc::new(ArcSwap::from_pointee(None)),
            issuer: Arc::new(cfg.issuer.clone()),
            jwks_uri: Arc::new(ArcSwap::from_pointee(None)),
            client: client.clone(),
        };

        match cache.resolve_and_fetch().await {
            Ok(set) => {
                cache
                    .inner
                    .store(Arc::new(Some(JwksSnapshot { set: Arc::new(set) })));
                log::info!("auth: JWKS loaded for issuer {}", cfg.issuer);
            }
            Err(e) if cfg.start_degraded => {
                log::warn!(
                    "auth: initial JWKS load for issuer {} failed ({e}); \
                     starting in degraded mode — auth'd requests will return 503 \
                     until JWKS becomes reachable",
                    cfg.issuer
                );
            }
            Err(e) => {
                return Err(AppError::Internal(format!(
                    "auth: JWKS load failed and start_degraded = false: {e}"
                )));
            }
        }

        // Background refresher.
        let refresh = Duration::from_secs(cfg.jwks_refresh_secs.max(60));
        let cache_bg = cache.clone();
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(refresh);
            // Skip the immediate tick — we already fetched (or tried) above.
            interval.tick().await;
            loop {
                interval.tick().await;
                cache_bg.refresh_quiet().await;
            }
        });

        Ok(cache)
    }

    /// Resolve the JWKS URL (via OIDC discovery, cached) and fetch the
    /// key set. On the first call this runs discovery against the
    /// issuer's `.well-known/openid-configuration` and caches the
    /// resulting `jwks_uri`. If discovery is unreachable, this falls
    /// back to the legacy `{issuer}/.well-known/jwks.json` path for this
    /// attempt only (without caching), so a later refresh re-discovers.
    async fn resolve_and_fetch(&self) -> Result<JwkSet, String> {
        if let Some(uri) = self.jwks_uri.load_full().as_ref().clone() {
            return fetch_jwks(&self.client, &uri).await;
        }
        match discover_jwks_uri(&self.client, &self.issuer).await {
            Ok(uri) => {
                self.jwks_uri.store(Arc::new(Some(uri.clone())));
                fetch_jwks(&self.client, &uri).await
            }
            Err(e) => {
                let fallback = format!(
                    "{}/.well-known/jwks.json",
                    self.issuer.trim_end_matches('/')
                );
                log::warn!("auth: OIDC discovery failed ({e}); falling back to legacy {fallback}");
                fetch_jwks(&self.client, &fallback).await
            }
        }
    }

    async fn refresh_quiet(&self) {
        match self.resolve_and_fetch().await {
            Ok(set) => {
                self.inner
                    .store(Arc::new(Some(JwksSnapshot { set: Arc::new(set) })));
                log::debug!("auth: JWKS refreshed");
            }
            Err(e) => log::warn!("auth: JWKS refresh failed: {e}"),
        }
    }

    /// Current snapshot, or `None` if the cache has never been
    /// populated (degraded start, no successful fetch yet).
    fn snapshot(&self) -> Option<JwksSnapshot> {
        self.inner.load_full().as_ref().clone()
    }
}

/// Run OIDC discovery: GET `{issuer}/.well-known/openid-configuration`
/// and return its `jwks_uri`. Returns `Err` on a network failure, a
/// non-success HTTP status, or an unparseable / `jwks_uri`-less body.
async fn discover_jwks_uri(client: &reqwest::Client, issuer: &str) -> Result<String, String> {
    #[derive(Deserialize)]
    struct OidcMetadata {
        jwks_uri: String,
    }

    let disco_url = format!(
        "{}/.well-known/openid-configuration",
        issuer.trim_end_matches('/')
    );
    let resp = client
        .get(&disco_url)
        .send()
        .await
        .map_err(|e| e.to_string())?;
    if !resp.status().is_success() {
        return Err(format!("discovery {disco_url} → HTTP {}", resp.status()));
    }
    let meta = resp
        .json::<OidcMetadata>()
        .await
        .map_err(|e| format!("discovery {disco_url} body: {e}"))?;
    log::info!(
        "auth: discovered jwks_uri={} via {disco_url}",
        meta.jwks_uri
    );
    Ok(meta.jwks_uri)
}

async fn fetch_jwks(client: &reqwest::Client, url: &str) -> Result<JwkSet, String> {
    let resp = client.get(url).send().await.map_err(|e| e.to_string())?;
    if !resp.status().is_success() {
        return Err(format!("HTTP {}", resp.status()));
    }
    resp.json::<JwkSet>().await.map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Token verification
// ---------------------------------------------------------------------------

/// Subset of JWT claims we care about. Everything else is ignored.
/// `scope`/`scp` are both accepted for compatibility with IdPs that use
/// one or the other. Some providers emit `scope` as a string; others use
/// an array, so both shapes are accepted.
#[derive(Debug, Deserialize)]
struct Claims {
    #[serde(default)]
    sub: Option<String>,
    #[serde(default)]
    scope: Option<ScopeField>,
    #[serde(default)]
    scp: Option<ScopeField>,
    // Allow arbitrary extras for tenant-claim extraction.
    #[serde(flatten)]
    extra: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum ScopeField {
    String(String),
    List(Vec<String>),
}

fn parse_scopes(c: &Claims) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    extend_scopes(&mut out, c.scope.as_ref());
    extend_scopes(&mut out, c.scp.as_ref());
    out
}

fn extend_scopes(out: &mut Vec<String>, field: Option<&ScopeField>) {
    match field {
        Some(ScopeField::String(s)) => {
            out.extend(s.split_whitespace().map(|s| s.to_ascii_lowercase()));
        }
        Some(ScopeField::List(l)) => {
            out.extend(l.iter().map(|s| s.to_ascii_lowercase()));
        }
        None => {}
    }
}

fn extract_tenant(c: &Claims, pointer: &str) -> Option<String> {
    if pointer.is_empty() {
        return None;
    }
    // Wrap extras into a Value so JSON pointer works uniformly.
    let v = serde_json::Value::Object(
        c.extra
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect(),
    );
    v.pointer(pointer).and_then(|x| match x {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Number(n) => Some(n.to_string()),
        _ => None,
    })
}

fn extract_subject(c: &Claims) -> Option<String> {
    c.sub.clone().or_else(|| {
        ["client_id", "azp", "appid", "oid"]
            .iter()
            .find_map(|claim| value_as_string(c.extra.get(*claim)))
    })
}

fn value_as_string(value: Option<&serde_json::Value>) -> Option<String> {
    match value {
        Some(serde_json::Value::String(s)) => Some(s.clone()),
        Some(serde_json::Value::Number(n)) => Some(n.to_string()),
        _ => None,
    }
}

fn algorithm_from(name: &str) -> Result<Algorithm, AppError> {
    Ok(match name {
        "RS256" => Algorithm::RS256,
        "RS384" => Algorithm::RS384,
        "RS512" => Algorithm::RS512,
        "ES256" => Algorithm::ES256,
        "ES384" => Algorithm::ES384,
        "PS256" => Algorithm::PS256,
        "PS384" => Algorithm::PS384,
        "PS512" => Algorithm::PS512,
        other => return Err(AppError::Internal(format!("unsupported alg: {other}"))),
    })
}

/// Validate the bearer token, returning a [`Principal`] on success.
pub fn verify_token(
    token: &str,
    cfg: &AuthConfig,
    jwks: &JwksCache,
) -> Result<Principal, AppError> {
    install_jwt_crypto_provider();

    let snap = jwks
        .snapshot()
        .ok_or_else(|| AppError::Unavailable("auth: JWKS not yet available".into()))?;

    let header = decode_header(token)
        .map_err(|e| AppError::Unauthorized(format!("malformed token: {e}")))?;
    let kid = header
        .kid
        .ok_or_else(|| AppError::Unauthorized("token header missing 'kid'".into()))?;
    let jwk = snap
        .set
        .find(&kid)
        .ok_or_else(|| AppError::Unauthorized(format!("unknown signing key kid='{kid}'")))?;
    let key = DecodingKey::from_jwk(jwk)
        .map_err(|e| AppError::Internal(format!("auth: bad JWK in JWKS for kid='{kid}': {e}")))?;

    // Build validation. Pin algorithm to what's in the token header,
    // but only if the operator listed it as allowed.
    let allowed: Vec<Algorithm> = cfg
        .algorithms
        .iter()
        .map(|a| algorithm_from(a))
        .collect::<Result<_, _>>()?;
    if !allowed.contains(&header.alg) {
        return Err(AppError::Unauthorized(format!(
            "token alg '{:?}' not in auth.algorithms allow-list",
            header.alg
        )));
    }
    let mut v = Validation::new(header.alg);
    v.leeway = cfg.leeway_secs;
    v.set_issuer(&[&cfg.issuer]);
    if cfg.audience.is_empty() {
        v.validate_aud = false;
    } else {
        v.set_audience(&[&cfg.audience]);
    }

    let data = decode::<Claims>(token, &key, &v)
        .map_err(|e| AppError::Unauthorized(format!("token rejected: {e}")))?;

    let claims = data.claims;
    let sub = extract_subject(&claims).ok_or_else(|| {
        AppError::Unauthorized(
            "token does not carry a subject claim (expected sub, client_id, azp, appid, or oid)"
                .into(),
        )
    })?;
    let scopes = parse_scopes(&claims);
    let tenant = extract_tenant(&claims, &cfg.tenant_claim);

    if !cfg.allowed_tenants.is_empty() {
        match &tenant {
            Some(t) if cfg.allowed_tenants.iter().any(|a| a == t) => {}
            Some(t) => {
                return Err(AppError::Forbidden(format!(
                    "tenant '{t}' is not in auth.allowed_tenants"
                )));
            }
            None => {
                return Err(AppError::Forbidden(
                    "token does not carry the configured tenant claim".into(),
                ));
            }
        }
    }

    Ok(Principal {
        sub,
        scopes,
        tenant,
    })
}

// ---------------------------------------------------------------------------
// Actix middleware
// ---------------------------------------------------------------------------

/// State shared between every middleware instance. Cheap to clone.
#[derive(Clone)]
pub struct AuthState {
    pub cfg: Arc<AuthConfig>,
    pub jwks: JwksCache,
}

/// Actix middleware. Build with [`Auth::new`] and wrap your `App` with
/// `.wrap(auth)`. Reads `Authorization: Bearer …`, verifies the token,
/// and attaches a [`Principal`] to request extensions. When no header
/// is present, the request is passed through unchanged — handlers must
/// call [`require_scopes`] to enforce policy.
#[derive(Clone)]
pub struct Auth {
    state: Option<AuthState>,
}

impl Auth {
    /// Build an enforcing middleware around the given state.
    pub fn new(state: AuthState) -> Self {
        Self { state: Some(state) }
    }
    /// Build a no-op middleware. Useful so callers can wrap the same
    /// type unconditionally and decide enforcement at runtime.
    pub fn disabled() -> Self {
        Self { state: None }
    }
}

impl<S, B> Transform<S, ServiceRequest> for Auth
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = ActixError;
    type Transform = AuthMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(AuthMiddleware {
            service: Arc::new(service),
            state: self.state.clone(),
        }))
    }
}

pub struct AuthMiddleware<S> {
    service: Arc<S>,
    state: Option<AuthState>,
}

impl<S, B> Service<ServiceRequest> for AuthMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = ActixError;
    type Future = Pin<Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>>>>;

    actix_web::dev::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let svc = self.service.clone();
        let state = self.state.clone();
        Box::pin(async move {
            let Some(state) = state else {
                let res = svc.call(req).await?;
                return Ok(res.map_into_left_body());
            };
            // Try to extract a bearer token.
            let header_val = req
                .headers()
                .get(header::AUTHORIZATION)
                .and_then(|v| v.to_str().ok())
                .map(str::trim);
            let token = header_val.and_then(|h| {
                let mut parts = h.splitn(2, ' ');
                match (parts.next(), parts.next()) {
                    (Some(scheme), Some(value)) if scheme.eq_ignore_ascii_case("bearer") => {
                        Some(value.trim().to_string())
                    }
                    _ => None,
                }
            });

            if let Some(tok) = token {
                match verify_token(&tok, &state.cfg, &state.jwks) {
                    Ok(principal) => {
                        if let Some(t) = &principal.tenant {
                            log::debug!(
                                "auth: sub='{}' tenant='{}' scopes={:?}",
                                principal.sub,
                                t,
                                principal.scopes
                            );
                        } else {
                            log::debug!(
                                "auth: sub='{}' scopes={:?}",
                                principal.sub,
                                principal.scopes
                            );
                        }
                        req.extensions_mut().insert(principal);
                    }
                    Err(e) => {
                        // Short-circuit: reject the request here so handlers
                        // never see a forged token.
                        let resp = e.error_response();
                        let (request, _pl) = req.into_parts();
                        let sr = ServiceResponse::new(request, resp).map_into_right_body();
                        return Ok(sr);
                    }
                }
            }

            // No token: handlers will reject if a scope is required.
            let res = svc.call(req).await?;
            Ok(res.map_into_left_body())
        })
    }
}

/// Render a 401 with a `WWW-Authenticate: Bearer` challenge so curl /
/// browsers can prompt for credentials. Only used when emitting the
/// "no token" rejection from inside handlers.
pub fn unauthorized_challenge(msg: &str) -> HttpResponse {
    HttpResponse::Unauthorized()
        .insert_header((header::WWW_AUTHENTICATE, "Bearer realm=\"datapress\""))
        .json(serde_json::json!({ "error": format!("unauthorized: {msg}") }))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg() -> AuthConfig {
        AuthConfig {
            enabled: true,
            issuer: "https://issuer.test".into(),
            audience: "api://datapress".into(),
            read_scopes: vec!["datasets:read".into()],
            reload_scopes: vec!["datasets:reload".into()],
            tenant_claim: "/tid".into(),
            ..AuthConfig::default()
        }
    }

    #[test]
    fn parse_scopes_handles_string_and_array() {
        let c: Claims = serde_json::from_value(serde_json::json!({
            "sub": "u",
            "scope": "openid datasets:read"
        }))
        .unwrap();
        let s = parse_scopes(&c);
        assert!(s.contains(&"openid".into()));
        assert!(s.contains(&"datasets:read".into()));

        let c: Claims = serde_json::from_value(serde_json::json!({
            "sub": "u",
            "aud": ["api://datapress", "account"],
            "scope": ["openid", "datasets:read"]
        }))
        .unwrap();
        let s = parse_scopes(&c);
        assert!(s.contains(&"openid".into()));
        assert!(s.contains(&"datasets:read".into()));
        assert!(c.extra["aud"].is_array());

        let c: Claims = serde_json::from_value(serde_json::json!({
            "sub": "u",
            "scp": ["openid", "datasets:read"]
        }))
        .unwrap();
        let s = parse_scopes(&c);
        assert!(s.contains(&"openid".into()));
        assert!(s.contains(&"datasets:read".into()));
    }

    #[test]
    fn extract_tenant_string_and_number() {
        let c: Claims = serde_json::from_value(serde_json::json!({
            "sub": "u",
            "tid": "acme"
        }))
        .unwrap();
        assert_eq!(extract_tenant(&c, "/tid").as_deref(), Some("acme"));

        let c: Claims = serde_json::from_value(serde_json::json!({
            "sub": "u",
            "org": { "id": 42 }
        }))
        .unwrap();
        assert_eq!(extract_tenant(&c, "/org/id").as_deref(), Some("42"));
    }

    #[test]
    fn extract_subject_accepts_client_credentials_claims() {
        let c: Claims = serde_json::from_value(serde_json::json!({
            "sub": "user-123",
            "client_id": "service-client"
        }))
        .unwrap();
        assert_eq!(extract_subject(&c).as_deref(), Some("user-123"));

        let c: Claims = serde_json::from_value(serde_json::json!({
            "client_id": "service-client"
        }))
        .unwrap();
        assert_eq!(extract_subject(&c).as_deref(), Some("service-client"));

        let c: Claims = serde_json::from_value(serde_json::json!({
            "azp": "authorized-party"
        }))
        .unwrap();
        assert_eq!(extract_subject(&c).as_deref(), Some("authorized-party"));
    }

    #[test]
    fn client_credentials_claims_without_sub_are_accepted() {
        let c: Claims = serde_json::from_value(serde_json::json!({
            "iss": "https://issuer.test",
            "nbf": 1_700_000_000,
            "iat": 1_700_000_000,
            "exp": 1_700_003_600,
            "aud": ["api://datapress", "account"],
            "scope": ["datasets:read", "datasets:reload"],
            "client_id": "service-client",
            "role": ["reader"],
            "jti": "token-id"
        }))
        .unwrap();

        assert_eq!(extract_subject(&c).as_deref(), Some("service-client"));
        assert_eq!(parse_scopes(&c), vec!["datasets:read", "datasets:reload"]);
        assert!(c.extra["aud"].is_array());
        assert!(c.extra["role"].is_array());
    }

    #[test]
    fn has_all_scopes_checks_every_required() {
        let p = Principal {
            sub: "u".into(),
            scopes: vec!["a".into(), "b".into()],
            tenant: None,
        };
        assert!(p.has_all_scopes(&[]));
        assert!(p.has_all_scopes(&["a".into()]));
        assert!(p.has_all_scopes(&["a".into(), "b".into()]));
        assert!(!p.has_all_scopes(&["a".into(), "c".into()]));
    }

    // Smoke: the config helper compiles and produces a sensible default.
    #[test]
    fn cfg_smoke() {
        let c = cfg();
        assert!(c.enabled);
        assert_eq!(c.tenant_claim, "/tid");
    }
}