kanade-backend 0.44.18

axum + SQLite projection backend for the kanade endpoint-management system. Hosts /api/* and the embedded SPA dashboard, projects JetStream streams into SQLite, drives the cron scheduler
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
//! Authentication + RBAC middleware for `/api/*`.
//!
//! Resolution order at request time:
//!
//!   1. `KANADE_AUTH_DISABLE=1` — open access, synthesised admin
//!      identity. Dev / local-only.
//!   2. `/api/auth/login` — public (the SPA / CLI POST credentials here
//!      to obtain a JWT, so it must be reachable without one).
//!   3. Static token (service token) — shared bearer secret. Caller
//!      sends `Authorization: Bearer <secret>`; a constant-time compare
//!      grants an **admin-equivalent** identity. For CI / non-interactive
//!      automation. A non-matching bearer falls through to JWT below
//!      (so user JWTs and a service token coexist).
//!   4. JWT mode (HS256) — `aud=kanade` + `exp`. On a valid signature the
//!      caller's `sub` is looked up in the SQLite `users` table and the
//!      **DB row is authoritative**: a missing row → 401, a `disabled`
//!      row → 403, otherwise the DB `role` (not the token's claim) is
//!      injected into [`Claims`]. This makes `disable` / role changes
//!      take effect immediately rather than waiting for `exp`.
//!
//! Secret resolution is registry-first, env-second:
//!
//! ```text
//! StaticToken:  HKLM\SOFTWARE\kanade\backend\StaticToken
//!$KANADE_AUTH_STATIC_TOKEN
//! JwtSecret:    HKLM\SOFTWARE\kanade\backend\JwtSecret
//!$KANADE_JWT_SECRET   (required for account login)
//! ```
//!
//! `JwtSecret` is the fleet-wide skeleton key (anyone holding it can
//! mint admin tokens), so it lives **only on the backend host** — agents
//! and the CLI never need it.
//!
//! Per-route role enforcement is via the [`require_operator`] /
//! [`require_admin`] `route_layer` middleware applied to the mutating /
//! admin route groups in [`crate::api::router`]; under-privileged
//! callers are rejected with `403` before the handler runs.

use axum::body::Body;
use axum::extract::{MatchedPath, Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
use kanade_shared::feature::Feature;
use kanade_shared::secrets;
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;
use std::env;
use std::sync::OnceLock;
use tracing::{error, warn};

/// Hierarchical role: `Viewer < Operator < Admin` (the derived `Ord`
/// follows declaration order). `admin ⊇ operator ⊇ viewer`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    Viewer,
    Operator,
    Admin,
}

impl Role {
    pub fn as_str(self) -> &'static str {
        match self {
            Role::Viewer => "viewer",
            Role::Operator => "operator",
            Role::Admin => "admin",
        }
    }

    pub fn parse(s: &str) -> Option<Role> {
        match s {
            "viewer" => Some(Role::Viewer),
            "operator" => Some(Role::Operator),
            "admin" => Some(Role::Admin),
            _ => None,
        }
    }

    /// True when this role satisfies a route's minimum requirement.
    pub fn allows(self, required: Role) -> bool {
        self >= required
    }
}

/// JWT claims yielded by the validator. Stashed in the request
/// extensions so downstream handlers can introspect the caller.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Claims {
    pub sub: String,
    pub exp: i64,
    #[serde(default)]
    pub aud: Option<String>,
    #[serde(default)]
    pub roles: Vec<String>,
    /// Per-account page allow-list, resolved from the DB
    /// (`users.allowed_features`) by [`verify`] — **not** trusted from the
    /// token. `None` = unrestricted (every page). `Some(list)` restricts the
    /// caller to those features plus the always-open commons (see
    /// [`crate::api::feature_for_path`]). `skip_serializing_if` keeps it out
    /// of minted JWTs entirely: like `roles`, the DB is authoritative and
    /// re-read on every request, so a token never carries a stale allow-list.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowed_features: Option<Vec<Feature>>,
}

impl Claims {
    /// The caller's effective role — the highest parseable entry in
    /// `roles`, defaulting to the least privilege (`Viewer`) when the
    /// token carries no recognised role.
    pub fn role(&self) -> Role {
        self.roles
            .iter()
            .filter_map(|r| Role::parse(r))
            .max()
            .unwrap_or(Role::Viewer)
    }

    /// Synthesised admin identity for the two table-less paths
    /// (`KANADE_AUTH_DISABLE` and the static service token).
    fn service(sub: &str) -> Self {
        Claims {
            sub: sub.to_string(),
            exp: 4_102_444_800, // 2100-01-01
            aud: Some(EXPECTED_AUDIENCE.to_string()),
            roles: vec![Role::Admin.as_str().to_string()],
            // Service / auth-disabled identities are unrestricted — they are
            // the escape hatch that can always reach every page (e.g. to
            // un-restrict an account that locked itself out of `/accounts`).
            allowed_features: None,
        }
    }
}

const ENV_DISABLE: &str = "KANADE_AUTH_DISABLE";
const ENV_STATIC_TOKEN: &str = "KANADE_AUTH_STATIC_TOKEN";
const ENV_SECRET: &str = "KANADE_JWT_SECRET";
const REG_SUBKEY: &str = r"SOFTWARE\kanade\backend";
const REG_STATIC_TOKEN: &str = "StaticToken";
const REG_JWT_SECRET: &str = "JwtSecret";
pub const EXPECTED_AUDIENCE: &str = "kanade";

/// Resolve the static service token, **cached for the process lifetime**.
/// Reading the registry / env on every request would be needless syscalls
/// at fleet scale (Gemini #331); a rotated token requires a backend
/// restart, which deploys already do.
fn resolve_static_token() -> Option<&'static str> {
    static CACHE: OnceLock<Option<String>> = OnceLock::new();
    CACHE
        .get_or_init(|| {
            if let Some(t) = secrets::read_hklm_value(REG_SUBKEY, REG_STATIC_TOKEN) {
                return Some(t);
            }
            match env::var(ENV_STATIC_TOKEN) {
                Ok(t) if !t.is_empty() => Some(t),
                _ => None,
            }
        })
        .as_deref()
}

/// Resolve the HS256 signing/verification secret. Returns `None` when
/// neither the registry value nor the env var is set.
fn resolve_jwt_secret() -> Option<String> {
    if let Some(s) = secrets::read_hklm_value(REG_SUBKEY, REG_JWT_SECRET) {
        return Some(s);
    }
    match env::var(ENV_SECRET) {
        Ok(s) if !s.is_empty() => Some(s),
        _ => None,
    }
}

/// The HS256 secret used to both verify and mint tokens, **cached for the
/// process lifetime** (same registry/restart rationale as the static
/// token). Falls back to a loud dev default when unset so `cargo run`
/// works — never acceptable in production, hence the one-time warning.
pub fn signing_secret() -> &'static str {
    static CACHE: OnceLock<String> = OnceLock::new();
    CACHE.get_or_init(|| {
        resolve_jwt_secret().unwrap_or_else(|| {
            warn!(
                "no JwtSecret registry value and no $KANADE_JWT_SECRET — using a hard-coded dev fallback (NEVER in production)"
            );
            "dev-secret-please-override".to_string()
        })
    })
}

/// The authoritative account facts [`verify`] re-reads on every request.
struct UserAuth {
    role: Role,
    disabled: bool,
    /// The account's **effective** page allow-list. `None` = unrestricted;
    /// `Some(list)` = restricted to those pages. Resolved with the permission
    /// group taking precedence over the per-user list (see [`lookup_user`]).
    /// Unknown / retired feature keys are dropped (a shrunk catalog must not
    /// deny access on a key the backend no longer knows).
    allowed_features: Option<Vec<Feature>>,
}

/// Look up a user's authoritative `(role, disabled, effective allow-list)`
/// from SQLite. A row whose `role` column fails to parse is treated as absent
/// (deny).
///
/// The effective allow-list is the account's **permission group** (#1008
/// Phase 3, live-referenced via the join) when it has one, otherwise its own
/// `allowed_features` (whose `NULL` means unrestricted). A group is always a
/// concrete set (its `'[]'` means "commons only"), so it wins over the
/// per-user column.
///
/// **Fail-closed for a group-assigned account** (Gemini HIGH on #1014): once
/// an account has a `permission_group`, its effective access can never be
/// `None`/unrestricted, even if that group is missing or its JSON is corrupt.
/// A dangling group (which the atomic `DELETE` guard already prevents) resolves
/// group → per-user list → `Some(Vec::new())` (commons only), never falling
/// open to every page. Only an account with **no** group falls through to the
/// per-user `NULL` = unrestricted default.
async fn lookup_user(pool: &SqlitePool, username: &str) -> Result<Option<UserAuth>, sqlx::Error> {
    let row = sqlx::query_as::<_, (String, i64, Option<String>, Option<String>, Option<String>)>(
        "SELECT u.role, u.disabled, u.allowed_features, g.features, u.permission_group \
         FROM users u \
         LEFT JOIN permission_groups g ON u.permission_group = g.name \
         WHERE u.username = ?",
    )
    .bind(username)
    .fetch_optional(pool)
    .await?;
    Ok(row.and_then(
        |(role, disabled, allowed, group_features, permission_group)| {
            Role::parse(&role).map(|role| {
                let allowed_features = if permission_group.is_some() {
                    // Group intended → never unrestricted. Prefer the group's
                    // set, then the per-user list, then commons-only.
                    parse_allowed_features(group_features.as_deref())
                        .or_else(|| parse_allowed_features(allowed.as_deref()))
                        .or_else(|| Some(Vec::new()))
                } else {
                    parse_allowed_features(allowed.as_deref())
                };
                UserAuth {
                    role,
                    disabled: disabled != 0,
                    allowed_features,
                }
            })
        },
    ))
}

/// Parse the stored `allowed_features` JSON (`NULL`/absent → `None` =
/// unrestricted). A malformed or non-array value is treated as `None`
/// (unrestricted) with a warning rather than locking the account out — a
/// corrupt column should fail *open* for its owner, never silently deny
/// every page. Individual unknown keys are dropped.
fn parse_allowed_features(raw: Option<&str>) -> Option<Vec<Feature>> {
    let raw = raw?;
    match serde_json::from_str::<Vec<String>>(raw) {
        Ok(keys) => Some(keys.iter().filter_map(|k| Feature::parse(k)).collect()),
        Err(e) => {
            warn!(error = %e, "malformed allowed_features JSON; treating as unrestricted");
            None
        }
    }
}

pub async fn verify(
    State(pool): State<SqlitePool>,
    req: Request,
    next: Next,
) -> Result<Response, Response> {
    // 1. Auth opt-out for local development.
    if env::var(ENV_DISABLE).is_ok() {
        let mut req = req;
        req.extensions_mut()
            .insert(Claims::service("auth-disabled"));
        return Ok(next.run(req).await);
    }

    // Only /api/* is protected; the SPA static files at / and the
    // health probe at /health stay public.
    let path = req.uri().path();
    if !path.starts_with("/api/") {
        return Ok(next.run(req).await);
    }

    // 2. Public endpoints reachable without a token: the login route, the
    //    backend version probe (so the SPA can show it pre-login), and the
    //    #770 password setup/reset link + forgot-password flow (the user
    //    has no session yet — the one-time token IS the credential).
    if path == "/api/auth/login"
        || path == "/api/version"
        || path == "/api/auth/forgot-password"
        || path.starts_with("/api/auth/password-setup/")
    {
        return Ok(next.run(req).await);
    }

    let token = req
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|h| h.strip_prefix("Bearer "))
        .map(str::trim)
        .filter(|t| !t.is_empty());
    let Some(token) = token else {
        return Err(unauth("missing bearer token"));
    };

    // 3. Static service token: admin-equivalent. A mismatch is NOT a
    //    rejection — fall through to JWT so user tokens coexist.
    if let Some(expected) = resolve_static_token()
        && constant_time_eq(token.as_bytes(), expected.as_bytes())
    {
        let mut req = req;
        req.extensions_mut()
            .insert(Claims::service("service-token"));
        return Ok(next.run(req).await);
    }

    // 4. JWT mode.
    let secret = signing_secret();
    let key = DecodingKey::from_secret(secret.as_bytes());
    let mut validation = Validation::new(Algorithm::HS256);
    validation.set_audience(&[EXPECTED_AUDIENCE]);

    let claims = match decode::<Claims>(token, &key, &validation) {
        Ok(data) => data.claims,
        Err(e) => {
            warn!(error = %e, path, "JWT verify failed");
            return Err(unauth(&format!("invalid token: {e}")));
        }
    };

    // DB is authoritative: re-read role + disabled now so account
    // changes apply immediately rather than at the token's exp.
    match lookup_user(&pool, &claims.sub).await {
        Ok(Some(user)) => {
            if user.disabled {
                // 401 (not 403) so the SPA's expired-token path logs the
                // user out instead of trapping them on a page that spams
                // permission toasts (Gemini #331).
                return Err(unauth("account disabled"));
            }
            let mut claims = claims;
            // DB is authoritative for BOTH role and the page allow-list —
            // overwrite whatever the token carried (the mint path never sets
            // allowed_features, but a hand-crafted token might).
            claims.roles = vec![user.role.as_str().to_string()];
            claims.allowed_features = user.allowed_features;
            let mut req = req;
            req.extensions_mut().insert(claims);
            Ok(next.run(req).await)
        }
        Ok(None) => Err(unauth("unknown account")),
        Err(e) => {
            // Fail closed: a DB hiccup must not grant access.
            error!(error = %e, sub = %claims.sub, "user lookup failed");
            Err(unauth("auth backend unavailable"))
        }
    }
}

/// Returns `Some(403)` unless the caller (identity injected by
/// [`verify`]) holds at least `required`; `None` when the request may
/// proceed. Used as a `route_layer` over the mutating / admin route
/// groups in [`crate::api::router`], so individual handlers stay free of
/// role boilerplate.
fn gate(req: &Request, required: Role) -> Option<Response> {
    let Some(claims) = req.extensions().get::<Claims>().cloned() else {
        return Some(forbidden("no authenticated identity"));
    };
    if claims.role().allows(required) {
        None
    } else {
        Some(forbidden(&format!(
            "{} role required (caller is {})",
            required.as_str(),
            claims.role().as_str()
        )))
    }
}

/// `route_layer` middleware: caller must be at least `operator`.
pub async fn require_operator(req: Request, next: Next) -> Result<Response, Response> {
    if let Some(rejection) = gate(&req, Role::Operator) {
        return Err(rejection);
    }
    Ok(next.run(req).await)
}

/// `route_layer` middleware: caller must be `admin`.
pub async fn require_admin(req: Request, next: Next) -> Result<Response, Response> {
    if let Some(rejection) = gate(&req, Role::Admin) {
        return Err(rejection);
    }
    Ok(next.run(req).await)
}

/// Per-account **page** enforcement (hard, `403`) — the horizontal axis
/// orthogonal to the vertical role gates above.
///
/// Layered over the whole API router (inside [`crate::api::router`], so it
/// runs *after* [`verify`] has injected [`Claims`] and *after* routing has
/// populated [`MatchedPath`]). The decision:
///
///   * caller unrestricted (`allowed_features == None`, or no identity /
///     service token) → allow;
///   * the matched route is **commons** (`feature_for_path` → `None`:
///     login, self-service, the Dashboard landing feeds, shared substrate)
///     → allow;
///   * otherwise allow iff the caller's allow-list intersects the route's
///     feature(s); else `403`.
///
/// Commons-by-default (an unmapped route is open to any authenticated
/// caller) is deliberate: most endpoints are shared substrate, and the
/// sensitive per-page data lives behind the mapped routes. A NEW topical
/// endpoint must be added to `feature_for_path` to be gated.
pub async fn require_features(req: Request, next: Next) -> Result<Response, Response> {
    // Decide entirely within a borrow of `req.extensions()` and yield only
    // owned data (`Feature::as_str` is `&'static str`), so no borrow — and no
    // clone of the allow-list — outlives the block. Then `req` is free to move
    // into `next.run`.
    let denied: Option<&'static str> = {
        let ext = req.extensions();
        match ext
            .get::<Claims>()
            .and_then(|c| c.allowed_features.as_ref())
        {
            // No authenticated identity (public route) or an unrestricted
            // caller (service token / NULL allow-list) → nothing to enforce.
            None => None,
            Some(allowed) => match ext
                .get::<MatchedPath>()
                .and_then(|m| crate::api::feature_for_path(m.as_str()))
            {
                // Commons route, or the caller is permitted this page.
                None => None,
                Some(feature) if allowed.contains(&feature) => None,
                Some(feature) => Some(feature.as_str()),
            },
        }
    };

    match denied {
        None => Ok(next.run(req).await),
        Some(want) => Err(forbidden(&format!(
            "account not permitted to access this page (requires {want})"
        ))),
    }
}

/// Length-checked, branch-free byte comparison. Tiny inline impl —
/// we don't want a crate dep just for this and the use site is a
/// non-adversarial config path anyway, but the constant-time shape
/// future-proofs us if the token surface ever gets exposed to
/// untrusted callers.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

fn unauth(msg: &str) -> Response {
    (StatusCode::UNAUTHORIZED, Body::from(msg.to_owned())).into_response()
}

fn forbidden(msg: &str) -> Response {
    (StatusCode::FORBIDDEN, Body::from(msg.to_owned())).into_response()
}

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

    #[test]
    fn role_hierarchy() {
        assert!(Role::Admin.allows(Role::Operator));
        assert!(Role::Admin.allows(Role::Viewer));
        assert!(Role::Operator.allows(Role::Viewer));
        assert!(!Role::Operator.allows(Role::Admin));
        assert!(!Role::Viewer.allows(Role::Operator));
        assert!(Role::Viewer.allows(Role::Viewer));
    }

    #[test]
    fn role_roundtrip() {
        for r in [Role::Viewer, Role::Operator, Role::Admin] {
            assert_eq!(Role::parse(r.as_str()), Some(r));
        }
        assert_eq!(Role::parse("root"), None);
    }

    #[test]
    fn jwt_hs256_roundtrip_does_not_panic() {
        // Regression: jsonwebtoken 10.x routes HS256 through a rustls-
        // style CryptoProvider and *panics at runtime* on the first
        // encode/decode unless a provider feature is pinned (see the dep
        // note in the workspace Cargo.toml). No test minted a token
        // before, so the panic shipped in v0.43.14 and only surfaced on
        // the first SPA login. This exercises the exact crypto path so CI
        // catches a missing / ambiguous provider feature instead of it
        // blowing up at runtime.
        use jsonwebtoken::{EncodingKey, Header, encode};

        let claims = Claims {
            sub: "alice".into(),
            exp: 4_102_444_800,
            aud: Some(EXPECTED_AUDIENCE.to_string()),
            roles: vec![Role::Admin.as_str().to_string()],
            allowed_features: None,
        };
        let key = b"regression-secret";
        let token = encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(key),
        )
        .expect("HS256 encode must not panic — pin a jsonwebtoken CryptoProvider feature");

        let mut validation = Validation::new(Algorithm::HS256);
        validation.set_audience(&[EXPECTED_AUDIENCE]);
        let decoded = decode::<Claims>(&token, &DecodingKey::from_secret(key), &validation)
            .expect("HS256 decode of our own token");
        assert_eq!(decoded.claims.sub, "alice");
        assert_eq!(decoded.claims.role(), Role::Admin);
    }

    #[test]
    fn allowed_features_parse() {
        // NULL / absent → unrestricted.
        assert!(parse_allowed_features(None).is_none());
        // A JSON array → those features, unknown keys dropped.
        let got = parse_allowed_features(Some(r#"["compliance","inventory","bogus"]"#)).unwrap();
        assert_eq!(got, vec![Feature::Compliance, Feature::Inventory]);
        // Empty array is a REAL restriction (commons only) — not None.
        assert_eq!(parse_allowed_features(Some("[]")), Some(vec![]));
        // Malformed → fail open (None), never lock the owner out.
        assert!(parse_allowed_features(Some("not json")).is_none());
        assert!(parse_allowed_features(Some(r#"{"x":1}"#)).is_none());
    }

    #[tokio::test]
    async fn effective_features_group_precedence() {
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        sqlx::migrate!("./migrations").run(&pool).await.unwrap();
        sqlx::query(
            "INSERT INTO permission_groups (name, features) VALUES ('sec', '[\"compliance\"]')",
        )
        .execute(&pool)
        .await
        .unwrap();
        sqlx::query("INSERT INTO permission_groups (name, features) VALUES ('locked', '[]')")
            .execute(&pool)
            .await
            .unwrap();

        let eff = |name: &'static str| {
            let pool = pool.clone();
            async move {
                lookup_user(&pool, name)
                    .await
                    .unwrap()
                    .unwrap()
                    .allowed_features
            }
        };

        // Group wins over the per-user list.
        sqlx::query("INSERT INTO users (username, password_hash, role, allowed_features, permission_group) VALUES ('g', 'x', 'viewer', '[\"audit\"]', 'sec')")
            .execute(&pool).await.unwrap();
        assert_eq!(eff("g").await, Some(vec![Feature::Compliance]));

        // A group with `[]` restricts to commons only — NOT unrestricted.
        sqlx::query("INSERT INTO users (username, password_hash, role, permission_group) VALUES ('l', 'x', 'viewer', 'locked')")
            .execute(&pool).await.unwrap();
        assert_eq!(eff("l").await, Some(vec![]));

        // No group → fall back to the per-user list.
        sqlx::query("INSERT INTO users (username, password_hash, role, allowed_features) VALUES ('p', 'x', 'viewer', '[\"audit\"]')")
            .execute(&pool).await.unwrap();
        assert_eq!(eff("p").await, Some(vec![Feature::Audit]));

        // Dangling group (references a missing group) → fall back to per-user.
        sqlx::query("INSERT INTO users (username, password_hash, role, allowed_features, permission_group) VALUES ('d', 'x', 'viewer', '[\"logs\"]', 'ghost')")
            .execute(&pool).await.unwrap();
        assert_eq!(eff("d").await, Some(vec![Feature::Logs]));

        // Dangling group with NO per-user list → commons-only, NEVER
        // unrestricted (fail-closed; a group-assigned account can't escalate).
        sqlx::query("INSERT INTO users (username, password_hash, role, permission_group) VALUES ('x', 'x', 'admin', 'ghost')")
            .execute(&pool).await.unwrap();
        assert_eq!(eff("x").await, Some(vec![]));

        // No group and no per-user list → unrestricted.
        sqlx::query("INSERT INTO users (username, password_hash, role) VALUES ('u', 'x', 'admin')")
            .execute(&pool)
            .await
            .unwrap();
        assert_eq!(eff("u").await, None);
    }

    #[test]
    fn claims_role_picks_highest() {
        let c = Claims {
            sub: "x".into(),
            exp: 0,
            aud: None,
            roles: vec!["viewer".into(), "admin".into()],
            allowed_features: None,
        };
        assert_eq!(c.role(), Role::Admin);
        let none = Claims {
            sub: "x".into(),
            exp: 0,
            aud: None,
            roles: vec![],
            allowed_features: None,
        };
        assert_eq!(none.role(), Role::Viewer);
    }
}