Skip to main content

aurelin_framework/authorization/
gate.rs

1use std::{
2    any::{Any, TypeId, type_name},
3    collections::HashMap,
4    future::Future,
5    pin::Pin,
6    sync::Arc,
7};
8
9use super::{AuthorizationResponse, IntoAuthorizationResponse, UserGate};
10use crate::events::{DispatchError, EventDispatcher};
11
12/// The result of a gate check, before the default denial is applied.
13pub struct GateEvaluated<User> {
14    /// The user being authorized, or a guest.
15    pub user: Option<User>,
16    /// The checked ability.
17    pub ability: String,
18    /// The resolved result, or `None` if no rule resolved the check.
19    pub result: Option<AuthorizationResponse>,
20    context: Arc<dyn Any + Send + Sync>,
21}
22
23impl<User> GateEvaluated<User> {
24    /// Recover the typed context supplied to the gate.
25    pub fn context<Context: Any>(&self) -> Option<&Context> {
26        self.context.downcast_ref()
27    }
28}
29
30type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
31type AbilityCallback<User> =
32    dyn Fn(Option<User>, &dyn Any) -> Result<BoxFuture<AuthorizationResponse>, GateError> + Send + Sync;
33type BeforeCallback<User> = dyn Fn(Option<User>, String) -> BoxFuture<Option<AuthorizationResponse>> + Send + Sync;
34type AfterCallback<User> = dyn Fn(Option<User>, String, Option<AuthorizationResponse>) -> BoxFuture<Option<AuthorizationResponse>>
35    + Send
36    + Sync;
37
38#[derive(Clone, Debug, Eq, Hash, PartialEq)]
39struct AbilityKey {
40    name: String,
41    context: TypeId,
42}
43
44/// An application policy that registers typed abilities and optional pre-authorization.
45pub trait Policy<User>: Clone + Send + Sync + Sized + 'static {
46    /// Resolve an ability before its policy method, or return `None` to continue.
47    fn before(&self, _user: &User, _ability: &str) -> Option<AuthorizationResponse> {
48        None
49    }
50
51    /// Register this policy's application-owned abilities.
52    fn register(&self, policy: &mut PolicyRegistrar<'_, User, Self>);
53}
54
55/// Registers abilities belonging to one application policy.
56pub struct PolicyRegistrar<'a, User, ApplicationPolicy> {
57    gate: &'a mut GateBuilder<User>,
58    policy: ApplicationPolicy,
59}
60
61impl<User, ApplicationPolicy> PolicyRegistrar<'_, User, ApplicationPolicy>
62where
63    User: Clone + Send + Sync + 'static,
64    ApplicationPolicy: Policy<User>,
65{
66    /// Register an authenticated-user policy ability.
67    pub fn define<Context, Check, CheckFuture, Result>(&mut self, ability: impl Into<String>, check: Check) -> &mut Self
68    where
69        Context: Any + Clone + Send + Sync + 'static,
70        Check: Fn(ApplicationPolicy, User, Context) -> CheckFuture + Send + Sync + 'static,
71        CheckFuture: Future<Output = Result> + Send + 'static,
72        Result: IntoAuthorizationResponse + 'static,
73    {
74        let ability = ability.into();
75        let callback_ability = ability.clone();
76        let policy = self.policy.clone();
77        let check = Arc::new(check);
78        self.gate.define(ability, move |user: User, context: Context| {
79            let policy = policy.clone();
80            let before = policy.before(&user, &callback_ability);
81            let check = Arc::clone(&check);
82            async move {
83                match before {
84                    Some(response) => response,
85                    None => check(policy, user, context).await.into_authorization_response(),
86                }
87            }
88        });
89        self
90    }
91
92    /// Register a guest-aware policy ability.
93    pub fn define_for_guests<Context, Check, CheckFuture, Result>(
94        &mut self,
95        ability: impl Into<String>,
96        check: Check,
97    ) -> &mut Self
98    where
99        Context: Any + Clone + Send + Sync + 'static,
100        Check: Fn(ApplicationPolicy, Option<User>, Context) -> CheckFuture + Send + Sync + 'static,
101        CheckFuture: Future<Output = Result> + Send + 'static,
102        Result: IntoAuthorizationResponse + 'static,
103    {
104        let ability = ability.into();
105        let callback_ability = ability.clone();
106        let policy = self.policy.clone();
107        let check = Arc::new(check);
108        self.gate.define_for_guests(ability, move |user: Option<User>, context: Context| {
109            let policy = policy.clone();
110            let before = user.as_ref().and_then(|user| policy.before(user, &callback_ability));
111            let check = Arc::clone(&check);
112            async move {
113                match before {
114                    Some(response) => response,
115                    None => check(policy, user, context).await.into_authorization_response(),
116                }
117            }
118        });
119        self
120    }
121}
122
123/// Builds an immutable authorization gate registry.
124pub struct GateBuilder<User> {
125    abilities: HashMap<AbilityKey, Arc<AbilityCallback<User>>>,
126    before: Vec<Arc<BeforeCallback<User>>>,
127    after: Vec<Arc<AfterCallback<User>>>,
128    default_denial: AuthorizationResponse,
129    events: Option<EventDispatcher>,
130}
131
132impl<User> Default for GateBuilder<User> {
133    fn default() -> Self {
134        Self {
135            abilities: HashMap::new(),
136            before: Vec::new(),
137            after: Vec::new(),
138            default_denial: AuthorizationResponse::deny(),
139            events: None,
140        }
141    }
142}
143
144impl<User> GateBuilder<User>
145where
146    User: Clone + Send + Sync + 'static,
147{
148    /// Create an empty gate registry builder.
149    pub fn new() -> Self {
150        Self::default()
151    }
152
153    /// Register an ability that requires an authenticated user.
154    pub fn define<Context, Check, CheckFuture, Result>(&mut self, ability: impl Into<String>, check: Check) -> &mut Self
155    where
156        Context: Any + Clone + Send + Sync + 'static,
157        Check: Fn(User, Context) -> CheckFuture + Send + Sync + 'static,
158        CheckFuture: Future<Output = Result> + Send + 'static,
159        Result: IntoAuthorizationResponse + 'static,
160    {
161        self.define_for_guests(ability, move |user: Option<User>, context| {
162            let check = user.map(|user| check(user, context));
163            async move {
164                match check {
165                    Some(result) => result.await.into_authorization_response(),
166                    None => AuthorizationResponse::deny(),
167                }
168            }
169        })
170    }
171
172    /// Register an ability that explicitly receives authenticated users or guests.
173    pub fn define_for_guests<Context, Check, CheckFuture, Result>(
174        &mut self,
175        ability: impl Into<String>,
176        check: Check,
177    ) -> &mut Self
178    where
179        Context: Any + Clone + Send + Sync + 'static,
180        Check: Fn(Option<User>, Context) -> CheckFuture + Send + Sync + 'static,
181        CheckFuture: Future<Output = Result> + Send + 'static,
182        Result: IntoAuthorizationResponse + 'static,
183    {
184        let name = ability.into();
185        let callback_name = name.clone();
186        let callback = move |user: Option<User>, context: &dyn Any| {
187            let context = context.downcast_ref::<Context>().cloned().ok_or_else(|| GateError::ContextMismatch {
188                ability: callback_name.clone(),
189                expected: type_name::<Context>(),
190            })?;
191            let future = check(user, context);
192            Ok(Box::pin(async move { future.await.into_authorization_response() }) as BoxFuture<_>)
193        };
194        let key = AbilityKey { name, context: TypeId::of::<Context>() };
195        self.abilities.insert(key, Arc::new(callback));
196        self
197    }
198
199    /// Register an application-owned policy.
200    pub fn policy<P>(&mut self, policy: P) -> &mut Self
201    where
202        P: Policy<User>,
203    {
204        let registration = policy.clone();
205        let mut registrar = PolicyRegistrar { gate: self, policy };
206        registration.register(&mut registrar);
207        self
208    }
209
210    /// Register a callback that can resolve an ability before its normal check.
211    pub fn before<Hook, HookFuture, Result>(&mut self, hook: Hook) -> &mut Self
212    where
213        Hook: Fn(Option<User>, String) -> HookFuture + Send + Sync + 'static,
214        HookFuture: Future<Output = Option<Result>> + Send + 'static,
215        Result: IntoAuthorizationResponse + 'static,
216    {
217        self.before.push(Arc::new(move |user, ability| {
218            let future = hook(user, ability);
219            Box::pin(async move { future.await.map(IntoAuthorizationResponse::into_authorization_response) })
220        }));
221        self
222    }
223
224    /// Register a callback that observes every check and may resolve an otherwise missing ability.
225    pub fn after<Hook, HookFuture, Result>(&mut self, hook: Hook) -> &mut Self
226    where
227        Hook: Fn(Option<User>, String, Option<AuthorizationResponse>) -> HookFuture + Send + Sync + 'static,
228        HookFuture: Future<Output = Option<Result>> + Send + 'static,
229        Result: IntoAuthorizationResponse + 'static,
230    {
231        self.after.push(Arc::new(move |user, ability, response| {
232            let future = hook(user, ability, response);
233            Box::pin(async move { future.await.map(IntoAuthorizationResponse::into_authorization_response) })
234        }));
235        self
236    }
237
238    /// Select the denial used when no ability or hook resolves a check.
239    pub fn default_denial(&mut self, response: AuthorizationResponse) -> &mut Self {
240        self.default_denial = response;
241        self
242    }
243
244    /// Dispatch gate evaluation events through the application's dispatcher.
245    pub fn events(&mut self, events: EventDispatcher) -> &mut Self {
246        self.events = Some(events);
247        self
248    }
249
250    /// Finish configuring the immutable gate registry.
251    pub fn build(&self) -> Gate<User> {
252        Gate {
253            inner: Arc::new(GateInner {
254                abilities: self.abilities.clone(),
255                before: self.before.clone(),
256                after: self.after.clone(),
257                default_denial: self.default_denial.clone(),
258                events: self.events.clone(),
259            }),
260        }
261    }
262}
263
264struct GateInner<User> {
265    abilities: HashMap<AbilityKey, Arc<AbilityCallback<User>>>,
266    before: Vec<Arc<BeforeCallback<User>>>,
267    after: Vec<Arc<AfterCallback<User>>>,
268    default_denial: AuthorizationResponse,
269    events: Option<EventDispatcher>,
270}
271
272/// A shared registry of application-defined authorization abilities.
273pub struct Gate<User> {
274    inner: Arc<GateInner<User>>,
275}
276
277impl<User> Clone for Gate<User> {
278    fn clone(&self) -> Self {
279        Self { inner: Arc::clone(&self.inner) }
280    }
281}
282
283impl<User> Gate<User>
284where
285    User: Clone + Send + Sync + 'static,
286{
287    /// Configure a gate registry.
288    pub fn builder() -> GateBuilder<User> {
289        GateBuilder::new()
290    }
291
292    /// Evaluate abilities for the supplied user or guest.
293    pub fn for_user(&self, user: Option<&User>) -> UserGate<User> {
294        UserGate::new(self.clone(), user.cloned())
295    }
296
297    pub(super) async fn inspect<Context>(
298        &self,
299        user: Option<User>,
300        ability: &str,
301        context: &Context,
302    ) -> Result<AuthorizationResponse, GateError>
303    where
304        Context: Any + Clone + Send + Sync + 'static,
305    {
306        let mut result = None;
307        for hook in &self.inner.before {
308            if let Some(response) = hook(user.clone(), ability.to_owned()).await {
309                result = Some(response);
310                break;
311            }
312        }
313
314        if result.is_none() {
315            let key = AbilityKey { name: ability.to_owned(), context: TypeId::of::<Context>() };
316            if let Some(callback) = self.inner.abilities.get(&key) {
317                result = Some(callback(user.clone(), context)?.await);
318            } else if self.inner.abilities.keys().any(|key| key.name == ability) {
319                return Err(GateError::ContextMismatch {
320                    ability: ability.to_owned(),
321                    expected: "the context type registered for this ability",
322                });
323            }
324        }
325
326        for hook in &self.inner.after {
327            let candidate = hook(user.clone(), ability.to_owned(), result.clone()).await;
328            if result.is_none() {
329                result = candidate;
330            }
331        }
332
333        if let Some(events) = &self.inner.events {
334            events
335                .dispatch(GateEvaluated {
336                    user,
337                    ability: ability.to_owned(),
338                    result: result.clone(),
339                    context: Arc::new(context.clone()),
340                })
341                .await?;
342        }
343        Ok(result.unwrap_or_else(|| self.inner.default_denial.clone()))
344    }
345}
346
347/// A gate was invoked with an incompatible typed context.
348#[derive(Debug, thiserror::Error)]
349pub enum GateError {
350    #[error("ability [{ability}] requires {expected}")]
351    ContextMismatch { ability: String, expected: &'static str },
352    /// An evaluation listener failed; authorization did not complete.
353    #[error(transparent)]
354    Event(#[from] DispatchError),
355}