Restify for Laravel for Rust

Docs / Migrating from PHP

Sanctum Tokens

keep the Laravel Sanctum tokens of a PHP application working after it moves to Rust, and create new ones.

Introduction #

Most Restify for PHP applications protect their API with auth:sanctum. Their clients hold Laravel Sanctum personal access tokens, such as 12|aBcD..., stored as hashes in the personal_access_tokens table.

restify::auth::Sanctum<User> is a request guard that accepts those same tokens, from that same table. When you move an application from PHP to Rust and keep its database, every client stays logged in. Nothing has to be re-issued.

It does what Sanctum 4.5's guard does for a bearer token. It also creates tokens in Sanctum's format, so PHP accepts the tokens Rust makes. The login, register and logout endpoints that hand them out are in Authentication.

Enabling the feature #

The guard is behind the sanctum Cargo feature:

# Cargo.toml
[dependencies]
laravel-restify = { version = "0.2", features = ["sanctum"] }

The guard reads tokens from Sanctum's personal_access_tokens table. A database that came from PHP has it: see What a migrated database needs. A new application creates it with the migration in Authentication.

Protecting routes #

Add the guard once as a provider. That registers it in the container and reads its settings. Then give its middleware to Restify, as you would any request guard:

// src/app.rs
use laravel::auth::Authenticate;
use restify::Restify;
use restify::auth::Sanctum;

use crate::models::{PostRepository, User};

Application::configure().with_providers(|providers| {
    providers.add(Sanctum::<User>::new());
    providers.add(
        Restify::new()
            .authenticate(Authenticate::via::<Sanctum<User>>())
            .repository::<PostRepository>(),
    );
})

User is your user model. It must derive Authenticatable, as the framework's authentication.md guide shows, and its key must be an integer, as in Sanctum's default migration.

The same middleware protects your own routes too:

route.authenticate(Authenticate::via::<Sanctum<User>>()).group(|route| {
    route.get("/me", me);
});

When the token is accepted, Authenticated<User>, Auth<User> and request.user() give the token's user. When it is refused, the client gets 401 with {"message": "Unauthenticated."}, the same answer as in PHP.

If you forget providers.add(Sanctum::<User>::new()), the guard is missing from the container and every protected request fails with a server error.

Reading the token's abilities #

A Sanctum token carries a list of abilities, such as ["posts:read"], or ["*"] for everything. AccessToken::current() returns the token that authenticated the current request. Call it in a handler, a policy or a repository:

use restify::auth::AccessToken;

pub async fn me(Authenticated(user): Authenticated<User>) -> Json<Value> {
    let token = AccessToken::current();
    let can_write = token.as_ref().is_some_and(|token| token.can("posts:write"));

    Json(json!({ "id": user.id, "token": token, "can_write": can_write }))
}

How PHP calls map to Rust:

PHPRust
$user->tokenCan('posts:write')AccessToken::current().is_some_and(|token| token.can("posts:write"))
$user->tokenCant('posts:write')AccessToken::current().is_none_or(|token| token.cant("posts:write"))
$user->currentAccessToken()->idAccessToken::current().map(|token| token.id)

AccessToken has the token's id, name and abilities. It never holds the secret or its hash.

AccessToken::current() is None when the Sanctum guard did not authenticate the request. That includes tests that log in with acting_as, because acting_as skips the guard.

Creating tokens #

create_token does what PHP's $user->createToken($name, $abilities, $expiresAt) does. Resolve the guard from the container, then call it:

use restify::auth::Sanctum;

let sanctum = laravel::resolve::<Sanctum<User>>().await?;
let token = sanctum.create_token(&user, "cli", &["posts:read"], None).await?;

It returns the token to give the client, such as 7|aBcD.... The format is Sanctum's: the row's id, |, then the secret, which is the token_prefix, 40 random letters and digits, and the CRC32 of those 40 in hex. The table stores only the SHA-256 of the secret, so nobody can read the token back later. Its tokenable_type is the first name the guard accepts: App\Models\User by default (see below).

To revoke a token, call delete on it. AccessToken::current() gives the token of the current request, which is how logout works:

if let Some(token) = AccessToken::current() {
    token.delete().await?;
}

Settings #

The settings live in the SanctumConfig section. They use the names and defaults of PHP's config/sanctum.php, so a migrated application sets the same values.

SettingVariableDefaultWhat it does
expirationSANCTUM_EXPIRATION, in minutesnoneA token stops working this long after its created_at. None or 0 means no limit.
last_used_atnonetrueAn accepted request writes the time to the token's last_used_at and updated_at, unless last_used_at already holds the same second. So a token writes at most once a second.
token_prefixSANCTUM_TOKEN_PREFIXemptyText put before the secret of each token that create_token makes.
cacheSANCTUM_CACHE, in secondsnoneThe guard remembers an accepted token and its user this long, and skips the database. None or 0 reads them on every request. Sanctum has no such setting: see Remembering tokens.

SANCTUM_EXPIRATION is not in Sanctum's published config file, which sets expiration to null. If your PHP application set a number there, set the same number in the variable. You can also change a setting in src/app.rs:

use laravel::time::ToSpan;
use restify::auth::SanctumConfig;

Application::configure().with_config(|config, _| {
    config.section_mut::<SanctumConfig>().expiration = Some(60.minutes().into());
})

A token's own expires_at column is always checked, whatever expiration says.

A prefixed token that PHP made, such as 12|myapp_aBcD..., needs no setting: PHP hashed the prefix with the secret, so it is checked like any other token.

What a token costs #

One query on PostgreSQL and MySQL. The guard reads the token and its user together, by the token's id, then compares the secret's hash, checks the expiry, and at most once a second writes last_used_at. Sanctum for PHP reads the token and the user with two queries.

The guard runs Sanctum's two queries in two cases. On SQLite, where a query is a function call and not a trip to a server, the joined query measured slower than the two. And when the user model has a connection of its own (#[model(connection = "..")]), because the tokens are on the default one.

A trip to the database is what costs, not the hashing or the checks, which take about 3 microseconds together. So a request that otherwise runs one query, such as showing one record, answers about 1.6 times fewer requests with a token than without one. A page of 15 records answers about 10% fewer. The measurements and the reasoning are in the benchmark's What a token costs, and why.

The connection pool's size (DB_MAX_CONNECTIONS, 10 by default) didn't change this in the benchmark: with 50 clients at once, a pool of 30 served as many requests as a pool of 10. Raise it when your requests wait for the database, not for the processor, such as when the database is on another machine.

Remembering tokens #

By default the guard asks the database on every request, as Sanctum does. So a deleted token stops working at once, and a change to a user shows on the next request.

You can trade that for speed. With SANCTUM_CACHE=30, the guard remembers each accepted token and its user for 30 seconds, in the memory of the process, and a request with a remembered token runs no query for it. In the benchmark, showing one record with a token then answered 9% to 16% fewer requests than without one, where it answers 37% to 45% fewer without the setting.

# .env
SANCTUM_CACHE=30

Or in src/app.rs:

use laravel::time::ToSpan;
use restify::auth::SanctumConfig;

Application::configure().with_config(|config, _| {
    config.section_mut::<SanctumConfig>().cache = Some(30.seconds().into());
})

What changes while a token is remembered, for up to the time you set:

What happensWithout cacheWith cache
A handler calls AccessToken::delete, or the client calls Restify's POST /api/logoutThe token is refused at onceThe same, in the process that ran it. Another process of the application keeps accepting the token until its own time for it passes
The token's row is deleted another way: by SQL, by the PHP application, by deleting it through the query builderRefused at onceStill accepted until the time passes
The user's row changes, such as is_admin, or is deletedSeen on the next requestSeen when the time passes
The token's abilities changeSeen on the next requestSeen when the time passes
The token passes its expires_at, or expirationRefused at onceRefused at once: the guard checks both on every request
last_used_atWritten at most once a secondThe same, by each process

So the time you set is the longest a revoked token can keep working. Choose it as you would choose the lifetime of a short-lived access token. A token sent without its id (no 12| in front) is never remembered. The guard remembers at most 10,000 tokens. When more than that are in use at once, the others are read from the database as before.

Many token requests on SQLite #

SQLite lets one connection write at a time. With its default settings, a write also waits until every read has ended, and reads wait for the write. Whoever waits sleeps and tries again after 1, 2, 5, 10 and up to 100 milliseconds, so under many requests at once some wait far longer than the write they wait for. A token adds a read to every request, and a write once a second.

Turn on SQLite's write-ahead log (WAL). Reads and the write then don't wait for each other, and a write costs less. Add journal_mode=wal to DATABASE_URL in .env, and in every environment that runs the application:

DATABASE_URL=sqlite://database/database.sqlite?mode=rwc&journal_mode=wal

The framework applies it to every connection it opens to that file (its database.md, "SQLite"). It is a setting of the URL, not of Restify, because an application's own src/config/database.rs runs after every provider and sets the connections again: a provider couldn't keep it there. For a PHP application on SQLite, restify:import writes a task to add it. PostgreSQL and MySQL don't need it: they lock a row, not the whole database.

To check that it is on, write one record, then ask the file: sqlite3 database/database.sqlite "PRAGMA journal_mode" answers wal.

Measured with the benchmark, creating a record with a token, 10 clients at once:

SettingsCreate a record
SQLite's defaults1,099 requests a second, p99 199 ms
journal_mode=wal3,474 requests a second, p99 54 ms

Three things to know before you turn it on:

  • The setting is stored in the database file. A PHP application that opens the same file uses the log too from then on. That is safe: PHP's SQLite reads and writes such a file like any other. Every process that uses the file must run on the same machine, because the log doesn't work over a network file system.
  • The database is three files. Next to app.sqlite, SQLite keeps app.sqlite-wal and app.sqlite-shm. Don't back up the database by copying the one file while the application runs. Use sqlite3 app.sqlite ".backup copy.sqlite", which writes a whole copy.
  • The first connection switches the file. That takes a moment in which nobody else uses the database. Start the application once while the PHP application is idle, or switch the file yourself with sqlite3 app.sqlite "PRAGMA journal_mode = WAL". To go back, remove journal_mode=wal from the URL, stop the application, and run sqlite3 app.sqlite "PRAGMA journal_mode = DELETE".

With the log, synchronous=normal makes writes faster still. The database file can't be damaged by it, but the last writes before a power cut or an operating system crash may be lost. Add it to the URL only if that is acceptable: ?mode=rwc&journal_mode=wal&synchronous=normal.

A connection you build in src/config/database.rs from SqliteConnectOptions instead of a URL sets its own journal_mode.

Why the log helps, with the measurements, is in the benchmark's Writes on SQLite.

What a migrated database needs #

The personal_access_tokens table, exactly as Sanctum's migration created it. The guard reads it with the query builder; there is no model to declare.

The tokenable_type column must name your user model. PHP writes one of two things there:

  • The class name, such as App\Models\User. This is the default.
  • An alias, if the application maps its models with Relation::morphMap or Relation::enforceMorphMap, such as user.

Sanctum::<User>::new() accepts App\Models\User and the model's morph name, which is user for a model named User (the struct's name in snake case, or what #[model(morph = "..")] sets). Look at what your table contains:

SELECT DISTINCT tokenable_type FROM personal_access_tokens;

If you see other values, list every one that means this model:

providers.add(Sanctum::<User>::new().tokenable_types(["App\\Models\\Account", "account"]));

The list replaces the defaults, and its first name is what new tokens store. If your PHP application maps users to an alias, put the alias first. Tokens whose tokenable_type is not in it are refused, so a token that belongs to another model can never log in as a user with the same id.

When a token is refused #

The guard follows Sanctum's Guard and PersonalAccessToken step by step. A token is refused when:

  • There is no Authorization: Bearer header, or the token is empty or 0.
  • The token has the form id|secret, and the id is not made only of digits, or the secret is empty or 0. Everything after the first | is the secret, even another |.
  • No row matches. A token id|secret finds the row by id and compares the SHA-256 of the secret with the stored hash in constant time. A token without | finds the row by the SHA-256 of the whole token.
  • expires_at is in the past, or expiration minutes have passed since created_at.
  • tokenable_type is not one of the accepted names, or the user with id tokenable_id no longer exists.

Sanctum finds the token first and its user second. On PostgreSQL and MySQL the guard reads both with one query, and refuses the same tokens.

Testing #

To test as a logged-in user without a token, use the framework's acting_as. To test the token itself, store a row the way Sanctum does and send it with token(..). This uses the sha2 and hex crates:

use laravel::db;
use sha2::{Digest, Sha256};

let id: i64 = db::table("personal_access_tokens")
    .insert_get_id(
        db::values! {
            tokenable_type: "user",
            tokenable_id: user.id,
            name: "test",
            token: hex::encode(Sha256::digest("secret")),
            abilities: r#"["*"]"#,
            created_at: laravel::now().timestamp(),
            updated_at: laravel::now().timestamp(),
        },
        "id",
    )
    .await?;

app.get("/api/me").header("accept", "application/json").token(&format!("{id}|secret")).await.assert_ok();

The example app's tests/sanctum_guard.rs, in the Restify for Rust repository, tests every rule on this page, including tokens created by real PHP Sanctum.

Limits #

  • Bearer tokens only. Sanctum also logs in single-page apps through the web session (sanctum.guard and stateful). This guard doesn't.
  • Integer keys. tokenable_id must be an integer, as Sanctum's morphs column is. Applications that used uuidMorphs are not supported.
  • No hooks. Sanctum's TokenAuthenticated event, Sanctum::getAccessTokenFromRequestUsing and Sanctum::authenticateAccessTokensUsing have no counterpart.
  • A token with no abilities (abilities is NULL) is accepted and grants nothing. PHP fails with a server error when such a token's abilities are checked.
  • Header parsing is the framework's request.bearer_token(). It reads the first word as the scheme, where PHP looks for the last Bearer in the header and stops at a comma. The two differ only for unusual headers, such as Bearer a,b or a token after two spaces.