Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

InterfaceYouDefault
HooksImplement the methods you needEvery method has a safe default
Extractors (FirstParty, FreshLogin, …)Name them in handlers—
Store, ReaderPick a store; call Reader to read rowsSqliteStore, PostgresStore, SeaOrmStore
Clock, DrawsNothing, except in testsSystem time and system random bytes
PlacementImplement it only with the places featureNoPlaces
MailerImplement it only without the axum adapterHooks::send in axum
ColumnsDeclare with member_columns! for your membership columns()
Http, PasskeysImplement them only in a client on a new platformbrowser::Fetch, browser::Passkey
ServiceNothing: Auth implements it—
Row, Field, WorkerNothing: 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
    }
}
GroupMethodsYou decide
Signupcommit_signup, valid_names, invite_data, may_inviteWho may join, your first rows
Devicesmay_request_device, may_approve, device_kind, commit_approve, commit_revokeWhich devices, who approves, your rows
Recoverycommit_recovery, commit_undo, may_recover, verified_address, find_accountNotices, your clean-up
Tenantsmay_create_tenant, may_manageWho runs a tenant
Othersmay_view, may_create_key, send, exchange, provider_keysSupport 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_revoke and commit_undo receive By { who, ip }: the caller and their address (None with without_addresses).

Extractors: proof in a handler’s signature

ExtractorThe request hasRefused with
FirstPartyA session of your own client, or a user deviceunauthenticated
InPersonThe user in person: not a machine, not someone who views as the userforbidden
FreshLogin<SECS>A passkey use in the last SECS secondsstep_up_required
ConnectedAppA token of an app that the user allowed, for this API. Check its scopesunauthenticated, forbidden
ApiKeyAn API key (only if turned on)unauthenticated
HereThe tenant of the request (the root tenant outside one)—
Member<C>A membership in the request’s tenant, with your columnsnot_found
At<P>The place of the request’s tenant or user503 not_ready or moving
CallerThe 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)
}
MethodDoes
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

TraitMethodsRecipe
Placementchoose a place for a new tenant or user; provision and remove its data (safe to repeat)directory
Mailersend(mail) -> bool; false tries again laterrecovery
ColumnsYour 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.

TraitYou giveIn a browser
Httpsend(request) -> response, with your HTTP librarybrowser::Fetch
Passkeyscreate, get, prfbrowser::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. Service names those types for handlers.
  • Row and Field map a struct to a table and a Rust value to a database value. The table! macro writes them.
  • Worker is the flow-level form of Placement, for code without the axum adapter.
  • The full list of hooks with their documentation: rust/adapters/axum/src/lib.rs, or cargo doc -p auth-chad-axum --open.