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

Policy, auth, tenancy

Three layers decide what a request may do. Authentication decides who is signed in. Tenancy limits a signed-in user to the rows of the tenant they act for. Policy — the resource’s ResourceDef::policy — decides what that user may do with each resource and record.

Policy

A policy answers one Ability at a time. The default policy is Deny, so a new resource exposes nothing until you allow it. Abilities declares who may do what, one ability per method, and refuses every ability it does not declare:

#![allow(unused)]
fn main() {
use tablo::prelude::*;

impl Resource for UserResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .policy(
                Abilities::<User>::new()
                    .view_any(|_cx| true)
                    .view(|_cx, _user| true)
                    .create(is_admin)
                    .update(|_cx, user| !user.sso_managed)
                    .delete(|cx, _user| is_admin(cx)),
                // No restore or action: each is refused until the policy declares it.
            )
    }
}
}

Each Ability variant names one thing a user may do: list, view, create, update, delete, restore, run an action. Its page says which pages and POSTs ask it.

A closure policy matches the variants itself. RunAny and Run carry action, the action’s NAME, so one policy tells a resource’s actions apart. ability.is_action::<Publish, _>() asks whether the ability is RunAny or Run for the action type Publish, so renaming the action’s NAME cannot leave a policy matching the old string:

#![allow(unused)]
fn main() {
pub fn post_policy(cx: &Cx, ability: Ability<'_, Post>) -> bool {
    match ability {
        Ability::ViewAny | Ability::View(_) => true,
        // `Publish` is the action's type, so renaming its `NAME` keeps this arm matching.
        _ if ability.is_action::<Publish, _>() => editors_only(cx),
        _ => false,
    }
}
}

The _ is the resource, inferred when the action belongs to one. A header action, which runs on no record, is asked RunHeader, which ability.is_header_action::<A>() matches.

Three rules shape every policy; Policy lists the rest:

  • Handlers ask what buttons ask. A hidden button is also a refused request, answered 403.
  • Reading rows asks ViewAny only. The list, the export, related tables and relationship choices show every row of the resource’s query. A policy is Rust code that cannot run in the database, and filtering rows after the query would leave pages short and counts wrong. Rows a user must not see belong out of ResourceDef::query; see Resources. View decides who opens a record: a list row it refuses shows without its actions.
  • Writes are checked against the stored row, loaded inside the write’s transaction, never against the submitted key.

The policy sees the row as stored, never what the submission writes over it. Who may change a field at all is field access: its edit rule disables the control and keeps the stored value. A rule about the values a write stores, such as who may set a post to published, belongs in Resource::before_commit, which receives the Change inside the write’s transaction: a Change::Create with the new row, a Change::Update with before and after, and a custom action’s Change::Action with each row’s before and after, so the same rule covers an action that publishes. before_commit’s Err rolls the write back:

#![allow(unused)]
fn main() {
/// Refuses a write that publishes a post unless an editor makes it. Called from
/// `PostResource::before_commit`, it sees what the write stores, which the policy does not.
pub async fn only_editors_publish(cx: &Cx, change: &tablo::Change<Post>) -> Result<()> {
    let published = |post: &Post| matches!(post.status, PostStatus::Published);
    let publishes = match change {
        tablo::Change::Create(post) => published(post),
        tablo::Change::Update { before, after } => !published(before) && published(after),
        tablo::Change::Action { records, .. } => records
            .iter()
            .any(|acted| !published(&acted.before) && acted.after.as_ref().is_some_and(published)),
        _ => false,
    };
    if publishes && !editors_only(cx) {
        return Err(topcoat::router::error::forbidden().into());
    }
    Ok(())
}
}

Building a policy

Allow, Deny, ReadOnly (ViewAny and View, no Export) and when(predicate) are policies, and each combines with another through and and or. when allows every ability while a predicate on the request holds, which suits a rule about the user or the tenant that several resources share. The rule reads the app’s own user type, Staff here (see Your own user table):

#![allow(unused)]
fn main() {
pub fn editors_only(cx: &Cx) -> bool {
    tablo::auth::user::<Staff>(cx).is_some_and(|staff| staff.editor)
}

impl Resource for PostResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .policy(ReadOnly.or(when(editors_only)))
    }
}

impl Resource for AuthorResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .policy(when(editors_only))
    }
}
}

A closure ending in _ => true allows every ability it does not name: the restore a soft delete adds, an action declared later, any ability a later Tablo release adds. Prefer Abilities, which refuses those, or name every variant so that a new one fails to compile. Abilities declares an action’s check with run::<A, _>:

#![allow(unused)]
fn main() {
pub fn post_abilities() -> Abilities<Post> {
    Abilities::<Post>::new()
        .view_any(|_cx| true)
        .view(|_cx, _post| true)
        .create(editors_only)
        .update(|cx, post| editors_only(cx) && post.status != PostStatus::Published)
        .run::<Publish, _>(|cx, _post| editors_only(cx))
    // No delete: `DeleteAny` and `Delete` are refused, and so is any action added later.
}
}

A write’s record check also allows the write at all, and view does not allow ViewAny: Abilities has the rules for each method. A header action is declared with run_header::<A>.

A policy that allows everything but some writes reads ability.written_record(), the record an update, delete, restore, force delete or record action’s run writes, so a record action the resource gains later is refused too. Create and RunHeader write no record they are handed and answer None; a policy that must refuse them matches them by name:

#![allow(unused)]
fn main() {
pub fn unfeatured_only(_cx: &Cx, ability: Ability<'_, Post>) -> bool {
    // Refuses an update, a delete, a restore, a force delete or a record action's run on a
    // featured post, and allows every other ability: a create or a header action writes no
    // existing record, so a policy that refuses those matches them by name.
    ability.written_record().is_none_or(|post| !post.featured)
}
}

policy takes any type that implements Policy<M>, Abilities among them, and policy_fn takes a closure |cx, ability| -> bool. Within declare, the def learns its resource from the return type only after the closure is checked, so a closure that reads the record names the ability’s type, ability: Ability<'_, User>, or the chain starts from ResourceDef::<Self>::new().

Loading what a policy reads

A policy is asked once per row and once per button, so it does not await: it reads the request. What it needs beyond the signed-in user, such as a plan’s limit or a count, the panel loads once for the request with Panel::load, and loaded::<T>(cx) reads it back:

#![allow(unused)]
fn main() {
/// How many posts the request's workspace holds, counted once for the request.
pub struct PostCount(pub usize);

impl tablo::Load for PostCount {
    async fn load(cx: &Cx) -> Result<Self> {
        let Some(workspace) = tablo::tenant_id(cx) else {
            return Ok(Self(0));
        };
        let mut db = tablo::db::db(cx)?;
        let posts = Post::filter(Post::fields().tenant_id().eq(workspace))
            .exec(&mut db)
            .await?;
        Ok(Self(posts.len()))
    }
}

/// Offers Create while the workspace holds fewer than ten posts.
pub fn under_quota(cx: &Cx) -> bool {
    tablo::loaded::<PostCount>(cx).is_some_and(|count| count.0 < 10)
}

pub fn quota_panel() -> Panel {
    Panel::new("admin").load::<PostCount>()
}
}

load runs after the auth gate admitted the request, so it reads the user and the tenant the request acts for. It runs on every request the panel answers, the runtime requests of its pages included: keep it to one or two statements. loaded answers None on a panel that does not load the type and on a signed-out page, which a policy reads as a refusal. A query_fn, a when predicate and a column’s or an action’s condition read it the same way.

A policy hides the button; a limit that must hold under two concurrent writes is checked again in Resource::create_record or before_commit, inside the write’s transaction.

In your own code

can::<R>(cx, ability) asks R’s policy, for a page or route that renders or writes R’s records itself. can_list::<R>(cx) answers whether the request may open R’s list: the panel’s sign-in, R’s tenant, and ViewAny, the checks the list handler makes. A dashboard that links to lists checks it before rendering each link.

A page, route or shard the app serves under a panel calls auth::guard(cx)? to require the panel’s signed-in user exactly as the panel’s own pages do. A shard needs it: Topcoat serves shards at its runtime path, where the page’s checks do not run. The panel declares the shards and procedures its pages use with Panel::endpoint, so they run as that panel.

A form route verifies the CSRF token it posted under csrf::FIELD_NAME with csrf::verify(cx, token).

Authentication

Authentication is on by default. The built-in login checks an email and password against the AdminUser table and keeps sessions in the AuthSession table. tablo::models! registers both beside the app’s models; create a user with auth::create_admin, which stores the password’s hash:

#![allow(unused)]
fn main() {
pub fn auth_models() {
    // `Book`, beside `AdminUser`, `AuthSession`, `ColumnPreference`, `AuthToken` and `AuthFactor`.
    let _ = tablo::models!(crate::Book);
}
}

A panel whose lists declare toggleable columns also keeps each user’s choice in the ColumnPreference table. A feature that mails links, such as a password reset, keeps its tokens in AuthToken, and two-factor sign-in its factors in AuthFactor; tablo::models! registers all three. An app listing its models with toasty::models! lists these too, and the mount names any it misses. Toasty names a table after its model, so an app with a model named as one of Tablo’s, such as its own AdminUser, lists its models that way.

#![allow(unused)]
fn main() {
pub async fn seed_admin(mut db: toasty::Db) -> Result<()> {
    // Stores the password's Argon2id hash, never the plaintext.
    tablo::auth::create_admin(&mut db, "admin@example.com", "secret", "Admin").await?;
    Ok(())
}

/// Your own user table hashes with the same function.
pub async fn staff_hash() -> Result<String> {
    tablo::auth::hash_password("secret").await
}
}

Your first panel shows the complete setup.

What a request gets

RequestSigned in with panel accessSigned in without panel accessNot signed in
GET of a panel pagethe page, or its error page403 page with Sign outredirect to /admin/login?next=…
any other panel requesthandled403401
/_topcoat/runtimehandled403401

After login, the user returns to next, which must be a same-origin path. A user has panel access when their AdminUser.active is true. The gate covers only the panel prefix and /_topcoat/runtime; routes elsewhere, including your app’s own routes and directories served with Panel::serve_dir, are public — a directory served under the panel prefix is the exception, since the gate covers the prefix. Panel::uploads_dir answers only at the signed URLs the panel’s pages render. On a router with several panels, /_topcoat/runtime answers 401 without a session only when every panel is gated.

  • Login verifies Argon2id hashes and treats an email’s case as insignificant; each login may make five attempts a minute from one address, which Auth::throttle changes; Auth::account_throttle adds an opt-in limit per login across addresses (Security). PasswordAuth has the details, and what to do about rows stored with capitals.
  • Sessions are rows in AuthSession, valid for seven days, and each belongs to the panel that signed the user in: a user signed in to /admin is anonymous on /portal. A back office usually wants less: Auth::sessions(Sessions::new().lifetime(..).idle_timeout(..)) shortens the lifetime and ends a session nobody uses (Sessions). AuthSession has the rules and the columns it needs.
  • Revoking. Call auth::revoke_sessions_for_user(cx, user_id) when a user’s password changes or their account is deactivated; otherwise existing sessions stay valid until they expire.

Read the signed-in user in your own code as your user type: auth::user::<AdminUser>(cx) returns Option<&AdminUser>, and auth::require_user::<AdminUser>(cx)? answers the request as the table above when nobody is signed in. auth::signed_in(cx) answers whether anyone is.

Your own user table

A table that signs in by email and password needs no seam of its own. Implement PasswordAccount for the model: four lenses name its name, email, password hash and verification time, and sign_in turns a row into the user the panel signs in, here the member with their workspaces:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model)]
pub struct Member {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub name: String,
    #[unique]
    pub email: String, // stored lowercase
    pub password_hash: String,
    pub email_verified_at: Option<jiff::Timestamp>,
    pub active: bool,
}

pub struct SignedMember {
    pub member: Member,
    pub workspaces: Vec<Membership>,
}

impl PanelUser for SignedMember {
    fn user_id(&self) -> String {
        self.member.id.to_string() // the key, as its `Display` spells it
    }
    fn display_name(&self) -> &str {
        &self.member.name
    }
    fn email(&self) -> Option<&str> {
        Some(&self.member.email)
    }
    fn can_access_panel(&self, _panel: &tablo::PanelId) -> bool {
        true
    }
    fn tenants(&self) -> &[Membership] {
        &self.workspaces
    }
}

impl PasswordAccount for Member {
    type User = SignedMember;

    fn name() -> Lens<Self, String> {
        lens!(Member.name)
    }
    fn email() -> Lens<Self, String> {
        lens!(Member.email)
    }
    fn password_hash() -> Lens<Self, String> {
        lens!(Member.password_hash)
    }
    fn email_verified_at() -> Lens<Self, Option<jiff::Timestamp>> {
        lens!(Member.email_verified_at)
    }
    fn account(user: &SignedMember) -> &Member {
        &user.member
    }
    async fn sign_in(
        self,
        _cx: &Cx,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Option<SignedMember>> {
        if !self.active {
            return Ok(None); // its login fails and its sessions end
        }
        let workspaces = member_workspaces(ex, &self).await?;
        Ok(Some(SignedMember {
            member: self,
            workspaces,
        }))
    }
}
}

PasswordAuth::<Member> is then the panel’s authenticator, and its profile editor, password resetter and email verifier too:

#![allow(unused)]
fn main() {
pub fn member_panel(mail: AuthMail) -> Panel {
    let members = PasswordAuth::<Member>::default();
    Panel::new("app").auth(
        Auth::custom(members)
            .profile(members)
            .mail(mail)
            .password_reset(PasswordReset::new(members))
            .email_verification(EmailVerification::new(members)),
    )
}
}

It signs in, edits, resets and verifies as it does for AdminUser, and stores each email trimmed and lowercased, so a sign-up that writes the table stores it as auth::normalize_email spells it. A resource’s edit form that changes a member’s email or password hash ends their sessions, as it does an admin’s. PasswordAccount lists its hooks: a profile change the app refuses, and where a picked locale is stored.

A table that signs in some other way implements PanelUser for the type the panel signs in, and Authenticator to load it:

#![allow(unused)]
fn main() {
use tablo::{Authenticator, Membership, PanelUser, auth::verify_password};

pub struct SignedStaff {
    pub staff: Staff, // your model
    pub workspaces: Vec<Membership>,
}

impl PanelUser for SignedStaff {
    fn user_id(&self) -> String {
        self.staff.id.to_string()
    }
    fn display_name(&self) -> &str {
        &self.staff.name
    }
    fn can_access_panel(&self, _panel: &tablo::PanelId) -> bool {
        self.staff.active
    }
    fn tenants(&self) -> &[Membership] {
        &self.workspaces
    }
}

pub struct StaffAuth;

impl Authenticator for StaffAuth {
    type User = SignedStaff;

    async fn verify(&self, cx: &Cx, login: &str, password: &str) -> Result<Option<SignedStaff>> {
        let staff = find_staff_by_email(cx, login).await?;
        if !verify_password(password, staff.as_ref().map(|s| s.password_hash.as_str())).await {
            return Ok(None);
        }
        // … load the memberships and return Some(SignedStaff { .. })
        todo!()
    }

    async fn find_by_id(&self, _cx: &Cx, _id: &str) -> Result<Option<SignedStaff>> {
        // … the same user and memberships, by `user_id`
        todo!()
    }
}

pub async fn find_staff_by_email(_cx: &Cx, _login: &str) -> Result<Option<Staff>> {
    todo!()
}
}
#![allow(unused)]
fn main() {
pub fn staff_auth_panel() -> Panel {
    Panel::new("admin").auth(Auth::custom(StaffAuth))
}
}
  • The user type is yours. It need not be a model: the showcase’s SignedStaff is a row plus the workspaces it holds a seat in. auth::user::<SignedStaff>(cx) reads it back, fields and all, and answers None on a panel whose authenticator loads another type.
  • verify checks credentials. Return Ok(None) for every credential failure. verify_password checks an Argon2id hash and, given None for an unknown account, does the same work, so response times do not reveal which accounts exist. It and hash_password run on Tokio’s blocking pool, so await them rather than hashing on the request’s task.
  • find_by_id reloads the user on every request, so deactivating a user or removing a membership takes effect immediately.
  • time_zone names the zone the user reads and enters times in, such as one they pick on their profile page and the app stores; it defaults to the panel’s. See Time zones.
  • locale names the locale the user reads the panel in; it defaults to the browser’s best match. See Translations.

Sessions stay in AuthSession, which tablo::models! registers. It registers the shipped AdminUser too, which only PasswordAuth::new() reads: with another authenticator its table stays empty.

An app with a sign-in of its own, such as SSO, keeps it through Auth::external: see Adding a panel to an existing app.

Sign-up

Auth::registration lets visitors create their own account at {prefix}/register, which the login page links to. PasswordSignUp registers an AdminUser from a name, an email address and a password typed twice:

#![allow(unused)]
fn main() {
pub fn open_sign_up_panel() -> Panel {
    Panel::new("admin").auth(Auth::password().registration(PasswordSignUp::pending()))
}
}

PasswordSignUp::pending stores each account inactive: the sign-up lands on the login page, and the account signs in once an administrator sets active. PasswordSignUp::open stores it active and signs it in at once, and an active AdminUser may open the whole panel, so choose it only where any visitor may hold an account.

Your own user table registers through a Registrar beside its Authenticator, which works like an action with input: Input is the form the page asks for, validate refuses a submission field by field, and register writes the account. Both run in one transaction the framework opens:

#![allow(unused)]
fn main() {
#[derive(FormInput)]
pub struct StaffSignUp {
    pub name: String,
    #[form(email)]
    pub email: String,
    #[form(password)]
    pub password: String,
    #[form(password, label = "Confirm password")]
    pub password_confirmation: String,
}

impl Registrar for StaffAuth {
    type Input = StaffSignUp;
    type User = SignedStaff;

    async fn validate(
        &self,
        _cx: &Cx,
        sign_up: &StaffSignUp,
        ex: &mut dyn toasty::Executor,
    ) -> Result<FieldErrors> {
        let mut errors = new_password_errors(&sign_up.password, &sign_up.password_confirmation);
        if email_taken(ex, &sign_up.email).await? {
            errors.add_field("email", "Email has already been taken");
        }
        Ok(errors)
    }

    async fn register(
        &self,
        _cx: &Cx,
        sign_up: StaffSignUp,
        ex: &mut dyn toasty::Executor,
    ) -> Result<SignedStaff> {
        let hash = hash_password(&sign_up.password).await?;
        let staff = create_staff(ex, &sign_up.name, &sign_up.email, &hash).await?;
        Ok(SignedStaff {
            staff,
            workspaces: Vec::new(),
        })
    }
}
}
#![allow(unused)]
fn main() {
pub fn staff_sign_up_panel() -> Panel {
    Panel::new("admin").auth(Auth::custom(StaffAuth).registration(StaffAuth))
}
}

Auth::registration lists how the form posts, where the visitor lands after the commit, what the mount refuses and how sign-ups are throttled. The sign-up page tells a visitor whether an email is taken, which the login page never does.

Profile

Auth::profile adds a profile page at {prefix}/profile, which the user menu links to, where the signed-in user edits their own account. PasswordAuth edits an AdminUser’s name, email address and password:

#![allow(unused)]
fn main() {
pub fn profile_panel() -> Panel {
    Panel::new("admin").auth(Auth::password().profile(PasswordAuth::new()))
}
}

It asks for the current password before the email or the password changes, refuses a new password new_password_errors refuses and, once the current password verifies, an email another account holds, and leaves the password as it is when the new-password field is blank.

A PasswordAccount table edits through its PasswordAuth as above. Another table edits through a ProfileEditor beside its Authenticator, which works like a Registrar: fill seeds the form from the signed-in user, validate refuses a submission field by field, and save writes it. validate and save run in one transaction the framework opens. The shipped Profile input fits any table with a name, an email and a password:

#![allow(unused)]
fn main() {
impl ProfileEditor for StaffAuth {
    type Input = Profile;
    type User = SignedStaff;

    fn fill(&self, _cx: &Cx, signed: &SignedStaff) -> Profile {
        Profile {
            name: signed.staff.name.clone(),
            email: signed.staff.email.clone(),
            password: None,
            password_confirmation: String::new(),
            current_password: None,
        }
    }

    async fn validate(
        &self,
        _cx: &Cx,
        signed: &SignedStaff,
        profile: &Profile,
        ex: &mut dyn toasty::Executor,
    ) -> Result<FieldErrors> {
        let mut errors = profile.password_errors();
        let current = profile.current_password.as_deref().unwrap_or_default();
        let credentials = profile.password.is_some() || profile.email != signed.staff.email;
        if credentials && !verify_password(current, Some(&signed.staff.password_hash)).await {
            errors.add_field("current_password", "The current password is incorrect");
        } else if profile.email != signed.staff.email && email_taken(ex, &profile.email).await? {
            // Asked only once the password verifies: a stolen session learns no addresses.
            errors.add_field("email", "Email has already been taken");
        }
        Ok(errors)
    }

    async fn save(
        &self,
        _cx: &Cx,
        signed: &SignedStaff,
        profile: Profile,
        ex: &mut dyn toasty::Executor,
    ) -> Result<ProfileUpdate> {
        let update = if profile.password.is_some() || profile.email != signed.staff.email {
            ProfileUpdate::Credentials
        } else {
            ProfileUpdate::Details
        };
        let hash = match &profile.password {
            Some(password) => Some(hash_password(password).await?),
            None => None,
        };
        update_staff(ex, &signed.staff, &profile.name, &profile.email, hash).await?;
        Ok(update)
    }
}
}

Auth::profile lists what the form renders, which saves end the user’s sessions, what the mount refuses and how saves are throttled.

Password reset

Auth::password_reset adds a “Forgot your password?” link to the login page. It leads to {prefix}/forgot-password, which mails a reset link, and the link opens {prefix}/reset-password, where the visitor chooses a new password. Auth::mail names the sender and the base URL every link the panel mails starts with. The mail goes through the router’s Mailer, so add one before mounting the panel, and add AuthToken to the Db’s models:

#![allow(unused)]
fn main() {
pub fn reset_router(db: toasty::Db) -> Result<Router> {
    let auth = Auth::password()
        .mail(AuthMail::new(
            Mailbox::named("Example", "no-reply@example.com")?,
            "https://admin.example.com",
        ))
        .password_reset(PasswordReset::new(PasswordAuth::new()));
    let mut builder = Router::builder()
        .with(db)
        // Before the panel, which checks for it. `SmtpTransport`, behind Topcoat's `mail-smtp`
        // feature, delivers in production; `FileTransport` writes `.eml` files instead.
        .with(Mailer::new(FileTransport::new("target/mail")));
    builder.panel(Panel::new("admin").auth(auth))?;
    Ok(builder.build())
}
}

The base URL is the scheme and host the app answers on. Reset links start with it rather than with the request’s Host header, which the client chooses and could point at another host.

Another user table than a PasswordAccount resets through a PasswordResetter beside its Authenticator: find_by_email loads the account an address signs in as, and reset_password sets the new password inside the reset’s transaction. The link goes to the address PanelUser::email answers; an account that answers none gets no link.

Auth::password_reset lists how long a link works, what a reset ends, what the mount refuses and how requests are throttled. The request page answers the same whether an account uses the address or not, so it never reveals one.

Email verification

Auth::email_verification makes every signed-in user prove they read the address PanelUser::email answers before the panel serves them anything else. It mails links through Auth::mail, like a password reset:

#![allow(unused)]
fn main() {
pub fn verified_auth() -> Result<Auth> {
    Ok(Auth::password()
        .mail(AuthMail::new(
            Mailbox::named("Example", "no-reply@example.com")?,
            "https://admin.example.com",
        ))
        .registration(PasswordSignUp::open())
        .email_verification(EmailVerification::new(PasswordAuth::new())))
}
}

Another user table than a PasswordAccount verifies through an EmailVerifier beside its Authenticator: is_verified says whether the user has proved their address, and store_verified_email stores the address a link proved and marks it verified, inside the link’s transaction. PasswordAuth keeps the proof in the account’s email_verified_at column; create_admin seeds a verified AdminUser.

Accounts that predate verification are unverified, seeded admins included: backfill email_verified_at for the addresses you already trust before turning it on. A new email waits for its own link: a profile editor calls auth::request_email_change from save instead of writing the address, as PasswordAuth does. Auth::email_verification lists what each link does and for how long, what the mount refuses and how links are throttled.

Two-factor sign-in

Auth::two_factor lets each signed-in user add an authenticator app, and asks an account that has one for a code from it after its password. The panel stores the factors itself, as AuthFactor rows, so it works with any Authenticator. Each authenticator secret is sealed under the router’s cookie Key, which the router must hold:

#![allow(unused)]
fn main() {
pub fn two_factor_router(db: toasty::Db, cookie_key: &[u8]) -> Result<Router> {
    let auth = Auth::password().two_factor(TwoFactor::new());
    let mut builder = Router::builder()
        .with(db)
        // Seals each authenticator secret. Load the same 64 random bytes or more at every start,
        // kept with the app's other secrets: a new key opens no secret sealed under the old one.
        .with(Key::from(cookie_key));
    builder.panel(Panel::new("admin").auth(auth))?;
    Ok(builder.build())
}
}

Add AuthFactor and AuthToken to the Db’s models.

Panels that load the same user type share an account’s factor: set up on one, it is asked on each that installs Auth::two_factor, and turning it off on one turns it off on all. The cookie Key seals the secrets, so rotating it makes every app code fail until its owner signs in with a recovery code. Auth::two_factor lists the setup, the challenge, codes by email, throttling and what the mount refuses.

Sign in with Google

Auth::oidc adds a “Continue with Google” button to the login page, and to the sign-up page when the panel has one. The button leaves for Google, and Google sends the browser back to {prefix}/sign-in/google/callback, where the panel checks the answer and signs in the user an IdentityLinker names:

#![allow(unused)]
fn main() {
impl IdentityLinker for StaffAuth {
    type User = SignedStaff;

    async fn sign_in(
        &self,
        cx: &Cx,
        identity: &ProviderIdentity,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Option<SignedStaff>> {
        // An identity linked before signs in as its staff member.
        if let Some(staff) = staff_linked_to(ex, &identity.issuer, &identity.subject).await? {
            return Ok(Some(staff));
        }
        // A new one links to the staff member holding the address, once Google verified it.
        let (Some(email), true) = (&identity.email, identity.email_verified) else {
            return Ok(None);
        };
        let Some(staff) = find_staff_by_email(cx, email).await? else {
            return Ok(None);
        };
        link_identity(ex, &staff, &identity.issuer, &identity.subject).await?;
        // … load the memberships and return Some(SignedStaff { .. })
        todo!()
    }
}

pub fn google_router(db: toasty::Db, cookie_key: &[u8]) -> Result<Router> {
    let google = OidcProvider::google(
        std::env::var("GOOGLE_CLIENT_ID").unwrap_or_default(),
        std::env::var("GOOGLE_CLIENT_SECRET").unwrap_or_default(),
    );
    let auth = Auth::custom(StaffAuth)
        .oidc(Oidc::new("https://admin.example.com", StaffAuth).provider(google));
    let mut builder = Router::builder()
        .with(db)
        // Seals each pending sign-in while the browser is at Google.
        .with(Key::from(cookie_key));
    builder.panel(Panel::new("admin").auth(auth))?;
    Ok(builder.build())
}

/// The staff member a row of the app's own identity table links `subject` at `issuer` to.
pub async fn staff_linked_to(
    _ex: &mut dyn toasty::Executor,
    _issuer: &str,
    _subject: &str,
) -> Result<Option<SignedStaff>> {
    todo!()
}

/// Stores a row of the app's own identity table linking `subject` at `issuer` to `staff`.
pub async fn link_identity(
    _ex: &mut dyn toasty::Executor,
    _staff: &Staff,
    _issuer: &str,
    _subject: &str,
) -> Result<()> {
    todo!()
}
}

Create an OAuth client of the “Web application” type in a Google Cloud project, and register https://admin.example.com/admin/sign-in/google/callback as its redirect URI: the base URL passed to Oidc::new, then the panel’s prefix. The base URL is the app’s public origin, for the same reason reset links use one rather than the request’s Host header. The router must hold a cookie Key, as for two-factor sign-in.

The linker is where the app decides who an identity is. Store the link as a row of your own, keyed by the identity’s issuer and subject: an address can change hands at the provider, its subject cannot. Link a new identity to an existing account only through an address the provider verified, or anyone who registers that address with the provider signs in as its owner. Returning None refuses the sign-in; creating the account there makes the button a sign-up. With several providers, linking by address trusts the least careful of them to verify it.

To admit the accounts of one Google Workspace domain only, check the identity’s hd claim in the linker, identity.claims.get("hd"); .param("hd", "example.com") on the provider only narrows the accounts Google’s page offers. .param("prompt", "select_account") lets a browser signed in to several Google accounts pick one, and .scope(..) asks for more than the address and name. ProviderIdentity::new builds an identity for a test of the linker alone.

Serve the panel on the base URL’s host only, redirecting any other such as www. to it: the pending sign-in’s cookie belongs to the host the browser started on, and the provider sends it back to the base URL. A browser holds one pending sign-in at a time, so a sign-in started in a second tab replaces the first’s. Callbacks count against the panel’s sign-in throttle.

A Google sign-in ends as a password one does: an account with a second factor answers the challenge, and the browser gets a new session. An account that has only ever signed in with Google has no password to confirm, so the pages that ask for it, such as the two-factor settings, need one set through the password reset first. OidcProvider::new signs in through any other provider that publishes an OpenID Connect discovery document. Auth::oidc lists what the mount refuses.

Acting as another user

Auth::impersonation lets a signed-in user act as another to see the panel as they see it. It is off until the app gives the rule deciding who may act as whom:

#![allow(unused)]
fn main() {
pub fn impersonating_panel() -> Panel {
    // An editor may act as a colleague who is not one, for half an hour at most.
    let rule = Impersonation::new(|_cx, actor: &SignedStaff, target: &SignedStaff| {
        actor.staff.editor && !target.staff.editor
    })
    .lifetime(std::time::Duration::from_secs(30 * 60));
    Panel::new("admin").auth(Auth::custom(StaffAuth).impersonation(rule))
}
}

The shipped Impersonate action places the button on a users resource whose model is the panel’s user type, and shows it only where the rule allows; a form of your own posts the user’s id as auth::IMPERSONATE_FIELD to {prefix}/impersonate. Every page then reads the target as the signed-in user, under a banner whose Stop restores the actor, and auth::impersonator names the actor in your own code.

Write the rule over both users: one that only checks the actor, such as “is support”, lets support act as an administrator too. Decide from the two users alone, since what cx signs in depends on when the rule is asked.

The rule is asked again on every request, and acting as someone ends with its lifetime, an hour unless you say otherwise and never more than a day. Nobody acts as themselves, as a user who may not enter the panel, or as a third user while acting as a second. On a panel that acts for tenants, the target must belong to no tenant the actor does not, so acting as them reaches nothing the actor could not already; Impersonation::across_tenants lifts that for a platform’s own staff. An actor who owes a step, such as a factor the panel now requires, is themselves again until they take it. The profile, two-factor, tenant settings, tenant registration and email-verification pages answer 403 meanwhile, so the actor never changes the target’s credentials.

Acting as someone is read-only. Every resource answers as if the panel mounted it ReadOnly, so its Create, Edit, Delete and action buttons are gone and their routes answer 403. No header action runs, on a resource or a page, and the notification bell offers nothing to mark or remove. tablo::can gives the same answers, so a page of your own that asks it before offering a write needs nothing more. A route of your own outside the panel’s resources and pages asks auth::impersonator. Impersonation::writable lets the actor write as the target, as far as the target’s policies allow; the credential pages stay closed either way.

A panel with the audit log records the start and the stop, an end the lifetime or the rule brings included, in the same transaction as the session’s change. Under a writable impersonation it also names the actor on every write made in between.

The session row stores the target in two nullable columns, impersonating and impersonating_until: an existing auth_sessions table gains them by ALTER TABLE.

Turning it off

#![allow(unused)]
fn main() {
pub fn open_panel() -> Panel {
    Panel::new("admin").auth(Auth::disabled())
}
}

Every panel route is then public and the login, sign-up, profile, password reset, two-factor, provider sign-in and tenant routes are not registered. Use it for public demos and tests only.

Tenancy

A tenant-owned resource shows each user only the rows of the tenant they act for. A user may act for each tenant PanelUser::tenants lists, as a Membership { tenant, name }; the provided AdminUser belongs to none, so a tenanted app signs in its own user table.

The request’s tenant is the membership the user selected, else the one PanelUser::default_tenant names, else their first; read it with tenant_id(cx), a TenantId, and the whole Membership with auth::membership(cx). A user with two or more memberships switches between them from a menu atop the sidebar (PanelUser::tenants). A panel acts for tenants when it offers a tenant registration or settings page, or mounts a tenant-scoped resource; any other acts for none, so tenant_id(cx) answers None there, in its custom pages and widgets too. No request header sets the tenant; server code such as a middleware or a test can, through a Tenant request extension or Tenant(id) on the Cx, where id is a TenantId: a bare Uuid does not compile there.

Auth::tenant_registration lets a signed-in user create a tenant, through a TenantRegistrar whose register writes the tenant and the user’s membership of it; required() sends a user with no membership there before anything else:

#![allow(unused)]
fn main() {
#[derive(FormInput)]
pub struct NewWorkspace {
    pub name: String,
}

impl TenantRegistrar for StaffAuth {
    type Input = NewWorkspace;
    type User = SignedStaff;

    async fn register(
        &self,
        _cx: &Cx,
        signed: &SignedStaff,
        workspace: NewWorkspace,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Membership> {
        let id = create_workspace(ex, &workspace.name).await?;
        seat_staff(ex, signed.staff.id, id).await?;
        Ok(Membership::new(id.into(), workspace.name))
    }
}

pub fn workspace_panel() -> Panel {
    Panel::new("admin").auth(
        Auth::custom(StaffAuth)
            .registration(StaffAuth)
            .tenant_registration(TenantRegistration::new(StaffAuth).required())
            .tenant_profile(StaffAuth),
    )
}
}

Auth::tenant_profile adds a settings page for the tenant the request acts for, through a TenantEditor whose may_edit says which members may open it:

#![allow(unused)]
fn main() {
impl TenantEditor for StaffAuth {
    type Input = NewWorkspace;
    type User = SignedStaff;

    fn may_edit(&self, _cx: &Cx, signed: &SignedStaff, _workspace: &Membership) -> bool {
        signed.staff.editor
    }

    async fn fill(
        &self,
        _cx: &Cx,
        _signed: &SignedStaff,
        workspace: &Membership,
    ) -> Result<NewWorkspace> {
        Ok(NewWorkspace {
            name: workspace.name.clone(),
        })
    }

    async fn save(
        &self,
        _cx: &Cx,
        _signed: &SignedStaff,
        workspace: &Membership,
        renamed: NewWorkspace,
        ex: &mut dyn toasty::Executor,
    ) -> Result<()> {
        rename_workspace(ex, workspace.tenant.get(), &renamed.name).await
    }
}
}

Auth::tenant_registration and Auth::tenant_profile list what each page does and what the mount refuses.

Declare the resource’s tenancy with the column its rows carry their tenant in:

#![allow(unused)]
fn main() {
impl Resource for PostResource {
    type Model = Post; // has `tenant_id: TenantId`
    // …

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .tenancy(Tenancy::column(lens!(Post.tenant_id)))
    }
}
}

That one declaration does three things:

  • The tenant check. Every handler of the resource answers 403 when the request has no tenant.
  • The scope. Every loader — list, export, detail, edit, delete, bulk delete, relationship options, related tables — adds tenant_id = <request tenant> to the resource’s query. A create sets the tenant column itself, so the record form leaves it out.
  • The write check. Before a create, edit, import or related form commits, the handler reads the written row back through the tenant scope. An overriding create_record that does not delegate to write_create, or an update_record that moves the row to another tenant, writes a row outside it: the transaction rolls back and the request answers 500.

The column is a TenantId field of the model, or Option<TenantId> for a nullable one, named by its lens. Do not repeat the filter in a ResourceDef::query narrowing. A resource over tenant-owned rows that declares no tenancy at all fails to mount, since it would serve every tenant’s rows; the mount errors say which declaration it needs. On a panel that acts for tenants, one that offers a tenant registration or settings page or mounts a tenant-scoped resource, every resource declares its tenancy: the mount cannot tell a tenant kept in a plain Uuid column from none.

A row that inherits its tenant. A comment has no tenant column of its own; it belongs to a post that does. Tenancy::via names the tenant through the relation, and the framework checks and filters exactly as it does for a column:

#![allow(unused)]
fn main() {
impl Resource for CommentResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .tenancy(Tenancy::via(Comment::fields().post().tenant_id()))
    }
}
}

Nothing is stamped on create: a comment’s tenant is its post’s. The lens starts at a belongs_to relation, and the form declares that relation’s foreign key (post_id) as a relationship field over a tenant-scoped resource, so a submitted post must be one of the request tenant’s posts. Mounting the panel refuses a form that writes the key any other way, or a lens that does not start at a belongs_to.

A deliberately cross-tenant resource — a super-admin view, or the panel’s own users — declares Tenancy::none() and filters in ResourceDef::query. That gives up both the tenant check and the scope.

In your own code, load rows with scoped_query::<PostResource>(cx)?. It applies the tenant scope and answers 403 when the request has no tenant. Query::all() applies neither the tenant scope nor the panel’s narrowings.

Foreign keys are re-checked inside the write. A relationship field’s key must be one of the related resource’s records for the request: in its scoped query, which its list and its choices read. The create and edit handlers check it when they validate the form, and again inside the write’s transaction, so a related record deleted, moved to another tenant or hidden in between refuses the write with the same field error. A create_record or update_record the panel’s create and edit POSTs call needs no check of its own.