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

Signing in: rind-auth

The Authentication chapter explains how a request becomes a user: an authenticator reads the Authorization header. This chapter explains how users get a token to put in that header in the first place. What they may then do is the subject of Permissions.

rind-auth is a crate of its own, for an application that wants rind to sign its users in. It gives:

  • tokens (JWTs) for a name and a password, and their refresh;
  • passwords, hashed and checked;
  • password reset by mail, and account activation by mail;
  • sign-in codes sent by mail, as an alternative to a password.

In Django, these come from django.contrib.auth (the password hashers, PasswordResetTokenGenerator), and from djangorestframework-simplejwt (the /token and /token/refresh views). rind-auth works on your own user and group models, as Django does with AUTH_USER_MODEL. It also reads and writes the same formats as Django: a database that Django signs its users in to, rind signs them in to the same way. This lets an application move from Django to rind one module at a time.

Adding rind-auth to a project

rind-auth is a separate crate. The rind crate does not re-export it, and no feature of rind turns it on: you add it as a dependency yourself. rind is not published on crates.io yet, so the dependency points to the same rind checkout (or the same git repository) as your rind dependency. rind new writes the rind line in the workspace’s Cargo.toml; add rind-auth beside it:

# Cargo.toml of the workspace
[workspace.dependencies]
rind = { path = "/path/to/rind/crates/rind" }
rind-auth = { path = "/path/to/rind/crates/rind-auth" }
# or, from git:
# rind = { git = "https://…/rind" }
# rind-auth = { git = "https://…/rind" }

Both must come from the same place. Otherwise Cargo builds two different rind crates, and the types of one do not fit the other.

Then two crates of your application use it:

# Cargo.toml of the users' models crate (for `user_base` and `AuthUser`)
# and of the application crate (for the plugin)
[dependencies]
rind-auth.workspace = true

rind-auth turns on the mail feature of rind by itself, since it sends mails.

A first example

Three steps: a user model that rind-auth can read, the plugin in app(), and a client asking for a token.

The user model adds the columns that signing in needs, and tells rind-auth how to read a user:

#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs (shortened)
use rind::prelude::*;

#[rind::with_fields(rind_auth::user_base)]   // password, last_login, is_active
#[derive(Debug, Clone, Model)]
#[model(table = "accounts_user")]
pub struct User {
    pub id: i64,
    #[column(max_length = 150, unique)]
    pub username: String,
    #[column(default = "false")]
    pub is_superuser: bool,
    #[column(default = "false")]
    pub is_staff: bool,
    #[column(max_length = 254)]
    pub email: Option<String>,
}

impl rind_auth::AuthUser for User {
    fn id(&self) -> i64 { self.id }
    fn username(&self) -> &str { &self.username }
    fn password_hash(&self) -> &str { &self.password }
    fn email(&self) -> Option<&str> { self.email.as_deref() }
    fn last_login(&self) -> Option<chrono::DateTime<chrono::Utc>> { self.last_login }
    fn is_active(&self) -> bool { self.is_active }
    fn is_superuser(&self) -> bool { self.is_superuser }
    fn is_staff(&self) -> bool { self.is_staff }
}
}

The application adds the plugin, and a mailer for the routes that send mails:

#![allow(unused)]
fn main() {
// app(), in the application crate
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
    // .models(…), .api(…), .auth(…)
    .with(rind::mail::Mailer::from_env()?)                      // the mails it sends
    .with(
        rind_auth::Auth::<accounts_models::User>::from_env()?   // RIND_JWT_SECRET
            .groups(rind_auth::SlugGroups::new(
                "accounts_user_groups", "user_id", "group_id", "accounts_group", "slug",
            )),
    )
}

Auth::from_env() reads the secret that signs the tokens from RIND_JWT_SECRET, and fails when it is not set. The sample uses .unwrap_or_else(|_| rind_auth::Auth::new("railway-development-secret")) so that it runs without any setting; do not do that in production.

A client now signs in with a name and a password:

POST /token
Content-Type: application/json

{"username": "alice", "password": "alice-password"}
{"refresh": "eyJ0eXAiOiJKV1Qi…", "access": "eyJ0eXAiOiJKV1Qi…"}

and sends the access token with each request:

GET /reservations
Authorization: Bearer eyJ0eXAiOiJKV1Qi…

A wrong name or password is answered 401:

{"detail": "No active account found with the given credentials"}

The plugin is also the application’s authenticator. A bearer token that looks like a JWT is checked here: its signature, its expiry, its audience and issuer when they are set, then that the user exists and is active, and then the user’s groups are read. Any other header goes to the authenticator the application had before. The sample keeps its simple Bearer root-token beside the JWTs this way. Install the plugin after .auth(..): it wraps the authenticator that is there when it is installed.

The user model

rind-auth needs two things from your user model.

The columns. #[rind::with_fields(rind_auth::user_base)] adds the three columns of Django’s AbstractBaseUser:

ColumnTypeDefault
passwordString, at most 128 characters'' (no usable password)
last_loginOption<DateTime<Utc>>NULL
is_activebooltrue

A model of an existing Django database already has these columns. You do not need user_base there; implement the trait on the inspected model (Inspecting a database).

The AuthUser trait, which says how to read a user. Its methods id, username, password_hash and email are required. The others (last_login, is_active, is_superuser, is_staff) have defaults (none, active, not a superuser, not staff) for a model that lacks them.

The trait’s constants name the columns, for a model whose columns are not Django’s:

ConstantDefaultUsed for
LOGIN&["username", "email"]where a sign-in name is looked up, without case. A name is looked up in the first column; a name with an @ is looked up in all of them
PASSWORD"password"the hash, written when a password is set
LAST_LOGINSome("last_login")written at each sign-in; None when there is no such column
IS_ACTIVESome("is_active")written by activation; None when there is no such column

When two accounts have the same name except for case (Alice and alice), neither can sign in by that name: rind-auth takes no guess.

Using the crate’s own user model

An application without users of its own can take the crate’s: rind_auth::models::User and rind_auth::models::Group, on the tables auth_user, auth_group and auth_user_groups. These are the columns of Django’s auth_user, except that a group has a slug, which the rules name. Give their migrations and their groups:

#![allow(unused)]
fn main() {
.models(rind_auth::models::migrations())          // the domain `auth`
// …
.with(
    rind_auth::Auth::<rind_auth::models::User>::from_env()?
        .groups(rind_auth::models::groups()),
)
}

Where the groups come from

A user’s groups, which #[rule(group("…"))] reads, come from a value that implements AuthGroups. Without .groups(..), a user has no group.

SlugGroups reads them through a link table, by their slugs, as Django’s user.groups does. Its arguments are the link table, its column for the user, its column for the group, the table of groups, and the column the rules name:

#![allow(unused)]
fn main() {
rind_auth::SlugGroups::new("accounts_user_groups", "user_id", "group_id", "accounts_group", "slug")
}

Groups that work differently (with validity dates, say, or computed from another table) are an AuthGroups of your own: one async function that gives the slugs of a user.

Adding to the identity

.identity(|db, user, identity| …) adds what your application knows of the user to the identity of each request, with Identity::with_data (Carrying more than the flags). It receives the database, the user row, and the identity built so far, and returns the identity to use:

#![allow(unused)]
fn main() {
.identity(|db, user, identity| Box::pin(async move {
    let stations = …;   // read with `db`, for `user`
    Ok(identity.with_data(Managed { stations }))
}))
}

Creating the first user and setting a password

Django has manage.py createsuperuser. rind has no such command, and rind-auth adds none: the only command it adds is auth-clean. A user row whose password is empty cannot sign in, and cannot ask for a password reset either: like Django, rind-auth sends no reset mail for an account without a usable password.

There are three ways to give the first user a password.

From code, with rind_auth::set_password. It hashes the password in Django’s format and writes it:

#![allow(unused)]
fn main() {
rind_auth::set_password::<User>(&db, user_id, "a-good-password", rind_auth::password::ITERATIONS).await?;
}

The last argument is the number of hashing iterations. rind_auth::password::ITERATIONS is the default, 1,200,000. The function does not check the minimum length.

The simplest way to use it is a command of your application, as Django’s management commands are (The application’s own commands):

// the application's main.rs
use accounts_models::User;
use rind::prelude::*;

fn main() -> std::process::ExitCode {
    rind::cli::Cli::new(app::app())
        .command("create-superuser", "creates a superuser: <username> <password>", create_superuser)
        .main()
}

async fn create_superuser(_app: &rind::Application, args: &[String]) -> rind::cli::Result {
    let [username, password] = args else {
        return Err("usage: create-superuser <username> <password>".into());
    };
    let db = Db::connect(&std::env::var("DATABASE_URL")?)?;
    let user = db
        .insert(
            &Insert::<User>::new()
                .value(User::username(), username.as_str())
                .value(User::is_staff(), true)
                .value(User::is_superuser(), true),
        )
        .await?;
    rind_auth::set_password::<User>(&db, user.id, password, rind_auth::password::ITERATIONS).await?;
    println!("user {} created", user.id);
    Ok(())
}
cargo run -p app -- create-superuser root 'a-good-password'

Columns not given take their database default: the user is active, and its other flags are off.

From Django. When rind works on a database that a Django application also uses, manage.py createsuperuser or changepassword there writes a hash that rind reads.

From the tests. The sample’s tests set the passwords of the seed users with set_password (sample/tests/auth.rs).

The routes

The plugin mounts these routes. They are plain routes, not resources:

RouteBodyAnswer
POST /tokenusername (or an email), password{refresh, access}; 401 {"detail": "No active account found with the given credentials"}
POST /token/refreshrefresh{access}; 401 {"detail": "Token is invalid or expired", "code": "token_not_valid"}
POST /auth/codeusername{success: true}, and a mail with a sign-in code
POST /auth/code/tokenusername, code{refresh, access}; 401 {"detail": "Invalid or expired code."}
POST /auth/pwresetusername{success: true}, and a mail with a reset token
POST /auth/pwreset/processusername, token, password{success: true}, or 400 {success: false}
POST /auth/activateusername{success: true}, and a mail with an activation token
POST /auth/activate/processusername, token{success: true}, or 400 {success: false}

A few rules hold for all of them:

  • A body is JSON, or a form (application/x-www-form-urlencoded), as simplejwt accepts.
  • A missing field is answered 400, in DRF’s shape: {"password": ["This field is required."]}.
  • The routes that send a mail answer the same whether the account exists or not. A client cannot use them to learn which names exist.
  • .prefix("/api/v3") puts every route below a path: /api/v3/token.
  • The password reset routes are on by default; .reset(false) removes them. The activation routes are off by default; .reactivation(true) mounts them.

Tokens

The tokens are simplejwt’s, so that Django and rind accept each other’s tokens when they share the secret. A token is signed with HS256 and carries these claims:

  • token_type: access or refresh;
  • user_id, the user’s id, written as text (as simplejwt writes it);
  • exp, iat and jti;
  • aud and iss, when an audience and an issuer are set: .audience("my-app", "my-app"), or RIND_JWT_AUDIENCE and RIND_JWT_ISSUER with from_env(). Once they are set, a token without them is refused;
  • su: "superuser" for a superuser;
  • your own claims, added with .claims(|user, claims| …), where claims is a JSON map.

An access token lasts 5 minutes and a refresh token 15 days. .lifetimes(access, refresh) changes both. A sign-in sets the user’s last_login.

POST /token/refresh gives a new access token for a refresh token, with the same extra claims, as long as the user still exists and is active. It does not give a new refresh token: the client signs in again when the refresh token expires.

Coming from Django: simplejwt’s default refresh lifetime is one day; rind-auth’s is 15 days. There is no token blacklist: a token stays valid until it expires, and signing out is the client forgetting its tokens.

Checking only: tokens another service issues

While an application moves to rind module by module, its clients may keep signing in to the old service (Django) and send the same token to both. .verify_only() turns the plugin into a token checker only:

#![allow(unused)]
fn main() {
.with(
    Auth::<User>::new(&secret)
        .audience("my-app", "my-app")
        .verify_only()
        .groups(MyGroups),
)
}

No route is mounted (/token answers 404), no table is added (no rind_auth_code), and no command. Each request is checked as usual: the user is read, an inactive one is refused, and the groups and .identity(..) are filled in. A refresh token is not accepted as an access token.

Passwords

Passwords are stored in Django’s format, which rind reads and writes:

pbkdf2_sha256$<iterations>$<salt>$<hash>

A new password is hashed with 1,200,000 iterations, Django 6’s count; .iterations(n) changes it. A password hashed with fewer iterations is hashed again at its next sign-in, as Django does. A hash of another algorithm (argon2$…), an empty one, or one that starts with ! (Django’s “unusable password”) never matches.

Two protections are built in:

  • A sign-in with an unknown name takes as long as one with a wrong password, so the time of the answer does not tell which names exist.
  • A new password set through the reset route has at least 8 characters; .min_password_length(n) changes it. A shorter one is answered 400: {"password": ["This password is too short: 8 characters at least."]}.

Password reset and activation by mail

POST /auth/pwreset mails a reset token to the user, when the account has a usable password and an email. POST /auth/pwreset/process takes the name, the token and the new password, and sets it. With .reactivation(true), a successful reset also makes the account active again.

POST /auth/activate mails a token in the same way, and POST /auth/activate/process makes the account active.

The tokens are those of Django’s PasswordResetTokenGenerator, keyed by Django’s SECRET_KEY: a link sent by Django works in rind, and the other way round. The key is RIND_AUTH_SECRET_KEY (or .django_secret(key)); when it is not set, it is the JWT secret. A token stops working once the password changes or the user signs in, and after 3 days.

Django reads its clock in local time for these tokens, so rind reads the process’s local time too. Run both in the same time zone.

Sign-in codes

A sign-in code lets a user sign in without a password: POST /auth/code mails a code, and POST /auth/code/token exchanges it for tokens.

A code has 6 digits and is valid 10 minutes; .codes(digits, valid) changes both (from 4 to 12 digits). A code is used once, and it is refused after 5 wrong attempts. It is kept hashed in the plugin’s table rind_auth_code, and asking again replaces it. Codes are only sent to an active account with an email.

The table belongs to the domain rind_auth, which the plugin adds to the application’s migrations by itself. The command auth-clean deletes the expired codes:

cargo run -p app -- auth-clean

Mails

The plugin renders the templates auth_code, auth_pwreset and auth_activate, with defaults of its own. A template of the mailer with one of those names replaces the default (Mail). The context of each template has:

  • user, with id, username and email;
  • code and minutes for a sign-in code, or token for a reset or an activation.

An application without a rind::mail::Mailer answers these routes 500.

Limits on attempts

Signing in is limited to 5 attempts a minute per account and per client address; the next attempt is answered 429 {"detail": "Too many attempts: wait a minute."}. .attempts(n, window) changes the limit. The routes that send a mail, and the ones that use a reset or activation token, are limited per account in the same way.

The client address is the peer’s. When the peer is one of the proxies given with .trusted_proxies(..), it is the first address of its X-Forwarded-For header instead.

The attempts are counted in the process, in memory. Several processes each count their own, and a restart forgets them.

Going further: a master password, sign-in by address

Some applications need two unusual ways to sign in. Both are off unless the application turns them on:

  • .master_password(hash) sets a password that opens any active account, except a superuser’s (add .master_password_for_superusers() for those). It is given as its hash in Django’s format, never in clear, or through RIND_AUTH_MASTER_PASSWORD_HASH with from_env(). Its tokens carry master: true, and each sign-in with it is logged at warning level.
  • .sign_in_by_ip("203.0.113.0/24", "kiosk")? makes a request from that network, signing in with the name and password loginbyip, the user kiosk. .ip_credentials(name, password) changes the special name and password. The address is read as the limits read it. A private address is refused outside a development build, since it is a proxy’s as often as a client’s. Its tokens carry by_ip: true. The method returns a Result, because the network may not parse.

Unless the application also calls .allow_in_production(), a warning is logged at start-up when either one is on.

Reference

What is not there

  • No createsuperuser command and no command to set a password: see Creating the first user.
  • No “who am I” route, no route for a signed-in user to change their password, and no sign-out route or token blacklist.
  • The routes are not in the OpenAPI document.
  • Sign-in codes cannot be turned off.

The builder

MethodDefaultWhat it does
Auth::new(secret)tokens signed with secret
Auth::from_env()reads the variables below; fails without RIND_JWT_SECRET
.groups(groups)no groupswhere a user’s groups come from: an AuthGroups (SlugGroups, models::groups())
.identity(f)adds to each request’s identity
.claims(f)adds claims to each token
.audience(audience, issuer)nonethe audience and issuer tokens carry and must carry
.django_secret(key)the JWT secretDjango’s SECRET_KEY, for reset and activation tokens
.lifetimes(access, refresh)5 minutes, 15 dayshow long tokens are valid
.prefix(path)nonethe routes below this path
.iterations(n)1,200,000the hashing iterations of a new password
.min_password_length(n)8the shortest new password
.reset(on)onthe password reset routes
.reactivation(on)offthe activation routes, and reactivation by a reset
.codes(digits, valid)6, 10 minutessign-in codes
.attempts(n, window)5 a minutethe limit on attempts
.trusted_proxies(list)noneproxies whose X-Forwarded-For is believed
.master_password(hash)offa password that opens any account
.master_password_for_superusers()off…superusers’ accounts too
.sign_in_by_ip(network, username)offsign-in by address; returns a Result
.ip_credentials(name, password)loginbyip, loginbyipthe special name and password of sign-in by address
.allow_in_production()no warning for the two above
.verify_only()only checks tokens: no route, table or command

Environment variables of from_env()

VariableMeaning
RIND_JWT_SECRETthe secret that signs the tokens (required)
RIND_AUTH_SECRET_KEYDjango’s SECRET_KEY, for reset and activation tokens
RIND_JWT_AUDIENCE, RIND_JWT_ISSUERthe audience and issuer
RIND_AUTH_MASTER_PASSWORD_HASHthe master password’s hash

Functions and modules

NameWhat it is
rind_auth::set_password::<U>(db, id, password, iterations)sets a user’s password
rind_auth::passwordhash, verify, usable, and ITERATIONS
rind_auth::tokens::Jwtsigns and checks tokens, for tests and tools
rind_auth::modelsthe crate’s own User and Group, their migrations() and groups()
rind_auth::migrations()the domain rind_auth (the codes’ table), which the plugin adds itself