dust

Authorization

Introduction

While authentication identifies who the current user is, authorization determines which actions they are permitted to perform. For example, in a blog application, any user may read a published post, while only its author may edit or delete it.

dust-framework organizes authorization rules into policies. Each policy is a struct whose methods define abilities (such as update or delete) for a specific model or resource. Because you pass the policy method itself when checking an ability, misspelled names or mismatched model types are caught at compile time:

rust
user.authorize(PostPolicy::update, &post).await?;

Writing policies

Define a policy by annotating an impl block with #[policy], typically on a unit struct named after the model. Each method accepts the user first, followed by the model (if applicable), and returns whether the action is allowed.

For example, suppose each Post model stores the author's user_id. This policy (placed in src/policies/post.rs, or directly alongside the model in src/models/post.rs) allows only the author to update or delete a post:

rust
use dust::auth::policy;use crate::models::{Post, User};pub struct PostPolicy;#[policy]impl PostPolicy {    pub fn update(user: &User, post: &Post) -> bool {        user.id == post.user_id    }    pub fn delete(user: &User, post: &Post) -> bool {        user.id == post.user_id    }}

If you define a policy alongside its model in src/models/post.rs, re-export it from src/models/mod.rs:

rust
// src/models/mod.rsmod post;mod user;pub use post::{Post, PostFactory, PostPolicy};pub use user::{User, UserFactory};

If you prefer keeping policies in their own src/policies directory, declare the policies module in src/lib.rs (as adding your own modules describes) and re-export each policy from src/policies/mod.rs:

rust
// src/lib.rspub mod policies;// src/policies/mod.rsmod post;pub use post::PostPolicy;

Name each method after the action it allows. The usual names are view_any, view, create, update, delete, restore, and force_delete, but you may add any ability your application needs.

Because #[policy] treats every function in the block as an ability, place shared helper functions in a separate impl block without #[policy]:

rust
#[policy]impl PostPolicy {    pub fn update(user: &User, post: &Post) -> bool {        Self::owns(user, post)    }    pub fn delete(user: &User, post: &Post) -> bool {        Self::owns(user, post)    }}impl PostPolicy {    fn owns(user: &User, post: &Post) -> bool {        user.id == post.user_id    }}

Policy responses

A policy method returning false denies the action with a 403 status and the default message "This action is unauthorized." To return a custom denial message instead, return an Access response using Access::allow() and Access::deny(..):

rust
use dust::auth::{Access, policy};#[policy]impl PostPolicy {    pub fn update(user: &User, post: &Post) -> Access {        if user.id == post.user_id {            Access::allow()        } else {            Access::deny("You do not own this post.")        }    }}

When you want to hide whether a record exists from unauthorized users (such as another team's private project), return Access::deny_as_not_found(), which responds with a 404 status instead of 403:

rust
#[policy]impl ProjectPolicy {    pub fn view(user: &User, project: &Project) -> Access {        if user.team_id == project.team_id {            Access::allow()        } else {            Access::deny_as_not_found()        }    }}

If you need a different HTTP status code altogether, call Access::deny_with_status(..), which responds with that status code and its standard reason phrase:

rust
Access::deny_with_status(401)

Abilities without a record

Some abilities don't involve a record yet, such as creating a post. Their methods take only the user. This one lets users create posts once they've verified their email:

rust
#[policy]impl PostPolicy {    pub fn create(user: &User) -> bool {        user.email_verified_at.is_some()    }    // ...}

Abilities that don't involve a specific model, such as viewing an admin dashboard, go in their own policy. For example, suppose your users have an is_admin column:

rust
use dust::auth::policy;use crate::models::User;pub struct AdminPolicy;#[policy]impl AdminPolicy {    pub fn view_dashboard(user: &User) -> bool {        user.is_admin    }}

Guests

By default, a policy method accepting &User automatically denies guests without running. To evaluate guests explicitly, accept Option<&User>, which receives None for unauthenticated visitors. For example, suppose posts have a published column so anyone may view published posts while only authors may view drafts:

rust
#[policy]impl PostPolicy {    pub fn view(user: Option<&User>, post: &Post) -> bool {        post.published || user.is_some_and(|user| user.id == post.user_id)    }    // ...}

Allowing administrators everything

Sometimes you may have administrators who are permitted to perform every action a policy covers. Rather than check is_admin in every method, add a before method. It takes the user and returns an Option<bool>:

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

The before method executes automatically before every other method in the policy:

  • Returning Some(true) immediately grants permission without running the requested ability method.
  • Returning Some(false) immediately denies permission.
  • Returning None falls through to the requested ability method (such as update or delete) so it can decide for itself.

Because before receives &User, it is skipped for unauthenticated guests, allowing guest-accessible methods that accept Option<&User> to evaluate guests directly.

If your before check needs to know which ability is being evaluated (for example, allowing administrators everything except permanently deleting posts), accept the method's name as a second &str parameter:

rust
#[policy]impl PostPolicy {    fn before(user: &User, ability: &str) -> Option<bool> {        if ability == "force_delete" {            return None;        }        user.is_admin.then_some(true)    }    // ...}

Asynchronous checks

When an authorization check needs to query the database, make the policy method async and return dust::Result. For example, this policy allows authors to delete a post only while it has no comments:

rust
use dust::auth::{Access, policy};use crate::models::{Comment, Post, User};#[policy]impl PostPolicy {    pub async fn delete(user: &User, post: &Post) -> dust::Result<Access> {        if user.id != post.user_id {            return Ok(Access::deny("You do not own this post."));        }        if Comment::query().filter(Comment::post_id.eq(post.id)).exists().await? {            return Ok(Access::deny("You can't delete a post with comments."));        }        Ok(Access::allow())    }    // ...}

If an asynchronous policy method returns an Err (such as from a failed database query), dust-framework fails the request with a 500 server error rather than treating it as an authorization denial.

Checking abilities

Once your policy is defined, check abilities in your handlers using authorize or can on your user type, passing the policy method followed by any additional arguments.

In a handler, extract the signed-in user with Authenticated<User> and resolve the target model via route model binding:

rust
use dust::prelude::*;use dust::view::View;use crate::models::{Post, User};use crate::policies::post::PostPolicy;pub async fn edit(    user: Authenticated<User>,    post: Post,) -> dust::Result<View> {    user.authorize(PostPolicy::update, &post).await?;    Ok(view("posts.edit", data! { post }))}pub async fn show(    user: Authenticated<User>,    post: Post,) -> dust::Result<View> {    let can_delete = user.can(PostPolicy::delete, &post).await?;    Ok(view("posts.show", data! { post, can_delete }))}

authorize returns an error when denied so ? aborts the handler with the configured status and message, while can returns a bool so you can branch on it yourself.

Call When the ability is denied
user.authorize(..) Returns an error with the policy's status, usually 403.
user.can(..) Returns false.
Access::deny("...") A 403 with that message.
Access::deny_as_not_found() A 404, hiding whether the record exists.
Access::deny_with_status(..) That status code and its standard reason phrase.

Both methods come from the Authorizable trait imported by the prelude and automatically implemented for every Authenticatable model.

For abilities that do not take a model or any additional arguments beyond the user (such as PostPolicy::create), pass () as the second argument:

rust
pub async fn create(user: Authenticated<User>) -> dust::Result<View> {    user.authorize(PostPolicy::create, ()).await?;    Ok(view("posts.create", data! {}))}

Authorizing via Auth or Request

When a route is accessible to guests as well as signed-in users, call can or authorize on Auth<User> or Request:

rust
use dust::auth::Auth;use dust::prelude::*;use dust::view::View;use crate::models::{Post, User};use crate::policies::post::PostPolicy;pub async fn show(auth: Auth<User>, post: Post) -> dust::Result<View> {    auth.authorize(PostPolicy::view, &post).await?;    Ok(view("posts.show", data! { post }))}pub async fn create(request: Request) -> dust::Result<View> {    request.authorize(PostPolicy::create, ()).await?;    Ok(view("posts.create", data! {}))}

Guests receive a 403 from authorize and false from can unless the policy method accepts Option<&User>.

Passing more arguments

A policy method may accept up to three additional arguments after the user when a decision depends on multiple models. For example, suppose an author may move a post into a Category only if that category is unlocked:

rust
use dust::auth::policy;use crate::models::{Category, Post, User};#[policy]impl PostPolicy {    pub fn move_to(user: &User, post: &Post, category: &Category) -> bool {        user.id == post.user_id && !category.locked    }    // ...}

Pass two or three arguments as a tuple, in the method's order:

rust
user.authorize(PostPolicy::move_to, (&post, &category)).await?;

Authorizing a form

A form type can authorize the incoming request automatically using #[validate(authorize(..))], so your handler does not need to call authorize itself. When the policy method expects a model (such as Post on a /posts/{post} route), pass route("post") to resolve that route parameter and pass the model to the policy:

rust
use dust::prelude::*;use crate::models::Post;use crate::policies::post::PostPolicy;#[dust::input]#[validate(authorize(PostPolicy::update, route("post")))]pub struct UpdatePost {    #[validate(required, max_length(255))]    title: String,}pub async fn update(post: Post, Valid(input): Valid<UpdatePost>) -> dust::Result<Redirect> {    // Only users who may update the post get here, with a valid title...    Ok(Redirect::back())}

Valid<UpdatePost> checks PostPolicy::update for the current user before it validates the input. A user who may not update the post gets the denial's response, not validation errors.

For an ability without a record, leave out the arguments, as in #[validate(authorize(PostPolicy::create))]. List several records in the method's order, as in authorize(PostPolicy::move_to, route("post"), route("category")).

Checking types other than users

A policy may decide abilities for a type other than your user, such as a team whose plan limits how many projects it has. Implement Authorizable for the type with an empty impl, and write the policy with the type first:

rust
use dust::auth::{Authorizable, policy};use crate::models::Team;impl Authorizable for Team {}pub struct ProjectPolicy;#[policy]impl ProjectPolicy {    pub fn create(team: &Team) -> bool {        team.projects_count < team.project_limit    }}

Then check the team as you would a user, such as in a handler for the route /teams/{team}/projects:

rust
pub async fn store(team: Team) -> dust::Result<Redirect> {    team.authorize(ProjectPolicy::create, ()).await?;    // ...}

Every method of a policy takes the same type first. To check abilities for both users and teams, write a policy for each.

Sharing abilities with the frontend

Your pages often need to know what the user may do, so they can hide an Edit button from someone who cannot edit. Check the abilities on the server and pass the results to your views or JSON responses. The HTML or JSON is only a convenience for the user: the route that performs the action must still call authorize, because anyone can send a request without your page.

In views

For server-rendered views, evaluate the abilities in your handler and pass them through data!:

rust
use dust::prelude::*;use dust::view::View;use crate::models::{Post, User};use crate::policies::post::PostPolicy;pub async fn show(user: Authenticated<User>, post: Post) -> dust::Result<View> {    let can = data! {        update => user.can(PostPolicy::update, &post).await?,        delete => user.can(PostPolicy::delete, &post).await?,    };    Ok(view("posts.show", data! { post, can }))}

Then branch on those booleans in your template:

html
{% if can.update %}    <a href="/posts/{{ post.id }}/edit">Edit</a>{% endif %}

For abilities that every template needs, share them for the current request with dust::view::share inside a middleware.

In JSON responses

For an API, include the abilities in the response body so the client can disable a button before it sends a request:

rust
use dust::prelude::*;use serde_json::{Value, json};use crate::models::{Post, User};use crate::policies::post::PostPolicy;pub async fn show(user: Authenticated<User>, post: Post) -> dust::Result<Json<Value>> {    let can = json!({        "update": user.can(PostPolicy::update, &post).await?,        "delete": user.can(PostPolicy::delete, &post).await?,    });    Ok(Json(json!({ "post": post, "can": can })))}

If the same abilities appear on many endpoints, compute them in a helper function or a middleware rather than repeating the checks. A hidden button does not protect an endpoint: a client that sees "delete": false may still send the request, so the route that deletes the post must call authorize.

Testing

To test a handler's authorization, send requests as different users with acting_as, and check each response:

rust
use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn only_the_author_may_update_a_post(app: Application) -> dust::Result<()> {    let author = create!(User {        name: "Taylor",        email: "taylor@example.com",        password: "password",    })    .await?;    let other = create!(User {        name: "Abigail",        email: "abigail@example.com",        password: "password",    })    .await?;    let post = create!(Post { user_id: author.id, title: "Hello", published: true }).await?;    app.put(format!("/posts/{}", post.id))        .acting_as(&other)        .json(json!({ "title": "Goodbye" }))        .await        .assert_forbidden()        .assert_json_path("message", "You do not own this post.");    app.put(format!("/posts/{}", post.id))        .acting_as(&author)        .json(json!({ "title": "Goodbye" }))        .await        .assert_redirect();    Ok(())}

A policy method is an ordinary function, so a unit test may also call it directly with records you build in the test, as in PostPolicy::update(&user, &post). before runs in a direct call too.