Expand description
§smeltery-hallmark
Hallmark, the API tokens of the Smeltery framework: personal access tokens
with abilities for API clients, mobile and desktop apps, command-line tools and other backends; the hallmark
bearer guard; token management; and revocation events for the app’s other processes.
Apps use it through the facade, as smeltery::hallmark:
use smeltery::auth::Authenticated;
use smeltery::hallmark::{CurrentToken, Hallmark, HallmarkExt as _, Tokens};
use smeltery::http::StatusCode;
use smeltery::prelude::*;
/// `GET /api/orders`: needs a token with the ability `orders:read` (the route's `abilities:` alias checks it).
async fn orders(who: Authenticated) -> Result<String> {
Ok(format!("the orders of user {}", who.user_id))
}
/// `DELETE /api/tokens/current`: the token signs itself out.
async fn sign_out(token: CurrentToken) -> Result<StatusCode> {
token.revoke().await?;
Ok(StatusCode::NO_CONTENT)
}
/// `GET /api/tokens`: the caller's tokens (never their secrets).
async fn list(who: Authenticated, tokens: Tokens) -> Result<Json<Vec<smeltery::hallmark::AccessToken>>> {
Ok(Json(tokens.list(who.user_id).await?))
}
fn build(app: AppBuilder) -> AppBuilder {
// `.auth::<User>()` comes first in a real app: Hallmark needs the user model.
app.hallmark(Hallmark::new()).api_routes(|r| {
r.get("/orders", orders).middleware("auth:hallmark").middleware("abilities:orders:read");
r.delete("/tokens/current", sign_out).middleware("auth:hallmark");
r.get("/tokens", list).middleware("auth:hallmark");
})
}§What it does
- Tokens are
smt_followed by 64 lowercase hex characters (32 bytes from the operating system’s random source). The table stores only their SHA-256; the plain text exists once, in theNewTokenthatTokens::createreturns.PlainTokenhas noDisplayand noSerialize, and itsDebugprintsPlainToken(smt_…). - The guard
hallmarkreads oneAuthorization: Bearer <token>header and nothing else: a token in the query string, a cookie, the body or another header is never read. Malformed tokens are refused before any database work; a found row is compared again in constant time. Missing, malformed, unknown, expired and revoked tokens all get the same 401{"error":"Unauthenticated."}withWWW-Authenticate: BearerandCache-Control: no-store. Requests the guard looked at answer withVary: Authorization, Cookie. Web routes never accept a bearer token (they keep the session and its CSRF check). - Guess budget: a client (its address after
TRUSTED_PROXIES, an IPv6 client by its /64) may sendHALLMARK_GUESS_LIMIT(60) invalid tokens a minute (malformed, unknown, expired and revoked alike). After that a bearer request from that address gets 429 withRetry-Afteruntil the minute ends, before any lookup, unless this process accepted its token in the last five minutes, so other clients behind the same address keep working. The count lives in the app’s cache store; a cache error answers 500. - Expiry: a new token expires after
HALLMARK_TOKEN_EXPIRATIONdays (365;0= never), and every check also refuses a token older than that, so lowering the setting shortens existing tokens. - Bound to the password: a token stores a hash of its user’s password hash and credentials epoch. Any password
change, by any code, and
auth::end_credentialsend every token of the user at its next use (it is deleted then), including a token issued while they ran. Password resets, signing out other devices,auth::password_changedandauth::end_credentialsdelete the user’s tokens at once (password_changedkeeps the calling token and binds it to the new password; when that token was signed out by a parallel request first, the change answers 401). - 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 fails these rules grants nothing. The middlewareabilities:a,bneeds every listed ability,ability:a,bat least one (403{"error":"Forbidden."}otherwise, 401 without a principal); putauth:hallmarkbefore them. A signed-in session holds every ability: abilities limit tokens, not users, so handlers still check that the user may touch a record. - Per-user cap: a user holds at most
HALLMARK_MAX_TOKENS_PER_USER(100) tokens; creating one more deletes the least recently used, in the same transaction. last_used_atis written at most once a minute per token, in the background with a 2 s timeout.- Revocation events:
Tokens::revoke,CurrentToken::revoke, a token deleted on use or by the cap publishAuthEvent::Revoked { key: "hallmark:token:<id>" }, andrevoke_all/revoke_all_exceptpublishAuthEvent::RevokedAll { kind: Tokens }, on the PubSub topicauth. - Issuing for an email and password:
issue_for_credentials(&app, &client, email, password, device_name, code, abilities)checks them with core’s login budgets and password gate (422 onemailwhen they do not match, 429 past a budget), asks the app’s login policies (a refusal answers its status), asks a registered second factor forcodewhen the user needs one (422 oncode, 429 past its budget, before any token exists), then creates the token;NewToken::created()answers 201 withCache-Control: no-store.revoke_currentis a handler forDELETE /api/tokens/current(204). - SPA mode (
.spa()/HALLMARK_SPA=true): a browser request on anauth:hallmarkAPI route that is first-party (Sec-Fetch-Site: same-origin;same-site/cross-sitewith anOriginlisted inHALLMARK_STATEFUL; withoutSec-Fetch-Site, anOrigin/Refererorigin equal toAPP_URL’s or a listed one) runs the web session stack, CSRF check first, and a signed-in session passes; every other request is bearer-only.GET /hallmark/csrf-cookiesets theXSRF-TOKENcookie. List only origins you control (any script on a listed origin acts with the signed-in session); a development origin such ashttp://localhost:5173never belongs in a production.env. - Console:
hallmark:prune-expired [--hours=24]deletes tokens that expired at least that long ago, 500 rows per statement. - Testing:
hallmark::testing::acting_as(&app, &user, &["orders:read"])creates a real token and sends it with every following request;token_forreturns one without changing the app’s headers.
The table comes from the app’s migration, which calls smeltery::hallmark::migrations::up / down.
§Licence
MIT OR Apache-2.0.
Modules§
- migrations
- The
personal_access_tokenstable, for the app’s migration. - testing
- Test helpers: real tokens for a
TestApp, checked by the real guard.
Structs§
- Access
Token - A token as the app sees it: never its secret or its hash.
- Current
Token - The token that authenticated this request, as a handler argument: on a route with
auth:hallmark(or any API route, where the stateless guards run for it). 401 when the request was not authenticated by a Hallmark token (a session, no credential);Option<CurrentToken>givesNoneinstead. - Hallmark
- Hallmark’s settings: read from
.envbyHallmark::new, changed with the builder methods, installed withHallmarkExt::hallmark. - NewToken
- A token just created: its plain text (shown once) and its stored data.
- Plain
Token - The plain text of a new token. It has no
Displayand noSerialize, and itsDebugshows onlyPlainToken(smt_…), so it never lands in a log line or a JSON body by accident. It has noPartialEqeither: tokens are verified by their hash, in constant time, never compared as text. - Tokens
- The app’s tokens: create, list, revoke and prune them. Get it with
Tokens::ofor as a handler argument.
Constants§
- CODE_
INVALID - The message on
codewhen the second factor is wrong. - CODE_
REQUIRED - The message on
codewhen the user needs a second factor and gave none. - FAILED
- The message on
emailwhen the address and password do not match (the same for unknown addresses). - GUARD
- The guard’s name: routes use it as
auth:hallmark. - MAX_
ABILITIES - The most abilities one token holds.
- MAX_
ABILITY_ LEN - The longest ability name, in bytes.
- MAX_
NAME_ LEN - The longest token name, in characters.
- TABLE
- The table tokens are stored in.
- TOKEN_
PREFIX - What every plain token starts with (secret scanners and log redaction find it by this).
Traits§
- Hallmark
Ext - Installs Hallmark on an
AppBuilder:.hallmark(Hallmark::new())inbootstrap/app.rs, after.auth::<User>(). - HasApi
Tokens - Token methods on the app’s user model (every
Authenticatabletype has them).
Functions§
- issue_
for_ credentials - Check
emailandpasswordand, when they match, create a token nameddevice_namewithabilitiesfor that user. The check is core’sverify_credentials: the login budgets (shared with the web login), a dummy hash for unknown addresses, the hash gate. Then the app’sLoginPolicys (App::check_login) decide, as at the web sign-in. When a second factor is registered (AppBuilder::second_factor) and the user needs one,codemust be a valid code, before any token exists. - revoke_
current - A handler for
DELETE /api/tokens/current(behindauth:hallmark): the token of the request is deleted (the device signs out) and 204 is answered. - valid_
ability - Whether
abilityis a valid ability name: exactly*, or 1 to 100 ofA-Z a-z 0-9 : . _ -.