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#[derive(Debug, Clone, PartialEq)]
16pub enum GateCheck {
17 Allowed,
19 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
55pub type GateCallback = Arc<dyn Fn(&AuthenticatedUser, &[String]) -> GateCheck + Send + Sync>;
59
60pub type BeforeHook =
62 Arc<dyn Fn(&AuthenticatedUser, &str, &[String]) -> Option<GateCheck> + Send + Sync>;
63
64pub type AfterHook =
66 Arc<dyn Fn(&AuthenticatedUser, &str, &[String], &GateCheck) -> Option<GateCheck> + Send + Sync>;
67
68pub 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 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 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 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 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 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 pub fn allows(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> bool {
202 self.inspect(user, ability, args).is_allowed()
203 }
204
205 pub fn denies(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> bool {
207 !self.allows(user, ability, args)
208 }
209
210 pub fn inspect(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> GateCheck {
212 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 let result = {
223 let abilities = self.abilities.lock().unwrap();
224 if let Some(callback) = abilities.get(ability) {
225 callback(user, args)
226 } else {
227 let policies = self.policies.lock().unwrap();
229 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 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 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 pub fn abilities(&self) -> Vec<String> {
281 let abilities = self.abilities.lock().unwrap();
282 abilities.keys().cloned().collect()
283 }
284
285 pub fn policy_resources(&self) -> Vec<String> {
287 let policies = self.policies.lock().unwrap();
288 policies.keys().cloned().collect()
289 }
290}
291
292pub trait Policy: Send + Sync + std::fmt::Debug {
322 fn resource(&self) -> &str;
324
325 fn check(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> Option<GateCheck>;
328
329 fn before(
332 &self,
333 _user: &AuthenticatedUser,
334 _ability: &str,
335 _args: &[String],
336 ) -> Option<GateCheck> {
337 None
338 }
339}
340
341pub 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
359pub 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
405pub 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 gate.before(|user, _ability, _args| {
508 if user.user_id == "admin" {
509 Some(GateCheck::Allowed)
510 } else {
511 None
512 }
513 });
514
515 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 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 assert!(gate.denies(&owner, "create-post", &[]));
606
607 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 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}