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

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 seeFile
The wiringsrc/app.rs
Users rows in the signup transactionsrc/accounts.rs
The migrationsrc/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 organizationsrc/extractors/mod.rs
Middleware that knows the caller, and who views (audit)src/middleware/mod.rs
Routes with a user, a visitor, a recent passkeysrc/controllers/home.rs
Data of an organization, with Loco’s tenant scopesrc/controllers/notes.rs
A role and a recent passkey togethersrc/controllers/orgs.rs
Connected apps (MCP)src/controllers/apps.rs
Moving accounts with passwordssrc/controllers/legacy.rs
Tests with Loco’s test servertests/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, not after_routes. Routes that are added in after_routes are outside of Loco’s middleware: no request ID, no panic handler, no remote IP.
  • install takes a function. Loco calls after_context for 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.pid is 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 OrgContext does. A separate tenant is for separate logins.
  • Reject with a response, not with a Loco error, in extractors. A Loco error loses WWW-Authenticate and is logged as an error for each visitor. auth_chad_loco::refused is 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

GapEffectPlan
The router serves one tenant (the root)Separate logins need own routes. The extractors already use a Tenant in the requestTenant from the request in adapters/axum
A read of the database for each request with a credentialSlower than a JWT; a logout works at onceAccepted
cargo loco routes does not list /auth and /oauthOnly the listLoco lists its own routes only
API keys are offMachines use a device with its own key, and need DPoPapi-keys, if a program can send only a header
No typed audit detailsThe example records method, path, status and userNeeds a decision
rusqlite (auth-chad-sqlite) and SQLx share one libsqlite3-sysSQLx needs a version below 0.41 and rusqlite 0.43 has 0.40, so both build together today. A newer rusqlite can break thatUse one of them in an application
The SeaORM adapter has more dependencies than the others183 crates with both drivers, and 84 for auth-chad-postgresAn 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, so Fresh refuses it, and there is no list of paths that someone must keep complete. See view-as.
  • resource_metadata in 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.