Skip to main content

larastvel_core/auth/
gates.rs

1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use axum::{
5    extract::Request,
6    http::StatusCode,
7    middleware::Next,
8    response::{IntoResponse, Json, Response},
9};
10use serde_json::json;
11
12use crate::auth::AuthenticatedUser;
13
14/// The result of an authorization check.
15#[derive(Debug, Clone, PartialEq)]
16pub enum GateCheck {
17    /// The action is allowed.
18    Allowed,
19    /// The action is denied with an optional message.
20    Denied(String),
21}
22
23impl IntoResponse for GateCheck {
24    fn into_response(self) -> Response {
25        match self {
26            GateCheck::Allowed => (StatusCode::OK).into_response(),
27            GateCheck::Denied(msg) => {
28                let body = json!({
29                    "error": msg,
30                    "message": "This action is unauthorized.",
31                });
32                (StatusCode::FORBIDDEN, Json(body)).into_response()
33            }
34        }
35    }
36}
37
38impl GateCheck {
39    pub fn is_allowed(&self) -> bool {
40        matches!(self, GateCheck::Allowed)
41    }
42
43    pub fn is_denied(&self) -> bool {
44        matches!(self, GateCheck::Denied(_))
45    }
46
47    pub fn message(&self) -> Option<&str> {
48        match self {
49            GateCheck::Denied(msg) => Some(msg),
50            _ => None,
51        }
52    }
53}
54
55/// Callback type for defining a gate.
56///
57/// Takes a reference to the authenticated user and optionally additional arguments.
58pub type GateCallback = Arc<dyn Fn(&AuthenticatedUser, &[String]) -> GateCheck + Send + Sync>;
59
60/// Callback type for `before` hooks (runs before all gates).
61pub type BeforeHook =
62    Arc<dyn Fn(&AuthenticatedUser, &str, &[String]) -> Option<GateCheck> + Send + Sync>;
63
64/// Callback type for `after` hooks (runs after all gates).
65pub type AfterHook =
66    Arc<dyn Fn(&AuthenticatedUser, &str, &[String], &GateCheck) -> Option<GateCheck> + Send + Sync>;
67
68/// Central authorization manager.
69///
70/// Manages gates (closure-based) and policies (class-based authorization rules).
71///
72/// # Example
73///
74/// ```ignore
75/// use larastvel_core::auth::{Gate, AuthenticatedUser, GateCheck};
76///
77/// let gate = Gate::new();
78/// gate.define("update-post", |user, args| {
79///     // In real usage, args[0] would be the post owner ID
80///     if args.first().map(|s| s.as_str()) == Some(&user.user_id) {
81///         GateCheck::Allowed
82///     } else {
83///         GateCheck::Denied("You do not own this post.".to_string())
84///     }
85/// });
86///
87/// let user = AuthenticatedUser { user_id: "1".to_string(), claims: ... };
88/// assert!(gate.allows(&user, "update-post", &["1".to_string()]));
89/// ```
90pub struct Gate {
91    abilities: Arc<Mutex<HashMap<String, GateCallback>>>,
92    policies: Arc<Mutex<HashMap<String, Arc<dyn Policy>>>>,
93    before_hooks: Arc<Mutex<Vec<BeforeHook>>>,
94    after_hooks: Arc<Mutex<Vec<AfterHook>>>,
95}
96
97impl std::fmt::Debug for Gate {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("Gate")
100            .field(
101                "abilities",
102                &self
103                    .abilities
104                    .lock()
105                    .unwrap()
106                    .keys()
107                    .cloned()
108                    .collect::<Vec<_>>(),
109            )
110            .field(
111                "policies",
112                &self
113                    .policies
114                    .lock()
115                    .unwrap()
116                    .keys()
117                    .cloned()
118                    .collect::<Vec<_>>(),
119            )
120            .field(
121                "before_hooks_count",
122                &self.before_hooks.lock().unwrap().len(),
123            )
124            .field("after_hooks_count", &self.after_hooks.lock().unwrap().len())
125            .finish()
126    }
127}
128
129impl Clone for Gate {
130    fn clone(&self) -> Self {
131        Self {
132            abilities: Arc::clone(&self.abilities),
133            policies: Arc::clone(&self.policies),
134            before_hooks: Arc::clone(&self.before_hooks),
135            after_hooks: Arc::clone(&self.after_hooks),
136        }
137    }
138}
139
140impl Default for Gate {
141    fn default() -> Self {
142        Self::new()
143    }
144}
145
146impl Gate {
147    /// Create a new Gate instance.
148    pub fn new() -> Self {
149        Self {
150            abilities: Arc::new(Mutex::new(HashMap::new())),
151            policies: Arc::new(Mutex::new(HashMap::new())),
152            before_hooks: Arc::new(Mutex::new(Vec::new())),
153            after_hooks: Arc::new(Mutex::new(Vec::new())),
154        }
155    }
156
157    /// Define a gate ability.
158    ///
159    /// The callback receives the authenticated user and a slice of string arguments.
160    pub fn define<F>(&self, ability: &str, f: F)
161    where
162        F: Fn(&AuthenticatedUser, &[String]) -> GateCheck + Send + Sync + 'static,
163    {
164        let mut abilities = self.abilities.lock().unwrap();
165        abilities.insert(ability.to_string(), Arc::new(f));
166    }
167
168    /// Register a before hook. Runs before all gate checks.
169    ///
170    /// If the hook returns `Some(GateCheck)`, that result is used immediately
171    /// and the normal gate check is skipped.
172    pub fn before<F>(&self, f: F)
173    where
174        F: Fn(&AuthenticatedUser, &str, &[String]) -> Option<GateCheck> + Send + Sync + 'static,
175    {
176        let mut hooks = self.before_hooks.lock().unwrap();
177        hooks.push(Arc::new(f));
178    }
179
180    /// Register an after hook. Runs after all gate checks.
181    ///
182    /// Can override the result of the normal gate check.
183    pub fn after<F>(&self, f: F)
184    where
185        F: Fn(&AuthenticatedUser, &str, &[String], &GateCheck) -> Option<GateCheck>
186            + Send
187            + Sync
188            + 'static,
189    {
190        let mut hooks = self.after_hooks.lock().unwrap();
191        hooks.push(Arc::new(f));
192    }
193
194    /// Register a policy class for a resource type.
195    pub fn register_policy(&self, resource: &str, policy: Arc<dyn Policy>) {
196        let mut policies = self.policies.lock().unwrap();
197        policies.insert(resource.to_string(), policy);
198    }
199
200    /// Check if a user is allowed to perform an ability.
201    pub fn allows(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> bool {
202        self.inspect(user, ability, args).is_allowed()
203    }
204
205    /// Check if a user is denied from performing an ability.
206    pub fn denies(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> bool {
207        !self.allows(user, ability, args)
208    }
209
210    /// Inspect a gate check and return the full result.
211    pub fn inspect(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> GateCheck {
212        // Run before hooks
213        let before_hooks = self.before_hooks.lock().unwrap();
214        for hook in before_hooks.iter() {
215            if let Some(result) = hook(user, ability, args) {
216                return result;
217            }
218        }
219        drop(before_hooks);
220
221        // Check gates first
222        let result = {
223            let abilities = self.abilities.lock().unwrap();
224            if let Some(callback) = abilities.get(ability) {
225                callback(user, args)
226            } else {
227                // Fall back to policy check
228                let policies = self.policies.lock().unwrap();
229                // Try to find a policy for the ability
230                // Convention: ability names like "update-post" map to resource "post"
231                let resource = ability
232                    .rsplit_once('-')
233                    .map(|(_, rest)| rest)
234                    .or_else(|| ability.rsplit_once('_').map(|(_, rest)| rest))
235                    .unwrap_or(ability);
236                if let Some(policy) = policies.get(resource) {
237                    policy
238                        .before(user, ability, args)
239                        .or_else(|| policy.check(user, ability, args))
240                        .unwrap_or_else(|| {
241                            GateCheck::Denied(format!(
242                                "Policy '{}' did not handle '{}'.",
243                                resource, ability
244                            ))
245                        })
246                } else {
247                    GateCheck::Denied(format!("No gate or policy registered for '{}'.", ability))
248                }
249            }
250        };
251
252        // Run after hooks
253        let after_hooks = self.after_hooks.lock().unwrap();
254        let mut final_result = result;
255        for hook in after_hooks.iter() {
256            if let Some(override_result) = hook(user, ability, args, &final_result) {
257                final_result = override_result;
258            }
259        }
260
261        final_result
262    }
263
264    /// Check if a gate or policy is defined for the given ability.
265    pub fn has(&self, ability: &str) -> bool {
266        let abilities = self.abilities.lock().unwrap();
267        if abilities.contains_key(ability) {
268            return true;
269        }
270        let policies = self.policies.lock().unwrap();
271        let resource = ability
272            .rsplit_once('-')
273            .map(|(_, rest)| rest)
274            .or_else(|| ability.rsplit_once('_').map(|(_, rest)| rest))
275            .unwrap_or(ability);
276        policies.contains_key(resource)
277    }
278
279    /// Get a list of all registered ability names.
280    pub fn abilities(&self) -> Vec<String> {
281        let abilities = self.abilities.lock().unwrap();
282        abilities.keys().cloned().collect()
283    }
284
285    /// Get a list of all registered policy resource names.
286    pub fn policy_resources(&self) -> Vec<String> {
287        let policies = self.policies.lock().unwrap();
288        policies.keys().cloned().collect()
289    }
290}
291
292/// Trait for policy classes.
293///
294/// Policies organize authorization logic around a particular model or resource.
295///
296/// # Example
297///
298/// ```ignore
299/// struct PostPolicy;
300///
301/// #[async_trait]
302/// impl Policy for PostPolicy {
303///     fn resource(&self) -> &str { "post" }
304///
305///     fn check(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> Option<GateCheck> {
306///         match ability {
307///             "create" => Some(GateCheck::Allowed),
308///             "update" => {
309///                 let owner_id = args.first()?;
310///                 if owner_id == &user.user_id {
311///                     Some(GateCheck::Allowed)
312///                 } else {
313///                     Some(GateCheck::Denied("You do not own this post.".to_string()))
314///                 }
315///             }
316///             _ => None,
317///         }
318///     }
319/// }
320/// ```
321pub trait Policy: Send + Sync + std::fmt::Debug {
322    /// The resource name this policy applies to (e.g. "post", "user").
323    fn resource(&self) -> &str;
324
325    /// Check the given ability for the user.
326    /// Returns `Some(GateCheck)` if this policy handles the ability, `None` otherwise.
327    fn check(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> Option<GateCheck>;
328
329    /// Before hook scoped to this policy. Called before `check`.
330    /// Returns `Some(GateCheck)` to short-circuit, `None` to proceed to `check`.
331    fn before(
332        &self,
333        _user: &AuthenticatedUser,
334        _ability: &str,
335        _args: &[String],
336    ) -> Option<GateCheck> {
337        None
338    }
339}
340
341/// Check if the authenticated user has a given ability using the Gate in
342/// request extensions. Returns `Ok(())` if allowed, `Err(GateCheck)` if denied.
343///
344/// This is the inner check used by middleware; use `require_ability` to create
345/// Axum-compatible middleware layers.
346pub async fn check_ability(
347    ability: &str,
348    user: &AuthenticatedUser,
349    gate: &Gate,
350) -> Result<(), GateCheck> {
351    let result = gate.inspect(user, ability, &[]);
352    if result.is_allowed() {
353        Ok(())
354    } else {
355        Err(result)
356    }
357}
358
359/// Create an Axum middleware layer that checks the given ability.
360///
361/// Requires both `AuthenticatedUser` and `Gate` to be present in request
362/// extensions (inserted by upstream middleware).
363///
364/// # Example
365///
366/// ```ignore
367/// use axum::{Router, middleware};
368/// use axum::routing::get;
369/// use larastvel_core::auth::require_ability;
370///
371/// let app = Router::new()
372///     .route("/admin", get(admin_handler))
373///     .route_layer(middleware::from_fn(require_ability("admin")));
374/// ```
375pub fn require_ability(
376    ability: &'static str,
377) -> impl Fn(
378    Request,
379    Next,
380) -> std::pin::Pin<
381    Box<dyn std::future::Future<Output = Result<Response, GateCheck>> + Send>,
382> + Send
383       + Clone {
384    move |req: Request, next: Next| {
385        let ability = ability;
386        Box::pin(async move {
387            let user = req
388                .extensions()
389                .get::<AuthenticatedUser>()
390                .cloned()
391                .ok_or_else(|| GateCheck::Denied("Not authenticated.".to_string()))?;
392
393            let gate = req.extensions().get::<Gate>().cloned().ok_or_else(|| {
394                GateCheck::Denied(
395                    "Gate not initialized. Add Gate to application state.".to_string(),
396                )
397            })?;
398
399            check_ability(ability, &user, &gate).await?;
400            Ok(next.run(req).await)
401        })
402    }
403}
404
405/// Convenience function to check authorization using a global Gate instance.
406///
407/// Requires the Gate to be stored in a global or passed explicitly. This free
408/// function provides a shorthand similar to Laravel's `$this->authorize()`.
409pub fn authorize(
410    gate: &Gate,
411    user: &AuthenticatedUser,
412    ability: &str,
413    args: &[String],
414) -> Result<(), GateCheck> {
415    let result = gate.inspect(user, ability, args);
416    if result.is_allowed() {
417        Ok(())
418    } else {
419        Err(result)
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use crate::auth::Claims;
427
428    fn test_user(id: &str) -> AuthenticatedUser {
429        AuthenticatedUser {
430            user_id: id.to_string(),
431            claims: Claims {
432                sub: id.to_string(),
433                exp: 9999999999,
434                iat: 0,
435            },
436        }
437    }
438
439    #[test]
440    fn test_gate_define_and_allows() {
441        let gate = Gate::new();
442        gate.define("admin", |user, _| {
443            if user.user_id == "admin" {
444                GateCheck::Allowed
445            } else {
446                GateCheck::Denied("Not admin.".to_string())
447            }
448        });
449
450        let admin = test_user("admin");
451        let user = test_user("user-1");
452
453        assert!(gate.allows(&admin, "admin", &[]));
454        assert!(!gate.allows(&user, "admin", &[]));
455    }
456
457    #[test]
458    fn test_gate_denies() {
459        let gate = Gate::new();
460        gate.define("secret", |user, _| {
461            if user.user_id == "root" {
462                GateCheck::Allowed
463            } else {
464                GateCheck::Denied("Access denied.".to_string())
465            }
466        });
467
468        let user = test_user("user-1");
469        assert!(gate.denies(&user, "secret", &[]));
470    }
471
472    #[test]
473    fn test_gate_inspect() {
474        let gate = Gate::new();
475        gate.define("delete", |_, _| {
476            GateCheck::Denied("Cannot delete.".to_string())
477        });
478
479        let user = test_user("user");
480        let result = gate.inspect(&user, "delete", &[]);
481        assert!(result.is_denied());
482        assert_eq!(result.message(), Some("Cannot delete."));
483    }
484
485    #[test]
486    fn test_gate_with_arguments() {
487        let gate = Gate::new();
488        gate.define("update-post", |user, args| {
489            if args.first().map(|s| s.as_str()) == Some(&user.user_id) {
490                GateCheck::Allowed
491            } else {
492                GateCheck::Denied("Not owned.".to_string())
493            }
494        });
495
496        let owner = test_user("user-1");
497        let other = test_user("user-2");
498
499        assert!(gate.allows(&owner, "update-post", &["user-1".to_string()]));
500        assert!(gate.denies(&other, "update-post", &["user-1".to_string()]));
501    }
502
503    #[test]
504    fn test_before_hook() {
505        let gate = Gate::new();
506        // A before hook that allows all admin actions
507        gate.before(|user, _ability, _args| {
508            if user.user_id == "admin" {
509                Some(GateCheck::Allowed)
510            } else {
511                None
512            }
513        });
514
515        // A gate that denies everything
516        gate.define("anything", |_, _| GateCheck::Denied("Nope.".to_string()));
517
518        let admin = test_user("admin");
519        let user = test_user("user");
520
521        assert!(gate.allows(&admin, "anything", &[]));
522        assert!(gate.denies(&user, "anything", &[]));
523    }
524
525    #[test]
526    fn test_after_hook() {
527        let gate = Gate::new();
528        // After hook that denies everything unless it's a super ability
529        gate.after(|user, ability, _args, result| {
530            if ability == "super-admin" && result.is_allowed() {
531                Some(GateCheck::Denied(
532                    "Super admin not allowed via after hook.".to_string(),
533                ))
534            } else if user.user_id == "override" {
535                Some(GateCheck::Allowed)
536            } else {
537                None
538            }
539        });
540
541        gate.define("super-admin", |_, _| GateCheck::Allowed);
542        gate.define("normal", |_, _| GateCheck::Denied("No.".to_string()));
543
544        let admin = test_user("super");
545        let overrider = test_user("override");
546
547        assert!(gate.denies(&admin, "super-admin", &[]));
548        assert!(gate.allows(&overrider, "normal", &[]));
549    }
550
551    #[test]
552    fn test_has() {
553        let gate = Gate::new();
554        gate.define("view-dashboard", |_, _| GateCheck::Allowed);
555        assert!(gate.has("view-dashboard"));
556        assert!(!gate.has("nonexistent"));
557    }
558
559    #[test]
560    fn test_abilities_list() {
561        let gate = Gate::new();
562        gate.define("a", |_, _| GateCheck::Allowed);
563        gate.define("b", |_, _| GateCheck::Allowed);
564        let mut abilities = gate.abilities();
565        abilities.sort();
566        assert_eq!(abilities, vec!["a", "b"]);
567    }
568
569    #[test]
570    fn test_policy_check() {
571        #[derive(Debug)]
572        struct PostPolicy;
573
574        impl Policy for PostPolicy {
575            fn resource(&self) -> &str {
576                "post"
577            }
578
579            fn check(
580                &self,
581                user: &AuthenticatedUser,
582                ability: &str,
583                args: &[String],
584            ) -> Option<GateCheck> {
585                match ability {
586                    "create-post" => Some(GateCheck::Allowed),
587                    "update-post" => {
588                        let owner_id = args.first()?;
589                        if owner_id == &user.user_id {
590                            Some(GateCheck::Allowed)
591                        } else {
592                            Some(GateCheck::Denied("Not your post.".to_string()))
593                        }
594                    }
595                    _ => None,
596                }
597            }
598        }
599
600        let gate = Gate::new();
601        let owner = test_user("owner");
602        let other = test_user("other");
603
604        // Without a policy registered, it should deny
605        assert!(gate.denies(&owner, "create-post", &[]));
606
607        // Register policy
608        gate.register_policy("post", Arc::new(PostPolicy));
609
610        assert!(gate.allows(&owner, "create-post", &[]));
611        assert!(gate.allows(&owner, "update-post", &["owner".to_string()]));
612        assert!(gate.denies(&other, "update-post", &["owner".to_string()]));
613    }
614
615    #[test]
616    fn test_policy_before_hook() {
617        #[derive(Debug)]
618        struct AdminPolicy;
619
620        impl Policy for AdminPolicy {
621            fn resource(&self) -> &str {
622                "admin"
623            }
624
625            fn before(
626                &self,
627                user: &AuthenticatedUser,
628                _ability: &str,
629                _args: &[String],
630            ) -> Option<GateCheck> {
631                if user.user_id == "super-admin" {
632                    Some(GateCheck::Allowed)
633                } else {
634                    None
635                }
636            }
637
638            fn check(
639                &self,
640                _user: &AuthenticatedUser,
641                _ability: &str,
642                _args: &[String],
643            ) -> Option<GateCheck> {
644                Some(GateCheck::Denied("Denied by policy.".to_string()))
645            }
646        }
647
648        let gate = Gate::new();
649        gate.register_policy("admin", Arc::new(AdminPolicy));
650
651        let super_admin = test_user("super-admin");
652        let normal = test_user("normal");
653
654        assert!(gate.allows(&super_admin, "access-admin", &[]));
655        assert!(gate.denies(&normal, "access-admin", &[]));
656    }
657
658    #[test]
659    fn test_authorize_function() {
660        let gate = Gate::new();
661        gate.define("view-reports", |user, _| {
662            if user.user_id == "admin" {
663                GateCheck::Allowed
664            } else {
665                GateCheck::Denied("No access.".to_string())
666            }
667        });
668
669        let admin = test_user("admin");
670        let user = test_user("user");
671
672        assert!(authorize(&gate, &admin, "view-reports", &[]).is_ok());
673        assert!(authorize(&gate, &user, "view-reports", &[]).is_err());
674    }
675
676    #[test]
677    fn test_gate_check_utility_methods() {
678        let allowed = GateCheck::Allowed;
679        assert!(allowed.is_allowed());
680        assert!(!allowed.is_denied());
681        assert!(allowed.message().is_none());
682
683        let denied = GateCheck::Denied("Forbidden".to_string());
684        assert!(!denied.is_allowed());
685        assert!(denied.is_denied());
686        assert_eq!(denied.message(), Some("Forbidden"));
687    }
688
689    #[test]
690    fn test_multiple_gates() {
691        let gate = Gate::new();
692        gate.define("read", |_, _| GateCheck::Allowed);
693        gate.define("write", |_, _| {
694            GateCheck::Denied("Read-only mode.".to_string())
695        });
696
697        let user = test_user("user");
698        assert!(gate.allows(&user, "read", &[]));
699        assert!(gate.denies(&user, "write", &[]));
700    }
701
702    #[test]
703    fn test_unknown_ability_returns_denied() {
704        let gate = Gate::new();
705        let user = test_user("user");
706        assert!(gate.denies(&user, "unknown-ability", &[]));
707        let result = gate.inspect(&user, "unknown-ability", &[]);
708        assert!(result
709            .message()
710            .unwrap()
711            .contains("No gate or policy registered"));
712    }
713
714    #[test]
715    fn test_policy_resources() {
716        #[derive(Debug)]
717        struct MyPolicy;
718        impl Policy for MyPolicy {
719            fn resource(&self) -> &str {
720                "my-resource"
721            }
722            fn check(&self, _: &AuthenticatedUser, _: &str, _: &[String]) -> Option<GateCheck> {
723                Some(GateCheck::Allowed)
724            }
725        }
726
727        let gate = Gate::new();
728        gate.register_policy("my-resource", Arc::new(MyPolicy));
729        let resources = gate.policy_resources();
730        assert_eq!(resources, vec!["my-resource"]);
731    }
732
733    #[test]
734    fn test_gate_default_impl() {
735        let gate = Gate::default();
736        assert!(gate.abilities().is_empty());
737    }
738
739    // -----------------------------------------------------------------------
740    // #[policy] macro tests
741    // -----------------------------------------------------------------------
742
743    use larastvel_macros::policy;
744    use std::sync::Arc;
745
746    #[policy("article")]
747    #[derive(Debug)]
748    struct ArticlePolicy;
749
750    impl ArticlePolicy {
751        fn check_ability(
752            &self,
753            _user: &AuthenticatedUser,
754            ability: &str,
755            _args: &[String],
756        ) -> Option<GateCheck> {
757            match ability {
758                "view" | "create" => Some(GateCheck::Allowed),
759                "delete" => Some(GateCheck::Denied("Admins only".to_string())),
760                _ => None,
761            }
762        }
763    }
764
765    #[policy("admin")]
766    #[derive(Debug)]
767    struct AdminPolicy;
768
769    impl AdminPolicy {
770        fn check_ability(
771            &self,
772            _user: &AuthenticatedUser,
773            _ability: &str,
774            _args: &[String],
775        ) -> Option<GateCheck> {
776            Some(GateCheck::Allowed)
777        }
778    }
779
780    #[test]
781    fn test_policy_macro_resource() {
782        let policy = ArticlePolicy;
783        assert_eq!(policy.resource(), "article");
784    }
785
786    #[test]
787    fn test_policy_macro_check_delegates() {
788        let policy = ArticlePolicy;
789        let user = AuthenticatedUser {
790            user_id: "1".to_string(),
791            claims: Claims {
792                sub: "1".to_string(),
793                exp: 0,
794                iat: 0,
795            },
796        };
797        assert_eq!(policy.check(&user, "view", &[]), Some(GateCheck::Allowed));
798        assert_eq!(policy.check(&user, "create", &[]), Some(GateCheck::Allowed));
799        assert_eq!(
800            policy.check(&user, "delete", &[]),
801            Some(GateCheck::Denied("Admins only".to_string()))
802        );
803        assert_eq!(policy.check(&user, "update", &[]), None);
804    }
805
806    #[test]
807    fn test_policy_macro_register() {
808        let gate = Gate::new();
809        ArticlePolicy::register(&gate);
810        assert!(gate.policy_resources().contains(&"article".to_string()));
811    }
812
813    #[test]
814    fn test_policy_macro_integration_with_gate() {
815        let gate = Gate::new();
816        AdminPolicy::register(&gate);
817        let user = AuthenticatedUser {
818            user_id: "1".to_string(),
819            claims: Claims {
820                sub: "1".to_string(),
821                exp: 0,
822                iat: 0,
823            },
824        };
825        let result = gate.inspect(&user, "do-admin", &[]);
826        assert_eq!(result, GateCheck::Allowed);
827    }
828
829    #[test]
830    fn test_policy_macro_multiple_policies() {
831        let gate = Gate::new();
832        ArticlePolicy::register(&gate);
833        AdminPolicy::register(&gate);
834        let mut resources = gate.policy_resources();
835        resources.sort();
836        assert_eq!(resources, vec!["admin", "article"]);
837    }
838}