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