axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
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
//! Declarative authorization helpers (CONTRACT.md §11) for Actix-Web.
//!
//! This module is the **runtime** half of the §11 helpers: the
//! `#[require_access]` / `#[require_auth]` / `#[require_role]` attribute
//! macros (feature `macros`) expand to thin wrappers that call the plain
//! functions and the [`RequireAccess`] builder defined here, so the
//! enforcement logic is ordinary, unit-testable library code rather than
//! macro output.
//!
//! The helpers run strictly *after* the §10 [`AxiamUser`] extractor and
//! consume the identity it injected — they never duplicate token extraction
//! or verification (§11.2.1). The authorization check is always issued for
//! the **request's** authenticated user: [`RequireAccess::check`] sends the
//! caller's `user_id` as `subject_id`, so the app's own (often
//! service-account) `AxiamClient` session is never mistaken for the end user
//! (§11.2.2).
//!
//! ## Error mapping (§11.5)
//!
//! All failures surface as [`AuthzGuardError`], whose
//! [`actix_web::ResponseError`] impl produces the standardized §10 JSON body
//! `{ "error", "message" }`:
//!
//! | Condition | Status | `error` code |
//! |-----------|--------|--------------|
//! | no verified identity | 401 | `authentication_failed` |
//! | `allowed = false` / server 403 | 403 | `authorization_denied` |
//! | resource id missing or not a UUID | 400 | `invalid_request` |
//! | transport failure reaching authz (fail closed) | 503 | `authz_unavailable` |
//! | `AxiamClient` app data not registered | 500 | `internal_error` |
//!
//! Deny and error paths never log or echo the token (§11.8): the token never
//! enters this module — only the already-verified [`AxiamUser`] does.
//!
//! ## The `WWW-Authenticate` challenge (§20.3, §28.5)
//!
//! A `no_grant` denial on a route that named a scope can carry a
//! `WWW-Authenticate` header two different ways, and only one is ever
//! emitted: [`RequireAccess::with_uma_challenge`] (§20.3, a live permission
//! ticket) takes priority when configured and its mint succeeds;
//! [`RequireAccess::with_resource_metadata_url`] (CONTRACT.md §28.5 rule 5,
//! the RFC 6750 `insufficient_scope` hint) is the fallback — used when §20.3
//! was never configured, or its mint failed. Both land in
//! [`AuthzGuardError::DeniedWithChallenge`]; the JSON body is unchanged
//! either way.

use actix_web::http::StatusCode;
use actix_web::{HttpRequest, HttpResponse};
use serde::Serialize;
use uuid::Uuid;

use crate::AxiamError;
use crate::client::AxiamClient;
use crate::middleware::AxiamUser;

/// The error type for the CONTRACT.md §11 declarative authorization helpers.
///
/// Each variant maps to a specific HTTP status and standardized JSON error
/// body via the [`actix_web::ResponseError`] impl (see the [module
/// docs](self) for the full table). Construct values through the associated
/// functions rather than the variants directly.
#[derive(Debug)]
pub enum AuthzGuardError {
    /// No verified identity was present — 401 `authentication_failed`.
    Unauthenticated(String),
    /// The authorization check denied the request — 403 `authorization_denied`.
    Denied(String),
    /// Denied, with a `WWW-Authenticate` challenge attached — 403
    /// `authorization_denied` carrying either the §20.3 UMA header or the
    /// CONTRACT.md §28.5 rule 5 RFC 6750 `insufficient_scope` hint (see the
    /// [module docs](self) for which one and why only one is ever emitted).
    ///
    /// Carries `(message, header_value)`. The header is built during the
    /// async [`RequireAccess::check`] — minting a UMA ticket is a wire call,
    /// and even the §28 form needs the async `deny` path's own
    /// `reason_code` — while [`actix_web::ResponseError::error_response`]
    /// is synchronous; by the time this variant exists the value is already
    /// in hand.
    DeniedWithChallenge(String, String),
    /// The resource id could not be resolved to a UUID — 400 `invalid_request`.
    InvalidResource(String),
    /// The authorization service could not be reached (fail closed) — 503
    /// `authz_unavailable`.
    Unavailable(String),
    /// The handler is misconfigured (e.g. no `AxiamClient` app data) — 500
    /// `internal_error`.
    Misconfigured(String),
}

impl AuthzGuardError {
    /// Build a 401 `authentication_failed` error with `message`.
    pub fn unauthenticated(message: impl Into<String>) -> Self {
        Self::Unauthenticated(message.into())
    }

    /// Build a 403 `authorization_denied` error with `message`.
    pub fn denied(message: impl Into<String>) -> Self {
        Self::Denied(message.into())
    }

    /// Build a 403 `authorization_denied` error that also carries a
    /// `WWW-Authenticate: UMA` challenge (§20.3).
    ///
    /// `header_value` is the complete header value, already formatted by
    /// [`crate::uma::uma_challenge_header`] — the ticket inside it is a live
    /// credential for its 60-second life, so it is built once, here, and never
    /// re-derived on a later render of the response.
    pub fn denied_with_challenge(
        message: impl Into<String>,
        header_value: impl Into<String>,
    ) -> Self {
        Self::DeniedWithChallenge(message.into(), header_value.into())
    }

    /// Build a 400 `invalid_request` error with `message`, for a resource id
    /// that is missing or not a valid UUID (§11.3).
    pub fn invalid_resource(message: impl Into<String>) -> Self {
        Self::InvalidResource(message.into())
    }

    /// Build a 503 `authz_unavailable` error with `message`, used on the
    /// fail-closed transport-failure path (§11.5).
    pub fn unavailable(message: impl Into<String>) -> Self {
        Self::Unavailable(message.into())
    }

    /// Build a 500 `internal_error` error with `message`, for handler
    /// misconfiguration.
    pub fn misconfigured(message: impl Into<String>) -> Self {
        Self::Misconfigured(message.into())
    }

    /// The `error` code string for the standardized JSON body.
    fn code(&self) -> &'static str {
        match self {
            Self::Unauthenticated(_) => "authentication_failed",
            Self::Denied(_) | Self::DeniedWithChallenge(..) => "authorization_denied",
            Self::InvalidResource(_) => "invalid_request",
            Self::Unavailable(_) => "authz_unavailable",
            Self::Misconfigured(_) => "internal_error",
        }
    }

    /// The human-readable message for the standardized JSON body.
    fn message(&self) -> &str {
        match self {
            Self::Unauthenticated(m)
            | Self::Denied(m)
            | Self::DeniedWithChallenge(m, _)
            | Self::InvalidResource(m)
            | Self::Unavailable(m)
            | Self::Misconfigured(m) => m,
        }
    }
}

impl std::fmt::Display for AuthzGuardError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code(), self.message())
    }
}

impl std::error::Error for AuthzGuardError {}

#[derive(Serialize)]
struct ErrorBody<'a> {
    error: &'a str,
    message: &'a str,
}

impl actix_web::ResponseError for AuthzGuardError {
    fn status_code(&self) -> StatusCode {
        match self {
            Self::Unauthenticated(_) => StatusCode::UNAUTHORIZED,
            Self::Denied(_) | Self::DeniedWithChallenge(..) => StatusCode::FORBIDDEN,
            Self::InvalidResource(_) => StatusCode::BAD_REQUEST,
            Self::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
            Self::Misconfigured(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    fn error_response(&self) -> HttpResponse {
        let mut builder = HttpResponse::build(self.status_code());
        if let Self::DeniedWithChallenge(_, header) = self {
            // §20.3: tell the caller where to redeem authority. The body is the
            // unchanged §11.5 shape — the challenge is additive, so a client
            // that does not speak UMA sees exactly the 403 it saw before.
            builder.insert_header((actix_web::http::header::WWW_AUTHENTICATE, header.as_str()));
        }
        builder.json(ErrorBody {
            error: self.code(),
            message: self.message(),
        })
    }
}

/// Resolve a resource [`Uuid`] from a named path/route parameter (§11.3b).
///
/// Returns [`AuthzGuardError::InvalidResource`] (400 `invalid_request`) if the
/// parameter is absent or does not parse as a UUID — never a silent allow and
/// never a nil-UUID fallback.
///
/// ```no_run
/// # use actix_web::HttpRequest;
/// # fn demo(req: &HttpRequest) -> Result<(), axiam_sdk::middleware::AuthzGuardError> {
/// let resource_id = axiam_sdk::middleware::resource_from_path(req, "id")?;
/// # let _ = resource_id;
/// # Ok(())
/// # }
/// ```
pub fn resource_from_path(req: &HttpRequest, param: &str) -> Result<Uuid, AuthzGuardError> {
    match req.match_info().get(param) {
        Some(raw) => Uuid::parse_str(raw).map_err(|_| {
            AuthzGuardError::invalid_resource(format!(
                "path parameter '{param}' is not a valid resource UUID"
            ))
        }),
        None => Err(AuthzGuardError::invalid_resource(format!(
            "missing path parameter '{param}'"
        ))),
    }
}

/// Resolve a resource [`Uuid`] from a static UUID string literal (§11.3a),
/// for singleton resources.
///
/// Returns [`AuthzGuardError::InvalidResource`] (400 `invalid_request`) if the
/// literal does not parse as a UUID.
pub fn resource_from_static(literal: &str) -> Result<Uuid, AuthzGuardError> {
    Uuid::parse_str(literal).map_err(|_| {
        AuthzGuardError::invalid_resource(format!(
            "static resource_id '{literal}' is not a valid UUID"
        ))
    })
}

/// Local role check (§11 `require_role`): succeeds if `user` holds at least
/// one of `required` roles, otherwise returns
/// [`AuthzGuardError::Denied`] (403 `authorization_denied`).
///
/// This is a purely local check against the verified token's claims; it never
/// contacts the server. Role names are tenant-defined and this is **not** a
/// substitute for the resource-level [`RequireAccess`] check.
///
/// ```
/// # use axiam_sdk::middleware::require_role_check;
/// # fn demo(user: &axiam_sdk::middleware::AxiamUser) {
/// let ok = require_role_check(user, &["admin", "superadmin"]).is_ok();
/// # let _ = ok;
/// # }
/// ```
pub fn require_role_check(user: &AxiamUser, required: &[&str]) -> Result<(), AuthzGuardError> {
    let granted = user
        .roles
        .iter()
        .any(|held| required.iter().any(|want| held == want));
    if granted {
        Ok(())
    } else {
        Err(AuthzGuardError::denied(
            "caller does not hold any of the required roles".to_string(),
        ))
    }
}

/// A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).
///
/// Attach one to a [`RequireAccess`] with
/// [`RequireAccess::with_uma_challenge`] and a denial stops being a bare 403:
/// the guard mints a fresh permission ticket for the pairs the caller lacked
/// and returns it in the header, so a UMA-aware client knows where to go for
/// authority instead of only being told "no".
///
/// **Opt-in, and deliberately so.** Emitting a challenge means minting a
/// credential — a wire call to the Protection API, and a live ticket, produced
/// on a path the caller did not explicitly request. A guard that did that on
/// every denial by default would turn each unauthorized request into a
/// Protection API call, which is a denial-of-service amplifier pointed at your
/// own authorization server. So it happens only where an application has said
/// it wants UMA semantics on this route.
///
/// # Failure is not escalation
///
/// If minting fails — the PAT expired, the Protection API is down, the
/// resource declares none of the requested scopes — the denial still surfaces
/// as an ordinary 403 without a challenge. A caller who was going to be refused
/// is refused either way; letting a Protection API outage turn a deny into a
/// 500 would hand the outage a second consequence, and letting it turn into an
/// allow would be a security bug.
#[derive(Clone)]
pub struct UmaChallenger {
    realm: String,
    as_uri: String,
    pat: crate::sensitive::Sensitive<String>,
}

impl UmaChallenger {
    /// Build a challenger.
    ///
    /// `realm` is the protection realm to name, `as_uri` the authorization
    /// server to send the caller to — normally this deployment's issuer, read
    /// from `/.well-known/uma2-configuration` rather than concatenated by hand.
    /// `pat` is a Protection API Token: a *client-credentials* token carrying
    /// the `uma_protection` scope (§20.2 rule 1).
    pub fn new(
        realm: impl Into<String>,
        as_uri: impl Into<String>,
        pat: crate::sensitive::Sensitive<String>,
    ) -> Self {
        Self {
            realm: realm.into(),
            as_uri: as_uri.into(),
            pat,
        }
    }
}

impl std::fmt::Debug for UmaChallenger {
    /// Renders without the PAT (§7): a challenger is configuration a caller may
    /// reasonably log, and the credential inside it is not.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UmaChallenger")
            .field("realm", &self.realm)
            .field("as_uri", &self.as_uri)
            .field("pat", &self.pat)
            .finish()
    }
}

/// Programmatic, framework-agnostic form of the §11 `require_access` check.
///
/// This is the builder the `#[require_access]` attribute macro expands to; it
/// is also usable directly inside a handler when the macro is not a good fit
/// (e.g. a resource resolved from the request body). Build it with an
/// `action`, optionally attach a `scope`, then call [`check`](Self::check)
/// with the app's [`AxiamClient`], the request's [`AxiamUser`], and the
/// resolved resource id.
///
/// ```no_run
/// use axiam_sdk::client::AxiamClient;
/// use axiam_sdk::middleware::{AxiamUser, RequireAccess};
/// use uuid::Uuid;
///
/// # async fn handler(client: &AxiamClient, user: &AxiamUser, id: Uuid)
/// #     -> Result<(), axiam_sdk::middleware::AuthzGuardError> {
/// RequireAccess::new("read")
///     .scope("confidential")
///     .check(client, user, id)
///     .await?;
/// // ... resource access authorized ...
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RequireAccess {
    action: String,
    scope: Option<String>,
    challenger: Option<UmaChallenger>,
    mcp: Option<crate::middleware::mcp::McpChallenges>,
}

impl RequireAccess {
    /// Start a check for `action` (e.g. `"read"`), with no scope.
    pub fn new(action: impl Into<String>) -> Self {
        Self {
            action: action.into(),
            scope: None,
            challenger: None,
            mcp: None,
        }
    }

    /// On denial, mint a permission ticket and emit the `WWW-Authenticate: UMA`
    /// challenge (§20.3) alongside the 403.
    ///
    /// The UMA scope requested is this check's **action** — the same mapping
    /// the server uses, so a deny rule vetoes an RPT exactly as it vetoes this
    /// check. See [`UmaChallenger`] for why this is opt-in and what happens
    /// when minting fails.
    pub fn with_uma_challenge(mut self, challenger: UmaChallenger) -> Self {
        self.challenger = Some(challenger);
        self
    }

    /// On a `no_grant` denial for a route that named a [`Self::scope`],
    /// attach the CONTRACT.md §28.5 rule 5 `insufficient_scope`
    /// `WWW-Authenticate` challenge alongside the 403.
    ///
    /// Reads the precomputed challenge from `verifier` — the SAME
    /// `resource_metadata_url`/expected-audience configuration already
    /// validated by
    /// [`crate::token::JwksVerifier::with_resource_metadata_url`] (§28.5
    /// rule 6: "an SDK MUST NOT add a second audience option for §28"). A
    /// no-op when `verifier` was not itself configured with it — §28 stays
    /// off. Where [`Self::with_uma_challenge`] is *also* configured, a
    /// successful UMA mint wins and this challenge is never reached; only a
    /// failed or absent UMA mint falls back to this one, and exactly one
    /// `WWW-Authenticate` value is ever emitted.
    #[must_use]
    pub fn with_resource_metadata_url(mut self, verifier: &crate::token::JwksVerifier) -> Self {
        self.mcp = verifier.mcp_challenges().cloned();
        self
    }

    /// Narrow the check to `scope`, passed through to `check_access` verbatim
    /// (§11.4).
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }

    /// Issue the authorization check for `user` on `resource_id`.
    ///
    /// Sends `subject_id = user.user_id` so the decision is made for the
    /// request's authenticated caller, not the app's client session (§11.2.2).
    /// No decision is cached (§11.6). Maps the outcome to [`AuthzGuardError`]:
    /// `allowed = false` or a server 403 → [`AuthzGuardError::Denied`]; a
    /// transport failure → [`AuthzGuardError::Unavailable`] (fail closed,
    /// §11.5); a server 401 → [`AuthzGuardError::Unauthenticated`].
    pub async fn check(
        &self,
        client: &AxiamClient,
        user: &AxiamUser,
        resource_id: Uuid,
    ) -> Result<(), AuthzGuardError> {
        let outcome = client
            .check_access_as(
                user.user_id,
                &self.action,
                resource_id,
                self.scope.as_deref(),
            )
            .await;
        match outcome {
            Ok(decision) if decision.allowed => Ok(()),
            // §28.5 rule 5 reads the decision's own `reason_code` — a
            // `no_grant` denial on a route that named a scope is the one
            // case that gains a challenge; every other value (including
            // `denied_by_rule` and an absent/unrecognised one) gets none.
            Ok(decision) => Err(self
                .deny(client, resource_id, decision.reason_code.as_deref())
                .await),
            // A server 403 with no structured body carries no reason code at
            // all — §28.5 rule 5 treats an absent code as ineligible too.
            Err(AxiamError::Authz { .. }) => Err(self.deny(client, resource_id, None).await),
            Err(AxiamError::Auth { .. }) => Err(AuthzGuardError::unauthenticated(
                "authentication rejected by the authorization service".to_string(),
            )),
            Err(AxiamError::Network { .. }) => Err(AuthzGuardError::unavailable(
                "authorization service unavailable".to_string(),
            )),
        }
    }

    /// Build the denial, minting a §20.3 challenge when one was configured,
    /// falling back to the CONTRACT.md §28.5 rule 5 challenge when §20.3 was
    /// not configured or its mint failed.
    ///
    /// Only ever called on a path that has already decided to refuse, so
    /// neither challenge can change the outcome — at worst either fails and
    /// the caller gets the plain 403 they would have got anyway.
    async fn deny(
        &self,
        client: &AxiamClient,
        resource_id: Uuid,
        reason_code: Option<&str>,
    ) -> AuthzGuardError {
        let message = format!("access denied for action '{}'", self.action);

        if let Some(challenger) = self.challenger.as_ref() {
            // §20.2: the UMA scope is the AXIAM *action*, which is what makes
            // the ticket ask for exactly the authority this check just
            // refused.
            let permission = crate::uma::RequestedPermission {
                resource_id,
                resource_scopes: vec![self.action.clone()],
            };
            // A minting failure (Protection API outage, expired PAT, ...) is
            // deliberately swallowed here: see UmaChallenger's "failure is
            // not escalation" note. The reason is not logged either, because
            // this module never writes the token or the ticket anywhere
            // (§11.8). Falls through to the §28.5 challenge, if one applies —
            // a Protection API outage should not also cost the caller the
            // RFC 6750 hint.
            if let Ok(ticket) = client
                .uma_request_ticket(&challenger.pat, std::slice::from_ref(&permission))
                .await
            {
                return AuthzGuardError::denied_with_challenge(
                    message,
                    crate::uma::uma_challenge_header(
                        &challenger.realm,
                        &challenger.as_uri,
                        &ticket,
                    ),
                );
            }
        }

        if let Some(header) = self.mcp_challenge(reason_code) {
            return AuthzGuardError::denied_with_challenge(message, header);
        }

        AuthzGuardError::denied(message)
    }

    /// CONTRACT.md §28.5 rule 5: only a `no_grant` denial on a route that
    /// named a scope gets a challenge — `denied_by_rule`, an absent or
    /// unrecognised `reason_code`, and a route with no scope argument all
    /// carry none. Rule 6: the scope is the route's own, verbatim — never
    /// synthesised, never derived, never substituted.
    ///
    /// A challenge build failure (an operator-chosen scope outside RFC
    /// 6750's syntax) degrades to no header rather than an error: the caller
    /// was going to be refused either way, mirroring
    /// [`UmaChallenger`]'s own "failure is not escalation" rule.
    fn mcp_challenge(&self, reason_code: Option<&str>) -> Option<String> {
        let mcp = self.mcp.as_ref()?;
        let scope = self.scope.as_deref()?;
        if reason_code != Some(crate::rest::authz::reason_code::NO_GRANT) {
            return None;
        }
        mcp.insufficient_scope_challenge(scope).ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::ResponseError;
    use actix_web::body::to_bytes;

    fn user_with_roles(roles: &[&str]) -> AxiamUser {
        AxiamUser {
            user_id: Uuid::new_v4(),
            tenant_id: Uuid::new_v4(),
            roles: roles.iter().map(|s| s.to_string()).collect(),
        }
    }

    #[test]
    fn error_status_and_code_mapping_covers_every_variant() {
        let cases = [
            (
                AuthzGuardError::unauthenticated("x"),
                StatusCode::UNAUTHORIZED,
                "authentication_failed",
            ),
            (
                AuthzGuardError::denied("x"),
                StatusCode::FORBIDDEN,
                "authorization_denied",
            ),
            (
                AuthzGuardError::invalid_resource("x"),
                StatusCode::BAD_REQUEST,
                "invalid_request",
            ),
            (
                AuthzGuardError::unavailable("x"),
                StatusCode::SERVICE_UNAVAILABLE,
                "authz_unavailable",
            ),
            (
                AuthzGuardError::misconfigured("x"),
                StatusCode::INTERNAL_SERVER_ERROR,
                "internal_error",
            ),
        ];
        for (err, status, code) in cases {
            assert_eq!(err.status_code(), status);
            assert_eq!(err.code(), code);
            assert_eq!(err.message(), "x");
            // Display renders "<code>: <message>".
            assert_eq!(err.to_string(), format!("{code}: x"));
        }
    }

    #[tokio::test]
    async fn error_response_emits_standardized_json_body() {
        let err = AuthzGuardError::denied("nope");
        let resp = err.error_response();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let bytes = to_bytes(resp.into_body()).await.expect("readable body");
        let body: serde_json::Value = serde_json::from_slice(&bytes).expect("valid JSON");
        assert_eq!(body["error"], "authorization_denied");
        assert_eq!(body["message"], "nope");
    }

    #[test]
    fn resource_from_path_rejects_a_missing_path_parameter() {
        // No route registered at all, so `match_info().get("id")` is `None` —
        // exercises the "missing path parameter" arm, distinct from
        // `resource_from_path`'s "present but not a UUID" arm covered
        // end-to-end by `tests/macro_require_access_test.rs::bad_uuid_returns_400`.
        let req = actix_web::test::TestRequest::default().to_http_request();
        let err = resource_from_path(&req, "id").expect_err("missing path parameter must fail");
        assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn resource_from_static_parses_and_rejects() {
        let id = Uuid::new_v4();
        assert_eq!(resource_from_static(&id.to_string()).unwrap(), id);

        let err = resource_from_static("not-a-uuid").expect_err("must reject non-UUID");
        assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn require_role_check_allows_when_one_role_matches() {
        let user = user_with_roles(&["editor", "admin"]);
        assert!(require_role_check(&user, &["admin", "superadmin"]).is_ok());
    }

    #[test]
    fn require_role_check_denies_when_no_role_matches() {
        let user = user_with_roles(&["viewer"]);
        let err = require_role_check(&user, &["admin"]).expect_err("must deny");
        assert_eq!(err.status_code(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn require_access_builder_records_action_and_scope() {
        let guard = RequireAccess::new("read").scope("confidential");
        assert_eq!(guard.action, "read");
        assert_eq!(guard.scope.as_deref(), Some("confidential"));
    }
}