laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::sync::atomic::{AtomicUsize, Ordering};

use laravel::auth::{Access, Auth, Authenticatable, Authenticated, Authorizable, RememberToken, UserProvider, policy};
use laravel::hash::PasswordHash;
use laravel::routing::{Bound, RouteModel};
use laravel::testing::prelude::*;
use laravel::validation::{Valid, Validate};
use serde::Deserialize;
use serde_json::json;

#[derive(Clone, Debug, Authenticatable)]
struct User {
    id: u64,
    is_admin: bool,
    password: Option<PasswordHash>,
    remember_token: Option<RememberToken>,
}

fn user(id: u64) -> User {
    User {
        id,
        is_admin: id == 9,
        password: None,
        remember_token: None,
    }
}

struct Users;

impl UserProvider for Users {
    type User = User;

    async fn find(&self, id: &u64) -> laravel::Result<Option<User>> {
        Ok(Some(user(*id)))
    }

    async fn find_for_login(&self, _: &str) -> laravel::Result<Option<User>> {
        Ok(None)
    }

    async fn update_password(&self, _: &User, _: &PasswordHash) -> laravel::Result<()> {
        Ok(())
    }

    async fn update_remember_token(&self, _: &User, _: &str) -> laravel::Result<()> {
        Ok(())
    }
}

#[derive(Clone, Debug)]
struct Post {
    id: u64,
    user_id: u64,
    published: bool,
}

/// Posts 1 and 2, by users 1 and 2. Only post 2 is published.
#[derive(Default)]
struct Posts {
    finds: AtomicUsize,
}

impl RouteModel for Post {
    const PARAMETER: &'static str = "post";
    type Key = u64;

    async fn find(id: u64) -> laravel::Result<Option<Self>> {
        let posts = laravel::resolve::<Posts>().await?;
        posts.finds.fetch_add(1, Ordering::SeqCst);

        Ok((1..=2).contains(&id).then_some(Post {
            id,
            user_id: id,
            published: id == 2,
        }))
    }
}

#[derive(Clone)]
struct Category {
    locked: bool,
}

impl RouteModel for Category {
    const PARAMETER: &'static str = "category";
    type Key = String;

    async fn find(slug: String) -> laravel::Result<Option<Self>> {
        Ok(Some(Category { locked: slug == "news" }))
    }
}

struct PostPolicy;

#[policy]
impl PostPolicy {
    fn before(user: &User) -> Option<bool> {
        user.is_admin.then_some(true)
    }

    fn view(user: Option<&User>, post: &Post) -> bool {
        post.published || user.is_some_and(|user| user.id == post.user_id)
    }

    fn update(user: &User, post: &Post) -> Access {
        if user.id == post.user_id {
            Access::allow()
        } else {
            Access::deny("You do not own this post.")
        }
    }

    async fn delete(user: &User, post: &Post) -> laravel::Result<Access> {
        let posts = laravel::resolve::<Posts>().await?;
        let _ = posts.finds.load(Ordering::SeqCst);

        Ok(if user.id == post.user_id {
            Access::allow()
        } else {
            Access::deny_as_not_found()
        })
    }

    async fn move_to(user: &User, post: &Post, category: &Category) -> bool {
        user.id == post.user_id && !category.locked
    }
}

#[derive(Deserialize, Validate)]
#[validate(authorize(PostPolicy::update, route("post")))]
struct UpdatePost {
    #[validate(required, max_length = 10)]
    title: String,
}

#[derive(Deserialize, Validate)]
#[validate(authorize(PostPolicy::move_to, route("post"), route("category")))]
struct MovePost {}

#[derive(Deserialize, Validate)]
#[validate(authenticated)]
struct UpdateName {
    #[validate(required)]
    name: String,
}

async fn show(auth: Auth<User>, Bound(post): Bound<Post>) -> laravel::Result<String> {
    auth.authorize(PostPolicy::view, &post).await?;

    Ok(format!("Post {}", post.id))
}

async fn update(Bound(post): Bound<Post>, Valid(input): Valid<UpdatePost>) -> String {
    format!("Post {} is now {}", post.id, input.title)
}

async fn destroy(user: Authenticated<User>, Bound(post): Bound<Post>) -> laravel::Result<String> {
    user.authorize(PostPolicy::delete, &post).await?;

    Ok(format!("Deleted post {}", post.id))
}

async fn move_post(Valid(_): Valid<MovePost>) -> &'static str {
    "Moved"
}

async fn update_name(Valid(input): Valid<UpdateName>) -> String {
    format!("Renamed to {}", input.name)
}

fn app() -> Application {
    Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_services(|app| {
            app.instance(Users);
            app.instance(Posts::default());
        })
        .with_auth(|auth, _| {
            auth.session::<Users>();
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.get("/posts/{post}", show);
                route.put("/posts/{post}", update);
                route.delete("/posts/{post}", destroy);
                route.put("/posts/{post}/categories/{category}", move_post);
                route.put("/name", update_name);
            });
        })
        .create()
}

async fn finds(app: &Application) -> usize {
    app.resolve::<Posts>().await.finds.load(Ordering::SeqCst)
}

#[tokio::test]
async fn handlers_authorize_bound_records_with_the_policys_response() {
    let app = app();

    app.delete("/posts/1")
        .acting_as(&user(1))
        .await
        .assert_ok()
        .assert_see("Deleted post 1");
    app.delete("/posts/1").acting_as(&user(2)).await.assert_not_found();
    app.delete("/posts/1").acting_as(&user(9)).await.assert_ok();
    app.delete("/posts/3").acting_as(&user(1)).await.assert_not_found();
    app.delete("/posts/first").acting_as(&user(1)).await.assert_not_found();
}

#[tokio::test]
async fn abilities_that_take_an_optional_user_run_for_guests() {
    let app = app();

    app.get("/posts/2").await.assert_ok().assert_see("Post 2");
    app.get("/posts/1")
        .header("accept", "application/json")
        .await
        .assert_forbidden()
        .assert_json_path("message", "This action is unauthorized.");
    app.get("/posts/1").acting_as(&user(1)).await.assert_ok();
}

#[tokio::test]
async fn form_types_authorize_with_a_policy_before_validating() {
    let app = app();

    app.put("/posts/1")
        .acting_as(&user(2))
        .json(json!({ "title": "" }))
        .await
        .assert_forbidden()
        .assert_json_path("message", "You do not own this post.");
    app.put("/posts/1")
        .json(json!({ "title": "Hello" }))
        .await
        .assert_forbidden()
        .assert_json_path("message", "This action is unauthorized.");
    app.put("/posts/1")
        .acting_as(&user(1))
        .json(json!({ "title": "" }))
        .await
        .assert_status(422)
        .assert_invalid(&["title"]);

    let before = finds(&app).await;
    app.put("/posts/1")
        .acting_as(&user(1))
        .json(json!({ "title": "Hello" }))
        .await
        .assert_ok()
        .assert_see("Post 1 is now Hello");
    assert_eq!(
        finds(&app).await - before,
        1,
        "`authorize` and `Bound` share one lookup"
    );

    app.put("/posts/3")
        .acting_as(&user(1))
        .json(json!({ "title": "Hello" }))
        .await
        .assert_not_found();
}

#[tokio::test]
async fn form_types_pass_several_records_to_a_policy() {
    let app = app();

    app.put("/posts/1/categories/rust")
        .acting_as(&user(1))
        .await
        .assert_ok()
        .assert_see("Moved");
    app.put("/posts/1/categories/news")
        .acting_as(&user(1))
        .await
        .assert_forbidden();
    app.put("/posts/1/categories/news")
        .acting_as(&user(9))
        .await
        .assert_ok();
}

#[tokio::test]
async fn authenticated_form_types_reject_guests_before_validating() {
    let app = app();

    app.put("/name")
        .json(json!({ "name": "" }))
        .await
        .assert_status(401)
        .assert_json_path("message", "Unauthenticated.");
    app.put("/name")
        .acting_as(&user(2))
        .json(json!({ "name": "" }))
        .await
        .assert_status(422)
        .assert_invalid(&["name"]);
    app.put("/name")
        .acting_as(&user(2))
        .json(json!({ "name": "Taylor" }))
        .await
        .assert_ok()
        .assert_see("Renamed to Taylor");
}

#[derive(Clone)]
struct Team {
    projects: usize,
    plan_limit: usize,
}

impl Authorizable for Team {}

struct ProjectPolicy;

#[policy]
impl ProjectPolicy {
    fn before(team: &Team, ability: &str) -> Option<bool> {
        (matches!(ability, "create" | "move") && team.plan_limit == usize::MAX).then_some(true)
    }

    fn create(team: &Team) -> bool {
        team.projects < team.plan_limit
    }

    fn r#move(_team: &Team) -> bool {
        false
    }

    fn transfer(team: &Team, projects: usize, to: &Team) -> laravel::Result<bool> {
        Ok(team.projects >= projects && to.projects + projects <= to.plan_limit)
    }
}

#[tokio::test]
async fn types_other_than_users_check_their_own_policies() {
    let full = Team {
        projects: 3,
        plan_limit: 3,
    };
    let unlimited = Team {
        projects: 3,
        plan_limit: usize::MAX,
    };

    assert!(!full.can(ProjectPolicy::create, ()).await.unwrap());
    assert!(unlimited.can(ProjectPolicy::create, ()).await.unwrap());
    assert!(!full.can(ProjectPolicy::r#move, ()).await.unwrap());
    assert!(
        unlimited.can(ProjectPolicy::r#move, ()).await.unwrap(),
        "`before` sees a raw identifier's plain name"
    );
    assert!(full.can(ProjectPolicy::transfer, (2, &unlimited)).await.unwrap());
    assert!(!unlimited.can(ProjectPolicy::transfer, (1, &full)).await.unwrap());
    assert_eq!(
        full.authorize(ProjectPolicy::create, ()).await.unwrap_err().status(),
        403
    );
    assert!(
        ProjectPolicy::create(&unlimited),
        "`before` runs when the method is called directly"
    );
}