Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Permissions: rules and modes

Once rind knows who is asking (Authentication), and users can get a token (Signing in), each resource decides what that user may do. rind keeps two questions apart:

  • Who may do what? This is answered by the rules. A rule gives an action to a kind of user, such as “the staff may do everything” or “anyone may list”. When no rule gives the action, it is refused.
  • On which rows, and seeing which fields? This is answered by the modes. A mode is a query (the rows the user can reach) and a list of fields it hides.

In Django REST framework, the first question is the viewset’s permission_classes (IsAdminUser, IsAuthenticatedOrReadOnly…) and get_permissions() when they change per action. The second is get_queryset(), which filters the rows by request.user, and has_object_permission(). In rind, both are attributes on the resource, next to each other, and a third tool controls single fields wherever they appear: readable(..) on a serializer field.

A first example

Everyone may read the timetable of the railway, and only the staff changes it:

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/views.rs
#[derive(Resource)]
#[resource(model = Journey, path = "journeys", /* … */ actions)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, rooms))]
pub struct JourneyResource;
}

An anonymous client can list the journeys:

GET /journeys
{"nav": {…}, "results": [{"id": 1, "code": "…", …}, …]}

but cannot create one. Without credentials, the answer is 401:

POST /journeys
{"detail": "Authentication credentials were not provided or are invalid."}

A signed-in user who is not staff gets a 403 instead:

POST /journeys
Authorization: Bearer alice-token
{"detail": "You do not have permission to perform this action."}

Rules

A rule says who it is for, and, optionally, which actions it allows. Without actions(..), it allows all of them. A resource has at least one rule; a resource without any is a compile error, since nobody could call it.

The rules are read in order, and the first rule that accepts the request decides. The others are not read. In the example, a superuser is accepted by the first rule for every action; an anonymous request passes over the first two rules, and the third one accepts it for list, retrieve and rooms only.

A rule names one kind of user:

WhoAccepts
anyoneevery request, signed in or not
authenticatedany signed-in user
staffa user whose identity has is_staff
superusera user whose identity has is_superuser
group("…")a signed-in user in that group (by its slug)

staff does not include the superusers, just as DRF’s IsAdminUser only reads is_staff. This is why the sample always writes #[rule(superuser)] first.

group(..) takes one or more slugs, and a member of any of them is accepted: group("drivers", "controllers"). A slug may hold *, which stands for one or more lowercase letters or digits. A pattern with a * only has to match the start of the slug: group("depot_*") accepts depot_12 and depot_12_night, but not depot_ or my_depot_1.

The actions a rule names

The actions are the operations of a resource, list, retrieve, create, update, partial_update and destroy, and the resource’s own actions, by their name.

A name that the resource has no action of is a compile error, shown at the name:

error[E0080]: evaluation panicked: a rule of `ProducerResource` names `remove_logo`:
the resource has no such action (its operations, its `#[actions]`, its behaviours' actions)

The names rind knows are the resource’s operations, its #[actions] (when #[resource(actions)] plugs them in), and the actions of its behaviours (their ACTIONS: Flags gives add_flag, remove_flag and get_flags; Images gives add_image…).

Coming from Django: in Django, a misspelt action name in a permission check matches nothing, silently. In a real Django application, a rule named remove_logo for an action called unset_logo, and nobody noticed. rind refuses to compile it.

What no rule allows does not exist

When no rule accepts the request, it is refused: with a 401 when the request has no credentials, and with a 403 when it is a user’s.

So an action that no rule names is closed to everybody. In the sample, nobody but a superuser changes a reservation, because no other rule names update:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[rule(superuser, mode = ReservationMode::Full)]
#[rule(staff, actions(list, retrieve, create, destroy, cancel), mode = ReservationMode::Full)]
#[rule(authenticated, actions(list, retrieve, create, cancel), mode = ReservationMode::Own)]
}

DRF’s IsAuthenticatedOrReadOnly is written as two rules:

#![allow(unused)]
fn main() {
#[rule(authenticated)]
#[rule(anyone, actions(list, retrieve))]
}

Modes: the rows and fields a user gets

The rules above also give a mode. A mode answers the second question: on which rows does this request work, and which fields does it see? It is rind’s get_queryset().

The modes of a resource are an enum of your own. The resource names it with mode = …, and gives each value a query and, optionally, the fields it hides:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReservationMode {
    /// The staff: every reservation, every field.
    Full,
    /// A signed-in user: the reservations they made.
    Own,
}

#[derive(Resource)]
#[resource(model = Reservation, path = "reservations", /* … */ mode = ReservationMode)]
#[rule(superuser, mode = ReservationMode::Full)]
#[rule(staff, actions(list, retrieve, create, destroy, cancel), mode = ReservationMode::Full)]
#[rule(authenticated, actions(list, retrieve, create, cancel), mode = ReservationMode::Own)]
#[mode(ReservationMode::Full, query = Query::new())]
#[mode(ReservationMode::Own, query = Reservation::made_by(user), hide(booked_by))]
pub struct ReservationResource;
}

The staff gets Full: every row (Query::new()) and every field. A signed-in user gets Own: only the reservations they made, without the booked_by field.

Two rules hold once a resource has modes, and the compiler checks both: every rule gives a mode (mode = …), and every value of the enum has its #[mode(..)] with a query = ….

In the query, user is the request’s Identity, and ctx is the request’s context. You do not unwrap an Option: when the request is anonymous, a query that names user matches no row.

An object outside the mode does not exist

Everything the resource does for the request happens inside the mode’s query: the list, the count, the filters, and each object. An object outside the query does not exist for that user. GET, PATCH, DELETE and the actions on it answer 404, not 403, so that the user learns nothing about what they cannot see. Reservation 1 of the sample was made by Alice, so Bob gets:

GET /reservations/1
Authorization: Bearer bob-token
{"detail": "Not found."}

The same holds after a write. A request may not create or change an object into something it could not see: the object is read again through the mode’s query, inside the write’s transaction. When it is not there, the write is refused with a 403 and rolled back.

Coming from Django: there is no has_object_permission(). What a user may touch is the query of their mode. A check that depends on the object’s values goes into that query, or into a hook of the write.

Hiding fields

A field in hide(..) is neither read from the database nor sent. If the client asks for it with ?fields=, it is simply absent. hide(..) also takes paths, for a field inside a nested one: hide(client_details.siret).

A query that depends on the action

A mode’s query is used by every action: the list, the retrieve, the object that a write or a detail action changes, and the object read again after a write. Sometimes you want a different query for some of them. ctx.action() says which action runs: Some("list"), "retrieve", "create", "update", "partial_update", "destroy", or the name of an #[action]. It is None outside a resource’s action (a job, a test’s context, a plugin’s route).

The sample’s users do not see their cancelled reservations in their list, but a link to one still answers:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[mode(ReservationMode::Own, query = own(ctx, user), hide(booked_by))]

fn own(ctx: &Ctx, user: &Identity) -> Query<Reservation> {
    let made = Reservation::made_by(user);
    match ctx.action() {
        Some("list") => made.filter(Reservation::status().ne(reservation_status::CANCELLED)),
        _ => made,
    }
}
}

Think of each arm as the rows its actions may touch. Here cancel falls in _, because it must find a cancelled reservation, to answer that it is already cancelled.

Be careful when you widen a query. Rows that are only for reading go to "retrieve" by name, never to _, so that no write reaches them. Since a write reads its object through the same query, a query that widens for retrieve only does not widen what can be changed.

In Django, this is the viewset’s get_queryset() reading self.action.

Scopes: queries on the model

The queries of the modes are best written as the model’s own scopes: plain functions that return a query, and that are easy to test without HTTP:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-models/src/lib.rs
impl Reservation {
    /// The reservations a user made.
    pub fn made_by(user: &Identity) -> Query<Reservation> {
        Query::new().filter(Reservation::booked_by_id().eq(user.id))
    }
}
}

They take the place of Django’s custom managers, such as Reservation.objects.readable(request). A scope can be as rich as the query layer: through relations, through groups, through a table of permissions per object. With data the authenticator attached to the identity, it needs no query of its own to know what the user manages (Carrying more than the flags).

A resource without modes

A resource that shows the same rows to everyone it accepts does not need modes. It may still give one base query, #[resource(query = …)], which works like a single mode’s query: if it names user, an anonymous request sees no row (Resources).

Who may read a field

A mode hides fields from one resource. Sometimes a field is not for every user, whichever resource sends it. The field then says so on the serializer, with readable(..):

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/serializers.rs
/// Its train: staff only.
#[field(name = "train", readable(staff))]
pub train_id: Option<i64>,
}

readable(..) takes one or more of staff, superuser, authenticated, group = "pattern" (which may be given several times), and with = function for a rule of your own, a fn(Option<&Identity>) -> bool. Any one of them is enough to read the field.

The rule holds wherever the serializer goes out: in its own resource, and in every nested field that shows it. Here, WagonOut is the serializer of the wagons inside a train (wagons_details), and a user who is not staff does not get their train.

A field the user may not read is absent, not an error. One request can serve every user, and each gets what they may read. The field is neither read nor sent, and the fields it implies(..) are not selected through it.

Coming from Django: DRF has no built-in field-level permission; one usually overrides to_representation() or get_fields(). Here it is one attribute.

Reference

#[rule(..)]

PartMeaning
anyone, authenticated, staff, superuserwho the rule accepts (exactly one per rule)
group("slug", …)a member of any of these groups; * matches one or more of [a-z0-9], and a pattern with * matches the start of the slug
actions(name, …)the actions it allows; all of them when absent. Each name is checked at compile time
mode = Mode::Valuethe mode it gives; required once the resource has mode = …

The rules are read in order, and the first that accepts decides. The OpenAPI document lists, for each operation, who may run it (x-allowed).

#[mode(..)]

PartMeaning
Mode::Value (first)the value of the mode enum this attribute describes
query = …the rows of the mode (required). user and ctx are in scope
hide(field, nested.field, …)fields neither read nor sent

readable(..) on a serializer field

PartAccepts
staff, superuser, authenticatedas in the rules
group = "pattern"a member of a group matching it; may be repeated
with = functiona fn(Option<&Identity>) -> bool of the application

What a client is answered

The request…is answered
has no credentials, and no rule accepts it401
is a user’s, and no rule accepts it403
is accepted, but the object is outside the mode’s query404
writes an object that ends up outside the mode’s query403, and the write is rolled back

What is not there

  • No per-model permissions as in Django’s auth_permission table (booking.add_reservation, DRF’s DjangoModelPermissions): use groups and rules.
  • No has_object_permission(): use the mode’s query or a hook.