Skip to main content

phoenix_auth/
lib.rs

1//! Default-deny RBAC and ABAC authorization for Phoenix applications.
2
3use std::{
4    collections::{HashMap, HashSet},
5    ops::Deref,
6    sync::Arc,
7};
8#[cfg(feature = "jwt")]
9use std::marker::PhantomData;
10
11#[cfg(feature = "jwt")]
12use phoenix_crypto::{Jwt, JwtClaims};
13use phoenix_http::{
14    BoxFuture, FromRequest, HeaderValue, IntoResponse, Middleware, Next, Request, Response,
15    StatusCode, header,
16};
17use serde_json::{Map, Value};
18use thiserror::Error;
19
20/// A validated, exact authorization capability such as `posts.update`.
21#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
22pub struct Permission(Arc<str>);
23
24impl Permission {
25    /// # Errors
26    ///
27    /// Returns an error unless the permission is a non-empty ASCII capability name.
28    pub fn new(value: impl AsRef<str>) -> Result<Self, RbacError> {
29        let value = value.as_ref();
30        if !valid_name(value) {
31            return Err(RbacError::InvalidPermission(value.to_owned()));
32        }
33        Ok(Self(Arc::from(value)))
34    }
35
36    #[must_use]
37    pub fn as_str(&self) -> &str {
38        &self.0
39    }
40}
41
42impl std::fmt::Display for Permission {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        formatter.write_str(self.as_str())
45    }
46}
47
48/// A role declaration with exact permissions and optional parent roles.
49#[derive(Clone, Debug)]
50pub struct Role {
51    name: Arc<str>,
52    permissions: HashSet<Permission>,
53    parents: HashSet<Arc<str>>,
54}
55
56impl Role {
57    /// # Errors
58    ///
59    /// Returns an error for an invalid role name.
60    pub fn new(name: impl AsRef<str>) -> Result<Self, RbacError> {
61        let name = name.as_ref();
62        if !valid_name(name) {
63            return Err(RbacError::InvalidRole(name.to_owned()));
64        }
65        Ok(Self {
66            name: Arc::from(name),
67            permissions: HashSet::new(),
68            parents: HashSet::new(),
69        })
70    }
71
72    /// # Errors
73    ///
74    /// Returns an error for an invalid permission name.
75    pub fn allow(mut self, permission: impl AsRef<str>) -> Result<Self, RbacError> {
76        self.permissions.insert(Permission::new(permission)?);
77        Ok(self)
78    }
79
80    /// # Errors
81    ///
82    /// Returns an error for an invalid parent-role name.
83    pub fn inherits(mut self, parent: impl AsRef<str>) -> Result<Self, RbacError> {
84        let parent = parent.as_ref();
85        if !valid_name(parent) {
86            return Err(RbacError::InvalidRole(parent.to_owned()));
87        }
88        self.parents.insert(Arc::from(parent));
89        Ok(self)
90    }
91
92    #[must_use]
93    pub fn name(&self) -> &str {
94        &self.name
95    }
96}
97
98/// A subject with assigned roles, direct grants/denials, and ABAC attributes.
99#[derive(Clone, Debug)]
100pub struct Principal {
101    subject: Arc<str>,
102    roles: HashSet<Arc<str>>,
103    permissions: HashSet<Permission>,
104    denied_permissions: HashSet<Permission>,
105    attributes: Map<String, Value>,
106}
107
108impl Principal {
109    #[must_use]
110    pub fn new(subject: impl Into<String>) -> Self {
111        Self {
112            subject: Arc::from(subject.into()),
113            roles: HashSet::new(),
114            permissions: HashSet::new(),
115            denied_permissions: HashSet::new(),
116            attributes: Map::new(),
117        }
118    }
119
120    #[must_use]
121    pub fn role(mut self, role: impl Into<String>) -> Self {
122        self.roles.insert(Arc::from(role.into()));
123        self
124    }
125
126    /// # Errors
127    ///
128    /// Returns an error for an invalid permission name.
129    pub fn allow(mut self, permission: impl AsRef<str>) -> Result<Self, RbacError> {
130        self.permissions.insert(Permission::new(permission)?);
131        Ok(self)
132    }
133
134    /// Add an explicit subject-level denial. Explicit denial always wins.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error for an invalid permission name.
139    pub fn deny(mut self, permission: impl AsRef<str>) -> Result<Self, RbacError> {
140        self.denied_permissions.insert(Permission::new(permission)?);
141        Ok(self)
142    }
143
144    #[must_use]
145    pub fn attribute(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
146        self.attributes.insert(name.into(), value.into());
147        self
148    }
149
150    #[must_use]
151    pub fn subject(&self) -> &str {
152        &self.subject
153    }
154
155    pub fn roles(&self) -> impl Iterator<Item = &str> {
156        self.roles.iter().map(AsRef::as_ref)
157    }
158
159    #[must_use]
160    pub fn attribute_value(&self, name: &str) -> Option<&Value> {
161        self.attributes.get(name)
162    }
163}
164
165/// Immutable role graph with inheritance resolved at startup.
166#[derive(Clone, Debug, Default)]
167pub struct Rbac {
168    expanded: Arc<HashMap<Arc<str>, HashSet<Permission>>>,
169}
170
171impl Rbac {
172    /// Compile roles, rejecting duplicate names, missing parents, and cycles.
173    ///
174    /// # Errors
175    ///
176    /// Returns a deterministic role-graph error.
177    pub fn build(roles: impl IntoIterator<Item = Role>) -> Result<Self, RbacError> {
178        let mut declarations = HashMap::<Arc<str>, Role>::new();
179        for role in roles {
180            let name = Arc::clone(&role.name);
181            if declarations.insert(Arc::clone(&name), role).is_some() {
182                return Err(RbacError::DuplicateRole(name.to_string()));
183            }
184        }
185        let mut expanded = HashMap::new();
186        for name in declarations.keys() {
187            let mut visiting = HashSet::new();
188            resolve_role(name, &declarations, &mut expanded, &mut visiting)?;
189        }
190        Ok(Self {
191            expanded: Arc::new(expanded),
192        })
193    }
194
195    fn evaluate(&self, principal: &Principal, permission: &Permission) -> AuthorizationDecision {
196        if principal.denied_permissions.contains(permission) {
197            return AuthorizationDecision::Deny;
198        }
199        if principal.permissions.contains(permission)
200            || principal.roles.iter().any(|role| {
201                self.expanded
202                    .get(role)
203                    .is_some_and(|permissions| permissions.contains(permission))
204            })
205        {
206            AuthorizationDecision::Allow
207        } else {
208            AuthorizationDecision::Abstain
209        }
210    }
211}
212
213fn resolve_role(
214    name: &Arc<str>,
215    declarations: &HashMap<Arc<str>, Role>,
216    expanded: &mut HashMap<Arc<str>, HashSet<Permission>>,
217    visiting: &mut HashSet<Arc<str>>,
218) -> Result<HashSet<Permission>, RbacError> {
219    if let Some(permissions) = expanded.get(name) {
220        return Ok(permissions.clone());
221    }
222    if !visiting.insert(Arc::clone(name)) {
223        return Err(RbacError::InheritanceCycle(name.to_string()));
224    }
225    let role = declarations
226        .get(name)
227        .ok_or_else(|| RbacError::UnknownRole(name.to_string()))?;
228    let mut permissions = role.permissions.clone();
229    for parent in &role.parents {
230        if !declarations.contains_key(parent) {
231            return Err(RbacError::UnknownRole(parent.to_string()));
232        }
233        permissions.extend(resolve_role(parent, declarations, expanded, visiting)?);
234    }
235    visiting.remove(name);
236    expanded.insert(Arc::clone(name), permissions.clone());
237    Ok(permissions)
238}
239
240fn valid_name(value: &str) -> bool {
241    !value.is_empty()
242        && value
243            .bytes()
244            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b':' | b'_' | b'-'))
245}
246
247#[derive(Clone, Copy, Debug, Eq, PartialEq)]
248pub enum AuthorizationDecision {
249    Allow,
250    Deny,
251    Abstain,
252}
253
254pub struct AuthorizationRequest<'a, Resource> {
255    pub principal: &'a Principal,
256    pub permission: &'a Permission,
257    pub resource: &'a Resource,
258}
259
260pub trait AbacPolicy<Resource>: Send + Sync + 'static {
261    fn evaluate(&self, request: &AuthorizationRequest<'_, Resource>) -> AuthorizationDecision;
262}
263
264pub struct PolicyFn<F>(F);
265
266#[must_use]
267pub fn policy_fn<F>(policy: F) -> PolicyFn<F> {
268    PolicyFn(policy)
269}
270
271impl<Resource, F> AbacPolicy<Resource> for PolicyFn<F>
272where
273    F: for<'a> Fn(&AuthorizationRequest<'a, Resource>) -> AuthorizationDecision
274        + Send
275        + Sync
276        + 'static,
277{
278    fn evaluate(&self, request: &AuthorizationRequest<'_, Resource>) -> AuthorizationDecision {
279        (self.0)(request)
280    }
281}
282
283#[derive(Clone, Copy, Debug, Eq, PartialEq)]
284pub enum AuditReason {
285    ExplicitDeny,
286    Allowed,
287    NoApplicableRule,
288}
289
290#[derive(Clone, Debug, Eq, PartialEq)]
291pub struct AuthorizationAuditEvent {
292    pub subject: String,
293    pub permission: String,
294    pub decision: AuthorizationDecision,
295    pub reason: AuditReason,
296}
297
298pub trait AuthorizationAudit: Send + Sync + 'static {
299    fn record(&self, event: &AuthorizationAuditEvent);
300}
301
302#[derive(Default)]
303struct NoopAudit;
304
305impl AuthorizationAudit for NoopAudit {
306    fn record(&self, _event: &AuthorizationAuditEvent) {}
307}
308
309/// Deny-overrides authorizer combining exact RBAC grants and ABAC policies.
310pub struct AuthorizationEngine<Resource> {
311    rbac: Rbac,
312    policies: Vec<Arc<dyn AbacPolicy<Resource>>>,
313    audit: Arc<dyn AuthorizationAudit>,
314}
315
316impl<Resource> Clone for AuthorizationEngine<Resource> {
317    fn clone(&self) -> Self {
318        Self {
319            rbac: self.rbac.clone(),
320            policies: self.policies.clone(),
321            audit: Arc::clone(&self.audit),
322        }
323    }
324}
325
326impl<Resource: 'static> AuthorizationEngine<Resource> {
327    #[must_use]
328    pub fn new(rbac: Rbac) -> Self {
329        Self {
330            rbac,
331            policies: Vec::new(),
332            audit: Arc::new(NoopAudit),
333        }
334    }
335
336    #[must_use]
337    pub fn policy(mut self, policy: impl AbacPolicy<Resource>) -> Self {
338        self.policies.push(Arc::new(policy));
339        self
340    }
341
342    #[must_use]
343    pub fn audit(mut self, audit: impl AuthorizationAudit) -> Self {
344        self.audit = Arc::new(audit);
345        self
346    }
347
348    /// Apply deny-overrides combining: any deny rejects, otherwise any allow permits.
349    ///
350    /// # Errors
351    ///
352    /// Returns a generic denial when no rule allows or any rule denies.
353    pub fn authorize(
354        &self,
355        principal: &Principal,
356        permission: &Permission,
357        resource: &Resource,
358    ) -> Result<(), AuthorizationError> {
359        let request = AuthorizationRequest {
360            principal,
361            permission,
362            resource,
363        };
364        let rbac_decision = self.rbac.evaluate(principal, permission);
365        let mut allowed = matches!(rbac_decision, AuthorizationDecision::Allow);
366        if matches!(rbac_decision, AuthorizationDecision::Deny) {
367            self.record(
368                principal,
369                permission,
370                AuthorizationDecision::Deny,
371                AuditReason::ExplicitDeny,
372            );
373            return Err(AuthorizationError::Denied);
374        }
375        for policy in &self.policies {
376            match policy.evaluate(&request) {
377                AuthorizationDecision::Deny => {
378                    self.record(
379                        principal,
380                        permission,
381                        AuthorizationDecision::Deny,
382                        AuditReason::ExplicitDeny,
383                    );
384                    return Err(AuthorizationError::Denied);
385                }
386                AuthorizationDecision::Allow => allowed = true,
387                AuthorizationDecision::Abstain => {}
388            }
389        }
390        if allowed {
391            self.record(
392                principal,
393                permission,
394                AuthorizationDecision::Allow,
395                AuditReason::Allowed,
396            );
397            Ok(())
398        } else {
399            self.record(
400                principal,
401                permission,
402                AuthorizationDecision::Deny,
403                AuditReason::NoApplicableRule,
404            );
405            Err(AuthorizationError::Denied)
406        }
407    }
408
409    fn record(
410        &self,
411        principal: &Principal,
412        permission: &Permission,
413        decision: AuthorizationDecision,
414        reason: AuditReason,
415    ) {
416        self.audit.record(&AuthorizationAuditEvent {
417            subject: principal.subject().to_owned(),
418            permission: permission.to_string(),
419            decision,
420            reason,
421        });
422    }
423}
424
425#[derive(Debug, Error, Eq, PartialEq)]
426pub enum RbacError {
427    #[error("invalid role name `{0}`")]
428    InvalidRole(String),
429    #[error("invalid permission name `{0}`")]
430    InvalidPermission(String),
431    #[error("duplicate role declaration `{0}`")]
432    DuplicateRole(String),
433    #[error("unknown inherited role `{0}`")]
434    UnknownRole(String),
435    #[error("role inheritance cycle at `{0}`")]
436    InheritanceCycle(String),
437}
438
439#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
440pub enum AuthorizationError {
441    #[error("authorization denied")]
442    Denied,
443}
444
445/// Authenticated principal extractor populated by an authentication adapter.
446pub struct CurrentPrincipal(Arc<Principal>);
447
448impl CurrentPrincipal {
449    #[must_use]
450    pub fn new(principal: Principal) -> Self {
451        Self(Arc::new(principal))
452    }
453}
454
455impl Clone for CurrentPrincipal {
456    fn clone(&self) -> Self {
457        Self(Arc::clone(&self.0))
458    }
459}
460
461impl Deref for CurrentPrincipal {
462    type Target = Principal;
463
464    fn deref(&self) -> &Self::Target {
465        &self.0
466    }
467}
468
469impl std::fmt::Debug for CurrentPrincipal {
470    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
471        formatter
472            .debug_struct("CurrentPrincipal")
473            .field("subject", &self.subject())
474            .finish_non_exhaustive()
475    }
476}
477
478impl FromRequest for CurrentPrincipal {
479    type Rejection = PrincipalRejection;
480
481    fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
482        request
483            .extensions()
484            .get::<Self>()
485            .cloned()
486            .ok_or(PrincipalRejection)
487    }
488}
489
490#[derive(Clone, Copy, Debug, Error)]
491#[error("authentication required")]
492pub struct PrincipalRejection;
493
494impl IntoResponse for PrincipalRejection {
495    fn into_response(self) -> Response {
496        unauthorized()
497    }
498}
499
500/// Convert verified typed JWT claims into an application principal.
501#[cfg(feature = "jwt")]
502pub struct PrincipalFromJwt<T, F> {
503    mapper: Arc<F>,
504    marker: PhantomData<fn() -> T>,
505}
506
507#[cfg(feature = "jwt")]
508impl<T, F> PrincipalFromJwt<T, F> {
509    #[must_use]
510    pub fn new(mapper: F) -> Self {
511        Self {
512            mapper: Arc::new(mapper),
513            marker: PhantomData,
514        }
515    }
516}
517
518#[cfg(feature = "jwt")]
519impl<T, F> Middleware for PrincipalFromJwt<T, F>
520where
521    T: Send + Sync + 'static,
522    F: Fn(&JwtClaims<T>) -> Principal + Send + Sync + 'static,
523{
524    fn handle(&self, mut request: Request, next: Next) -> BoxFuture<Response> {
525        let mapper = Arc::clone(&self.mapper);
526        Box::pin(async move {
527            let Some(claims) = request.extensions().get::<Jwt<T>>() else {
528                return unauthorized();
529            };
530            let principal = mapper(claims);
531            request
532                .extensions_mut()
533                .insert(CurrentPrincipal::new(principal));
534            next.run(request).await
535        })
536    }
537}
538
539/// Route middleware for resource-independent permissions.
540#[derive(Clone)]
541pub struct RequirePermission {
542    authorizer: Arc<AuthorizationEngine<()>>,
543    permission: Permission,
544}
545
546impl RequirePermission {
547    #[must_use]
548    pub fn new(authorizer: Arc<AuthorizationEngine<()>>, permission: Permission) -> Self {
549        Self {
550            authorizer,
551            permission,
552        }
553    }
554}
555
556impl std::fmt::Debug for RequirePermission {
557    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
558        formatter
559            .debug_struct("RequirePermission")
560            .field("permission", &self.permission)
561            .finish_non_exhaustive()
562    }
563}
564
565impl Middleware for RequirePermission {
566    fn handle(&self, request: Request, next: Next) -> BoxFuture<Response> {
567        let authorizer = Arc::clone(&self.authorizer);
568        let permission = self.permission.clone();
569        Box::pin(async move {
570            let Some(principal) = request.extensions().get::<CurrentPrincipal>() else {
571                return unauthorized();
572            };
573            if authorizer.authorize(principal, &permission, &()).is_err() {
574                return Response::text("Forbidden").with_status(StatusCode::FORBIDDEN);
575            }
576            next.run(request).await
577        })
578    }
579}
580
581fn unauthorized() -> Response {
582    let mut response = Response::text("Unauthorized").with_status(StatusCode::UNAUTHORIZED);
583    response
584        .headers_mut()
585        .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
586    response
587}
588
589#[cfg(test)]
590mod tests {
591    use std::sync::Mutex;
592
593    use phoenix_http::{Method, typed};
594    use phoenix_routing::Routes;
595
596    use super::*;
597
598    #[cfg(feature = "jwt")]
599    use std::time::Duration;
600
601    #[cfg(feature = "jwt")]
602    use phoenix_crypto::{
603        JwtAuth, JwtConfig, JwtKey, JwtManager, MemoryTokenStore, StatefulJwtAuth, TokenService,
604    };
605    #[cfg(feature = "jwt")]
606    use serde::{Deserialize, Serialize};
607
608    fn rbac() -> Rbac {
609        Rbac::build([
610            Role::new("writer")
611                .unwrap()
612                .allow("posts.read")
613                .unwrap()
614                .allow("posts.update")
615                .unwrap(),
616            Role::new("admin")
617                .unwrap()
618                .inherits("writer")
619                .unwrap()
620                .allow("posts.delete")
621                .unwrap(),
622        ])
623        .unwrap()
624    }
625
626    #[test]
627    fn resolves_role_inheritance_and_rejects_invalid_graphs() {
628        let engine = AuthorizationEngine::new(rbac());
629        let admin = Principal::new("user-1").role("admin");
630        assert!(
631            engine
632                .authorize(&admin, &Permission::new("posts.update").unwrap(), &())
633                .is_ok()
634        );
635
636        let cycle = Rbac::build([
637            Role::new("one").unwrap().inherits("two").unwrap(),
638            Role::new("two").unwrap().inherits("one").unwrap(),
639        ]);
640        assert!(matches!(cycle, Err(RbacError::InheritanceCycle(_))));
641        assert!(matches!(
642            Rbac::build([Role::new("child").unwrap().inherits("missing").unwrap()]),
643            Err(RbacError::UnknownRole(_))
644        ));
645        assert_eq!(
646            Rbac::build([Role::new("writer").unwrap(), Role::new("writer").unwrap()]).unwrap_err(),
647            RbacError::DuplicateRole("writer".to_owned())
648        );
649    }
650
651    #[derive(Clone)]
652    struct Document {
653        owner: String,
654        classification: &'static str,
655    }
656
657    #[test]
658    fn abac_allows_owners_but_explicit_denial_overrides_every_grant() {
659        let engine = AuthorizationEngine::new(rbac()).policy(policy_fn(
660            |request: &AuthorizationRequest<'_, Document>| {
661                if request.resource.classification == "restricted"
662                    && request
663                        .principal
664                        .attribute_value("clearance")
665                        .and_then(Value::as_str)
666                        != Some("restricted")
667                {
668                    AuthorizationDecision::Deny
669                } else if request.resource.owner == request.principal.subject() {
670                    AuthorizationDecision::Allow
671                } else {
672                    AuthorizationDecision::Abstain
673                }
674            },
675        ));
676        let owner = Principal::new("user-1");
677        let document = Document {
678            owner: "user-1".to_owned(),
679            classification: "public",
680        };
681        assert!(
682            engine
683                .authorize(&owner, &Permission::new("posts.update").unwrap(), &document)
684                .is_ok()
685        );
686
687        let denied = Principal::new("user-1")
688            .role("admin")
689            .deny("posts.update")
690            .unwrap();
691        assert_eq!(
692            engine.authorize(
693                &denied,
694                &Permission::new("posts.update").unwrap(),
695                &document
696            ),
697            Err(AuthorizationError::Denied)
698        );
699    }
700
701    #[derive(Default)]
702    struct AuditLog(Mutex<Vec<AuthorizationAuditEvent>>);
703
704    impl AuthorizationAudit for Arc<AuditLog> {
705        fn record(&self, event: &AuthorizationAuditEvent) {
706            self.0.lock().unwrap().push(event.clone());
707        }
708    }
709
710    #[test]
711    fn default_deny_records_a_generic_audit_decision() {
712        let audit = Arc::new(AuditLog::default());
713        let engine = AuthorizationEngine::new(rbac()).audit(Arc::clone(&audit));
714        let result = engine.authorize(
715            &Principal::new("user-2"),
716            &Permission::new("posts.delete").unwrap(),
717            &(),
718        );
719        assert_eq!(result, Err(AuthorizationError::Denied));
720        let events = audit.0.lock().unwrap();
721        assert_eq!(events.len(), 1);
722        assert_eq!(events[0].reason, AuditReason::NoApplicableRule);
723    }
724
725    #[cfg(feature = "jwt")]
726    #[derive(Clone, Debug, Deserialize, Serialize)]
727    struct AccessClaims {
728        roles: Vec<String>,
729    }
730
731    #[cfg(feature = "jwt")]
732    #[tokio::test]
733    async fn jwt_principal_and_permission_middleware_distinguish_401_and_403() {
734        let jwt = Arc::new(
735            JwtManager::new(
736                JwtKey::new("active", [3_u8; 32]).unwrap(),
737                JwtConfig::default(),
738            )
739            .unwrap(),
740        );
741        let authorizer = Arc::new(AuthorizationEngine::new(rbac()));
742        let router = Routes::new()
743            .get(
744                "/admin",
745                typed(|principal: CurrentPrincipal| async move { principal.subject().to_owned() }),
746            )
747            .with_middleware(JwtAuth::<AccessClaims>::new(Arc::clone(&jwt)))
748            .with_middleware(PrincipalFromJwt::new(|claims: &JwtClaims<AccessClaims>| {
749                claims
750                    .custom
751                    .roles
752                    .iter()
753                    .fold(Principal::new(&claims.sub), |principal, role| {
754                        principal.role(role)
755                    })
756            }))
757            .with_middleware(RequirePermission::new(
758                authorizer,
759                Permission::new("posts.delete").unwrap(),
760            ))
761            .build()
762            .unwrap();
763
764        let missing = router
765            .handle(Request::new(Method::GET, "/admin".parse().unwrap()))
766            .await;
767        assert_eq!(missing.status(), StatusCode::UNAUTHORIZED);
768
769        let member_token = jwt
770            .issue(
771                "member-1",
772                AccessClaims {
773                    roles: vec!["writer".to_owned()],
774                },
775            )
776            .unwrap();
777        let mut member = Request::new(Method::GET, "/admin".parse().unwrap());
778        member.headers_mut().insert(
779            header::AUTHORIZATION,
780            HeaderValue::from_str(&format!("Bearer {member_token}")).unwrap(),
781        );
782        assert_eq!(router.handle(member).await.status(), StatusCode::FORBIDDEN);
783
784        let admin_token = jwt
785            .issue(
786                "admin-1",
787                AccessClaims {
788                    roles: vec!["admin".to_owned()],
789                },
790            )
791            .unwrap();
792        let mut admin = Request::new(Method::GET, "/admin".parse().unwrap());
793        admin.headers_mut().insert(
794            header::AUTHORIZATION,
795            HeaderValue::from_str(&format!("Bearer {admin_token}")).unwrap(),
796        );
797        let response = router.handle(admin).await;
798        assert_eq!(response.status(), StatusCode::OK);
799        assert_eq!(response.body(), "admin-1");
800    }
801
802    #[cfg(feature = "jwt")]
803    #[tokio::test]
804    async fn stateful_jwt_revocation_precedes_principal_authorization() {
805        let jwt = JwtManager::new(
806            JwtKey::new("active", [4_u8; 32]).unwrap(),
807            JwtConfig::new(Duration::from_mins(5)),
808        )
809        .unwrap();
810        let service = Arc::new(
811            TokenService::new(
812                jwt,
813                Arc::new(MemoryTokenStore::new()),
814                Duration::from_hours(720),
815            )
816            .unwrap(),
817        );
818        let authorizer = Arc::new(AuthorizationEngine::new(rbac()));
819        let router = Routes::new()
820            .get(
821                "/admin",
822                typed(|principal: CurrentPrincipal| async move { principal.subject().to_owned() }),
823            )
824            .with_middleware(StatefulJwtAuth::<AccessClaims, _>::new(Arc::clone(
825                &service,
826            )))
827            .with_middleware(PrincipalFromJwt::new(|claims: &JwtClaims<AccessClaims>| {
828                claims
829                    .custom
830                    .roles
831                    .iter()
832                    .fold(Principal::new(&claims.sub), |principal, role| {
833                        principal.role(role)
834                    })
835            }))
836            .with_middleware(RequirePermission::new(
837                authorizer,
838                Permission::new("posts.delete").unwrap(),
839            ))
840            .build()
841            .unwrap();
842        let pair = service
843            .issue(
844                "admin-2",
845                AccessClaims {
846                    roles: vec!["admin".to_owned()],
847                },
848            )
849            .await
850            .unwrap();
851
852        let request = || {
853            let mut request = Request::new(Method::GET, "/admin".parse().unwrap());
854            request.headers_mut().insert(
855                header::AUTHORIZATION,
856                HeaderValue::from_str(&format!("Bearer {}", pair.access_token)).unwrap(),
857            );
858            request
859        };
860        assert_eq!(router.handle(request()).await.status(), StatusCode::OK);
861        service.revoke_access(&pair.access_token).await.unwrap();
862        assert_eq!(
863            router.handle(request()).await.status(),
864            StatusCode::UNAUTHORIZED
865        );
866    }
867}