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.