axum-gate 1.1.0

Flexible authentication and authorization for Axum with JWT cookies or bearer tokens, optional OAuth2, and role/group/permission RBAC. Suitable for single-node and distributed systems.
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
//! Bearer gate implementation supporting two compile-time distinct modes:
//! - JWT bearer authentication & authorization (policy-based)
//! - Static shared-secret bearer token (boolean authorization)
//!
//! Each mode exposes only the relevant builder methods at compile time:
//!
//! JWT Mode (BearerGate<_, _, _, JwtConfig<_, _>>):
//!   - with_policy(...)
//!   - require_login()            (requires R: Default; baseline role + supervisors)
//!   - allow_anonymous_with_optional_user()
//!   - with_static_token(token)   (transitions to static token mode)
//!
//! Static Token Mode (BearerGate<_, _, _, StaticTokenConfig>):
//!   - allow_anonymous_with_optional_user()
//!
//! Optional Mode Semantics:
//!   - JWT optional: always forwards; inserts:
//!       * `Option<Account<R,G>>`
//!       * `Option<RegisteredClaims>`
//!   - Static token optional: always forwards; inserts:
//!       * StaticTokenAuthorized(bool)
//!
//! Strict Mode Semantics:
//!   - JWT strict: validates Authorization: Bearer `<jwt>`, enforces AccessPolicy;
//!     inserts `Account<R,G>` and `RegisteredClaims` on success, 401 otherwise
//!   - Static token strict: requires `Authorization: Bearer <exact_token>`;
//!     inserts `StaticTokenAuthorized(true)` on success, 401 otherwise
//!
//! Example (JWT strict):
//! ```rust
//! use std::sync::Arc;
//! use axum::Router;
//! use axum_gate::prelude::*;
//! let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
//!
//! let router = Router::<()>::new();
//! let gate = Gate::bearer::<JsonWebToken::<JwtClaims<Account<Role, Group>>>, Role, Group>("my-app", codec)
//!     .with_policy(AccessPolicy::require_role(Role::Admin));
//! router.layer(gate);
//! ```
//!
//! Example (JWT optional):
//! ```rust
//! use std::sync::Arc;
//! use axum_gate::prelude::*;
//! let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
//!
//! let gate = Gate::bearer::<JsonWebToken::<JwtClaims<Account<Role, Group>>>, Role, Group>("my-app", codec)
//!     .allow_anonymous_with_optional_user(); // Option<Account>, Option<RegisteredClaims>
//! ```
//!
//! Transition to static token mode (compile-time change of available methods):
//! ```rust
//! use std::sync::Arc;
//! use axum_gate::prelude::*;
//! let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
//!
//! let gate = Gate::bearer::<JsonWebToken::<JwtClaims<Account<Role, Group>>>, Role, Group>("svc-a", codec)
//!     .with_static_token("shared-secret"); // now static token mode (no with_policy)
//! ```
//!
//! Static token optional:
//! ```rust
//! use std::sync::Arc;
//! use axum_gate::prelude::*;
//! let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
//!
//! let gate = Gate::bearer::<JsonWebToken::<JwtClaims<Account<Role, Group>>>, Role, Group>("svc-a", codec)
//!     .with_static_token("shared-secret")
//!     .allow_anonymous_with_optional_user(); // installs StaticTokenAuthorized(bool)
//! ```
//!
//! Handler extraction (static token optional):
//! ```rust
//! use axum_gate::gate::bearer::StaticTokenAuthorized;
//!
//! async fn handler(
//!     axum::Extension(token_auth): axum::Extension<StaticTokenAuthorized>
//! ) {
//!     if token_auth.is_authorized() { /* privileged */ } else { /* public */ }
//! }
//! ```

use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use axum::{body::Body, extract::Request, http::Response};
use http::StatusCode;
use tower::{Layer, Service};
use tracing::{debug, trace, warn};

pub use self::static_token_authorized::StaticTokenAuthorized;
use crate::accounts::Account;
use crate::authz::{AccessHierarchy, AccessPolicy, AuthorizationService};
use crate::codecs::Codec;
use crate::codecs::jwt::{JwtClaims, JwtValidationResult, JwtValidationService, RegisteredClaims};

mod static_token_authorized;

/// JWT mode configuration (compile-time).
#[derive(Clone)]
pub struct JwtConfig<R, G>
where
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq,
{
    policy: AccessPolicy<R, G>,
    optional: bool,
}

impl<R, G> std::fmt::Debug for JwtConfig<R, G>
where
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JwtConfig")
            .field("optional", &self.optional)
            .finish_non_exhaustive()
    }
}

/// Static token mode configuration (compile-time).
#[derive(Clone)]
pub struct StaticTokenConfig {
    token: String,
    optional: bool,
}

impl std::fmt::Debug for StaticTokenConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StaticTokenConfig")
            .field("token", &"<redacted>")
            .field("optional", &self.optional)
            .finish_non_exhaustive()
    }
}

/// Generic bearer gate with compile-time mode parameter.
#[derive(Clone)]
pub struct BearerGate<C, R, G, M>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq,
{
    issuer: String,
    codec: Arc<C>,
    mode: M,
    _phantom: std::marker::PhantomData<(R, G)>,
}

impl<C, R, G> BearerGate<C, R, G, JwtConfig<R, G>>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq + Clone,
{
    /// Internal constructor (used by `Gate::bearer`).
    pub(crate) fn new_with_codec(issuer: &str, codec: Arc<C>) -> Self {
        Self {
            issuer: issuer.to_string(),
            codec,
            mode: JwtConfig {
                policy: AccessPolicy::deny_all(),
                optional: false,
            },
            _phantom: std::marker::PhantomData,
        }
    }

    /// Set access policy (OR semantics between requirements).
    pub fn with_policy(mut self, policy: AccessPolicy<R, G>) -> Self {
        self.mode.policy = policy;
        self
    }

    /// Turn on optional mode (install `Option<Account>`, `Option<RegisteredClaims>`).
    pub fn allow_anonymous_with_optional_user(mut self) -> Self {
        self.mode.optional = true;
        self
    }

    /// Configure the gate to allow any authenticated user: the baseline role (least
    /// privileged) from `Default::default()` and all supervisor roles as defined by
    /// your `AccessHierarchy`.
    ///
    /// Equivalent to `with_policy(AccessPolicy::require_role_or_supervisor(R::default()))`.
    /// Requires `R: Default`.
    pub fn require_login(mut self) -> Self
    where
        R: Default,
    {
        let baseline = R::default();
        self.mode.policy = AccessPolicy::require_role_or_supervisor(baseline);
        self
    }

    /// Enables Prometheus metrics for audit logging (JWT bearer mode).
    ///
    /// No-op unless both `audit-logging` and `prometheus` features are enabled.
    /// Safe to call multiple times; registration is idempotent.
    #[cfg(feature = "prometheus")]
    pub fn with_prometheus_metrics(self) -> Self {
        let _ = crate::audit::prometheus_metrics::install_prometheus_metrics();
        self
    }

    /// Installs Prometheus metrics into the provided registry (JWT bearer mode).
    ///
    /// No-op if metrics already installed. Returns `self` for builder chaining.
    #[cfg(feature = "prometheus")]
    pub fn with_prometheus_registry(self, registry: &prometheus::Registry) -> Self {
        let _ =
            crate::audit::prometheus_metrics::install_prometheus_metrics_with_registry(registry);
        self
    }

    /// Transition to static token mode: policies are discarded.
    pub fn with_static_token(
        self,
        token: impl Into<String>,
    ) -> BearerGate<C, R, G, StaticTokenConfig> {
        BearerGate {
            issuer: self.issuer,
            codec: self.codec,
            mode: StaticTokenConfig {
                token: token.into(),
                optional: false,
            },
            _phantom: std::marker::PhantomData,
        }
    }
}

// (require_login specialization for crate::auth::Role/Group temporarily removed to resolve generic issues)

impl<C, R, G> BearerGate<C, R, G, StaticTokenConfig>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq + Clone,
{
    /// Enable optional mode (install StaticTokenAuthorized(bool)).
    pub fn allow_anonymous_with_optional_user(mut self) -> Self {
        self.mode.optional = true;
        self
    }
}

// ===================== LAYER IMPLEMENTATIONS ======================

impl<S, C, R, G> Layer<S> for BearerGate<C, R, G, JwtConfig<R, G>>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display + Sync + Send + 'static,
    G: Eq + Clone + Sync + Send + 'static,
{
    type Service = JwtBearerService<C, R, G, S>;

    fn layer(&self, inner: S) -> Self::Service {
        if self.mode.optional {
            JwtBearerService::new_optional(
                inner,
                &self.issuer,
                self.mode.policy.clone(), // policy unused in optional mode but cloned for uniform struct
                Arc::clone(&self.codec),
            )
        } else {
            JwtBearerService::new(
                inner,
                &self.issuer,
                self.mode.policy.clone(),
                Arc::clone(&self.codec),
            )
        }
    }
}

impl<S, C, R, G> Layer<S> for BearerGate<C, R, G, StaticTokenConfig>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq + Clone,
{
    type Service = StaticTokenService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        if self.mode.optional {
            StaticTokenService::new_optional(inner, self.mode.token.clone())
        } else {
            StaticTokenService::new(inner, self.mode.token.clone())
        }
    }
}

// ===================== JWT SERVICE ======================

#[derive(Clone)]
/// JWT bearer token authentication service.
///
/// This service handles JWT bearer token authentication for protected routes,
/// validating tokens from the `Authorization: Bearer <token>` header.
pub struct JwtBearerService<C, R, G, S>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq + Clone,
{
    inner: S,
    authorization: AuthorizationService<R, G>,
    validator: JwtValidationService<C>,
    optional: bool,
}

impl<C, R, G, S> JwtBearerService<C, R, G, S>
where
    C: Codec,
    R: AccessHierarchy + Eq + std::fmt::Display,
    G: Eq + Clone,
{
    fn new(inner: S, issuer: &str, policy: AccessPolicy<R, G>, codec: Arc<C>) -> Self {
        Self {
            inner,
            authorization: AuthorizationService::new(policy),
            validator: JwtValidationService::new(codec, issuer),
            optional: false,
        }
    }

    fn new_optional(inner: S, issuer: &str, policy: AccessPolicy<R, G>, codec: Arc<C>) -> Self {
        // policy retained only for debugging; not used in optional path
        Self {
            inner,
            authorization: AuthorizationService::new(policy),
            validator: JwtValidationService::new(codec, issuer),
            optional: true,
        }
    }

    #[allow(clippy::expect_used)]
    fn unauthorized() -> Response<Body> {
        Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .header(http::header::WWW_AUTHENTICATE, "Bearer")
            .body(Body::from("Unauthorized"))
            .expect("static unauthorized response")
    }

    fn bearer_token(req: &Request<Body>) -> Option<&str> {
        let value = req.headers().get(http::header::AUTHORIZATION)?;
        let value = value.to_str().ok()?.trim();
        let mut parts = value.split_whitespace();
        let scheme = parts.next()?;
        if !scheme.eq_ignore_ascii_case("Bearer") {
            return None;
        }
        parts.next()
    }
}

impl<C, R, G, S> Service<Request<Body>> for JwtBearerService<C, R, G, S>
where
    S: Service<Request<Body>, Response = Response<Body>, Error = Infallible> + Send + 'static,
    S::Future: Send + 'static,
    Account<R, G>: Clone,
    C: Codec<Payload = JwtClaims<Account<R, G>>>,
    R: AccessHierarchy + Eq + std::fmt::Display + Sync + Send + 'static,
    G: Eq + Clone + Sync + Send + 'static,
{
    type Response = Response<Body>;
    type Error = Infallible;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<Body>) -> Self::Future {
        #[cfg(feature = "audit-logging")]
        use crate::audit;

        let unauthorized_future = Box::pin(async move { Ok(Self::unauthorized()) });

        #[cfg(feature = "audit-logging")]
        let _span = audit::request_span(req.method().as_str(), req.uri().path(), None);

        if self.optional {
            let mut opt_account: Option<Account<R, G>> = None;
            let mut opt_claims: Option<RegisteredClaims> = None;

            if let Some(token) = Self::bearer_token(&req) {
                trace!("JWT optional bearer header present");
                if let JwtValidationResult::Valid(jwt) = self.validator.validate_token(token) {
                    // Valid JWT present; optional mode inserts only Option<...> extensions
                    opt_account = Some(jwt.custom_claims.clone());
                    opt_claims = Some(jwt.registered_claims.clone());
                } else {
                    debug!("Optional JWT: invalid token; inserting None extensions");
                }
            }

            req.extensions_mut().insert(opt_account);
            req.extensions_mut().insert(opt_claims);

            let fut = self.inner.call(req);
            return Box::pin(fut);
        }

        if self.authorization.policy_denies_all_access() {
            debug!("Bearer JWT gate denying access (deny-all policy)");
            #[cfg(feature = "audit-logging")]
            audit::denied(None, "policy_denies_all");
            return unauthorized_future;
        }

        let Some(token) = Self::bearer_token(&req) else {
            #[cfg(feature = "audit-logging")]
            audit::denied(None, "missing_authorization_header");
            return unauthorized_future;
        };

        #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
        let jwt_validation_start = std::time::Instant::now();

        let jwt = match self.validator.validate_token(token) {
            JwtValidationResult::Valid(jwt) => {
                #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
                crate::audit::prometheus_metrics::observe_jwt_validation_latency(
                    jwt_validation_start,
                    crate::audit::prometheus_metrics::JwtValidationOutcome::Valid,
                );
                jwt
            }
            JwtValidationResult::InvalidToken => {
                #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
                crate::audit::prometheus_metrics::observe_jwt_validation_latency(
                    jwt_validation_start,
                    crate::audit::prometheus_metrics::JwtValidationOutcome::InvalidToken,
                );
                debug!("JWT token validation failed");
                #[cfg(feature = "audit-logging")]
                audit::jwt_invalid_token("validation_failed");
                return unauthorized_future;
            }
            JwtValidationResult::InvalidIssuer { expected, actual } => {
                #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
                crate::audit::prometheus_metrics::observe_jwt_validation_latency(
                    jwt_validation_start,
                    crate::audit::prometheus_metrics::JwtValidationOutcome::InvalidIssuer,
                );
                warn!("JWT issuer mismatch. Expected='{expected}', Actual='{actual}'");
                #[cfg(feature = "audit-logging")]
                audit::jwt_invalid_issuer(&expected, &actual);
                return unauthorized_future;
            }
        };

        #[cfg(feature = "audit-logging")]
        let _authz_span = audit::authorization_span(Some(&jwt.custom_claims.account_id), None);
        #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
        let authz_start = std::time::Instant::now();

        if !self.authorization.is_authorized(&jwt.custom_claims) {
            #[cfg(feature = "audit-logging")]
            audit::denied(Some(&jwt.custom_claims.account_id), "policy_denied");
            #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
            crate::audit::observe_authz_latency(authz_start, crate::audit::AuthzOutcome::Denied);
            return unauthorized_future;
        }

        #[cfg(feature = "audit-logging")]
        audit::authorized(&jwt.custom_claims.account_id, None);
        #[cfg(all(feature = "audit-logging", feature = "prometheus"))]
        crate::audit::observe_authz_latency(authz_start, crate::audit::AuthzOutcome::Authorized);

        req.extensions_mut().insert(jwt.custom_claims.clone());
        req.extensions_mut().insert(jwt.registered_claims.clone());

        let fut = self.inner.call(req);
        Box::pin(fut)
    }
}

// ===================== STATIC TOKEN SERVICE ======================

#[derive(Clone)]
/// Static bearer token authentication service.
///
/// This service handles authentication using pre-configured static tokens
/// from the `Authorization: Bearer <token>` header.
pub struct StaticTokenService<S> {
    inner: S,
    token: String,
    optional: bool,
}

impl<S> StaticTokenService<S> {
    fn new(inner: S, token: String) -> Self {
        Self {
            inner,
            token,
            optional: false,
        }
    }

    fn new_optional(inner: S, token: String) -> Self {
        Self {
            inner,
            token,
            optional: true,
        }
    }

    #[allow(clippy::expect_used)]
    fn unauthorized() -> Response<Body> {
        Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .header(http::header::WWW_AUTHENTICATE, "Bearer")
            .body(Body::from("Unauthorized"))
            .expect("static unauthorized response")
    }

    fn bearer_token(req: &Request<Body>) -> Option<&str> {
        let value = req.headers().get(http::header::AUTHORIZATION)?;
        let value = value.to_str().ok()?.trim();
        let mut parts = value.split_whitespace();
        let scheme = parts.next()?;
        if !scheme.eq_ignore_ascii_case("Bearer") {
            return None;
        }
        parts.next()
    }
}

impl<S> Service<Request<Body>> for StaticTokenService<S>
where
    S: Service<Request<Body>, Response = Response<Body>, Error = Infallible> + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = Response<Body>;
    type Error = Infallible;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<Body>) -> Self::Future {
        #[cfg(feature = "audit-logging")]
        use crate::audit;

        #[cfg(feature = "audit-logging")]
        let _span = audit::request_span(req.method().as_str(), req.uri().path(), None);

        if self.optional {
            let provided = Self::bearer_token(&req);
            let authorized = provided.map(|v| v == self.token).unwrap_or(false);
            req.extensions_mut()
                .insert(StaticTokenAuthorized::new(authorized));
            let fut = self.inner.call(req);
            return Box::pin(fut);
        }

        let Some(provided) = Self::bearer_token(&req) else {
            #[cfg(feature = "audit-logging")]
            audit::denied(None, "missing_authorization_header");
            return Box::pin(async move { Ok(Self::unauthorized()) });
        };

        if provided != self.token {
            #[cfg(feature = "audit-logging")]
            audit::denied(None, "static_token_mismatch");
            return Box::pin(async move { Ok(Self::unauthorized()) });
        }

        // Strict static token success: insert positive indicator
        req.extensions_mut()
            .insert(StaticTokenAuthorized::new(true));

        let fut = self.inner.call(req);
        Box::pin(fut)
    }
}

// ===================== TESTS ======================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::accounts::Account;
    use crate::codecs::jwt::{JsonWebToken, JwtClaims};
    use crate::groups::Group;
    use crate::roles::Role;

    type BearerGateJsonwebtoken = BearerGate<
        JsonWebToken<JwtClaims<Account<Role, Group>>>,
        Role,
        Group,
        JwtConfig<Role, Group>,
    >;

    #[test]
    fn jwt_gate_initial_deny_all() {
        let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
        let gate: BearerGateJsonwebtoken = BearerGate::new_with_codec("issuer", codec);
        assert!(gate.mode.policy.denies_all());
        assert!(!gate.mode.optional);
    }

    #[test]
    fn jwt_gate_policy_set() {
        let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
        let gate =
            BearerGate::new_with_codec("issuer", codec)
                .with_policy(AccessPolicy::<Role, Group>::require_role(Role::Admin));
        assert!(!gate.mode.policy.denies_all());
    }

    #[test]
    fn transition_to_static_mode() {
        let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
        let static_gate: BearerGate<_, Role, Group, StaticTokenConfig> =
            BearerGate::new_with_codec("issuer", codec).with_static_token("secret");
        assert_eq!(static_gate.mode.token, "secret");
        assert!(!static_gate.mode.optional);
    }

    #[test]
    fn static_optional_mode() {
        let codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
        let static_gate: BearerGate<_, Role, Group, StaticTokenConfig> =
            BearerGate::new_with_codec("issuer", codec)
                .with_static_token("secret")
                .allow_anonymous_with_optional_user();
        assert!(static_gate.mode.optional);
    }

    #[test]
    fn jwt_unauthorized_has_www_authenticate() {
        tokio_test::block_on(async {
            use axum::{body::Body, extract::Request, http::Response};
            use std::convert::Infallible;
            use tower::ServiceExt;

            let codec =
                std::sync::Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
            let gate: BearerGateJsonwebtoken = BearerGate::new_with_codec("issuer", codec)
                .with_policy(AccessPolicy::<Role, Group>::require_role(Role::Admin));

            let svc = gate.layer(tower::service_fn(|_req: Request<Body>| async {
                Ok::<_, Infallible>(Response::new(Body::from("ok")))
            }));

            let req = Request::new(Body::empty());
            let resp = svc.oneshot(req).await.unwrap();

            assert_eq!(resp.status(), http::StatusCode::UNAUTHORIZED);
            let hdr = resp
                .headers()
                .get(http::header::WWW_AUTHENTICATE)
                .and_then(|v| v.to_str().ok());
            assert_eq!(hdr, Some("Bearer"));
        });
    }

    #[test]
    fn static_token_unauthorized_has_www_authenticate() {
        tokio_test::block_on(async {
            use axum::{body::Body, extract::Request, http::Response};
            use std::convert::Infallible;
            use tower::ServiceExt;

            let codec =
                std::sync::Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
            let gate: BearerGate<_, Role, Group, StaticTokenConfig> =
                BearerGate::new_with_codec("issuer", codec).with_static_token("secret");

            let svc = gate.layer(tower::service_fn(|_req: Request<Body>| async {
                Ok::<_, Infallible>(Response::new(Body::from("ok")))
            }));

            let req = Request::new(Body::empty());
            let resp = svc.oneshot(req).await.unwrap();

            assert_eq!(resp.status(), http::StatusCode::UNAUTHORIZED);
            let hdr = resp
                .headers()
                .get(http::header::WWW_AUTHENTICATE)
                .and_then(|v| v.to_str().ok());
            assert_eq!(hdr, Some("Bearer"));
        });
    }
}