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};
pub type Arg = dyn Any + Send + Sync;
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>;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, thiserror::Error)]
#[error("this action is unauthorized")]
pub struct Forbidden {
not_found: bool,
}
impl Forbidden {
pub fn new() -> Self {
Self { not_found: false }
}
pub fn from_error<E: 'static>(e: &E) -> Option<Self> {
(e as &dyn std::any::Any).downcast_ref::<Self>().copied()
}
pub fn is_not_found(&self) -> bool {
self.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()
}
}
}
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 }
}
}
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()
}
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)))),
);
}
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));
}
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));
}
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,
}
}
pub async fn allows(&self, user: &U, ability: &str, arg: &Arg) -> bool {
self.resolve(user, ability, arg, arg.type_id()).await
}
pub async fn denies(&self, user: &U, ability: &str, arg: &Arg) -> bool {
!self.allows(user, ability, arg).await
}
pub async fn check(&self, user: &U, ability: &str, arg: &Arg) -> bool {
self.allows(user, ability, arg).await
}
pub async fn allows_for<M: 'static>(&self, user: &U, ability: &str) -> bool {
self.resolve(user, ability, &(), TypeId::of::<M>()).await
}
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())
}
}
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())
);
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); 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); assert!(!g.allows(&user(1), "publish", &p).await); 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); assert!(!g.allows(&user(1), "view", &"not a post").await); }
#[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
);
}
}