Smeltery
Get started

Hallmark (API tokens)

v0.1

API tokens

Hallmark (smeltery::hallmark) gives an app personal access tokens: API clients, mobile and desktop apps, command-line tools and other backends send Authorization: Bearer smt_… to API routes, and each token carries a list of abilities.

rust
use smeltery::auth::Authenticated;
use smeltery::hallmark::{CurrentToken, Hallmark, HallmarkExt as _, HasApiTokens as _};
use smeltery::http::{HeaderValue, StatusCode, header};
use smeltery::prelude::*;

/// `POST /api/tokens/cli`: a signed-in API client issues a second token for a command-line tool.
async fn issue(who: Authenticated, app: App) -> Result<Response> {
    let user: User = who.user(&app).await?.ok_or_else(Error::unauthorized)?;
    let new = user.create_token(&app, "cli", &["deploy"]).await?;
    let mut res = Json(new.to_json()).into_response();
    res.headers_mut()
        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    Ok(res)
}

async fn orders(who: Authenticated) -> String {
    format!("the orders of user {}", who.user_id)
}

async fn sign_out(token: CurrentToken) -> Result<StatusCode> {
    token.revoke().await?;
    Ok(StatusCode::NO_CONTENT)
}

fn build(app: AppBuilder) -> AppBuilder {
    app.auth::<User>()
        .hallmark(Hallmark::new())
        .api_routes(|r| {
            r.post("/tokens/cli", issue)
                .middleware("auth:hallmark")
                .middleware("abilities:tokens:create");
            r.get("/orders", orders)
                .middleware("auth:hallmark")
                .middleware("abilities:orders:read");
            r.delete("/tokens/current", sign_out).middleware("auth:hallmark");
        })
}

A route that issues tokens to a token holder checks an ability (abilities:tokens:create above): without it any token, even one that may do nothing, could issue itself a new one with more abilities.

.hallmark(Hallmark::new()) (after .auth::<User>(); without a user model the app stops at boot) registers the guard hallmark, the middleware families abilities: and ability:, the Tokens service, a credential listener and the console command hallmark:prune-expired. The table comes from a migration that calls smeltery::hallmark::migrations::up(schema) / down(schema); serve logs an error when the table is missing.

Call Does
Tokens::of(&app)? / tokens: Tokens (handler argument) the token service
tokens.create(user_id, "Ada's phone", &["orders:read"], None).await? a new token (NewToken): plain_text() is the token, shown once and never stored; token() its stored data; to_json() the answer {"token":"smt_…","token_type":"Bearer","expires_at":…,"abilities":[…]}. Some(time) sets an earlier expiry
user.create_token(&app, name, abilities) / user.tokens(&app) / user.revoke_tokens(&app) the same on any user model (HasApiTokens)
tokens.list(user_id).await? the user's tokens (AccessToken: id, user_id, name, abilities, last_used_at, expires_at, created_at), newest first; never a token or its hash
tokens.find(user_id, id) / tokens.revoke(user_id, id) one token of that user: ids from a request reach only that user's tokens
tokens.revoke_all(user_id) / tokens.revoke_all_except(user_id, keep_id) delete the user's tokens (all, or all but one); the number deleted
tokens.prune_expired(Duration) / hallmark:prune-expired [--hours=24] delete tokens expired at least that long ago, 500 rows per statement
.middleware("auth:hallmark") the request needs a valid token (on API routes)
.middleware("abilities:a,b") / .middleware("ability:a,b") the principal needs every listed ability / at least one; 403 {"error":"Forbidden."}, 401 without a principal. Put auth:hallmark first
CurrentToken (handler argument) the token of this request (id(), name(), abilities(), can(), expires_at(), revoke()); 401 when a token did not authenticate the request, None as Option<CurrentToken>
  • Tokens are smt_ followed by 64 lowercase hex characters (32 random bytes). The table stores only their SHA-256; PlainToken has no Display and no Serialize, and its Debug prints PlainToken(smt_…).
  • The guard reads one Authorization: Bearer <token> header (the scheme in any letter case), never a query string, cookie, body or other header. A malformed token is refused before any database work; a found row is compared again in constant time. Missing, malformed, unknown, expired and revoked tokens get the same 401 {"error":"Unauthenticated."} with WWW-Authenticate: Bearer and Cache-Control: no-store, and requests the guard looked at answer with Vary: Authorization, Cookie. Web routes (routes/web.rs) never accept a bearer token: they keep the session and its CSRF check.
  • Guesses: one client (its address after TRUSTED_PROXIES, an IPv6 client by its /64) may send HALLMARK_GUESS_LIMIT invalid tokens a minute (malformed, unknown, expired and revoked ones alike). Past that, a bearer request from that address gets 429 with Retry-After until the minute ends, before any lookup, unless this process accepted its token in the last five minutes: clients sharing the address (a carrier or office network) keep working with the tokens they use. The count lives in the app's cache store and is shared by the app's processes (each bearer request reads it once); a cache error answers 500. Requests that reach the app without any connection information (only outside its server) are not counted. Without TRUSTED_PROXIES behind a proxy every client is the proxy's address and shares one budget.
  • Expiry: a new token expires after HALLMARK_TOKEN_EXPIRATION days (an explicit later time is shortened to that), and every request also refuses a token older than that, so lowering the setting shortens existing tokens. An expired token is deleted when it is next presented; hallmark:prune-expired deletes the rest.
  • Passwords: a token is bound to its user's password hash. A password written by any code ends the user's tokens at their next use; a password reset, Auth::logout_other_devices, Auth::set_password and auth::password_changed delete them at once (password_changed keeps the token of the request that called it). Deleting the user deletes the tokens (foreign key).
  • Abilities are exact names (1 to 100 of A-Z a-z 0-9 : . _ -) or * alone (every ability), at most 64 per token; there are no patterns (orders:* is refused). A token created with &[] may do nothing; a stored list that breaks these rules grants nothing (logged as an error with the token id). A signed-in session holds every ability: abilities limit tokens, not users, so handlers still check that the user may touch a record.
  • Limits: a user holds at most HALLMARK_MAX_TOKENS_PER_USER tokens; creating one more deletes the least recently used, in the same transaction. last_used_at is written at most once a minute per token, in the background with a 2 s timeout.
  • Events: revoke, CurrentToken::revoke, a token deleted when presented and a token deleted by the cap publish AuthEvent::Revoked { key: "hallmark:token:<id>" }; revoke_all / revoke_all_except publish AuthEvent::RevokedAll { kind: Tokens } on the PubSub topic auth (see PubSub).

Clients without a browser session (mobile and desktop apps, command-line tools) get their token for an email and password:

rust
use serde::Deserialize;
use smeltery::hallmark::{issue_for_credentials, revoke_current};
use smeltery::http::ClientInfo;
use smeltery::prelude::*;

#[derive(Deserialize)]
struct TokenRequest {
    email: String,
    password: String,
    device_name: String,
    code: Option<String>,
}

async fn store(app: App, client: ClientInfo, Json(form): Json<TokenRequest>) -> Result<Response> {
    let issued = issue_for_credentials(
        &app, &client, &form.email, &form.password, &form.device_name, form.code.as_deref(), &["*"],
    )
    .await?;
    Ok(issued.created())
}

fn routes(r: &mut smeltery::routing::Router) {
    r.post("/tokens", store).middleware("throttle:10,1");
    r.delete("/tokens/current", revoke_current).middleware("auth:hallmark");
}
  • issue_for_credentials checks the address and password with core's auth::verify_credentials: the login budgets (shared with the web login form), the same work for unknown addresses, the password-hash gate. A wrong address or password answers 422 with "These credentials do not match our records." on email; past a budget 429; a device_name that is empty, longer than 255 characters or holds control characters 422 on device_name.
  • The app's login policies (AppBuilder::login_policy, such as refusing a suspended account) decide next, as at the web sign-in: a refusal answers the policy's status with its message on email, and no token is created.
  • When a second factor is registered (AppBuilder::second_factor) and the user needs one, code must be valid before any token exists: 422 "A two-factor code is required." or "The two-factor code is invalid." on code; past the second factor's own attempt budget, 429 with Retry-After.
  • issued.created() answers 201 {"token":"smt_…","token_type":"Bearer","expires_at":…,"abilities":[…]} with Cache-Control: no-store. revoke_current deletes the token of the request and answers 204.
.env Builder Default
HALLMARK_TOKEN_EXPIRATION (days; 0 = never) .expiration(Duration) 365
HALLMARK_MAX_TOKENS_PER_USER .max_tokens_per_user(n) 100
HALLMARK_GUESS_LIMIT (invalid tokens per client a minute) .guess_limit(n) 60
HALLMARK_SPA (true / false) .spa() false
HALLMARK_STATEFUL (first-party origins besides APP_URL's) .stateful(&[...]) empty

In tests, smeltery::hallmark::testing::acting_as(&app, &user, &["orders:read"]) creates a real token and sends it with every following request; token_for(&app, &user, &["*"]) returns one without changing the app's headers.

↑↓ moveEnter openEsc close