auth-chad
Summary: what auth-chad is, what it is for, what it is not for, and where to start.
Key terms: passkey, device key, first-party, connected app, authentication, authorization.
Related: Concepts · Map · Recipes
auth-chad is a Rust authentication library that runs inside your application and stores its data in your database. People sign in with passkeys, which are bound to the site and resist phishing. Programs such as CLIs, servers and build jobs sign in with device keys that a person approves once. Other companies’ apps get short, scoped tokens through OAuth after the user consents.
auth-chad establishes who made a request and how recently they proved it. Your application decides what that person may do.
The picture as text
flowchart LR
P[Person with a passkey] --> A
M[Program with a device key] --> A
O[Another company's app, with consent] --> A
A[Your application<br/>with auth-chad inside] --> D[(Your database:<br/>users and your data)]
What it is for
| You want | auth-chad gives |
|---|---|
| Accounts with passkeys | Signup, login, more passkeys, logout, and a fresh passkey check before a risky action |
| Only invited people | Invite-only signup, with your own data on the invite |
| A CLI or a server that acts for a person, or as itself | Device login (approved in the browser) and machine keys |
| Other apps (for example an AI assistant) that read data for a user | OAuth with consent, short tokens, limited scopes |
| A way back after a lost phone | A recovery key, recovery by tenant owners, or email (unavailable with end-to-end encryption) |
| Organizations with members | Tenants and memberships, with your own columns such as a role |
| Data that the server must not read | End-to-end encryption keys that only a passkey or the recovery key can open |
| Growth from one machine to many | The same program on one process or many; see Scaling |
What it is not for
| Not for | Reason and alternative |
|---|---|
| Password logins, SMS codes, authenticator-app codes | They can be phished or copied. A password can be checked once, to move an old account to a passkey |
| Login links sent by email | Whoever controls the mailbox controls the account |
| “Log in with another company” as the only proof | That company would control the account. auth-chad accepts it as extra proof of identity only |
| Roles, permissions, sharing rules | These are authorization. Your application decides them with its own data |
| A hosted login service | auth-chad runs inside your program, on your database |
| SAML, old OAuth grants, a choice of algorithms | Each adds attack surface or allows downgrade attacks. There is one strict profile |
| Servers in many regions that cannot reach the users’ database | Unsupported; see Scaling |
Where to start
| You are | Read |
|---|---|
| New to the project | Concepts: the model and the vocabulary |
| Adding auth-chad to an application | Recipes, starting with start |
| Changing auth-chad | Map, Data, Flows, Interfaces, then the spec |
| A coding agent | INDEX.md, then one recipe or page |
| Reviewing the security | Threats and the spec |
| Planning hosting | Scaling |
Getting started
cd rust && cargo run -p example-minimal # a whole application with passkeys, on http://localhost:3000
[dependencies]
auth-chad = { git = "https://github.com/audiochad/auth-chad", rev = "<commit>", features = ["axum", "sqlite"] }
- Status: before a first release. The Rust crates work and are tested. No external security review has happened yet; values marked † in the spec need that review.
- The core rule: login is proof of a key. Anything that can be copied must be short-lived, single-use or limited.
- Exact rules: the spec is the contract. Where this wiki and the spec differ, the spec is correct.
- Decisions and their reasons: decisions.
- MIT license.
Concepts
Summary: the model behind auth-chad in seven ideas, and the vocabulary that the code and the spec use.
Key terms: flow, decision, write, commit, Authenticated, tenant, realm, policy, DPoP, ceremony, envelope.
Related: Data · Flows · Interfaces · spec 01
Every account change in auth-chad follows the same pattern. A pure function, called a flow, reads the database and
returns a decision: the result plus the list of rows to write. The application commits those rows in one
transaction, and only then is the result real. Every request carries a key proof, and the library alone turns a valid
proof into an Authenticated value that handlers can use. Configuration can make the rules stricter and has no
setting that weakens them.
The seven ideas
1. Login is proof of a key
A person proves a passkey. A program proves a device key. A browser session or an app signs every request with its session key (DPoP). A copied database row, log line or token cannot log anyone in.
2. A flow decides, the application commits
Each step (signup, login, device approval) is a flow: a function that reads, applies the rules and returns a decision. A decision has an output and a list of writes. The writes are committed together in one transaction, and the output is valid only after that commit succeeds. The application can add its own writes to the same transaction.
use auth_chad::{Decision, Store};
async fn finish<S: Store, T>(store: &S, decision: Decision<T>) -> Result<T, auth_chad::Error> {
store.commit(decision.writes).await?; // all or nothing
Ok(decision.out) // valid only after the commit
}
3. Every write has a condition
Another request can change a row between the read and the commit. Each write therefore states what it expects: “no
row with this key exists”, or “the row is still at version 7”. If any condition fails, the commit stores nothing and
the request fails with conflict. When two requests use the same single-use token, exactly one succeeds.
4. Only the library makes a proof
When a request passes the checks, the library creates an Authenticated value. It records who the caller is, the
tenant, the client level (first-party, connected app or API key), the key, and the last passkey use. Application code
cannot construct one. A handler declares in its signature what it needs, and requests that lack it are rejected before
the handler runs.
use auth_chad::axum::{FirstParty, FreshLogin, Refused};
async fn notes(who: FirstParty) -> Result<String, Refused> {
Ok(format!("notes of {}", who.user()?))
}
async fn delete_account(_fresh: FreshLogin<300>) -> &'static str {
"the passkey was used in the last 5 minutes"
}
5. Two levels of client
| First-party | Connected app | |
|---|---|---|
| Who | Your own web app, apps, CLIs and machines | Other companies’ apps, with the user’s consent |
| Token | Bound to a key, or a secure cookie for page loads | Short-lived, one audience, limited scopes |
| May change passkeys, sessions or recovery | Yes, after a fresh login | No |
6. Rules only get stricter
One profile fixes the algorithms, checks and upper limits. An instance, a tenant and a route can each add a policy. Policies combine, and the strictest value wins. No setting turns a check off.
7. All effects come from outside
Time, random bytes, storage, network and mail reach the library through traits. The library writes no logs. It returns audit events as writes in the same commit, so a change cannot be stored without its event. Every flow can be tested with a fake clock and fake random bytes.
Where the details are
- The exact model (realms, tenants, users, credentials, proofs, policies): spec 01.
- The contract of a flow (protected reads, writes, single use, effects, audit): spec 02.
Authenticatedand its fields:rust/formats/core/src/proof.rs.DecisionandWrite:rust/formats/core/src/store.rs.- The reasons for the strict rules: decision 001.
Glossary
| Term | Meaning | In the code |
|---|---|---|
| Realm | One set of users, one passkey domain (RP ID), one login origin | Config |
| Tenant | An organization or customer inside a realm. Each session belongs to one tenant. Without tenants, everything is in the root tenant | Tenant, Tenant::ROOT |
| Membership | Permission for a user to enter a tenant, with your own columns such as a role | Membership, Member |
| Passkey | A key on a person’s device, checked with WebAuthn | Passkey row, passkey flow |
| Device key | A key that a CLI, app or machine holds. A user device acts as its user; a machine acts as itself | Device, Subject::Machine |
| Session | A lasting login: a cookie for page loads, or a key-bound token | Session |
| DPoP | Demonstration of Proof of Possession: the client signs each request with the session’s key, so a stolen token is useless alone | dpop crate |
| Fresh login | A passkey use within the last few minutes. Risky actions require it | FreshLogin<SECS>, step_up_required |
| First-party | Your own clients | Level::FirstParty, FirstParty |
| Connected app | Another company’s app that a user allowed | Level::Connected, ConnectedApp |
| API key | A secret for a program that can only send a header. Off by default and discouraged | ApiKey |
| Flow | A function that decides one step and does no I/O | crates in rust/flows/ |
| Decision | What a flow returns: an output and writes | Decision { out, writes } |
| Write | A row change with a condition | Write |
| Commit | Storing a list of writes, all or nothing | Store::commit |
| Ceremony | A two-request step (start, finish) whose state travels in a sealed token | ceremony_invalid |
| Policy | Extra requirements; the strictest value wins | Policy |
| Hook | A point where your application decides or adds its own writes | Hooks |
| Event | An audit row for each change to an account | Event |
| Outbox | Work that runs after a commit, such as sending mail, at least once | Outbox, work |
| Place | The location of a tenant’s or user’s data when it is outside the users’ database | Place, Placement |
| Envelope | An encrypted copy of an end-to-end encryption secret that one passkey (PRF) or the recovery key opens | Envelope |
| Recovery key | A long random key that the person stores, used to regain access | RecoveryKey |
| Hold | A period after a recovery when old passkeys cannot be removed, so the owner can undo a theft | hold_until |
| Profile | The fixed set of algorithms and limits of a release | AC1 in the spec |
| † | A proposed value that needs a security review | spec |
Map
Summary: how the repository and the Rust crates are laid out, which crate may depend on which, and where to make a change.
Key terms: formats, flows, adapters, crate, feature, no_std, dependency rule.
Related: Interfaces · Data · AGENTS.md
The Rust code has three layers. Formats parse and verify signatures, keys and tokens. Flows apply the authentication rules to the rows they read and return decisions; they do no I/O. Adapters connect the flows to a database, a web framework and the system clock. Dependencies point downward only, so every rule can be tested without a database or a network.
The picture as text
flowchart TB
subgraph adapters [Adapters: all I/O]
axum[axum: HTTP API]
sqlite[sqlite]
postgres[postgres]
seaorm[sea-orm]
end
subgraph flows [Flows: decisions, no I/O]
signup
passkey
session
device
recovery
more[tenant, place, provider, oidc, e2ee, api-key]
end
subgraph formats [Formats: parse and check]
core
webauthn
dpop
jose
keys
end
adapters --> flows --> formats
adapters --> formats
The repository
| Folder | Contents |
|---|---|
spec/ | The exact rules. Change it in the same commit as the behavior |
schema/ | Reference SQL for SQLite and PostgreSQL: the core tables and each optional feature |
docs/wiki/ | This wiki |
docs/recipes/ | One page per task. Their Rust code compiles |
docs/decisions/ | Decisions and their reasons |
skills/ | Instructions for coding agents that add auth-chad to an application |
rust/ | The Rust workspace |
rust/loco/ | A separate workspace: the Loco adapter and an example |
The crates
| Crate | Layer | Job |
|---|---|---|
auth-chad-core | format | Shared types: IDs, rows and tables, writes and decisions, Authenticated, policies, errors, shared state (single-use marks, limits, leases), SQL text |
auth-chad-keys | format | ES256, Ed25519 and RS256 keys, JWK, thumbprints |
auth-chad-webauthn | format | Verifies passkey registrations and assertions |
auth-chad-jose | format | A strict subset of JWS, JWK and JWT |
auth-chad-dpop | format | DPoP proofs and nonces |
auth-chad-signup | flow | Open, invite-only and external signup |
auth-chad-passkey | flow | Register, log in, add and remove passkeys |
auth-chad-session | flow | Cookie or key-bound sessions, renewal, fresh login, logout, entering a tenant |
auth-chad-tenant | flow | Tenants and memberships |
auth-chad-place | flow | The location of a tenant’s or user’s data |
auth-chad-recovery | flow | Recovery key, tenant owners, email |
auth-chad-device | flow | Device login (RFC 8628) and machine keys |
auth-chad-api-key | flow | API keys (optional, discouraged) |
auth-chad-oidc | flow | Identity proof from another provider |
auth-chad-provider | flow | OAuth for first-party and connected apps |
auth-chad-e2ee | flow | End-to-end encryption: identity secrets, envelopes, recovery |
auth-chad-sqlite | adapter | Store on SQLite |
auth-chad-postgres | adapter | Store on PostgreSQL |
auth-chad-sea-orm | adapter | Store on the application’s SeaORM connection |
auth-chad-axum | adapter | The HTTP API, extractors, hooks, the worker, the browser script |
auth-chad | facade | Re-exports the crates by feature. Applications depend on this crate |
auth-chad-client | client | The account API from a CLI, or from wasm in a browser (feature browser) |
auth-chad-cli | tool | The auth-chad command: schema, features, memberships, after-restore, doctor, docs |
auth-chad-testing | test | A memory store, a fake clock, fake random bytes, a software authenticator, storage tests |
auth-chad-flow-tests | test | All flows together |
auth-chad-recipes | test | Compiles the Rust code in the recipes and in this wiki |
example-minimal | example | A whole application with passkeys |
auth-chad-loco | adapter | Loco integration (in rust/loco/) |
example-loco | example | A Loco application with auth-chad (in rust/loco/) |
Dependency rules
formatsdepend onformatsonly.flowsdepend onformats. Adapters depend on both.- A flow depends on no other flow, with these exceptions:
signupandrecoveryusepasskey;recoveryandtenantusesessionto end sessions. Shared types are incore. formatsandflowsareno_stdwithalloc: no async runtime, clock, randomness or environment.- Only adapters name a database, a web framework or an async runtime.
- No crate knows an application’s domain.
Features of the auth-chad crate
auth-chad = { git = "https://github.com/audiochad/auth-chad", rev = "<commit>", features = ["axum", "postgres"] }
| Feature | Adds |
|---|---|
passkey, session, signup | The default |
tenant, place, recovery, device, provider, oidc, api-key, e2ee | One flow each |
sqlite, postgres, sea-orm | A store |
axum | The HTTP API, with every flow it needs |
client | The Rust client |
rs256-sign | RS256 ID tokens for the provider |
Where to make a change
| Change | Place |
|---|---|
| A table or column | rust/formats/core/src/rows.rs, then AUTH_CHAD_BLESS=1 cargo test -p auth-chad-sqlite -p auth-chad-postgres |
| A limit or a policy | rust/formats/core/src/{config,policy}.rs |
| A login, session or OAuth rule | rust/flows/* |
| An HTTP route, extractor or hook | rust/adapters/axum/src |
| A refusal code | rust/formats/core/src/error.rs and rust/adapters/axum/src/error.rs |
| A task page | docs/recipes/, and add it to rust/recipes/src/lib.rs |
Code rules
- Pure functions. Side effects go behind traits, used through generics instead of
dyn. - Borrow before owning:
&strbeforeString. - No logging, no
unsafe, nounwrapoutside tests, no comments that repeat the code. - Tests run in parallel and need no network.
- A new dependency needs a reason in the pull request. Never write cryptography.
Tests
| Test | Covers |
|---|---|
| Official vectors, Wycheproof | formats |
| Unit and property tests with a fake clock | Every flow |
Storage conformance (auth-chad-testing::conformance) | Every store |
HTTP tests (rust/adapters/axum/tests) | Every route |
| Browser tests with a virtual authenticator | example-minimal, the Loco example |
| Compiled recipes and wiki | auth-chad-recipes |
All crates share one version and release together. Before 1.0, an application pins a commit.
Data
Summary: the tables that auth-chad keeps, the types that carry a request through the code, and how a row becomes a write.
Key terms: row, table, version, Stored, Write, Decision, Authenticated, Ctx, hash at rest, prefix, feature.
Related: Flows · Interfaces · spec 10
auth-chad stores its data in ordinary tables in your database, prefixed with auth_. Each row has a version that
increases with every change, and every write names the version it expects. Tokens, invites and codes are stored as
hashes, and keys are stored as public keys. A copy of the database is therefore not enough to log in.
The picture as text
erDiagram
users ||--o{ passkeys : has
users ||--o{ sessions : has
users ||--o{ devices : approved
users ||--o| recovery_keys : has
users ||--o{ envelopes : "e2ee only"
sessions ||--o{ tokens : issues
devices ||--o{ tokens : issues
tenants ||--o{ memberships : has
users ||--o{ memberships : has
users ||--o{ events : "audit"
The tables
People and their credentials
| Table | One row is | Notes |
|---|---|---|
users | A user | ID (16 bytes), optional handle or address, disabled, recovery hold. Names and profiles belong in your tables |
passkeys | A passkey | Public key (COSE), sign counter, last use |
recovery_keys | A recovery key | Only the public verifier derived from the key |
identities | An account at another provider | Proof of identity; it cannot log in |
envelopes | An encrypted copy of the e2ee secret | One per passkey (PRF) and one for the recovery key |
Lasting logins
| Table | One row is | Notes |
|---|---|---|
sessions | A login | Tenant, kind (browser, cookie, native), key thumbprint, last passkey use, expiry |
tokens | An access, cookie, refresh or connected-app token | Stored as a hash. A used refresh token stays, so reuse is detected |
devices | An approved CLI, app or machine | Public key, kind (user or machine), scope, your data |
device_requests | A device waiting for approval | User code (hash), address, state |
api_keys | An API key | Hash, scopes, expiry (at most 90 days) |
Other companies’ apps
| Table | One row is | Notes |
|---|---|---|
clients | A connected app | Redirect URIs, keys |
grants | A user’s consent to an app | Scope, audience, the key it is bound to |
codes | An authorization code, a pushed request, or a code to enter a tenant | Hash, single use |
Account recovery
| Table | One row is | Notes |
|---|---|---|
recoveries | A pending recovery (email or owners) | Hash, ready time, expiry |
invites | An invite | Hash, optional identifier, your data |
Bookkeeping
| Table | One row is | Notes |
|---|---|---|
events | An audit event | Time, user, device, action, target, address. No secrets or names |
outbox | Work after a commit, such as a mail | Retried until it succeeds, at most five times |
used | A single-use mark | The hash of a used challenge or proof |
limits | One counted call for a rate limit | Expires after one minute |
leases | The process that currently owns a piece of work | Prevents two processes from sending the same mail |
features | An optional group of tables that this database has | tenants, places |
Optional features
| Table | Feature | One row is |
|---|---|---|
tenants | tenants | An organization or customer, with its tag for a host or path |
memberships | tenants | A user who may enter a tenant, plus your own columns |
places | places | The location of a tenant’s or user’s data |
Run auth-chad schema sqlite --with tenants to print the SQL.
The types that carry a request
| Type | Holds | Created by |
|---|---|---|
Ctx | The current time, the tenant, the config and keys, the caller’s address and device | The adapter, once per request |
Stored<T> | A row and its version | The store, on a read |
Write | A change with its condition | A flow, or your code |
Decision<T> | out and writes | A flow |
Authenticated | Who, tenant, level, binding, session, device, last passkey use, scopes | The library only |
Refused | A refusal code, sent as {"error": "<code>"} | Extractors and routes |
use auth_chad::core::rows::Session;
use auth_chad::core::row::Field;
use auth_chad::core::StoreError;
use auth_chad::{Reader, UserId};
async fn count_sessions<R: Reader>(db: &R, user: UserId) -> Result<usize, StoreError> {
let rows = db.find_by::<Session>("user", user.store()).await?;
Ok(rows.len()) // each item is a Stored<Session>: the row and its version
}
From a row to a write
A read returns Stored<T>. Each write that depends on that read names its version.
| Write | Condition | Use |
|---|---|---|
Write::insert(row) | No row with this key or unique value exists | New rows |
stored.replace(row) | The row is still at this version | Changes |
stored.delete() | The row is still at this version | Removals |
stored.require() | The row is still at this version; nothing changes | A decision depends on the row |
stored.touch() | Like replace with the same row | Two commits that depend on the row cannot both succeed |
Write::delete_where::<T>(column, value) | None | Clean-up, such as ending all sessions of a user |
Rules for rows
- Each table is declared once, with the
table!macro inrust/formats/core/src/rows.rs. The SQL for SQLite and PostgreSQL is generated from that declaration. - User, tenant, session and device IDs are 16 bytes. Your application maps its own IDs to them.
- Every tenant-scoped read takes the tenant as an argument. There is no form without it.
- The prefix (
auth_by default) is set when the store opens. The SQL text is built once. - Optional tables exist only when the database was migrated with their feature.
check_tablesrefuses to start a server that needs a feature that the database lacks. - Your own data about people (name, picture, role names) lives in your tables, with the user ID as a plain value.
Where the details are
- Exact columns and indexes: spec 10 and
schema/. - Shared state (marks, limits, leases): spec 10, shared state.
- Your own tables in the same commit: own-tables recipe.
Flows
Summary: how data moves through auth-chad: the check on every request, the decide-then-commit loop, and the main journeys (signup, login, device login, recovery, connected apps).
Key terms: request check, decide, commit, ceremony, DPoP, fresh login, device code, envelope, hold, outbox, worker.
Related: Data · Concepts · spec 02
Every request passes the same check. The auth-chad layer reads the cookie or the signed token, looks up the session in
the database, and either creates an Authenticated value or rejects the request; then your handler runs. A request
that changes an account calls a flow, which decides the change. The change and its audit event are stored in one
transaction. Work that must follow the change, such as a mail, waits in the outbox until the worker runs it.
The check on every request
The picture as text
sequenceDiagram
participant C as Client
participant L as auth-chad layer
participant DB as Users' database
participant H as Your handler
C->>L: request + cookie, or token + DPoP proof
L->>DB: read the session or token, mark the proof as used
alt valid
L->>H: Authenticated (who, tenant, level, key, last passkey use)
H-->>C: your response
else invalid
L-->>C: 401 or 403 with {"error": code}
end
- The check runs on every request, and its result is never cached. A logout takes effect on the next request, in every process.
- If the database cannot answer, the request fails with
503.
Decide, then commit
The picture as text
flowchart LR
R[Request] --> F["Flow<br/>(reads, decides)"]
F --> D["Decision<br/>out + writes"]
D --> A["+ your writes<br/>(hooks)"]
A --> T[["One transaction<br/>all or nothing"]]
T -->|ok| O[Use out: respond to the client]
T -->|a condition failed| X[conflict: nothing changed]
A login in code: the passkey flow proves the person, the session flow opens a session, and one commit stores both.
use auth_chad::core::Draws;
use auth_chad::passkey::{self, Assertion};
use auth_chad::session::{self, Bind, Opened};
use auth_chad::{Ctx, Error, Store};
async fn log_in<S: Store>(
ctx: &Ctx<'_>,
store: &S,
draws: &mut impl Draws,
ceremony: &str,
assertion: &Assertion,
jkt: [u8; 32],
) -> Result<Opened, Error> {
let proved = passkey::login_finish(ctx, store, draws, ceremony, assertion).await?;
let opened = session::open(ctx, store, draws, &proved.out, Bind::Key { jkt, native: false }).await?;
let opened = opened.and(proved.writes);
store.commit(opened.writes).await?;
Ok(opened.out)
}
The axum adapter’s routes do this for you. Call flows directly only when you build your own routes.
Signup
The picture as text
sequenceDiagram
participant B as Browser
participant S as Server
participant DB as Database
B->>S: signup/start (invite, names)
S-->>B: challenge, in a sealed ceremony token
Note over B: the person creates a passkey
B->>S: signup/finish (ceremony, new passkey, key proof)
S->>S: check the passkey and the invite
S->>DB: one commit: user, passkey, session, invite used, event, your rows (commit_signup)
S-->>B: session
- A ceremony takes two requests. Its state travels in a sealed token, and the challenge is marked as used at the end, so each ceremony works once.
- Your
commit_signuphook adds your own rows (a profile, a first project) to the same commit, or refuses the signup.
Login and fresh login
login/startreturns a challenge, and the person uses a passkey.login/finishverifies it and opens a session, bound to the client’s key (DPoP) or, for page loads, to a cookie.- A risky action requires a fresh login: a passkey use within the last few minutes. Without one, the response is
step_up_required, and the client asks for the passkey again (step-up).
Device login (CLI, app, machine)
The picture as text
sequenceDiagram
participant D as Device (CLI)
participant S as Server
participant P as Person's browser
D->>S: device_authorization (name, scope, its public key)
S-->>D: device code + user code + link
D->>P: shows the link and the code
P->>S: opens the link, sees name, scope and address
P->>S: approve (fresh login, your app data)
S->>S: hooks: may_approve, device_kind, commit_approve
loop until approved
D->>S: token (device code, signed with its key)
end
S-->>D: key-bound token
- A user device acts as the person. A machine acts as itself, with its own scopes.
- The device holds no copyable secret: it signs every token request with its own key.
Recovery
| Method | Proof | Works with end-to-end encryption |
|---|---|---|
| Recovery key | The person presents a key they stored | Yes: the key also opens its envelope |
| Tenant owners | Owners approve | No |
| A mailed link, after a waiting period | No |
After a recovery, the account is on hold: old passkeys cannot be removed for a while. During the hold, the real owner can undo a recovery that a thief started. Undo removes everything added since the recovery: passkeys, sessions, devices, connected-app grants and API keys.
Connected apps (OAuth, MCP)
- The app sends the person to the login origin with a pushed authorization request.
- The person logs in and consents to named scopes, which creates a grant.
- The app receives short-lived tokens for one audience. These tokens cannot change passkeys, sessions or recovery.
After the commit: outbox and worker
work(&auth) runs every few seconds, in the web process or in a separate worker process. It:
- removes expired rows (limits, single-use marks, sessions, codes);
- sends mail from the outbox and retries failures;
- runs place work (
provision,remove).
Each piece of work holds a lease in the database, so two processes never run it at the same time.
Where the details are
- The exact contract of a flow (no clock, no randomness, protected reads): spec 02.
- Every route and its codes: spec 04, 05, 06, 07, 08.
- The hooks where your code joins a flow: Interfaces.
- Recipes: devices, recovery, sensitive-action, connected-apps.
Interfaces
Summary: the traits and types where your code meets auth-chad: what you implement, what you call, and what you put in a handler’s signature.
Key terms: trait, generic, Store, Reader, Clock, Draws, Hooks, Refusal, By, extractor, Placement, Mailer, Http, Passkeys.
Related: Map · Data · Recipes
auth-chad performs no I/O of its own. It receives storage, time, random bytes and your application’s rules through a
few Rust traits, passed as generic parameters. Most applications implement one trait, Hooks, and override only
the methods they need, since every method has a safe default. Handlers state the proof they require by naming an
extractor in their signature.
The picture as text
flowchart LR
subgraph you [Your application]
H[Hooks: your rules and rows]
R[Handlers: name an extractor]
P[Placement: where data lives]
end
subgraph lib [auth-chad]
A[Auth]
end
S[(Store: SQLite, PostgreSQL, SeaORM)]
C[Clock + Draws]
A --> H
R --> A
A --> P
A --> S
A --> C
What you implement, what you call
| Interface | You | Default |
|---|---|---|
Hooks | Implement the methods you need | Every method has a safe default |
Extractors (FirstParty, FreshLogin, …) | Name them in handlers | — |
Store, Reader | Pick a store; call Reader to read rows | SqliteStore, PostgresStore, SeaOrmStore |
Clock, Draws | Nothing, except in tests | System time and system random bytes |
Placement | Implement it only with the places feature | NoPlaces |
Mailer | Implement it only without the axum adapter | Hooks::send in axum |
Columns | Declare with member_columns! for your membership columns | () |
Http, Passkeys | Implement them only in a client on a new platform | browser::Fetch, browser::Passkey |
Service | Nothing: Auth implements it | — |
Row, Field, Worker | Nothing: used inside the library | — |
Hooks
Hooks holds your application’s rules in one type. Every method is optional.
use auth_chad::axum::{Hooks, Refusal};
use auth_chad::core::Store as _;
use auth_chad::signup::Created;
use auth_chad::sqlite::SqliteStore;
use auth_chad::{Authenticated, Code, Tenant, Write};
struct Rules;
impl Hooks<SqliteStore> for Rules {
async fn may_invite(&self, _: &SqliteStore, who: &Authenticated, tenant: Tenant) -> bool {
tenant == Tenant::ROOT && who.is_first_party() // ask your own tables: is this an admin?
}
async fn commit_signup(
&self,
store: &SqliteStore,
_created: &Created,
app: &serde_json::Value,
writes: Vec<Write>,
) -> Result<(), Refusal> {
if app["terms"] != true {
return Err(Code::InvalidRequest.into());
}
Ok(store.commit(writes).await?) // or commit_with: your rows in the same transaction
}
}
| Group | Methods | You decide |
|---|---|---|
| Signup | commit_signup, valid_names, invite_data, may_invite | Who may join, your first rows |
| Devices | may_request_device, may_approve, device_kind, commit_approve, commit_revoke | Which devices, who approves, your rows |
| Recovery | commit_recovery, commit_undo, may_recover, verified_address, find_account | Notices, your clean-up |
| Tenants | may_create_tenant, may_manage | Who runs a tenant |
| Others | may_view, may_create_key, send, exchange, provider_keys | Support access, API keys, mail, external login |
- A commit hook receives the writes of the decision and must commit them, together with any writes of your own.
- A commit hook refuses with a
Refusal: a library code (Code::Forbidden.into()) or your own status and code (Refusal::App(StatusCode::CONFLICT, "name_taken")). commit_approve,commit_revokeandcommit_undoreceiveBy { who, ip }: the caller and their address (Nonewithwithout_addresses).
Extractors: proof in a handler’s signature
| Extractor | The request has | Refused with |
|---|---|---|
FirstParty | A session of your own client, or a user device | unauthenticated |
InPerson | The user in person: not a machine, not someone who views as the user | forbidden |
FreshLogin<SECS> | A passkey use in the last SECS seconds | step_up_required |
ConnectedApp | A token of an app that the user allowed, for this API. Check its scopes | unauthenticated, forbidden |
ApiKey | An API key (only if turned on) | unauthenticated |
Here | The tenant of the request (the root tenant outside one) | — |
Member<C> | A membership in the request’s tenant, with your columns | not_found |
At<P> | The place of the request’s tenant or user | 503 not_ready or moving |
Caller | The result of the layer’s check, for your own extractors and middleware | — |
use auth_chad::axum::{Caller, Refused};
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
struct Admin(auth_chad::UserId);
impl<S: Sync> FromRequestParts<S> for Admin {
type Rejection = Refused;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Refused> {
let user = Caller::of(parts)?.first_party()?.user()?;
Ok(Self(user)) // then ask your tables: is this user an admin?
}
}
Store and Reader
A store reads rows and commits writes, all or nothing. Use it through generics instead of dyn.
use auth_chad::core::rows::Passkey;
use auth_chad::core::row::Field;
use auth_chad::{Reader, UserId};
async fn has_two_passkeys<R: Reader>(db: &R, user: UserId) -> bool {
db.find_by::<Passkey>("user", user.store()).await.is_ok_and(|rows| rows.len() >= 2)
}
| Method | Does |
|---|---|
Reader::get::<T>(key) | One row and its version |
Reader::find_by::<T>(column, value) | Rows by an indexed column |
Store::commit(writes) | All or nothing, in order |
Store::prune(now) | Removes expired rows (the worker calls it) |
commit_with(writes, f) (SQLite, PostgreSQL) | Your SQL in the same transaction |
Clock and Draws
Time and random bytes are injected, so tests are deterministic. Production code uses the defaults.
use auth_chad::UnixTime;
use auth_chad::core::{Clock, Draws};
struct Fixed;
impl Clock for Fixed {
fn now(&self) -> UnixTime {
UnixTime(1_800_000_000)
}
}
struct Counting(u8);
impl Draws for Counting {
fn fill(&mut self, _name: &'static str, out: &mut [u8]) {
self.0 = self.0.wrapping_add(1);
out.fill(self.0); // for tests only: auth-chad-testing has FakeClock and SeqDraws
}
}
Auth::new(...).with_sources(clock, draws) puts them in.
Placement, Mailer, Columns
| Trait | Methods | Recipe |
|---|---|---|
Placement | choose a place for a new tenant or user; provision and remove its data (safe to repeat) | directory |
Mailer | send(mail) -> bool; false tries again later | recovery |
Columns | Your columns of the memberships table, declared with member_columns! | tenants |
The client: Http and Passkeys
auth-chad-client calls the account API from a CLI, or from wasm in a browser.
| Trait | You give | In a browser |
|---|---|---|
Http | send(request) -> response, with your HTTP library | browser::Fetch |
Passkeys | create, get, prf | browser::Passkey |
See the client recipe.
Type parameters
Auth<S, H, C, D, M, P>carries the store, hooks, clock, draws, membership columns and placement as type parameters.Servicenames those types for handlers.RowandFieldmap a struct to a table and a Rust value to a database value. Thetable!macro writes them.Workeris the flow-level form ofPlacement, for code without the axum adapter.- The full list of hooks with their documentation:
rust/adapters/axum/src/lib.rs, orcargo doc -p auth-chad-axum --open.
Scaling
Summary: how an application with auth-chad grows from one process and one database to many processes and many databases, without changing its handlers.
Key terms: step, users’ database, directory, place, load balancer, with_proxies, worker, lease, shared state.
Related: Flows · load-balancer recipe · directory recipe · spec 15
An application with auth-chad scales in three steps: one process with one database, many processes with one database, and many processes with data spread over several database servers. Every request checks its session in the users’ database before your code runs, so processes share no state and need no trust between them. Moving to the next step changes configuration and hosting; handlers stay the same. Most applications stay at step 1.
The picture as text
flowchart TB
subgraph s1 [Step 1]
direction LR
A1[One process] --> D1[(One database)]
end
subgraph s2 [Step 2]
direction LR
L2[Load balancer] --> A2[Process 1] & B2[Process N]
A2 & B2 --> D2[(PostgreSQL)]
end
subgraph s3 [Step 3]
direction LR
L3[Load balancer] --> A3[Process 1] & B3[Process N]
A3 & B3 --> U3[(Users' database:<br/>who and where)]
A3 & B3 --> X3[(Data server 1)] & Y3[(Data server 2)]
end
s1 --> s2 --> s3
Which step
Answer these questions in order and stop at the first that fits.
| Question | Step |
|---|---|
| Does one process carry the load? | Step 1. Most applications. Tenants do not change the answer |
| Do you need more processes, or a second machine for failover? | Step 2. Move to PostgreSQL, put a load balancer in front |
| Is the data too large for one database, or do you want a database for each customer? | Step 3. The users’ database also says where each tenant’s or user’s data is |
Multiple regions, and servers that cannot reach the users’ database, are out of scope.
| Data | Processes | Database | |
|---|---|---|---|
| Step 1 | One database | One | SQLite (recommended) or PostgreSQL |
| Step 2 | One database | Many identical, behind a load balancer | PostgreSQL |
| Step 3 | Users’ database, and your data on one or many servers | Many identical | PostgreSQL |
Step 1: one process, one database
- Signup and your first rows in one transaction. Foreign keys and joins to users. One backup.
- Limits: one machine (with SQLite, several processes on that machine can share the file, for example during a deploy), and all data must fit in one database.
Step 2: many processes, one database
- More capacity; deploys and failures without downtime. Any process serves any request.
- Needs: PostgreSQL (SQLite is not synced between machines), the real client address with
with_proxies(n), and the worker. Rate limits, single-use marks and leases are stored in the database, so every process sees them.
Step 3: your data on database servers
- Any number of PostgreSQL servers, each with one shared database or one database for each customer. A tenant can be moved, restored or deleted alone. The session carries the place, so no extra lookup is needed.
- Costs: no shared transaction and no foreign keys between users and your data (an outbox joins signup and your data); every process must reach the users’ database and every data server.
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
struct Place {
server: String, // "db2": the process maps it to a connection string from its own settings
database: String, // "customer_7". Never a password
}
Requests get 503 not_ready until provision answers true, and 503 moving during a move.
The three independent decisions
| Decision | Choices | What it changes for auth |
|---|---|---|
| A. Data | One database, or users’ database plus data databases | The second adds the places feature |
| B. Processes | One, or many identical processes behind a load balancer | Many processes need PostgreSQL, with_proxies and a worker |
| C. Tenant address | None, a path (/t/acme/), or a host (acme.example.com) | The tenants feature, cookies, your DNS. Every step works with every choice |
- A path for each tenant: one host name and one certificate; one cookie per tenant (
__Host-session-acme, at most 20† at once). All tenants share one web origin, so a script flaw in one tenant’s pages affects all of them. - A host for each tenant: a wildcard DNS record and certificate. Each tenant has its own origin and cookie. A browser enters with a one-use code of 60 seconds. One passkey for the parent domain works on all hosts.
What we assume about the network
| Assumption | Why |
|---|---|
| Every process reaches the users’ database, and in step 3 every data server | Each request is checked there |
The load balancer passes the Host header | Host tenants and key proofs name that host |
The load balancer adds the client address to X-Forwarded-For, and the program knows the number of proxies (with_proxies(n)) | Rate limits count each client; a client cannot write its own entry |
| The processes are reachable only through the load balancer | Otherwise a client can write X-Forwarded-For itself |
TLS can end at the load balancer or at the process. Sticky sessions are not needed.
The worker
work(&auth) does the background work: removes expired rows, sends mails that wait, runs the work of places.
- Axum or your own server: call it every few seconds in a loop, in the web process (step 1) or in a worker process
of the same binary, for example with
ROLE=worker(steps 2 and 3). - Loco: register the task
auth_workand run it from Loco’s scheduler, for example every 10 seconds. - Any number of processes can run it. Each piece of work holds a lease (a mail one minute, a place five minutes).
provisionandremovemust be safe to repeat.
Rules in every step
| Subject | Rule |
|---|---|
| Sessions, tokens, devices, API keys, memberships | Only in the users’ database |
| The check | Once for each request, before your code. Never cached |
| Logout, removal, disabled user | Works from the next request, in every process |
| Check not possible | 503 |
| WebSocket, event stream | Checked when it opens; your server closes it after 5 minutes† at the latest |
| Signed link (media, download) | Works until its own end, at most 10 minutes†, also after a logout |
| What a person may do | Your code, with your data |
| Place | By tenant or by user. An application chooses one, never both |
Patterns we do not support
| Pattern | What goes wrong |
|---|---|
| Sessions in application databases | Each logout must reach every database |
| A JWT that processes check without the database | Logout and removal take effect only when the token expires |
| Cached answers of the check | The same, for the time of the cache |
A header like X-User from a proxy | Whoever reaches the process can write it |
| A proxy that checks sessions for the processes | A second way in, with its own rules |
| SQLite on several machines | Syncing a database is a problem of its own |
| Routing tenants to machines at the load balancer | Not needed: any process serves any tenant |
What lives where
- With the users: users, passkeys, sessions, tokens, devices, invites, events, the outbox, rate limits, single-use marks, leases; tenants, memberships (with your columns) and places with their features; your own tables about people.
- Your data: everything else, with the user ID and tenant ID as plain values.
auth-chad memberships postgres role:text=member seat:int?prints the migration for your membership columns and the Rust declaration.
Moving between steps
| Step | What you do |
|---|---|
| 1 → 2 | Move to PostgreSQL. Put a load balancer in front, set with_proxies. Run the worker. Start more processes |
| 2 → 3 | Move your tables to data servers. Remove foreign keys to users. Implement Placement |
| Back | The same steps in the other order |
Costs of step 3
| You lose | What the library gives |
|---|---|
| One transaction for auth and your data | An outbox: provision after signup, perhaps more than once |
| Foreign keys and joins to users | The user ID |
| A consistent backup | place::in_states lists places that wait for their data |
| Few connections | Nothing: keep pools small, or share a database between customers |
| Valid sessions after restoring an old users’ database | auth-chad after-restore prints SQL that ends all sessions, tokens, codes and API keys |
Capacity of one process
This estimate uses published SQLite measurements; auth-chad has no benchmark of its own yet. On a 5-dollar machine, one published test reached about 300,000 reads and 28,000 write transactions a second. One million people a day, with 100 requests each, is about 23,000 reads and 6,100 writes a second at peak: well inside one process.
Status: all three steps work today, for SQLite and PostgreSQL, with tenants, memberships and places.
Recipes
Summary: one short page for each task, with code that compiles. Find your task here.
Key terms: recipe, feature, start, route, device, tenant, recovery, client, e2ee.
Related: Interfaces · Concepts · skill for agents
Each recipe shows how to add one capability to an application, with code that compiles. Find the task in the table,
copy the code, and adapt the names. The table lists the auth-chad crate feature that each recipe needs.
The recipes
| You need | Recipe | Feature |
|---|---|---|
| Passkey accounts in a new application | start | axum, sqlite or postgres |
| A handler that needs a user | protect-a-route | axum |
| The passkey again before a risky action | sensitive-action | axum |
| Invite only, admins | invites | axum |
| Your own tables in the same transaction | own-tables | sqlite, postgres |
| A CLI, device or machine | devices | axum |
| Other apps as clients (OAuth, MCP) | connected-apps | axum |
| An API key for a program that can only send a header (not recommended) | api-keys | axum |
| A way back into an account | recovery | axum |
| “Sign in with…”, company login | external-login | axum |
| Organizations with members (tenants) | tenants | axum |
| Data of each tenant or user in its own database | directory | axum, postgres |
| Many processes, a load balancer, the worker | load-balancer | axum |
| A CLI or a Rust/wasm web app as a client | client | client |
| End-to-end encryption | e2ee | e2ee |
| Support staff who see the application as a user | view-as | axum |
| Tests | testing | dev-dependency auth-chad-testing |
| A Loco or SeaORM application | loco | auth-chad-loco, or sea-orm |
How recipes stay correct
- The Rust code on the recipe pages and on the wiki pages compiles:
rust/recipesincludes each page as a documentation test. A new page goes intorust/recipes/src/lib.rs. - A recipe shows one task. The wiki pages explain the reasons, and the spec has the exact rules.
Start
[dependencies]
auth-chad = { git = "https://github.com/audiochad/auth-chad", rev = "<commit>", features = ["axum", "sqlite"] }
use std::{path::Path, sync::Arc};
use auth_chad::{Config, Prefix, axum::Auth, sqlite::SqliteStore};
fn auth(master: &[u8; 32]) -> Result<Arc<Auth<SqliteStore>>, Box<dyn std::error::Error>> {
let config = Config::new(
"myapp/v1", // never change it
"https://app.example.com", // where the API is
"app.example.com", // passkeys belong to this domain: never change it
"My app",
&["https://app.example.com"], // pages that may call the API
)?;
let store = SqliteStore::open(Path::new("/var/lib/myapp/app.db"), &Prefix::default(), 4)?;
Ok(Arc::new(Auth::new(config, master, store)?))
}
- Master key: 32 random bytes from a secret store. Never in the repository.
- Tables: run the migration as a deploy step, not at start.
auth-chad schema sqliteprints the SQL, andSqliteStore::create(path, prefix, readers, &[])runs it.opennever creates tables. Tenants and places are optional features: add them with&[Feature::Tenants]when you use them, and callauth.check_tables()at start. - Routes:
Router::new()….with_state(auth.clone()).merge(auth.router()). The API is below/auth. - Page:
import { signup, login, logout, session, stepUp } from "/auth/auth-chad.js". Call them from a click. - Behind a proxy:
with_proxies(n)(load-balancer). - A web app on another host (for example
app.example.comcallingapi.example.com): list its origin inConfigorigins (for passkeys) and inwith_web_origins(for CORS). Its calls carry no cookies, so it logs in with a key-bound token, for example with the Rust client. A key-bound policy refuses cookies everywhere. - No client addresses in audit events:
without_addresses(). Rate limits still use them. - Housekeeping: call
auth_chad::axum::work(&auth)every few seconds: it prunes, sends mails and runs places.
A whole application: rust/examples/minimal.
Protect a route
Add Auth::layer to the routes, and an extractor to the handler. The state of the application can be anything.
use std::sync::Arc;
use auth_chad::axum::{Auth, FirstParty, Refused};
use auth_chad::sqlite::SqliteStore;
use axum::Router;
use axum::routing::get;
async fn notes(who: FirstParty) -> Result<String, Refused> {
let user = who.user()?; // a UserId; a machine gives `forbidden`
Ok(format!("notes of {user}"))
}
async fn home(who: Option<FirstParty>) -> &'static str {
if who.is_some() { "welcome back" } else { "hello" }
}
fn app(auth: &Arc<Auth<SqliteStore>>) -> Router {
let routes = Router::new().route("/notes", get(notes)).route("/", get(home));
auth.layer(routes).merge(auth.router())
}
Your own extractor builds on it, for example for a user’s role:
use auth_chad::axum::{Caller, Refused};
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
struct Admin(auth_chad::UserId);
impl<S: Sync> FromRequestParts<S> for Admin {
type Rejection = Refused;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Refused> {
let user = Caller::of(parts)?.first_party()?.user()?;
// Ask your database: is this user an admin?
Ok(Self(user))
}
}
- Cookies and DPoP both work. A
POSTwith a cookie must come from a page inConfig.origins. - The layer runs once per request and refuses nothing. Without it, the extractors answer 503 to everyone.
- Other middleware can read
Caller, for example to log who did what. It must be inside the layer. - May this user do this? That is the application’s decision. The library says who it is.
Ask for the passkey again
use auth_chad::axum::FreshLogin;
async fn delete_account(fresh: FreshLogin<300>) -> String {
format!("{} proved it in the last 5 minutes", fresh.0.user())
}
More than 900 seconds does not compile. In the page:
import { stepUp } from "/auth/auth-chad.js";
button.onclick = async () => {
let res = await fetch("/account", { method: "DELETE" });
if (res.status === 401 && (await res.json()).error === "step_up_required") {
await stepUp("delete account");
res = await fetch("/account", { method: "DELETE" });
}
};
Inside the application, take Fresh<300> as an argument. Then no caller can forget the check:
use auth_chad::Fresh;
fn transfer(_proof: Fresh<300>, _to: &str) {}
Invites
use auth_chad::core::policy::Policy;
use auth_chad::{Authenticated, Config, Store, Tenant};
use auth_chad::axum::Hooks;
fn invite_only(config: Config) -> Config {
config.with_policy(Policy::invite_only())
}
#[derive(Clone)]
struct App;
impl<S: Store> Hooks<S> for App {
async fn may_invite(&self, _: &S, who: &Authenticated, tenant: Tenant) -> bool {
tenant == Tenant::ROOT && who.is_first_party() // replace with: is this user an admin?
}
}
POST /auth/invites gives a token once. For a tenant: /auth/tenants/{name}/invites, and the new user becomes a member. The link is https://app.example.com/signup?invite=<token>, for one account and
7 days. GET lists and DELETE /auth/invites/{id} cancels.
The first account, from the host: signup::create_invite(&ctx, &mut draws, None, None, "admin"), then commit. The last
argument is your own data: it comes back in Created.invite at signup.
data in POST /auth/invites is your own data too, and the list shows it. If it gives rights, check it in
Hooks::invite_data: the default stores what the person asked for, so an admin could make admin invites.
Your own tables in the same transaction
use auth_chad::core::CommitError;
use auth_chad::signup::Created;
use auth_chad::sqlite::SqliteStore;
use auth_chad::axum::{Hooks, Refusal};
use auth_chad::{Code, Write};
#[derive(Clone)]
struct App;
impl Hooks<SqliteStore> for App {
async fn commit_signup(
&self,
store: &SqliteStore,
created: &Created,
app: &serde_json::Value,
writes: Vec<Write>,
) -> Result<(), Refusal> {
let user = created.user.id.0;
let color = app["color"].as_str().unwrap_or("blue").to_owned(); // the signup's own "app" field
if color.len() > 20 {
return Err(Code::InvalidRequest.into());
}
store
.commit_with(writes, move |tx| {
tx.execute("INSERT INTO profiles (owner, color) VALUES (?1, ?2)", (user, color))
.map(|_| ())
.map_err(|_| CommitError::Backend)
})
.await?;
Ok(())
}
}
profiles.owner can be BLOB REFERENCES auth_users (id). If your check or your insert fails, the user is not created.
The signup’s JSON can carry your own data in "app". To refuse with your own code, return
Refusal::App(StatusCode::CONFLICT, "name_taken"): the client gets that status and {"error": "name_taken"}.
An application with its own connections calls auth_chad::sqlite::apply(&tx, &sql, writes) or
auth_chad::postgres::apply(&tx, &sql, writes).await inside its own transaction. get and find read with any
connection.
CLIs and machines
Merge auth.oauth_router() at the root. A device makes a key, and sends it with a DPoP proof:
| Step | Who | Call |
|---|---|---|
| 1 | Device | POST /oauth/device_authorization with device_name, scope, data |
| 2 | Device | Shows user_code, the link, and its fingerprint (device::fingerprint) |
| 3 | Page | GET /auth/device/{code}: show the name, scope and fingerprint. The person compares |
| 4 | Page | POST /auth/device/{code}/approve with {"machine": false}. Needs a fresh login |
| 5 | Device | POST /oauth/token with the device code, every 5 seconds |
| 6 | Device | Later: POST /oauth/token with a signed assertion. There is no refresh token to lose |
scope and data mean what your application wants. Decide in the hook:
use auth_chad::{Authenticated, Store};
use auth_chad::axum::Hooks;
use auth_chad::core::rows::DeviceKind;
#[derive(Clone)]
struct App;
impl<S: Store> Hooks<S> for App {
async fn may_request_device(&self, scope: &str, _data: &str) -> bool {
scope == "user" || scope == "machine" // anything else: invalid_scope
}
async fn may_approve(&self, _who: &Authenticated, scope: &str, _data: &str) -> bool {
scope == "user" // also who may see and deny the request
}
fn device_kind(&self, scope: &str, _data: &str, _asked: DeviceKind) -> Option<DeviceKind> {
Some(if scope == "machine" { DeviceKind::Machine } else { DeviceKind::User }) // the scope decides
}
}
commit_approvegets the approval’s own"app"field and the writes: add your rows, for example a key sealed to the device, in the same commit.commit_revokedoes the same for a revocation, and can refuse it.- These hooks get
By { who, ip }: who acts, and the address of the request, for your own audit rows.ipisNonewithwithout_addresses. - A hook refuses with a
Refusal: a library code, or your own status and code (Refusal::App). GET /auth/devices?kind=userlists only one kind.- The request page and the list have the device’s
public_key(a canonical JWK), and the list has yourdata: an application can show a fingerprint of its own.
A user device acts as the user. A machine acts as itself (Subject::Machine). Neither is ever fresh.
Apps of others: OAuth and MCP
use std::sync::Arc;
use auth_chad::axum::{Auth, ConnectedApp, Refused};
use auth_chad::provider::{Provider, Scope};
use auth_chad::sqlite::SqliteStore;
use auth_chad::Code;
fn connect(auth: Auth<SqliteStore>) -> Arc<Auth<SqliteStore>> {
let read = Scope { name: "notes:read".into(), description: "Read your notes".into(), connected: true, write: false };
let provider = Provider {
scopes: vec![read],
audiences: vec!["https://app.example.com/mcp".into()],
dynamic_registration: true, // some MCP clients still need it
..Provider::default()
};
Arc::new(auth.with_provider(provider).with_pages("/consent", "/device"))
}
async fn mcp(app: ConnectedApp) -> Result<&'static str, Refused> {
if app.0.has_scope("notes:read") { Ok("data") } else { Err(Code::Forbidden.into()) }
}
- Merge
auth.oauth_router()at the root: metadata, authorize, token, revoke, register. - Consent page: it gets
?request=<id>.GET /auth/consent/{id}shows the client, its redirect host and the scopes;POST {"allow": true}answers{"redirect": "…"}. Show the host ofredirect_uri: a name proves nothing. - Client metadata documents: implement
Hooks::fetch_clientwith your HTTP client. Public addresses only, no redirects, 64 KiB, a timeout: the URL comes from a stranger. - MCP: answer 401 with
WWW-Authenticate: Bearer resource_metadata="https://app.example.com/.well-known/oauth-protected-resource". - A connected app never reaches a
FirstPartyhandler.
API keys
We do not recommend them. Whoever has the text of a key can use it. Use a device for your own CLIs and machines, and a connected app for programs of others. Use an API key only if a program can send nothing but a fixed header.
They are off until you turn them on:
use auth_chad::api_key::ApiKeys;
use auth_chad::axum::{ApiKey, Auth, Hooks};
use auth_chad::{Authenticated, Error, Store};
fn turn_on<S: Store, H>(auth: Auth<S, H>) -> Result<Auth<S, H>, Error> {
Ok(auth.with_api_keys(ApiKeys::new("example_", &["reports:read"])?))
}
struct App;
impl<S: Store> Hooks<S> for App {
async fn may_create_key(&self, _who: &Authenticated, scopes: &[&str]) -> bool {
scopes == ["reports:read"]
}
}
async fn reports(key: ApiKey) -> Result<String, auth_chad::axum::Refused> {
if !key.0.has_scope("reports:read") {
return Err(auth_chad::Code::Forbidden.into());
}
Ok(format!("reports of {}", key.user()?))
}
| Call | Does |
|---|---|
POST /auth/keys with name, scopes, lifetime in seconds | Makes a key. Needs a fresh login. secret is in the answer once |
GET /auth/keys | Lists them, with the last use and its address (up to five minutes old) |
DELETE /auth/keys/{id} | Ends one |
In the browser: newApiKey({ name, scopes, days }), apiKeys(), endApiKey(id). Show the secret once, and keep it nowhere.
- A key lives at most 90 days, and has no renewal. Make the next one before it ends.
- Only
ApiKeyaccepts a key.FirstParty,InPerson,FreshLoginandConnectedApprefuse it, and so does the whole account API. A route for both a user and a key decides withCaller. ApiKeyis the user that made the key, not the user in person. Let a key read before you let it write.- Tell your users: never in a page, an app or a repository. The prefix lets secret scanners find it. Never change the prefix: every key stops working.
Policy.key_boundrefuses every key. Withoutwith_api_keys, no key works.- Do not log the
Authorizationheader.
A way back into an account
Offer a second passkey first. Then choose:
| Method | Routes below /auth | The application does | Strength |
|---|---|---|---|
| Recovery key | recovery/key, recovery/key/start, recovery/key/finish | Nothing, if users have an identifier | Strong |
| Approval by an owner | recovery/owner, then the link | Hooks::may_recover | Strong, if people check each other |
recovery/email, then the link | Config::with_email_recovery, verified_address, send | Weak: 24 hours of waiting, notices, 72 hours of hold |
use auth_chad::axum::{Hooks, Mail};
use auth_chad::sqlite::SqliteStore;
use auth_chad::{Authenticated, UserId};
struct App;
impl Hooks<SqliteStore> for App {
async fn verified_address(&self, _store: &SqliteStore, address: &str) -> Option<UserId> {
None // look up an address that you verified, never one that a person only typed
}
async fn may_recover(&self, who: &Authenticated, user: UserId) -> bool {
false // is `who` an owner of an organization of `user`?
}
async fn send(&self, mail: Mail<'_>) -> bool {
match mail {
// A secret. The link opens a page with a button: mail scanners open links.
Mail::Link { to, token } => false,
// "Someone asked for a new passkey. It works at … . Cancel it here."
Mail::Notice { to, ready_at } => false,
}
}
}
In the browser (/auth/auth-chad.js):
const text = await newRecoveryKey(); // show it once; needs a recent passkey
await recoverWithKey({ identifier: "jane", displayName: "Jane", key: text });
await recoverByEmail("jane@example.com"); // the same answer if there is no account
await recoverWithLink({ token, userName: "jane", displayName: "Jane" });
const { ready_at, hold_until } = await recovery(); // show it: cancelRecovery(), undoRecovery()
- Run the worker (
auth_chad::axum::work, see load-balancer): it sends a mail that failed again. - Show
ready_aton every page of a logged-in user. A cancel there stops someone who has the mailbox. - Use
Hooks::commit_recoveryto add a notice for every other address of the user.
Never use email recovery with e2ee: it cannot restore a key.
Another provider
It proves a claim. It never logs a user in: after it comes a passkey.
use auth_chad::axum::{External, Hooks};
use auth_chad::oidc::KeySet;
use auth_chad::sqlite::SqliteStore;
fn company() -> External {
External {
id: "company".into(),
issuer: "https://login.company.example".into(),
client_id: "…".into(),
authorization_endpoint: "https://login.company.example/authorize".into(),
token_endpoint: "https://login.company.example/token".into(),
sends_iss: true,
authoritative_for: vec!["company.example".into()],
}
}
struct App;
impl Hooks<SqliteStore> for App {
async fn exchange(&self, provider: &External, form: &[(&'static str, String)]) -> Option<String> {
// POST `form` to `provider.token_endpoint` with your client secret or key. Return `id_token`.
None
}
async fn provider_keys(&self, provider: &External) -> Option<KeySet> {
// GET the provider's `jwks_uri`, and keep it for some minutes.
None
}
}
Then Auth::new(…)?.with_hooks(App).with_external(vec![company()], "/welcome"). Register the redirect URI
<issuer>/auth/external/company/callback at the provider. In the browser:
await external("company", "signup"); // comes back to /welcome?purpose=signup or /welcome?error=…
await signup({ displayName, external: true });
await external("company", "link"); // comes back to /welcome?purpose=link
await linkExternal(); // from a click, with a recent passkey
await external("company", "refresh"); // for a company rule, when login() fails with external_identity_refused
await login();
- Sign up: allow
SignupMode::Externalin the policy. - Company rule: add the issuer to
Policy.external. A login then needs a company login of the last 24 hours. - The answer of the provider must be a redirect with a query. A form post (
response_mode=form_post) does not work: the browser does not send the cookie with it.
Never look up an account by the email address.
Tenants
A tenant is an organization or a customer: a boundary for sessions, with members. Rules: spec 14. How to grow: the wiki. Load balancer settings for both kinds of address: load-balancer.
use std::sync::Arc;
use auth_chad::{Authenticated, Store, Tenant};
use auth_chad::axum::{Auth, FirstParty, Here, Hooks, Member, Tenancy};
use auth_chad::core::member;
auth_chad::core::member_columns! {
pub struct Membership { role: String } // your columns; `auth-chad memberships` writes their migration
}
#[derive(Clone)]
struct App;
impl<S: Store> Hooks<S> for App {
async fn may_create_tenant(&self, who: &Authenticated) -> bool {
who.is_first_party() // replace with your rule
}
async fn may_manage(&self, store: &S, who: &Authenticated, tenant: Tenant) -> bool {
let Ok(user) = who.user() else { return false };
let found = member::read::<Membership>(store, tenant, user).await;
matches!(found, Ok(Some(m)) if m.columns.role == "owner")
}
async fn may_invite(&self, store: &S, who: &Authenticated, tenant: Tenant) -> bool {
tenant != Tenant::ROOT && self.may_manage(store, who, tenant).await
}
}
fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl auth_chad::axum::Service> {
Arc::new(auth.with_hooks(App).with_members::<Membership>().with_tenancy(Tenancy::Host { parent: "example.com".into() }))
}
async fn report(who: FirstParty, here: Here, member: Member<Membership>) -> String {
format!("{} in {:?} as {}", who.0.tenant(), here.name, member.0.columns.role)
}
- Where the tenant is in a request:
Tenancy::Host(acme.example.com: each tenant has its own web origin; needs a wildcard DNS record and certificate) orTenancy::Path(/t/acme/: one host and certificate, one cookie for each tenant). The hosts of your configured origins are the root. - Tables: tenants are an optional feature. Migrate with it (
SqliteStore::create(…, &[auth_chad::Feature::Tenants]), orauth-chad feature sqlite tenants), and callauth.check_tables()at start: it fails if they are missing. - Members: the table is in the database of the users. Your columns need a default:
auth-chad memberships sqlite role:text=memberprints the migration and the declaration.Member<Membership>reads them with each request in a tenant. - Routes, all at the login origin with the root session:
GET/POST /auth/tenants,POST /auth/tenants/{name}/enter,/members,/members/{user}(PATCH {"state":"suspended"},DELETE),/invites,/accept. - Entering on a tenant’s host: send the browser to
https://acme.example.com/auth/enter/start?return=/. Without a session, the login page ofwith_login_pagecomes first. Key-bound clientsPOST /auth/tenants/{name}/enterwith their root token. - Signup with an invite of a tenant: add
"tenant": "<name>"to both signup calls. The new user is a member. - Ending a membership ends the person’s sessions, tokens, devices, grants and API keys in that tenant at once.
Machines stay. Add your own changes to the same commit with
tenant::endandcommit_with.
A separate directory
The users’ database becomes the directory: users, sessions, tenants, memberships and the place of each tenant or user. Your data is on PostgreSQL servers: each with one database for many tenants, or one database for each. Rules: spec 15. When to use it: the wiki.
use std::collections::HashMap;
use std::sync::Arc;
use auth_chad::Store;
use auth_chad::axum::{At, Auth, FirstParty, PlaceBy, Placement, Service, run_places};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
struct Place {
server: String, // a name, for example "db2"
database: String, // no password here: it belongs to the process's configuration
}
struct Databases {
servers: HashMap<String, String>, // name → connection string, from environment variables
}
impl Databases {
fn from_env() -> Self {
let names = std::env::var("DB_SERVERS").unwrap_or_default(); // "db1,db2"
let url = |name: &str| std::env::var(format!("DB_{}_URL", name.to_uppercase())).ok();
Self { servers: names.split(',').filter_map(|n| Some((n.to_owned(), url(n)?))).collect() }
}
}
async fn create_database(url: &str, name: &str) -> bool {
let _ = (url, name); // CREATE DATABASE if it is missing, then your migrations
true
}
async fn drop_database(url: &str, name: &str) -> bool {
let _ = (url, name); // DROP DATABASE IF EXISTS
true
}
impl Placement for Databases {
type Place = Place;
const BY: Option<PlaceBy> = Some(PlaceBy::Tenant);
async fn choose(&self, owner: [u8; 16]) -> Option<Place> {
let mut names: Vec<&String> = self.servers.keys().collect();
names.sort();
let server = names.get(usize::from(owner[0]) % names.len().max(1))?; // or: where there is room
let database = format!("tenant_{}", owner.iter().map(|b| format!("{b:02x}")).collect::<String>());
Some(Place { server: (*server).clone(), database })
}
async fn provision(&self, _owner: [u8; 16], place: &Place, _id: [u8; 16]) -> bool {
let Some(url) = self.servers.get(&place.server) else { return false };
create_database(url, &place.database).await // safe to repeat
}
async fn remove(&self, _owner: [u8; 16], place: &Place, _id: [u8; 16]) -> bool {
let Some(url) = self.servers.get(&place.server) else { return false };
drop_database(url, &place.database).await
}
}
fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl Service> {
Arc::new(auth.with_places(Databases::from_env()))
}
async fn after_signup<A: Service>(auth: &A) {
run_places(auth).await.ok(); // sooner than the next run of the worker
}
async fn notes(who: FirstParty, at: At<Place>) -> String {
format!("{} uses {} on {}", who.0.tenant(), at.place.database, at.place.server)
}
- Tables: places are an optional feature (
Feature::Places, andFeature::Tenantsto place by tenant). Migrate with them and callauth.check_tables()at start. - By tenant or by user:
BYdecides. Never both. - One database for many tenants: give them the same
database, and give your tables a tenant column. - A new tenant or user gets its place in the same commit, in the state
creating. Untilprovisionanswerstrue,Atgives503 not_readywithRetry-After. - The worker runs
provisionandremove(load-balancer). Work that fails runs again after its lease of 5 minutes. - Moving:
place::begin_move(requests get503 moving), copy the data, thenplace::finish_movewith the new place. The generation grows. - Removing:
place::remove. Requests get404at once, andremoveruns until it answerstrue. - Waiting too long:
place::in_states(store, PlaceState::Creating). - Connections: a PostgreSQL connection is for one database. With a database for each tenant, keep a small pool for each active one.
- After a restore of the directory:
auth-chad after-restore postgresprints the SQL that ends every session.
Many processes behind a load balancer
The same binary runs in every process. Each request is checked in the users’ database, so any process serves any request. Steps and rules: the wiki.
use std::sync::Arc;
use std::time::Duration;
use auth_chad::Store;
use auth_chad::axum::{Auth, Service, work};
fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl Service> {
Arc::new(auth.with_proxies(1)) // one load balancer adds the client address to X-Forwarded-For
}
async fn worker<A: Service>(auth: Arc<A>) {
loop {
work(auth.as_ref()).await.ok(); // prunes, sends mails that wait, runs the work of places
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
async fn start<A: Service>(auth: Arc<A>) {
match std::env::var("ROLE").as_deref() {
Ok("worker") => worker(auth).await,
Ok("web") => { /* serve the router only */ }
_ => {
tokio::spawn(worker(Arc::clone(&auth))); // one process does both: good for one machine
/* serve the router */
}
}
}
- Database: PostgreSQL for more than one machine. Rate limits, single-use marks of key proofs and leases are in it, so every process sees them.
- Worker: any number of processes can call
workat once. Each piece of work has a lease (a mail one minute, a place 5 minutes), so it runs in one place at a time. Work that takes longer, or a crash, can run it twice:provisionandremovemust be safe to repeat. With Loco: registerauth::Workand run the taskauth_workfrom Loco’s scheduler. with_proxies(n): the number of proxies that add an entry toX-Forwarded-For. The address is the entry that the outer one added. The processes must be reachable only through the proxies. Without proxies, keep the default 0.- What the load balancer must do: pass the
Hostheader, and add the client address toX-Forwarded-For. Sticky sessions are not needed.
Caddy, a path for each tenant
app.example.com {
reverse_proxy app1:3000 app2:3000 app3:3000 {
lb_policy round_robin
health_uri /healthz
}
}
Caddy passes Host and sets X-Forwarded-For to the client address: with_proxies(1). /healthz is a route of your
application. Tenants are at
app.example.com/t/acme/ (Tenancy::Path).
Caddy, a host for each tenant
example.com, *.example.com {
tls {
dns cloudflare {env.CLOUDFLARE_API_TOKEN}
}
reverse_proxy app1:3000 app2:3000 {
lb_policy round_robin
health_uri /healthz
}
}
A wildcard certificate needs a DNS challenge, so Caddy needs the module of your DNS provider (here
caddy-dns/cloudflare). Tenants are at acme.example.com (Tenancy::Host { parent: "example.com" }), and the login
origin is example.com.
nginx
upstream app {
server app1:3000;
server app2:3000;
}
server {
listen 443 ssl;
server_name example.com *.example.com;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
$proxy_add_x_forwarded_for adds the client address at the end: with_proxies(1).
Two proxies
A CDN in front of Caddy is two proxies: with_proxies(2). The inner proxy must keep the entry of the outer one. In
Caddy, list the CDN’s addresses in trusted_proxies, or Caddy replaces the header.
Other load balancers
An AWS Application Load Balancer adds the client address to X-Forwarded-For: with_proxies(1).
A Rust client: CLI or wasm in a browser
auth_chad::client::Client talks to the account API. It proves its own key with DPoP on each call, renews its token,
and with end-to-end encryption seals and opens the identity key. It sends requests through your Http, so the same
code runs in a CLI and in a browser.
use auth_chad::client::{Client, Error, Http, Request, Response, Signup};
use auth_chad::core::{Clock, Draws, UnixTime};
use auth_chad::keys::SigningKey;
struct Net; // your HTTP library: send the method, URL, headers and body, return status, `dpop-nonce` and body
impl Http for Net {
async fn send(&self, _request: Request) -> Result<Response, Error> {
Err(Error::Network)
}
}
async fn device_login<C: Clock, D: Draws + Clone>(clock: C, draws: D, key: SigningKey) -> Result<(), Error> {
let mut client = Client::new(Net, clock, draws, "https://api.example.com", "myapp/v1", key).mounted_at("/v1/auth");
let waiting = client.request_device("laptop", "user", "").await?;
println!("Open {} and enter {}", waiting.verification_uri, waiting.user_code);
// every `waiting.interval` seconds, until it says Approved:
client.poll(&waiting).await?;
let _sessions: serde_json::Value = client.get("/sessions").await?; // renews the token when needed
Ok(())
}
fn keep(client: &Client<Net, impl Clock, impl Draws + Clone>) -> Option<(String, UnixTime)> {
client.token().map(|(t, end)| (t.to_owned(), end)) // store it with the key; `resume` continues
}
In a browser, add the crate with the browser feature and build for wasm32-unknown-unknown. It gives Fetch (no
cookies, no redirects), WebClock, WebDraws and Passkey (WebAuthn with the PRF extension). Call passkey methods from
a click:
use auth_chad_client::browser::{Fetch, Passkey, WebClock, WebDraws};
let mut client = Client::new(Fetch, WebClock, WebDraws, "https://api.example.com", "myapp/v1", key);
let (_session, keys) = client.signup(&Passkey, Signup { display_name: "Jane", ..Signup::default() }, true).await?;
let keys = keys.expect("with e2ee"); // show keys.recovery.display() once; keep keys.secret in memory only
let back = client.login(&Passkey, true).await?; // back.secret: the identity secret, opened with the passkey
- Where the API is:
mounted_atfollows the server’sAuth::mounted_at; the default is/auth. - The page on another host: see start:
Configorigins andwith_web_origins. - End-to-end encryption:
signup(.., true)makes the identity secret and a recovery key.login,recover,add_passkey(.., Some(&secret))andnew_recovery_keykeep the envelopes. A passkey that gives no PRF output at creation is asked once more. - Your own routes:
callsends a request with the login to any path;call_withadds headers, for exampleIf-Match, and takes a body that is already JSON. - Data from the secret in the signup: make the secret first and pass it in
Signup::secret, for example to send public keys that come from it inapp. - Errors:
Error::StepUpmeans: callstep_upand try again.Error::Refusedcarries the server’s code. - The text of a user in envelopes is the user ID. An application with envelopes from before can set its own with
with_label.
End-to-end encryption
Each user has a 64-byte identity secret. The client makes it and seals it; the server stores envelopes.
use auth_chad::core::Draws;
use auth_chad::e2ee::{self, Context, Method, OpenError, RecoveryKey};
fn seal(draws: &mut impl Draws, prf: &[u8; 32], user: &str, kid: &str, secret: &[u8; 64]) -> Result<e2ee::Envelope, OpenError> {
let context = Context { namespace: "myapp/v1", user, kid, method: Method::Prf };
e2ee::seal(draws, prf, context, secret)
}
fn new_recovery_key(draws: &mut impl Draws) -> RecoveryKey {
RecoveryKey::generate(draws) // show `display()` once, seal with Method::Recovery
}
Turn the mode on in the routes with Auth::with_e2ee(). The routes then keep each envelope in the commit that adds,
uses or removes its passkey:
| Call | Adds | Gets |
|---|---|---|
POST /auth/signup/finish | "e2ee": { "envelope", "recovery_envelope", "recovery_verifier" } | |
POST /auth/login/finish | "envelope": the one of the passkey that was used | |
POST /auth/passkeys | "envelope" for the new passkey | |
DELETE /auth/passkeys/{id} | its envelope goes too | |
PUT /auth/recovery/key | "envelope" sealed with the new recovery key | |
POST /auth/recovery/key/start | "envelope" sealed with the recovery key; a decoy for an unknown name | |
POST /auth/recovery/key/finish | "envelope" for the new passkey |
- A call without its envelope, or with one when the mode is off, gets
400 invalid_request. - A passkey from before the mode logs in without an envelope. Give it one by adding a new passkey with the secret.
recovery_verifieris the public key ofrecovery::recovery_signer(namespace, key): the recovery key both opens its envelope and proves the recovery.- Recovery by email, by a link or by an owner gets
403: it cannot restore the key. - Ask for the PRF extension with
e2ee::prf_input(namespace)increateandget. Never send its output. - Without the routes: add
e2ee::attach_passkeyandattach_recoveryto the signup’s commit, ande2ee::detachto a passkey’s removal. - New identity:
replace_identity, with your own rewrapped data in the same commit. - Losing every passkey, the recovery key and every device loses the data. Say so in the page.
Support: see the application as a user
Nobody may, until the application says so.
use auth_chad::axum::{Caller, Hooks, InPerson, ViewMode};
use auth_chad::sqlite::SqliteStore;
use auth_chad::{Authenticated, UserId};
struct App;
impl Hooks<SqliteStore> for App {
async fn may_view(&self, who: &Authenticated, user: UserId) -> Option<ViewMode> {
None // is `who` support staff, and may they see this user? Some(ViewMode::ReadOnly)
}
}
// Only the user in person: a billing portal, a data export, an address change.
async fn export(who: InPerson) -> String {
format!("{:?}", who.user())
}
// For an audit: both people.
fn people(caller: &Caller) -> Option<(UserId, Option<UserId>)> {
let who = caller.who().ok()?;
Some((who.user().ok()?, who.view().map(|v| v.by)))
}
In the browser: await viewAs(user) from a click, with a recent passkey. session() then has view: show it on every page,
with a button for await endView().
What the library does, without a list of paths to maintain:
FreshLoginrefuses a view. So every sensitive action of the application refuses it.- The account API refuses it: passkeys, sessions, devices, apps, recovery, invites, signed links, events.
ReadOnlyallows only safe methods. AGETthat changes something is a mistake of the application.- A view ends after an hour, with the person’s own login, if either account is disabled, and if the user ends it in the list of sessions. It needs the person’s own cookie beside it.
- After the end, requests fail with
view_endeduntilendView(). They never continue as the person’s own account. - Both people have an event with the other’s ID:
viewedandview_as.
A handler with FirstParty accepts a view. Use InPerson where only the user may act.
Tests
use auth_chad_testing::{MemStore, World, block_on};
use auth_chad::{Store, passkey};
fn a_login_starts() {
block_on(async {
let w = World::default(); // memory store, fake clock, repeatable randomness
let options = passkey::login_start(&w.ctx(), &mut w.draws()).unwrap();
assert_eq!(options.rp_id, "login.example.com");
w.clock.advance(301); // the ceremony is over
w.store.commit(vec![]).await.unwrap();
});
}
World::passkey(1)is a passkey in software:createandget.- HTTP:
Auth::new(config, &[1; 32], MemStore::default())?.with_sources(clock, draws)androuter.oneshot(request).rust/adapters/axum/tests/http.rshas every step. - Browser:
rust/examples/minimal/e2e/run.mjsdrives Chromium with a virtual passkey and no packages. - Never put a real token, key or address in a test.
auth-chad in a Loco application
It works with Loco 1.1 to 1.3 and SeaORM 2, on SQLite and PostgreSQL. A whole application, with tests, is in
rust/loco/example.
| You want to see | File |
|---|---|
| The wiring | src/app.rs |
| Users rows in the signup transaction | src/accounts.rs |
| The migration | src/migration.rs: auth_chad::sea_orm::create(conn, &prefix, &[]), with features such as Feature::Tenants if you use them; a later migration adds one with upgrade |
| Extractors for the user’s row and the organization | src/extractors/mod.rs |
| Middleware that knows the caller, and who views (audit) | src/middleware/mod.rs |
| Routes with a user, a visitor, a recent passkey | src/controllers/home.rs |
| Data of an organization, with Loco’s tenant scope | src/controllers/notes.rs |
| A role and a recent passkey together | src/controllers/orgs.rs |
| Connected apps (MCP) | src/controllers/apps.rs |
| Moving accounts with passwords | src/controllers/legacy.rs |
| Tests with Loco’s test server | tests/requests.rs |
cd rust/loco
cargo run -p example-loco -- start # in example/: http://localhost:5150
cargo test
Wiring
async fn after_context(ctx: AppContext) -> Result<AppContext> {
auth::install(&ctx, accounts::build);
Ok(ctx)
}
async fn initializers(_: &AppContext) -> Result<Vec<Box<dyn Initializer>>> {
Ok(vec![Box::new(auth::Tables::<AppAuth>::default())]) // refuses to start without the key or the tables
}
async fn before_routes(ctx: &AppContext) -> Result<Router<AppContext>> {
auth::routes::<AppAuth>(ctx) // /auth, /oauth, /.well-known
}
fn middlewares(ctx: &AppContext) -> Vec<Box<dyn MiddlewareLayer>> {
auth::middlewares::<AppAuth>(ctx) // Loco's, and the caller
}
fn register_tasks(tasks: &mut Tasks) {
tasks.register(auth::Work::<AppAuth>::default()); // auth_work: prune, mails, places
}
settings:
auth_chad:
namespace: example/v1
issuer: https://api.example.com
rp_id: example.com
rp_name: Example
origins: ["https://example.com"]
The environment variable AUTH_CHAD_MASTER has the master key: 32 random bytes, base64url without padding. It is not in the
YAML file, because cargo loco doctor --config prints the configuration. The server does not start without it. Tasks of
auth-chad need it too; db migrate and other commands do not.
Why it is like this
before_routes, notafter_routes. Routes that are added inafter_routesare outside of Loco’s middleware: no request ID, no panic handler, no remote IP.installtakes a function. Loco callsafter_contextfor each command, and before it runs migrations. The function runs once, when the server starts (Tables) or when a task needs it.- The middleware is innermost. It runs after Loco knows the remote IP, and not for static files. Your middleware that reads the caller goes to index 0.
- Extractors read the request, not the state. Loco’s state is always
AppContext, a type of Loco. users.pidis the auth-chad user ID. Both are 16 bytes. Your integer keys stay.- An organization is data of the application. Use one auth-chad tenant (the root) and memberships in your tables, as
OrgContextdoes. A separate tenant is for separate logins. - Reject with a response, not with a Loco error, in extractors. A Loco error loses
WWW-Authenticateand is logged as an error for each visitor.auth_chad_loco::refusedis for handlers.
What it replaces
Remove auth: from the configuration, the auth feature of loco-rs if you need no password hashes, the auth::JWT and
JWTWithUser extractors, Authenticable, and the password, magic link and reset columns. Generated controllers use
auth::JWT: replace it with CurrentUser or your own extractor.
Exclude the tables from cargo loco db entities: add them to ignore-tables in [package.metadata.db.entity].
Worker
Run the task auth_work from Loco’s scheduler every few seconds. It removes expired rows, sends the mails that wait and
runs the work of places. Any number of processes can run it at once.
scheduler:
jobs:
auth_work:
run: auth_work
cron: "*/10 * * * * *"
Start the scheduler in the process that should do the work: cargo loco start --scheduler, or a worker process. Behind
a load balancer, set Loco’s trusted proxies (remote_ip middleware): auth-chad uses the address that Loco gives.
Gaps
| Gap | Effect | Plan |
|---|---|---|
| The router serves one tenant (the root) | Separate logins need own routes. The extractors already use a Tenant in the request | Tenant from the request in adapters/axum |
| A read of the database for each request with a credential | Slower than a JWT; a logout works at once | Accepted |
cargo loco routes does not list /auth and /oauth | Only the list | Loco lists its own routes only |
| API keys are off | Machines use a device with its own key, and need DPoP | api-keys, if a program can send only a header |
| No typed audit details | The example records method, path, status and user | Needs a decision |
rusqlite (auth-chad-sqlite) and SQLx share one libsqlite3-sys | SQLx needs a version below 0.41 and rusqlite 0.43 has 0.40, so both build together today. A newer rusqlite can break that | Use one of them in an application |
| The SeaORM adapter has more dependencies than the others | 183 crates with both drivers, and 84 for auth-chad-postgres | An application with SeaORM has them already |
Ideas from a Loco application with several organizations
Taken:
- One middleware finds the caller. Extractors and other middleware read it. It was one check in each extractor.
- An optional caller, for pages that visitors also see.
- An extractor for the organization that is the only place that decides membership.
- An audit middleware inside the authentication layer.
- View as, for support. It is a property of
Authenticated, soFreshrefuses it, and there is no list of paths that someone must keep complete. See view-as. resource_metadatain the challenge of an API for MCP clients. The adapter did not send it, and MCP clients need it.
Worth a decision:
- Audit details from the handler. A handle in the request that a handler fills, and the middleware stores.
Not taken: stateless JWT sessions, bearer tokens for first-party apps, and API keys that act as the user.
Specification
Draft 0, profile AC1. The key words MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119 and RFC 8174.
| File | Content |
|---|---|
| 00-conventions | Encodings, algorithms, labels, the profile |
| 01-model | Realms, tenants, users, credentials, proofs, policies |
| 02-flows | How a flow decides, preconditions, effects |
| 03-passkeys | Registration and login |
| 04-sessions | Cookies, key-bound tokens, fresh login |
| 05-signup | Open, invite only, external proof |
| 06-recovery | Recovery key, owners, email |
| 07-devices | CLIs and machines |
| 08-provider | First-party and connected apps |
| 09-external-identity | OpenID Connect at another provider |
| 10-storage | Schema, table prefix, transactions |
| 11-traces | Trace format |
| 12-e2ee | Identity keys for end-to-end encryption |
| 13-api-keys | Secrets for programs that cannot hold a key |
| 14-tenants | Tenants, memberships, entering a tenant |
| 15-places | Where the data of a tenant or a user is, with a separate directory |
| 16-encrypted-sync | Draft, not built: an encrypted keyring and log for each user |
Values marked † are proposals that need a review before the profile is final.
00 Conventions
Encodings
- Time is an integer: seconds since the Unix epoch. There are no leap seconds.
- Binary values in JSON and URLs are base64url without padding. A decoder MUST reject padding, other characters and non-zero trailing bits.
- JSON that is signed, hashed or compared is canonical (RFC 8785). A parser MUST reject duplicate members.
- A parser MUST reject trailing data. Each format has a maximum size, and a parser checks it first.
- Random values have at least 128 bits. Tokens and challenges have 256 bits.
Profile AC1
A profile is a fixed set. A deployment runs one profile. There is no negotiation inside a profile.
| Use | Algorithms |
|---|---|
| Passkey signatures | ES256, Ed25519, RS256 (COSE -7, -8, -257) |
| DPoP and device signatures | ES256, Ed25519 |
| ID tokens of other providers, client assertions | ES256, Ed25519, RS256 |
| ID tokens of this provider | ES256, or RS256 if the application adds an RSA key |
| Hash of tokens at rest | SHA-256 over 256 bits of entropy |
| Derivation | HKDF-SHA256 |
| MAC | HMAC-SHA256 |
Encryption (e2ee) | XChaCha20-Poly1305; HPKE X25519, HKDF-SHA256, ChaCha20-Poly1305 |
The key fixes the algorithm. A verifier MUST NOT take the algorithm from a message: it compares the message’s alg
with the key’s and rejects a difference. alg: none and symmetric alg values are always rejected.
ECDSA: keys are uncompressed P-256 points on the curve. Ed25519: verification is strict, and small-order keys are rejected. RSA: 2048 to 4096 bits, exponent 65537, PKCS #1 v1.5 with SHA-256. Only passkeys and other parties use RSA: this profile never makes an RSA key for a user, a device or a session.
Labels
Every derivation, MAC and signature has a label <namespace>/<purpose>. The application sets the namespace once, for
example example/v1. Two purposes never share a label.
input(label, parts…) = label || for each part: u32_be(len) || part
Server keys
The server holds one 32-byte master key. Nonce, ceremony and cookie keys are derived from it. Provider signing keys are
separate, have a kid, and rotate with an overlap that is longer than the longest token.
Errors
A refusal has a stable code. The text for a person is the application’s. Two refusals that would let a caller learn if an account exists MUST have the same code, the same shape and comparable work.
Upper limits
| Value | Upper limit † |
|---|---|
| Ceremony | 5 minutes |
| First-party access token | 15 minutes |
| Browser session | 1 day idle, 7 days absolute |
| Native or CLI session, key-bound | 90 days idle |
| Connected-app access token | 1 hour |
| Connected-app refresh token | 90 days idle, one use |
| Invite | 7 days |
| Device code | 15 minutes |
| Fresh login | 15 minutes |
An application MAY set shorter values. It cannot set longer ones.
01 Model
Realm and tenant
- A realm is one set of users, one WebAuthn RP ID and one login origin.
- A tenant belongs to one realm and has a 16-byte ID. An application without tenants uses the root tenant: 16 zero bytes.
- A passkey belongs to a realm, because it is bound to the RP ID. Tenants on other domains use the provider (08) and send the user to the login origin. Implementations MUST NOT use related origins to share passkeys between tenants.
Isolation
- Every tenant-scoped storage operation takes the tenant as an argument. A form without one MUST NOT exist.
- Every tenant-scoped MAC, derivation and token includes the tenant.
- Each tenant has its own issuer, and its own provider keys.
- An identifier from one tenant that is used in another gives the same refusal as an unknown one.
User
A user has an ID (16 bytes, random by default; an application maps its own IDs to 16 bytes), a state (active or disabled)
and credentials. Names, addresses and profile data belong to the application. An identifier such as a handle or an
email address is optional, and unique in the realm if used.
Disabling a user ends sessions, tokens and device keys in the same commit.
Entering a tenant
A user may enter a tenant with an active membership (14). A session is for one tenant. Entering another tenant creates another session, and can need another login if that tenant’s policy is stricter. The library stores no roles: the application adds its own columns to the memberships table.
Credentials
| Kind | Held by | Proves |
|---|---|---|
| Passkey | A person | The person |
| Device key | A CLI, native app or machine | The device, and the user that approved it |
| Session key (DPoP) | A browser or app | The session |
| API key (13) | Whoever has it | The scopes that its user gave it |
| External identity | A person at another provider | A claim, never a login |
| Recovery method | A person | Permission to create a passkey |
Proof
A successful check gives an Authenticated value:
| Field | Content |
|---|---|
subject | User or device |
tenant | Tenant |
level | first_party, connected(client, scopes) or api_key(id, scopes) |
methods | What was proved, for example passkey with user verification |
proved_at | Time of the last passkey assertion |
binding | Key thumbprint, or cookie, or bearer |
Only the library can create it. A handler states what it needs in its type: level, maximum age, binding. A request that does not have it never reaches the handler.
Policy
A policy is a set of requirements. Policies from the profile, instance, tenant and route combine to the strictest:
| Requirement | Combine |
|---|---|
| Lifetimes | Minimum |
| Maximum age of a passkey assertion | Minimum |
| Passkey must not sync (BE flag clear) | Or |
| External identity required: list of providers | Both lists must be satisfied |
| Signup modes, recovery methods | Intersection |
| Binding required | Or |
Combination MUST be associative, commutative and idempotent. An empty signup set means that nobody can sign up.
A requirement that the current login does not meet gives the refusal step_up_required, with the requirement.
02 Flows
Contract
A flow step is a function that decides:
step(context, reader, draws, input) -> decision | refusal
context = time, realm, tenant, policy, settings, caller's address
decision = output, writes
refusal = code
- A step reads through
readeronly, and gets random bytes fromdrawsonly. With the same answers from both it gives the same decision, in every language. - A step MUST NOT read a clock, a random source, the network or the environment, and MUST NOT write.
- A decision has no effect until its writes are committed. The output MUST NOT be used before that.
- A refusal changes nothing. A step that must change state and answer with an error (a poll that is too early, a reused token) returns a decision whose output is the error.
Writes and preconditions
Between reads and commit, another request can change the state. Each write therefore has its precondition:
| Write | Precondition |
|---|---|
insert(row) | No row with this key or unique value |
replace(row, version) | The stored row has this version |
delete(key, version) | The stored row has this version |
require(key, version) | The stored row has this version (no change) |
delete_where(column, value) | None |
Writes are plain data. An application can add them to its own transaction. Each row has a version that grows with every change. Writes apply in order.
commit(writes, app_writes) runs in one transaction. If a precondition fails, nothing is stored and the result is
conflict. A caller MAY run the flow again, at most three times. It MUST use new draws.
Security decisions MUST depend only on loaded state that a precondition protects, or on state that cannot become less permissive in a harmful way. Each flow lists its protected reads.
Single use
A challenge is used by inserting its hash. An invite or a device request is deleted, and a code or a refresh token is marked as used, with its version. This is in the same commit as the result. Of two requests with one token, exactly one succeeds.
Effects
An effect is work outside the database: send mail, call back a client. Effects are stored in an outbox in the same commit, and run at least once after it. An effect has an ID, so that a receiver can ignore a repeat. Each effect has a lease (10), so that two processes do not run it at the same time. The secret part of a mail is in the outbox only until it is sent.
Audit
Every decision that changes an account gives an event: time, tenant, subject, action, target, the client address and the device of the caller if known, and method. An application can keep addresses out of events. Events have no secrets, no names and no free text from a client. They are writes, so a change without its event cannot exist.
Ceremonies
A ceremony spans two requests. Its state is in a MAC-protected token that the client returns, with the challenge, kind, tenant and expiry. The challenge is stored as used at the end (single use), so a ceremony works once.
03 Passkeys
WebAuthn Level 3, with the following policy.
Both ceremonies
- User presence and user verification are required.
- The origin matches a configured origin exactly.
crossOrigin: trueand anytopOriginare rejected. - The RP ID hash matches the realm.
- Client data is valid UTF-8 JSON. Authenticator data has no trailing bytes. Extension data is one CBOR map.
- BS without BE is rejected. BE MUST NOT change after registration.
Registration
residentKey: required,userVerification: required,attestation: none.- The public key has exactly the required COSE parameters.
- The client sends
excludeCredentialsfor a user that has passkeys. - A credential ID is unique in the realm, at most 1023 bytes.
- The WebAuthn user handle is the user ID. It is not personal data.
Login
- Discoverable credentials only. The login page asks for no identifier.
- The assertion carries the user handle, and it matches the credential’s owner.
- The signature counter MUST increase if either side is non-zero. Otherwise the assertion is refused and an event is written.
- A login starts a new session. It never continues an old one.
Managing
- Adding and removing a passkey needs a fresh login on the first-party level.
- A user keeps at least one passkey. Removing one ends the sessions that it started.
- A change sends a notice to the user, if the application has a way to.
Client rule
A browser can refuse a second passkey prompt without a new user gesture. A client MUST NOT start two prompts from one gesture.
04 Sessions
Key-bound sessions
For JavaScript clients, native apps and CLIs. The client makes a key pair for the session and proves it with DPoP (RFC 9449).
- When the policy requires key-bound sessions, a login without a proof is refused with
invalid_dpop_proof. - The server requires a nonce in each proof, and accepts each
jtionce in the proof’s window, in all its processes (10). htm,htu,iat,nonceand, with a token,athare checked. The key’s thumbprint (RFC 7638) is in the token record.- The access token is opaque: 256 random bits. The server stores its hash.
- A renewal needs a proof with the session’s key. It gives a new token and does not extend the absolute limit.
- Platform hardware keys SHOULD be used where they exist. That is why the profile has ES256.
Cookie sessions
For page loads, where a browser cannot send a proof.
- Name
__Host-…, withSecure,HttpOnly,Path=/,SameSite=Strict. An application that needs to arrive logged in from a link MAY useLax. - The value is 256 random bits, stored as a hash. It changes at login, at step-up and when the tenant changes.
- A request that can change state MUST have an allowed
Origin, andSec-Fetch-Site: same-originif the header is present.GETchanges nothing. - A cookie session reaches sensitive handlers only with a fresh login.
Fresh login
A fresh login is a new passkey assertion, bound to the session and to the action’s name. It satisfies Fresh<n> for at
most n seconds. Sensitive actions include: credentials, recovery, sessions of others, account deletion, approving a
device, and consent to a connected app with write scopes.
Media and downloads
Some players and download managers send neither a proof nor a safe cookie. The application can create a signed link: one path, one method, one subject, at most 10 minutes†, MAC with a purpose label. It gives no session.
Ending
Logout ends one session, and the sessions in tenants that it is the root session of (14). “Log out everywhere” ends all sessions, tokens, connected-app grants and API keys of the user, and can keep device keys. Both are commits: after them, no token works.
Refused
Tokens in URLs, tokens in localStorage without encryption, sessions without an absolute limit, and “remember me” that
skips the passkey.
View as another user
A person can see the application as another user, for example for support. The application decides who may.
- It needs a fresh login, and is a session of the user with the person (
actor) and the person’s session (parent). - It is valid only with the parent session, for one hour†, and not longer than the parent. It opens no other view.
- It is not a proof of the user: there is no time of a proof, so nothing that needs a fresh login accepts it. Functions that change an account, a session or a credential, or make a link or a grant, refuse it.
- A read-only view allows safe methods only.
- With cookies, it has its own cookie beside the person’s cookie. If it is there and not valid, the request is refused, and not treated as the person’s own.
- Both users have an event that names the other. The user sees it in the list of sessions, and can end it.
05 Signup
Signup has two parts: permission, then a passkey. Permission alone creates nothing.
Modes
| Mode | Permission |
|---|---|
open | Anyone, with rate limits |
invite | A single-use invite |
external | A verified claim from an external identity provider (09), that matches an invite or a tenant’s rule |
app | The application says so, for example after it checked an old password |
A tenant’s policy gives the allowed set. The instance can allow fewer. The application chooses who may create invites.
Grant
Permission gives a signup grant: realm, tenant, mode, optional fixed identifier, optional verified claims, expiry. It is part of the ceremony token, and the step that creates the user consumes its source in the same commit. If an invite is cancelled while a signup runs, that signup is refused.
Creating the user
One commit: consume the permission, insert the user, insert the passkey, insert external identities, insert the recovery method if given, write the event, add the application’s own rows.
Invites
- 256 random bits, stored as a hash, shown once, at most 7 days, single use.
- An invite can be listed and cancelled. A list never shows the link.
- An invite gives no rights by itself. The application can attach its own data to it.
Verifying an email address
A link with a single-use token. Opening the link shows a page with a button; only the button’s request uses the token, because mail scanners open links. A verified address is a claim, not a login.
06 Recovery
Recovery gives permission to create a passkey for an existing user. It is not a login. An application chooses its methods; policy can only remove some.
| Method | Strength |
|---|---|
| Another passkey | Not recovery: log in with it |
| Recovery key | Strong: 256 bits, shown once, stored as a verifier |
| Approval by tenant owners | Strong, if people check each other by another channel |
Weak. MUST NOT be enabled together with e2ee |
All methods
- All sessions and tokens of the user end in the same commit that adds the new passkey.
- The user gets a notice on every known channel.
- Other passkeys stay. For 72 hours† a recovered account cannot remove passkeys that are older than the recovery, change its recovery methods or its addresses. A person who lost the mailbox but has a passkey can therefore take the account back.
- A login with an older passkey in this time can undo the recovery. One commit removes what was added since the recovery: passkeys and their sessions, devices and their tokens, external identities and a recovery key. It also removes every connected-app grant, authorization code and API key. What the caller did to application data, or to other accounts, belongs to the application: the audit log shows it.
- A request gives the same answer, after the same time, for known and unknown addresses. A message that cannot be sent is tried five times and then removed: it has a secret.
- The account waits 24 hours†. Notices go out at the start. Any logged-in session can cancel.
- After the wait, a single-use link allows one passkey registration.
A tenant with stricter rules can require a longer wait or an owner’s approval in addition.
Recovery key
A user signs a server challenge with a key from the recovery key, or opens an envelope with it (e2ee). The server
never sees the recovery key. It can be replaced after a fresh login.
07 Devices
CLIs and machines use RFC 8628, with a key from the first request.
Request
The device makes its keys and sends the public key, a name and a requested scope with a DPoP proof. The answer has a device code, a user code and the verification address. The fingerprint of the device key is shown on the device.
Approval
- On the first-party level, with a fresh login.
- The page shows the fingerprint, the name, the requested scope, the time, and the country or network of the request if the application knows it. The user confirms that the fingerprint is the same on the device.
- A user code alone opens nothing: 8 characters from an unambiguous alphabet, rate-limited, single use, at most 15 minutes.
- Denying is one click, and ends the request.
- The application decides which scopes a device may ask for, who may see, approve and deny a request, and the kind of the approved device. It can add its own writes to the commits of an approval and a revocation.
Tokens
- A device gets access tokens by signing an assertion (RFC 7523) with its key. There is no refresh token and no shared secret.
- The device key is the only credential. Revoking it ends its tokens in the same commit.
Kinds
| Kind | Acts as | Ends |
|---|---|---|
| User device | The user, first-party | With the user or when revoked |
| Machine | Itself, with a scope from the application | When revoked; survives the user that approved it, if the application says so |
A machine never satisfies Fresh.
08 Provider
An OAuth 2.1 authorization server with two fixed levels (decision 001).
Both levels
- Authorization code with PKCE
S256only. A code lives 60 seconds, works once, and reuse revokes what it gave. - Redirect URIs match exactly. Loopback addresses (RFC 8252) may differ in port only.
- A bad request shows an error page and never redirects: anyone can register a client, so a redirect without the user’s choice would make the server an open redirector.
issin every authorization response (RFC 9207). Metadata per RFC 8414.resource(RFC 8707) is required. A token has one audience, and an API MUST check it.- Tokens are opaque. ID tokens exist only for
openidrequests, are signed, and are for the client only. - The user is asked for consent by the login origin. No consent is remembered for write scopes of connected apps.
First-party clients
Registered by the application in its configuration. They use pushed requests (RFC 9126) and DPoP. Confidential clients
use private_key_jwt. This is the base for login on tenant domains.
Connected apps
Apps by others, for example agents that connect through a protocol with public clients and bearer tokens.
| Rule | |
|---|---|
| Registration | Client ID Metadata Documents first; RFC 7591 where a protocol needs it, rate-limited, removed when unused |
| Client authentication | private_key_jwt if the client offers it, else public with PKCE. No client secrets |
| Token | Bearer, or DPoP if the client offers it. Once a grant used DPoP, it stays with DPoP |
| Access token | At most 1 hour |
| Refresh token | One use. Reuse of an old one revokes the grant |
| Scope | From a list that the application marks as allowed for connected apps |
| Never | Credentials, sessions, recovery, devices, consent, invites |
| Protected resource metadata | RFC 9728 for each API |
| The user can | List, inspect and revoke grants |
A metadata document is fetched over HTTPS from a public address only. The fetcher refuses redirects, private, loopback and link-local addresses after DNS resolution, and more than 64 KiB†, and has a timeout. The consent page shows the client’s host name, because a name in a document proves nothing.
Relation to other profiles
First-party clients follow the direction of FAPI 2.0, plus rules for public clients. ID tokens are signed with ES256. An application whose clients need RS256 adds an RSA key, which OpenID Connect Core requires of a provider. Other parts of OpenID Connect (userinfo, dynamic scopes, front-channel logout) do not exist, so this is not a certified provider.
09 External identity
Another OpenID provider can prove a claim. Uses: permission to sign up, linking, a tenant rule (“a valid company login is required”).
- Authorization code with PKCE,
stateandnonce, all bound to the browser.issis checked (RFC 9207) where the provider sends it, and one redirect URI is used for each provider. - The ID token’s signature is always verified, with keys from the provider’s published set. The key fixes the algorithm.
- The identity is the pair
(iss, sub). An email address is never used as a key for an account. email_verifiedcounts only for a provider that the application lists as authoritative for that domain.- Tokens from the provider are discarded, unless the application asks for them and stores them itself.
The way back
The provider’s redirect comes from another site, so the browser does not send the session there. The callback checks the
answer, opens no session, and puts the checked identity into a __Host- cookie (HttpOnly, SameSite=Lax, five minutes,
for one purpose). A page of the application then uses it: for a signup, or with a fresh login for a link. A start needs an
allowed Origin.
Required company login
A signup with an identity of this provider has the required login.
A tenant can require a recent login at its own provider and a passkey. The requirement has a maximum age. When the company removes a person, the next check fails, and the person cannot enter the tenant.
Linking needs a fresh login. Two users cannot link one (iss, sub) in a realm.
10 Storage
Schema
schema/ has the reference schema for SQLite and PostgreSQL: the core (sqlite.sql, postgres.sql) and each feature
(sqlite.tenants.sql, …). An implementation in any language that uses these tables
can run on the same data. Column meanings are part of this specification. Indexes are not.
Secrets in rows are hashes, public keys, verifiers or ciphertexts. No row alone lets its reader act as a user, except an unsent mail in the outbox.
Table prefix
Auth tables live in the application’s database. Their prefix is configurable.
- Default
auth_. Pattern^([a-z][a-z0-9_]{0,14}_)?$: empty, or at most 16 characters that end with_. A start withsqlite_orpg_is refused. A prefix goes into SQL text, so an implementation MUST check the pattern before it builds any SQL. - The prefix applies to tables, indexes, constraints, sequences and triggers. Base names have at most 40 characters, so that a full name fits the 63 bytes of PostgreSQL.
- On PostgreSQL the schema (namespace) is configurable too, with the same pattern without the last
_. SQL names it explicitly and does not usesearch_path. - Two installations with different prefixes can share a database. They share nothing else: the prefix is not part of any key derivation, token or trace.
- Migrations run as an explicit step. Opening a store MUST NOT create tables. With a wrong prefix, opening fails with
schema_missing. Otherwise a typing error would start an empty user database, with open bootstrap. renamechanges the prefix of an installation in one transaction, while no server runs.
Application tables can refer to <prefix>users.
Transactions
commit(writes, app_writes) (02) runs both in one transaction, at an isolation level where the
preconditions hold until commit: SQLite with an immediate transaction; PostgreSQL with row locks for require,
replace, delete and consume, and unique keys for insert. Row locks are taken in key order.
app_writes can read and write application tables. If it fails, nothing is stored.
Migrations
The version number of the core is in <prefix>meta. Migrations are append-only and apply in one transaction where the
database allows it. A server refuses a version that it does not know. Opening never migrates: the migration step does,
from version 4 on.
| Version | Adds |
|---|---|
| 6 | limits, leases, features |
Version 5 existed only before a release, and has no migration.
Features
Some tables exist only when the application uses them. The migration step adds the tables of the features that it is
given, and records each in <prefix>features with its level. It never removes a feature.
| Feature | Tables | Needed for |
|---|---|---|
tenants | tenants, memberships | Tenants (14) |
places | places | A separate directory (15) |
A server that is configured for a feature MUST refuse to start when the database does not have its tables. Columns
named tenant in core tables exist in every database: without tenants they hold the root tenant.
Shared state
Any number of server processes can use one store. State that a check needs is in the store, never in the memory of one process:
- Single-use marks (
used): the hash of eachDPoPproof’s key andjti, and of each client or device assertion’s subject andjti, until the proof or assertion expires. A second use is refused. A ceremony’s challenge is a mark too. - Call limits (
limits): one row for each counted call, under the hash of its key (a client address, or a user) and the minute. A refused call writes nothing, so a key has at most its limit of rows. Calls at the same moment can pass the limit by their number. The key is hashed, so the table holds no address. - Leases (
leases): a piece of background work runs in one process at a time. A lease has an end, so a process that stops does not hold it for ever. Work that takes longer than its lease can run twice.
The client address that limits count is the address of the connection. Behind n proxies it is the n-th entry from the
end of X-Forwarded-For, without a port: each proxy adds one, so a client cannot choose it. An entry that is not an
address gives no address. The server must be reachable only through
these proxies.
Retention
Expired rows (tokens, challenges, invites, single-use marks, limits and leases) are removed in small batches, by background work that runs every few seconds. Audit events and client addresses have separate retention times that the application sets.
11 Traces
A trace is a JSON file that fixes all inputs of a flow and gives the expected decision. Every implementation replays every trace.
{
"trace": 1,
"profile": "AC1",
"name": "invite signup, cancelled while it runs",
"namespace": "example/v1",
"settings": { "rp_id": "login.example.com", "origins": ["https://login.example.com"] },
"steps": [
{
"flow": "signup.start",
"time": 1700000000,
"tenant": "t1",
"draws": [ ["user", "AwQF…"], ["challenge", "AAEC…"] ],
"reads": [ { "get": "invites", "key": ["…"], "row": { "…": "…" }, "version": 1 } ],
"input": { "invite": "…" },
"expect": { "output": { "…": "…" }, "writes": [] }
}
]
}
(The values in this example are shortened.)
State: the format is a draft. Traces are not recorded yet; the Rust tests cover the same flows in memory.
Rules
timeanddrawsare the only sources of time and randomness. Draws have a name and a length, and come in order. A step that asks for another draw fails, and so does a step that leaves one unused.readsare in order, with their answers. A row that does not exist isnull.- Comparison is exact, on canonical JSON (RFC 8785).
writesare in order and include preconditions. - Signatures in traces are deterministic: Ed25519, and ECDSA as in RFC 6979.
- A trace MUST NOT have data of a real person or a live key.
- A
refusalreplacesoutputin a refused step. Its code is compared, not its text.
Coverage
Each normative sentence with MUST or MUST NOT that a flow can violate has at least one trace that fails if an implementation ignores it. A trace names the sentence by file and heading.
Storage behavior (races, crashes, preconditions) cannot be a trace. The storage conformance tests cover it.
Black-box runner
conformance/ runs scenarios over HTTP against a live test server: wrong origin, replay, reused codes, mixed tenants,
downgraded algorithms, missing nonces. It needs no access to the implementation.
12 End-to-end encryption (optional)
Gives each user an identity key pair that the server cannot read. The application builds on it.
- The identity key is sealed once for each passkey, with the WebAuthn PRF output, and once for the recovery key.
- The PRF input is fixed:
<namespace>/passkey-prf. Each credential has its own PRF secret, so outputs differ. One prompt signs and gives the output. - The envelope has a random salt, so that two envelopes never share a wrapping key.
- PRF output never leaves the client. A client removes it from what it sends.
- A user device gets the identity key sealed to its own key by the approving client, after both sides compared fingerprints.
- Replacing the identity key is signed by the old one, needs a passkey assertion, and runs application writes in the same commit, because the application must seal its data again.
- With
e2ee, recovery by email, by a link and by owners cannot restore the key, so the server refuses it. Only a passkey, the recovery key or a user device can.
In the routes
Each envelope is in the commit that adds, uses or removes its passkey. A request without its envelope, or with one when the mode is off, is refused.
- Signup stores the passkey’s envelope, the recovery envelope and the recovery key’s verifier.
- Login returns the envelope of the passkey that was used.
- Adding a passkey stores its envelope; removing it deletes the envelope.
- A new recovery key replaces the recovery envelope and the verifier together.
- Recovery with the key returns the recovery envelope before the proof. For an unknown name it returns a decoy that has the same shape and is the same each time, so the answer does not show which names exist. Finishing stores the new passkey’s envelope.
- Undoing a recovery deletes the envelopes sealed since the recovery.
In a browser
The identity key is kept for the life of the session, encrypted with a non-extractable key. This protects a copy of the browser profile that lacks that key. It does not protect against a script on the origin. See THREATS.md.
13 API keys
For programs that can only send a fixed header. Off unless the application turns them on, and not recommended: a device key (07) or a connected app (08) does the same without a secret that can be copied.
Form
<prefix><secret>. The prefix matches ^[a-z][a-z0-9_]{0,14}_$, belongs to the application and never changes, so that
scanners find keys. The secret is 256 random bits in base64url, 43 characters. No other token has this length with the
prefix. The server stores SHA-256 of the whole text.
Creation
- It needs the user in person, with a fresh login. The application decides who may, and for which scopes.
- Name, scopes and lifetime are required. The lifetime is at most 90 days†. An implementation refuses a longer one and does not shorten it. Use does not extend it, and there is no renewal.
- Scopes come from the list of the application, which is not empty.
- The secret is in the answer once.
Use
- Only
Authorization: Bearer. Never a URL, a cookie or a body. - The level is
api_key, the binding isbearer, and there is no time of a proof. It is not first-party, not fresh, and not a connected app. An account API never accepts it. - Scopes that the application no longer offers are not given.
- The record gets the time and address of the use at most every five minutes. A new address makes an event.
- A policy that needs key-bound sessions refuses every API key. So does an application that turned them off.
End
A key ends with its lifetime, when its user ends it, with “log out everywhere”, a recovery or the undo of one, and when the user is disabled. Ending it needs no fresh login and works while the key is in use.
14 Tenants and memberships
A tenant is a boundary for sessions, for example an organization or a customer. It is not a role system. Its tables
are the feature tenants (10).
Tenant
| Column | Content |
|---|---|
id | 16 random bytes |
name | The tag in a host name or a path: ^[a-z0-9](https://github.com/audiochad/auth-chad/blob/main/spec/[a-z0-9-]{0,30}[a-z0-9])?$, unique |
created | Time |
The root tenant (01) has no row and no memberships. The HTTP layer refuses a name whose tenant host would be a configured origin.
Tenant names are not secret: a host or a path shows that a tenant exists. What a refusal does not show is whether a person may enter it.
Membership
A membership says who may enter a tenant. The library owns four columns: tenant, user, state (active or
suspended) and version. The application MAY add its own columns, for example a role. Each one MUST have a default in
the database, because the library inserts only its own columns. The application can set them in the same transaction.
- Memberships are in the same database as users, so that one commit can end a membership and everything that it allowed.
- The library reads the application’s columns with each request in a tenant, and hands them to the handler. It does not use them.
- An unknown tenant, and a tenant that the user may not enter, give the same refusal:
not_found.
The rule
A session, token, device, grant or API key in a tenant needs an active membership of its user:
- when it is made: the commit has a precondition on the membership row;
- with each request: a membership that is gone or suspended refuses the request, also if a row was left behind.
Machines act as themselves (07), so rule 2 does not apply to them.
Entering
A login makes a root session: a session in the root tenant. A user enters a tenant with it.
- Entering makes a session in the tenant with the root session as
parent. It has the passkey of the root session, and its end is not later. Its proof time is the later of its own and the root session’s, so a fresh login at the login origin counts in every tenant. - Use of a session in a tenant renews its root session too.
- The root session MUST be the user’s own: not a view, not a session in a tenant.
- Ending the root session ends its sessions in tenants in the same commit.
- A session in a tenant is valid only while its root session is valid.
On the tenant’s own host
A cookie belongs to one host. A tenant at <name>.<parent> therefore gets its session with a code:
- The tenant’s host makes a verifier (256 random bits) and keeps it in its own cookie
__Host-enter,SameSite=Lax, at most 5 minutes. It sends the browser to the login origin withchallenge= SHA-256 of the verifier. - The login origin needs the root session. It makes a code: 256 random bits, stored as a hash, single use, 60 seconds, for one tenant, with the root session and the challenge. It sends the browser back to the tenant’s host.
- The tenant’s host sends the code and the verifier. A wrong verifier, another tenant, or a used or late code gives
invalid_grant. A root session that ended givesunauthenticated, and a membership that ended givesnot_found.
These two GET requests change state, as in the authorization code flow of OAuth. A code alone opens nothing: the
verifier is in a cookie of the tenant’s host only. The address to return to MUST be a path on the same host: it starts with one /, and has only printable ASCII
without \.
Key-bound clients enter at the login origin with their root token and a proof by the same key. A key-bound token renews in its own tenant, at any path.
Ending
| Action | Ends in the tenant, in the same commit |
|---|---|
| Suspend | Sessions with their tokens, the user’s devices with their tokens, connected-app grants and their codes, API keys |
| End | The same, and the membership row |
| Remove the tenant | The same for each member, the invites of the tenant, and the tenant row |
Resuming a membership opens nothing: the user enters again.
Invites
An invite belongs to one tenant (05).
- A signup with an invite of a tenant makes the user a member in the same commit. The signup opens a root session. Without an invite of that tenant, a signup in a tenant is closed.
- A user with an account accepts an invite of a tenant: the invite is used and the membership is made in one commit. An
invite for another identifier is refused, and a second membership is
taken.
Requests
An application names the tenant of a request in one way, set when it starts:
| Way | Tenant | Session cookie |
|---|---|---|
| None | Root only | __Host-session |
| Host | <name>.<parent>. The hosts of the configured origins are the root tenant | __Host-session on each host |
| Path | <prefix><name>/… on the login origin | __Host-session-<name> |
- With hosts, each tenant has its own web origin. A
DPoPproof names the tenant’s host, and a request that changes state accepts the tenant’s own origin. - With paths, all tenants share one web origin. A script flaw in one tenant reaches the sessions of all open tenants. Browsers limit the number of cookies of a host: keep the open tenants of a person below 20†.
Accounts, sessions, recovery, invites and members are managed at the login origin with the root session. The application decides who may manage members, often from its own columns. The commit then has a precondition on the manager’s own membership row, so a manager who is suspended meanwhile cannot finish.
15 Places
An application can keep its data apart from the auth tables: the auth database is then the directory database. It
has the users, the sessions, the tenants, the memberships, and for each tenant or user its place. The data is in
one or many other databases. The table is the feature places (10).
Choice
An application places by tenant or by user. It chooses one when it is set up, and never has both. By tenant, a request outside a tenant has no place.
Place
| Column | Content |
|---|---|
owner | The 16 bytes of the tenant or the user |
place | JSON of the application’s own type, at most 4 KiB |
state | creating, active, moving or removing |
generation | 1, and one more with each move |
created | Time |
The library does not read the content. It MUST NOT hold credentials: a password belongs to the configuration of the server that opens the database.
States
| State | A request | Next |
|---|---|---|
creating | 503 not_ready, Retry-After | active, when the application’s work says that the data is there |
active | The place and its generation | moving, removing |
moving | 503 moving, Retry-After | active with the new place and the next generation, or the old place |
removing | 404 not_found | Gone, when the application’s work says that the data is gone |
Work
A new place and its work are in the commit that creates the tenant or the user. A removal and its work are in one commit too. The work is in the outbox (02) and runs at least once after the commit.
- Each call has an ID. A call can come again with the same ID, so the application’s work MUST be safe to repeat.
- Each piece of work has a lease of 300 seconds†. Any number of runners can run at once, and one piece runs in one place at a time. Work that takes longer than its lease can run twice. Work that fails stays, and runs again when its lease ends.
- Work to provision a place that no longer waits for it, for example after a removal, is dropped.
- After a move, the data at the old place is the application’s to delete.
- The application lists places that wait too long by their state.
Costs
A separate directory has no transaction across users and data, no foreign keys to users, and no consistent backup of both. The application keeps names that it shows in its own data. A restored directory has sessions that ended since the copy: after a restore, end all sessions, tokens and API keys.
16 Encrypted sync (draft, not built)
State: a proposal for review. Nothing here is implemented. Values marked † are proposals.
An application with end-to-end encryption (12) keeps each user’s data on the server as ciphertext and works on a local copy in each client, for example a SQLite database that the client queries directly. The library stores and orders the ciphertext and checks who may write. It never reads the data, and it does not merge it: merging belongs to the client.
Keys
- The identity secret of 12 is the account key. Each passkey and the recovery key unlock it.
- The keyring holds the content keys, one for each period, sealed with a key derived from the identity secret. A client adds a period to rotate: data written later uses the new key. Old periods stay, so old data still opens.
- A new unlock method needs only the identity secret, not the other methods’ secrets.
Keyring
| Field | Content |
|---|---|
user | Owner |
version | 1, and one more with each change |
period | The current period |
ciphertext | The sealed keyring, at most 64 KiB† |
created | Time |
- A change names the version it replaces (compare-and-swap). A stale version is refused.
periodgrows by exactly one, or stays. A larger jump is refused.- The server keeps every version for 30 days† and returns them on request, so a broken update cannot destroy the only copy.
- A change needs a fresh login, as for credentials (04).
Log
Each user has an append-only log of encrypted entries.
| Field | Content |
|---|---|
seq | Assigned by the server: gap-free, one more for each entry of this user |
device | The device that wrote it. It MUST be the device of the session |
counter | The device’s own counter: one more for each entry of that device |
period | The period of the key that sealed it |
previous | The hash of the entry before it, as the writing client saw it |
ciphertext | At most 1 MiB† |
signature | By the writing device’s key, over all fields above except seq |
- An entry with an old period after the keyring moved on is refused.
- A retry with the same
deviceandcounterand the same bytes returns the firstseq. The same pair with other bytes is refused. - A read gives entries after a
seq, in pages of at most 1000†, and the current head (seqand hash). - The application gets a hook when the head moves, for example to tell open clients.
Snapshots
- A snapshot is the sealed state up to a
seq(covers). A client writes one when its log is long, for example every 300 entries†. - The server keeps the 2† newest snapshots, and may delete entries up to the older one’s
covers. A client that asks for deleted entries gets410 compacted, and starts from the newest snapshot. - Snapshot bodies can be in an object store. The table keeps the place, the size and the hash.
What a client checks
- Every entry’s signature, by a device that the client knows as the user’s.
- The chain: each
previousis the hash of the entry before it. A gap or a fork means the server withheld or changed entries: the client stops writing and tells the person. - The counter of each device: a gap or a repeat is a warning.
- The newest head it has seen is kept in the keyring, so the next device can check that the server did not roll back.
Revoking
- Revoking a device or removing a passkey and the keyring update with a new period are one server transaction. The request carries the new keyring. Without it, the revocation is refused.
- The identity secret does not change on a revocation. A device that kept a copy can still open later keyrings that it obtains. A person who fears that replaces the identity key (12), which seals everything again.
The local copy
- The local copy holds plaintext. A client SHOULD encrypt it at rest with a key that the page cannot export, and lock it when idle.
- A browser cannot protect it from a script on the same origin (THREATS.md).
What the server sees
Per entry: user, seq, device, counter, period, size and time. Per snapshot: size and time. The keyring’s version and
period. Activity times. Not the content, and not the shape of the data inside the ciphertext.
Quotas
Each user has a limit for log bytes, snapshot bytes and entries per minute†. A write over the limit is refused with
413 or 429.
Open questions
- Is the signed chain worth its cost for every application, or an option?
- Should the library also hold the blobs of large files (images), each with its own key, or leave them to an object store that the application signs URLs for?
- Should the hook for a moving head be a server-sent event stream in the library, or only a callback?
- Is 30 days of keyring versions right, and who may read old versions: every device, or only after a fresh login?
Threat model
Assets
Accounts, sessions, credentials, the link between a person and an account, tenant boundaries, and (with the e2ee part)
the users’ identity keys.
Attackers
| Attacker | Can do | Must not be able to | Defence |
|---|---|---|---|
| Phisher with a look-alike page | Show any page, relay messages live | Log in as the user | Passkeys are bound to the RP ID and origin |
| Thief of a database copy | Read every row | Log in, or call an API | Public keys and hashes only; no reusable secret at rest |
| Thief of a log | Read metadata | Log in | The library writes no logs; tokens are never in URLs, except single-use links |
| Thief of a first-party token | Replay it | Use it | DPoP with server nonces |
| Thief of a session cookie | Use it until it ends | Change credentials, stay forever | Short life, hashed, fresh proof for sensitive actions |
| Thief of a connected-app token | Use its scopes at one audience until it ends | Change the account, use another API, renew after reuse | Audience, scope, one-use refresh tokens |
| Thief of an API key | Use its scopes until it ends or the owner ends it | Change the account, reach a first-party route | Off by default, own level, hashed, at most 90 days, last use and address shown |
| Malicious connected app | Ask for consent | Get more than the consent, pose as another app | Verified client identity, exact redirect URIs, consent page |
| Owner of a mailbox | Receive links | Log in silently, remove the owner’s passkeys | Delay, notices, cancel, frozen credential removal |
| Malicious identity provider | Claim any identity | Log in without the passkey | Rule 3 |
| Tenant administrator | Set rules, remove members | Log in as a member, weaken a rule, see another tenant | Policies tighten only; tenant in every key |
| Network attacker | Read and change traffic | Anything | TLS; iss checks (RFC 9207); exact origins |
| Cross-site page | Send requests with cookies | Change state | Origin and Sec-Fetch-Site checks, SameSite |
| Bot | Send many requests | Lock out users, enumerate accounts at scale | Rate limits; discoverable login needs no identifier |
What the design does not protect against
- Code on the application’s own origin. A script there can act as the user, and can read keys that the page can read. The defence is a strict CSP and no third-party code.
- A compromised user device, while it is unlocked.
- A malicious server operator. The operator can log in anyone, except that the
e2eepart keeps content keys from the operator. A malicious page can still steal those keys when the user unlocks them. - A compromised passkey provider. A synced passkey is as strong as the account that syncs it. A policy can require passkeys that do not sync.
- A user who approves a device that is not theirs. RFC 8628 can be phished. The approval page shows the device key’s fingerprint and where the request came from, and the user must compare it.
- Denial of service beyond rate limits.
Weakest links, in order
- Recovery by email, where an application enables it.
- Device approval by a careless user.
- API keys, where an application turns them on.
- Session cookies.
- The passkey provider’s account recovery.
A change that adds a weaker link than these needs a change to the thesis first.
Decisions
Summary: what we decided, and why, one short page each. The wiki explains how things work; these pages keep the reasons.
Key terms: decision, reason, refused, not now.
Related: wiki · spec
Each page has: the date, what was decided, why, and what it rules out. A new decision gets the next number. A decision that changes gets a new page that names the old one.
| No. | Decision | Date |
|---|---|---|
| 001 | Authentication only, keys only, one strict profile | 2026-11-24 |
| 002 | One program and a scaling path of three steps | 2026-11-25 |
| 003 | Tenants as session boundaries; places by tenant or by user | 2026-11-25 |
| 004 | Tenants and places are optional table features | 2026-11-25 |
| 005 | End-to-end encryption and app hooks in the HTTP routes | 2026-11-26 |
001 Authentication only, keys only, one strict profile
Summary: why auth-chad logs people in with keys only, leaves authorization to the application, and has no weaker settings.
Key terms: passkey, device key, profile, policy, refused, not now.
Related: Concepts · Threats
Date: 2026-11-24. State: in force.
Decided
- Login is proof of a key. Anything that can be copied must be short-lived, single-use or limited. A stolen database, log line or token must not let a thief log in.
- Authentication only. The library answers who, how, how recently, with which key, in which tenant. The application answers what they may do. Roles, permissions and sharing are out of scope.
- One profile. A release has one set of algorithms, checks and upper limits. Policies only tighten.
- The application owns its data. Auth tables live in its database, next to its own.
- Nothing hidden. Clock, randomness, storage, network and mail are inputs. No logs; events are writes.
- The spec is the product. Each language implements it. Rust is the first.
Refused
| Refused | Reason |
|---|---|
| Passwords, SMS codes, TOTP as login | They can be phished or copied |
| Sign-in by email link alone | The mailbox becomes the credential |
| Sign-in at another provider alone | That provider, or its account recovery, becomes the credential |
OAuth implicit and password grants, PKCE plain | Replaced by RFC 9700 |
| SAML | XML signatures are a large attack surface |
Algorithm negotiation, alg: none | Downgrade attacks |
| API keys without an end, or that act as the user | A device key does the same without a copyable secret |
| A compatibility mode | Every mode is a weaker way in |
Not now
| Not now | What can change it |
|---|---|
| Email links as login | An application that needs them. Then only as an opt-in, with short sessions, no fresh login, never with e2ee |
| Passwords | Only to move old accounts: check an old password once, and use the result as permission to create a passkey |
What we write and what we use
We write protocol logic and small, strict parsers, because they must match in every language. We use well-reviewed libraries for curves, hashes, ciphers, TLS and database drivers. Fewer dependencies is a goal; own cryptography is not.
Before 1.0
A short working example, a doctor command, ready screens that an application can replace, runbooks (key rotation,
stolen database, lost passkeys), and an external security review.
002 One program and a scaling path of three steps
Summary: why the same binary runs in every process, every request is checked in the users’ database, and growth happens in three steps.
Key terms: step, users’ database, shared state, worker, with_proxies.
Related: Scaling · spec 10
Date: 2026-11-25. State: in force. It replaced an earlier list of four separate architectures.
Decided
| Subject | Decision |
|---|---|
| Frame | A scaling path with three independent decisions: where the data is, how many processes, how a request names its tenant |
| Program | One binary everywhere. Configuration chooses web, worker or both |
| The check | Every request, in the users’ database. No cache of answers, so a logout works from the next request |
| Shared state | Rate limits, single-use marks and leases live in the database, pruned by the worker |
| Proxies and signed passes | None. Any load balancer in front of identical processes |
| SQLite | Recommended for step 1. Never on several machines |
| Step 3 | PostgreSQL only. Any number of data servers, each with one database or one for each customer |
| Database credentials | In the process’s configuration, never in the places table |
| WebSocket and event stream | A new check after 5 minutes† at the latest |
Why
A process that trusts another process’s word about a session, or a cache of the answer, lets access outlive a logout. Putting shared state in the database that every process already reads makes one process and many behave the same, with nothing to configure.
Not now
Regions and processes that cannot reach the users’ database. Signed passes are one possible answer, with a delay before a logout works.
003 Tenants as session boundaries; places by tenant or by user
Summary: why a tenant is a boundary for sessions and not a role system, and why the data’s place is chosen by tenant or by user, never both.
Key terms: tenant, membership, place, directory, PlaceBy.
Related: Scaling · spec 14 · spec 15
Date: 2026-11-25. State: in force, built.
Decided
- A tenant is a boundary for sessions. A session belongs to one tenant. Entering another tenant makes another session, and may need a new passkey use if its rules are stricter. An unknown tenant and a forbidden one give the same refusal.
- Memberships without roles. The library keeps tenant, user and state. The application adds its own columns, such as a role, and decides what they mean. Ending a membership ends that user’s sessions, tokens, devices, grants and API keys in that tenant, in the same commit.
- Memberships live with the users, in every step, so a removal ends access in one commit.
- A place is chosen by tenant or by user. An application chooses one when it is set up. “Both” would give three answers to one question.
- Tenant address: a path or a host; both supported, with recipes.
- No gateway. Every process reaches the users’ database and checks the request itself.
Why
Roles differ in every application, and a library that stores them must also judge them. A session boundary is generic, and it is needed for security: a token of one tenant must open nothing in another.
004 Tenants and places are optional table features
Summary: why the tenants, memberships and places tables exist only in databases that ask for them.
Key terms: feature, migration, check_tables, schema version.
Related: Data · spec 10
Date: 2026-11-25. State: in force, built.
Decided
- The core tables exist in every database.
tenants(tenants and memberships) andplacesare features. migrate,createandupgradetake the list of features.auth-chad schema --withandauth-chad featureprint the SQL.- A server that is configured to use a feature refuses to start if the database lacks its tables (
check_tables). - The
featurestable records which features a database has.
Why
An application without tenants should not carry empty tables that look important. Failing at start is better than failing on the first request that needs a missing table.
005 End-to-end encryption and app hooks in the HTTP routes
Summary: why the HTTP routes carry encryption envelopes, recovery by key only, and hooks where an application adds its rules and rows.
Key terms: e2ee mode, envelope, recovery verifier, decoy, hook, Refusal, By, mount path.
Related: Interfaces · spec 12 · e2ee recipe
Date: 2026-11-26. State: in force, built. The first application with end-to-end encryption moved onto these routes.
Decided
- E2EE mode (
Auth::with_e2ee): signup, passkey add, recovery-key set and recovery finish carry envelopes; login returns the passkey’s envelope; passkey removal deletes it. - Recovery with a key only. In e2ee mode, email, link and owner recovery are refused, because they cannot open the encryption key. Recovery start returns the envelope, or a decoy for an unknown user, after the same work, so an answer does not show which accounts exist.
- Undo of a recovery deletes the envelopes made since the recovery; the
commit_undohook lets the application treat the removed devices as revoked. - Hooks for the application’s rules and rows: names, invite data, device requests, who may approve, the device kind, and commit hooks for signup, approve, revoke and undo.
- Refusals from hooks keep the application’s own codes (
Refusal::App), and commit hooks get the request’s address (By { who, ip }) for the application’s audit. - One error format (
{"error": code}) and base64url IDs. No compatibility mode for older client formats. - A configurable mount path (
mounted_at), with/authas the default. - One client crate for CLIs and wasm, with a
browserfeature, instead of a client in each application.
Why
An application with end-to-end encryption needs the encryption secret to travel with every credential change, in the same commit. Doing it in the library once is safer than doing it in every application.
auth-chad wiki index
For coding agents and search. One line for each page: what it answers, and its key terms. Read the page you need, not
all of them. Exact rules are in spec/; task code is in docs/recipes/.
- index.md: what auth-chad is, what it is for and not for, where to start. Terms: passkey, device key, authentication, authorization, status.
- concepts.md: the mental model in seven ideas, and the glossary. Terms: flow, decision, write, commit, Authenticated, tenant, realm, policy, DPoP, ceremony, envelope, hold.
- map.md: repository and crate layout, dependency rules, where to change things, code rules, tests. Terms: formats, flows, adapters, crate, feature, no_std.
- data.md: every table, the request types, rows and versions, writes and their conditions. Terms: row, version, Stored, Write, Decision, Ctx, hash at rest, prefix.
- flows.md: the request check, decide-then-commit, signup, login, device login, recovery, connected apps, outbox and worker. Terms: ceremony, fresh login, device code, grant, lease.
- interfaces.md: traits and extractors: Hooks, Refusal, By, Store, Reader, Clock, Draws, Placement, Mailer, Columns, Http, Passkeys, Service, Row, Field, Worker; FirstParty, InPerson, FreshLogin, ConnectedApp, ApiKey, Member, Here, At, Caller.
- scaling.md: from one process to many, and from one database to many; network assumptions; the worker; unsupported patterns. Terms: step, users’ database, directory, place, with_proxies.
- recipes.md: the task index, with the feature each task needs.
- ../decisions/README.md: decisions and their reasons.
- ../../spec/README.md: the normative spec, by topic.
- ../../THREATS.md: what the design protects against, and what it does not.
Build the site: scripts/wiki.py build (output in rust/target/wiki). Check it: scripts/wiki.py check.
From the CLI: auth-chad docs, auth-chad docs <page>, auth-chad docs --open.