0021 · Auth: one Authenticator port, two adapters (OIDC, local sessions)
Status: Accepted (2026-10-12). Spec: PLAN.md § Phase 16. Builds on ADR-0017 (runtime crates:
ports in core, adapters in their own crate, the domain part generated), ADR-0007 (the error
contract) and ADR-0013 (the web frontend).
Context
Section titled “Context”Three ways to sign people in were asked for: Auth0, Keycloak and a project’s own database. They are not three adapters. Auth0 and Keycloak are both standard OpenID Connect providers, and for the API the job is the same with either: it is an OAuth2 resource server that verifies a JWT access token and turns its claims into a caller. The only real difference is where the roles are:
| Provider | Roles claim |
|---|---|
| Keycloak | realm_access.roles (realm roles) or resource_access.<client>.roles |
| Auth0 | permissions (RBAC on), or a namespaced custom claim (https://example.com/roles) |
A project’s own database is a different thing: there the API is the identity provider. It registers, hashes passwords, opens and closes sessions — later, resets passwords and verifies addresses.
How the frameworks Puerto is compared with split it:
- Spring Security — one
oauth2ResourceServer().jwt()configured byissuer-uri; Auth0 and Keycloak are configuration, the roles are mapped by aJwtAuthenticationConverter. - ASP.NET Core — one generic
AddJwtBearer(Authority, Audience); per-provider differences are configuration. Authorization is a separate step:[Authorize(Roles = "admin")]or policies. - Laravel — guards (how a request is authenticated) are separate from providers (where the user comes from). A Keycloak guard verifies the JWT and may or may not load a local user.
- NestJS / Passport — interchangeable strategies behind one
AuthGuard, roles through a@Roles()decorator and a guard. - Rails 8 — authentication is a generator, not a gem:
User,Sessionand the controllers belong to the app, the primitives (has_secure_password) stay in the framework. Sessions are rows in asessionstable.
Decision
Section titled “Decision”1. One port, two adapters
Section titled “1. One port, two adapters”puerto_core::auth:Principal { user_id: Uuid, subject, email: Option<String>, name: Option<String>, roles: Vec<String> }withhas_role(&str); the portAuthenticator { async fn authenticate(&self, token: &str) -> Result<Principal, AuthError> };AuthError:: {Invalid, Expired, Unavailable}(#[non_exhaustive]).puerto-auth(new runtime crate), featureoidc:OidcAuthenticator— discovery fromAUTH_ISSUER/.well-known/openid-configuration, the JWKS fetched and cached (refetched on an unknownkid), signature +iss+aud+expchecked, roles read fromAUTH_ROLES_CLAIM. Auth0, Keycloak or any other OIDC provider is configuration.puerto-auth, featurelocal: password hashing (argon2id,Argon2Hasher). The sessions — their tokens too — arepuerto-sqlx’sPgSessions, which is theAuthenticatorof a local project; it hashes the presented token on every request, so the token belongs with it. The ports the generated use cases see (PasswordHasher,CredentialStore,SessionStore) arepuerto-core::auth’s.
A route never knows where its caller came from, and tests use MockAuthenticator. A project
picks one with puerto new --auth oidc|local; [project] auth records it.
2. Local sessions are opaque rows, not self-issued JWTs
Section titled “2. Local sessions are opaque rows, not self-issued JWTs”POST /auth/login returns a random 256-bit token; the database keeps its SHA-256 hash, the user and
an expiry. Revoking — logout, a stolen token — is a DELETE. There is no signing key to keep or
rotate, and a lookup per request is the cost (Rails 8 pays the same). A self-issued JWT would
save the lookup and lose revocation, and the local mode is never the one that has to scale past
a primary key lookup.
3. Every authenticated caller is a local User row
Section titled “3. Every authenticated caller is a local User row”A generated User entity (UserId, email, name, roles, and for OIDC issuer + subject)
is what other entities point at (owner: UserId). It is the same entity in both modes, so moving
from local to OIDC does not touch the domain:
- OIDC:
ProvisioningAuthenticator { inner, users }(generated, infrastructure) looks the caller up by(issuer, subject)and creates the row on the first request (just-in-time provisioning). A short in-memory cache keyed by the subject keeps it off the database on every request. Roles come from the token only: the column is not read in OIDC projects, so one place decides. - Local: the password lives in
credentials (user_id, password_hash)and the sessions insessions, soUsercarries no secret. Roles come from therolescolumn.
GET /me answers the user and the roles as the API resolved them, in both modes. The frontend
never reads provider-specific claims. User becomes a reserved entity name in auth projects.
4. Protected by default; roles are one attribute on the route
Section titled “4. Protected by default; roles are one attribute on the route”- A handler that takes
auth: BearerAuth(a poem-openapiSecurityScheme,puerto-web) is authenticated: no or a bad token →401 auth.unauthenticated. The OpenAPI spec carries thesecurityrequirement, so the frontend’s wire types know it. BearerAuthimplements poem-openapi’sApiExtractorby hand; only the spec registration comes from a private#[derive(SecurityScheme)]struct. The derive’s checker runs only once a bearer header was found: a request without one gets poem’s plain-text 401, not anErrorResponse, and the checker has no way to answer 503. By hand, every refusal is anErrorResponseJSON body — 401auth.unauthenticated(no header,Invalid,Expired), 503auth.unavailable, and 500auth.not_configuredwhen the routes carry noArc<dyn Authenticator>(bootstrap.rsdid not register one).#[require_role("admin")](puerto-macros, re-exported bypuerto-web) on the handler adds a403 auth.forbiddencheck at its top. One line, visible, written by the generator and by hand alike. The 16.1 spike (poem-openapi 5.1.16) proved it works inside#[OpenApi] impl: poem-openapi leaves attributes it does not own on the method, so the route still registers and its spec entry still carriessecurity: [{"BearerAuth": []}]. That holds whichever of the two attributes comes first, and clippy-D warningsis clean on the expansion. What the macro relies on:- the handler has a parameter whose type’s last segment is
BearerAuth(a type alias hides it; no parameter is a compile error naming the attribute), and - the return type has
from_status(StatusCode, Json<ErrorResponse>), which every generated response enum has. It does not document the 403: the response enum’sForbiddenvariant does. On error the macro must still emit the method unchanged, or rustc adds a confusing “no method named …” error.
- the handler has a parameter whose type’s last segment is
- Scaffold protects every CRUD route of an auth project.
puerto.tomlrecords the exceptions:public = [...](noBearerAuth) androles = { use_case = [...] }. - Rules that depend on data (“only the owner edits”) are not annotations: protected use cases take
actor: Principalin their params and decide, returning{Entity}Error::Forbidden→ 403. The domain sees aPrincipal, never a token.
5. The frontend: an AuthGateway port, bearer tokens, two adapters
Section titled “5. The frontend: an AuthGateway port, bearer tokens, two adapters”domain/auth/session.ts:CurrentUser(fromGET /me) and the portAuthGateway { currentUser, accessToken, login, completeLogin, logout }(completeLoginredeems the provider’s answer on/auth/callback; a no-op for local).infrastructure/auth/oidc-auth-gateway.ts—oidc-client-ts, Authorization Code + PKCE, works with Auth0 (plus theaudienceparameter) and Keycloak;local-auth-gateway.ts— the/auth/*endpoints, which also implements the local-only portAccounts { register, signIn }(domain/auth/accounts.ts) the/loginand/registerpages use.infrastructure/auth/bearer-middleware.ts: an openapi-fetch middleware, attached to the client by the composition root, addsAuthorization: Bearer …; a 401 startslogin().presentation/core/auth.tsx:AuthProvider+useAuth()→{ user, can(role), login, logout }; the generated route table wraps every non-public route in<RequireAuth>; generated screens hide actions the user’s roles do not allow. The API stays the authority: a 403 reaches the existingErrorAlertasauth.forbidden.- Where the token is kept: in memory for OIDC (
InMemoryWebStorage) — a reload redirects to the provider, whose own session sends the user straight back;localStoragefor local — there is no provider session to fall back on, and an opaque token that leaks is revoked server-side.
6. Development and tests run against Keycloak
Section titled “6. Development and tests run against Keycloak”An OIDC project’s docker-compose.yml gains Keycloak with an imported realm: a public web client
(PKCE, redirect to the Vite dev server), an audience mapper for the API and a user with the
admin role. make test/auth runs puerto-auth and a generated project against it. Auth0
cannot run locally; being the same adapter, its claim mapping is covered by unit tests over
signed tokens and a static JWKS.
Alternatives rejected
Section titled “Alternatives rejected”- An adapter per provider (
puerto-auth0,puerto-keycloak). Same verification twice, a crate to add for every new provider, and none of the compared frameworks does it. - Self-issued JWTs in local mode. See § 2.
- The API as a backend-for-frontend with an HttpOnly cookie. Safer against XSS, but it adds CSRF protection, a server-side session for OIDC too, and a proxy in front of the SPA. Bearer keeps one shape for the web, the Swagger UI and any other client.
- Roles from both the token and the
Userrow in OIDC. Two places deciding; when they disagree nobody can say which one won. - A
Principalwithout a local user (OIDC). Simpler, but every entity that belongs to someone would hold a provider subject, and changing provider would orphan the data.
Consequences
Section titled “Consequences”- Two more runtime crates,
puerto-authandpuerto-macros, released in lockstep beforepuerto. - An auth project’s response enums gain 401/403 variants, its protected params an
actor, and its route tests aMockAuthenticator. A project without--authis generated exactly as today. - Password reset and address verification need a mail sent from a use case — the
deliver_nowADR-0020 left out. Local auth is the first feature that needs it. - One local-user lookup per request in OIDC projects (cached) and one session lookup in local ones.