ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! Authorization gates and policies, shaped like Laravel's `Gate`.
//!
//! Abilities are closures over `(user, argument)`; policies group the
//! `view/create/update/delete` abilities of one model type. Anything not
//! defined is **denied** (fail closed).
//!
//! ```
//! use ryuk::gate::{Arg, Gate};
//!
//! struct User { id: i64, admin: bool }
//! struct Post { owner: i64 }
//!
//! let mut gate = Gate::<User>::new();
//! gate.before(|u, _ability, _arg| u.admin.then_some(true)); // super-admin
//! gate.define("update-post", |u, arg: &Arg| {
//!     arg.downcast_ref::<Post>().is_some_and(|p| p.owner == u.id)
//! });
//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
//! let (me, boss) = (User { id: 1, admin: false }, User { id: 9, admin: true });
//! assert!(gate.allows(&me, "update-post", &Post { owner: 1 }).await);
//! assert!(!gate.allows(&me, "update-post", &Post { owner: 2 }).await);
//! assert!(gate.allows(&boss, "update-post", &Post { owner: 2 }).await);
//! assert!(gate.denies(&me, "no-such-ability", &()).await); // unknown: denied
//! assert!(gate.authorize(&me, "update-post", &Post { owner: 2 }).await.is_err());
//! # });
//! ```
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};

/// The argument handed to an ability (usually the model being acted on);
/// pass `&()` when there is none. Downcast with `arg.downcast_ref::<Post>()`.
pub type Arg = dyn Any + Send + Sync;
/// Boxed future returned by async abilities.
pub type Fut<'a, T = bool> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

type Rule<U> = Box<dyn for<'a> Fn(&'a U, &'a Arg) -> Fut<'a> + Send + Sync>;
type Before<U> = Box<dyn Fn(&U, &str, &Arg) -> Option<bool> + Send + Sync>;
type PolicyFn<U> = Box<dyn for<'a> Fn(&'a U, &'a str, &'a Arg) -> Fut<'a> + Send + Sync>;

/// Returned by [`Gate::authorize`]; renders as 403 (or 404 after
/// [`Forbidden::deny_as_not_found`], to hide that a resource exists).
///
/// It is a `std::error::Error`, so an app error type with a blanket `impl<E: Error> From<E>` (the
/// generated `AppError`) swallows it as a 500 unless that conversion looks for it. The generated app's
/// does: it downcasts with [`Forbidden::from_error`]. Do the same in your own error type.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, thiserror::Error)]
#[error("this action is unauthorized")]
pub struct Forbidden {
    not_found: bool,
}

impl Forbidden {
    /// A 403, for the cases the gate cannot decide (a hand-written check): `return Err(Forbidden::new())`.
    pub fn new() -> Self {
        Self { not_found: false }
    }

    /// `Some` when `e` is a `Forbidden`, for a blanket `From<E: Error + 'static>` to route it to its
    /// 403/404 response instead of a 500:
    /// ```
    /// use ryuk::gate::Forbidden;
    /// let e = Forbidden::new().deny_as_not_found();
    /// assert_eq!(Forbidden::from_error(&e), Some(e));
    /// assert_eq!(Forbidden::from_error(&std::fmt::Error), None);
    /// ```
    pub fn from_error<E: 'static>(e: &E) -> Option<Self> {
        (e as &dyn std::any::Any).downcast_ref::<Self>().copied()
    }

    /// Whether this renders as 404 ([`Forbidden::deny_as_not_found`]) instead of 403.
    pub fn is_not_found(&self) -> bool {
        self.not_found
    }

    /// Answer 404 instead of 403: `gate.authorize(..).await.map_err(Forbidden::deny_as_not_found)?`.
    pub fn deny_as_not_found(mut self) -> Self {
        self.not_found = true;
        self
    }
}

impl IntoResponse for Forbidden {
    fn into_response(self) -> Response {
        if self.not_found {
            (StatusCode::NOT_FOUND, "Not Found").into_response()
        } else {
            (StatusCode::FORBIDDEN, "Forbidden").into_response()
        }
    }
}

/// Per-model abilities. Every method denies by default; override the ones you allow.
/// `create` has no model instance (check it with [`Gate::allows_for`]).
pub trait Policy<U, M>: Send + Sync + 'static {
    fn view(&self, _user: &U, _model: &M) -> impl Future<Output = bool> + Send {
        async { false }
    }
    fn create(&self, _user: &U) -> impl Future<Output = bool> + Send {
        async { false }
    }
    fn update(&self, _user: &U, _model: &M) -> impl Future<Output = bool> + Send {
        async { false }
    }
    fn delete(&self, _user: &U, _model: &M) -> impl Future<Output = bool> + Send {
        async { false }
    }
}

/// Registry of abilities, `before` hooks and policies for user type `U`.
/// Build once at startup, share in an `Arc`.
pub struct Gate<U> {
    rules: HashMap<String, Rule<U>>,
    befores: Vec<Before<U>>,
    policies: HashMap<TypeId, PolicyFn<U>>,
}

impl<U> Default for Gate<U> {
    fn default() -> Self {
        Self {
            rules: HashMap::new(),
            befores: Vec::new(),
            policies: HashMap::new(),
        }
    }
}

impl<U: Send + Sync + 'static> Gate<U> {
    pub fn new() -> Self {
        Self::default()
    }

    /// Define a synchronous ability.
    pub fn define<F>(&mut self, name: &str, f: F)
    where
        F: Fn(&U, &Arg) -> bool + Send + Sync + 'static,
    {
        self.rules.insert(
            name.into(),
            Box::new(move |u, a| Box::pin(std::future::ready(f(u, a)))),
        );
    }

    /// Define an ability that needs `.await` (e.g. a DB lookup):
    /// `gate.define_async("x", |u, a| Box::pin(async move { true }))`.
    pub fn define_async<F>(&mut self, name: &str, f: F)
    where
        F: for<'a> Fn(&'a U, &'a Arg) -> Fut<'a> + Send + Sync + 'static,
    {
        self.rules.insert(name.into(), Box::new(f));
    }

    /// Run before every check, in registration order. `Some(true)` allows and
    /// `Some(false)` denies without consulting abilities; `None` continues.
    // shortcut: before hooks are sync (read a flag off the user); make async if one must hit the DB.
    pub fn before<F>(&mut self, f: F)
    where
        F: Fn(&U, &str, &Arg) -> Option<bool> + Send + Sync + 'static,
    {
        self.befores.push(Box::new(f));
    }

    /// Register a policy for model `M`: abilities `view`, `create`, `update`,
    /// `delete` resolve through it when the argument is an `M`.
    pub fn policy<M, P>(&mut self, policy: P)
    where
        M: Send + Sync + 'static,
        P: Policy<U, M>,
    {
        let policy = Arc::new(policy);
        self.policies.insert(
            TypeId::of::<M>(),
            Box::new(move |u, ability, arg| {
                let policy = policy.clone();
                Box::pin(async move {
                    let m = arg.downcast_ref::<M>();
                    match (ability, m) {
                        ("create", _) => policy.create(u).await,
                        ("view", Some(m)) => policy.view(u, m).await,
                        ("update", Some(m)) => policy.update(u, m).await,
                        ("delete", Some(m)) => policy.delete(u, m).await,
                        _ => false,
                    }
                })
            }),
        );
    }

    async fn resolve(&self, user: &U, ability: &str, arg: &Arg, model: TypeId) -> bool {
        for b in &self.befores {
            if let Some(v) = b(user, ability, arg) {
                return v;
            }
        }
        if let Some(rule) = self.rules.get(ability) {
            return rule(user, arg).await;
        }
        match self.policies.get(&model) {
            Some(p) => p(user, ability, arg).await,
            None => false,
        }
    }

    /// Is `user` allowed `ability` on `arg`? Unknown abilities are denied.
    pub async fn allows(&self, user: &U, ability: &str, arg: &Arg) -> bool {
        self.resolve(user, ability, arg, arg.type_id()).await
    }

    /// Inverse of [`Gate::allows`].
    pub async fn denies(&self, user: &U, ability: &str, arg: &Arg) -> bool {
        !self.allows(user, ability, arg).await
    }

    /// Alias of [`Gate::allows`] (Laravel's `check`).
    pub async fn check(&self, user: &U, ability: &str, arg: &Arg) -> bool {
        self.allows(user, ability, arg).await
    }

    /// Check an ability that has no instance, against model type `M`'s policy
    /// (`gate.allows_for::<Post>(&user, "create")`).
    pub async fn allows_for<M: 'static>(&self, user: &U, ability: &str) -> bool {
        self.resolve(user, ability, &(), TypeId::of::<M>()).await
    }

    /// `Ok(())` when allowed, otherwise [`Forbidden`] (an axum 403 response):
    /// `gate.authorize(&user, "update-post", &post).await?`.
    ///
    /// Policies are found by the **type of `arg`**, so `authorize(&user, "create", &())` has no policy
    /// to ask and always denies; for abilities without an instance use [`Gate::authorize_for`].
    pub async fn authorize(&self, user: &U, ability: &str, arg: &Arg) -> Result<(), Forbidden> {
        if self.allows(user, ability, arg).await {
            Ok(())
        } else {
            Err(Forbidden::new())
        }
    }

    /// [`Gate::authorize`] for an ability with no instance, against model type `M`'s policy:
    /// `gate.authorize_for::<Post>(&user, "create").await?`.
    pub async fn authorize_for<M: 'static>(
        &self,
        user: &U,
        ability: &str,
    ) -> Result<(), Forbidden> {
        if self.allows_for::<M>(user, ability).await {
            Ok(())
        } else {
            Err(Forbidden::new())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct User {
        id: i64,
        admin: bool,
    }
    struct Post {
        owner: i64,
    }
    struct PostPolicy;
    impl Policy<User, Post> for PostPolicy {
        async fn view(&self, _: &User, _: &Post) -> bool {
            true
        }
        async fn create(&self, u: &User) -> bool {
            u.id > 0
        }
        async fn update(&self, u: &User, p: &Post) -> bool {
            u.id == p.owner
        }
    }

    fn user(id: i64) -> User {
        User { id, admin: false }
    }

    #[tokio::test]
    async fn authorize_for_checks_instance_free_abilities_and_the_unit_arg_denies() {
        let mut g = Gate::<User>::new();
        g.policy::<Post, _>(PostPolicy);
        assert!(g.authorize_for::<Post>(&user(1), "create").await.is_ok());
        assert_eq!(
            g.authorize_for::<Post>(&user(0), "create").await,
            Err(Forbidden::new())
        );
        // The trap authorize_for exists for: a `()` argument has no policy, so "create" is denied.
        assert!(g.authorize(&user(1), "create", &()).await.is_err());
    }

    #[test]
    fn forbidden_renders_403_or_404() {
        assert_eq!(
            Forbidden::new().into_response().status(),
            StatusCode::FORBIDDEN
        );
        let hidden = Forbidden::new().deny_as_not_found();
        assert!(hidden.is_not_found());
        assert_eq!(hidden.into_response().status(), StatusCode::NOT_FOUND);
        assert_eq!(Forbidden::new().to_string(), "this action is unauthorized");
    }

    #[tokio::test]
    async fn unknown_ability_denies() {
        let g = Gate::<User>::new();
        assert!(g.denies(&user(1), "anything", &()).await);
        assert!(g.authorize(&user(1), "anything", &()).await.is_err());
    }

    #[tokio::test]
    async fn define_sync_and_async() {
        let mut g = Gate::<User>::new();
        g.define("sync", |u, _| u.id == 1);
        g.define_async("async", |u, _| Box::pin(async move { u.id == 2 }));
        assert!(g.allows(&user(1), "sync", &()).await);
        assert!(!g.allows(&user(2), "sync", &()).await);
        assert!(g.allows(&user(2), "async", &()).await);
        assert!(!g.check(&user(1), "async", &()).await);
    }

    #[tokio::test]
    async fn before_overrides_both_ways() {
        let mut g = Gate::<User>::new();
        g.define("x", |_, _| false);
        g.define("y", |_, _| true);
        g.before(|u, ability, _| {
            if u.admin {
                Some(true)
            } else if ability == "y" {
                Some(false)
            } else {
                None
            }
        });
        let admin = User { id: 1, admin: true };
        assert!(g.allows(&admin, "x", &()).await);
        assert!(g.allows(&admin, "nope", &()).await); // before wins, even unknown
        assert!(!g.allows(&user(2), "y", &()).await);
        assert!(!g.allows(&user(2), "x", &()).await);
    }

    #[tokio::test]
    async fn policy_maps_abilities() {
        let mut g = Gate::<User>::new();
        g.policy::<Post, _>(PostPolicy);
        let p = Post { owner: 1 };
        assert!(g.allows(&user(2), "view", &p).await);
        assert!(g.allows(&user(1), "update", &p).await);
        assert!(!g.allows(&user(2), "update", &p).await);
        assert!(!g.allows(&user(1), "delete", &p).await); // not overridden: denied
        assert!(!g.allows(&user(1), "publish", &p).await); // unknown ability
        assert!(g.allows_for::<Post>(&user(1), "create").await);
        assert!(!g.allows_for::<Post>(&user(0), "create").await);
        assert!(!g.allows_for::<Post>(&user(1), "update").await); // needs an instance
        assert!(!g.allows(&user(1), "view", &"not a post").await); // other type: no policy
    }

    #[tokio::test]
    async fn forbidden_statuses() {
        let g = Gate::<User>::new();
        let e = g.authorize(&user(1), "x", &()).await.unwrap_err();
        assert_eq!(e.into_response().status(), StatusCode::FORBIDDEN);
        assert_eq!(
            e.deny_as_not_found().into_response().status(),
            StatusCode::NOT_FOUND
        );
    }
}