Records Architecture decision

ADR-079

Renewable Bearer Sessions with Rotating Refresh Credentials

Partially superseded Decided 2026-08-22 Source file
Updated
2026-11-10
Partially superseded by
ADR-081 for renewable-session expiry storage.
Partially supersedes
ADR-024 and ADR-036 for human bearer-credential lifetime and renewal. Their opaque-token and runtime-state decisions remain current.

Context

Chatto's human bearer credentials originally used a sliding RUNTIME_STATE TTL. Every successful API request renewed the same opaque credential. A copied bearer token could therefore remain useful indefinitely if either its legitimate owner or an attacker kept using it.

Giving that token a fixed expiry without a replacement path would turn normal session maintenance into an interactive authentication event. In particular, the bundled multi-server client would have to reopen the remote server's OAuth authorization flow, take the user away from their current work, and repeat that interruption independently for every connected server. Non-browser clients would have no equivalent automatic path.

The replacement must work with multiple Chatto replicas, survive a lost token response, limit replay, preserve the frontend's current route and realtime projection, and avoid storing raw credentials. Cookie sessions and bot API keys have different presentation and lifecycle models and do not need this renewal protocol.

Decision

Human bearer authentication uses a renewable session consisting of:

  • a short-lived opaque access token for ConnectRPC, HTTP, and realtime traffic;
  • a rotating opaque refresh credential normally used at /oauth/token and also presented by the bundled client at /auth/logout for stable-session revocation; and
  • one stable latest-value renewable-session record in RUNTIME_STATE.

This applies to first-party bearer sessions issued by password, registration, and explicit external-identity account-creation flows, and to delegated bearer sessions issued by OAuth Authorization Code with PKCE. OAuth sessions remain bound to their validated client ID. Bot API keys remain non-expiring durable bot credentials, and same-origin cookie sessions use the separate stable-key renewal behavior in ADR-081.

The default access-token lifetime is 15 minutes and is configurable with auth.access_token_ttl / CHATTO_AUTH_ACCESS_TOKEN_TTL. The renewable session has a 90-day renewal window, configured by the existing auth.token_ttl / CHATTO_AUTH_TOKEN_TTL. A successful refresh in the final quarter advances the window to the configured lifetime from that refresh. An inactive session expires after one complete window. An access token issued near the end of a window is clamped to its remaining lifetime. Sessions of the built-in loopback OAuth client are the exception: they keep a fixed window of at most 24 hours from creation, never advance it, and validation shortens a longer stored window. See ADR-071 and FDR-023.

Runtime-state representation

RUNTIME_STATE stores two related records:

  • renewable_session.{hmac} is the stable authority for one renewable session. Its JSON value contains the user, optional OAuth client ID, credential kind and source, safe audit request metadata, creation and current window expiry, user auth generation, current rotation generation, previous refresh-request verifier and rotation time, the highest used generation, and authoritative fresh-auth metadata. The verifier is a purpose-separated HMAC of the raw recovery nonce. Each revision preserves or advances its explicit expiry and sets its per-message TTL to the remaining lifetime. A loopback-client revision can instead shorten its expiry to the fixed loopback window. Refresh, revocation, and every update read this record through the stream leader, not through a direct get. A direct get can come from a replica that lags behind a committed rotation. Refresh would then see an older generation and reject a valid credential or treat it as reuse.
  • Access-token and cookie validation run on every request, so they first read from any replica. That read can accept a credential but never rejects one. A rejection, such as a missing record, an older session generation, or a passed expiry, is decided again through the stream leader. Only that second pass removes invalid records. Thus a request with an unknown token costs one leader read. An accepted credential can show privileged-mode, fresh-auth, or revocation state that is older by the replica lag. Fresh-authentication checks therefore read through the leader. In this first pass, the auth generation check can also read the local User Auth projection for the auth generation check window of 60 seconds after a strict check accepted the user or the replica took a replica proof (ADR-127). Only an acceptance can come from that read.
  • session.{hmac} is one short-lived access-token verifier record. It includes its fixed expiry, renewable-session ID, access generation, user auth generation, and the established typed-credential metadata. Validation resolves fresh-auth values from the stable session, so a fresh-auth change does not modify deterministic lost-response recovery. Validation does not renew the access record's TTL.

The stable session ID is opaque and HMAC-keyed before it enters RUNTIME_STATE. Access tokens and refresh credentials are deterministic, purpose-separated HMAC credentials derived from that ID and the rotation generation. The raw values are returned to the client but are never stored. As with Chatto's other runtime credentials, restoring RUNTIME_STATE preserves sessions only when [core].secret_key is also preserved.

Every access-token validation checks both its own fixed expiry and the stable renewable-session authority. Deleting that authority rejects every access generation on its next API request or realtime connection, even if individual verifier records remain until TTL cleanup. A realtime socket that already completed authentication retains its authorized context only until that access token's fixed expiry, unless a separate logout or account-lifecycle signal ends it sooner. Password and account lifecycle changes still use the durable user auth generation as their primary revocation fence. Blocking an OAuth client also invalidates the stable sessions issued to that client.

Rotation, concurrency, and replay

Refresh uses the public /oauth/token endpoint with grant_type=refresh_token. The request includes the refresh credential, the OAuth client_id when the session is delegated, and a client-generated refresh_request_id. The request ID is a cryptographically random UUID version 4. It is a show-once recovery nonce, so the server stores only its HMAC verifier. The endpoint accepts the existing JSON and standard form encodings, returns the rotated access and refresh credentials with both remaining lifetimes, and marks responses non-cacheable.

The client must persist the request ID before sending the request and keep it until a valid response has been persisted. The server rotates as follows:

  1. Authenticate the HMAC refresh credential, stable session, client binding, current window expiry, OAuth-client policy, and user auth generation.
  2. Increment the generation and record the request-ID verifier and rotation time by updating the stable key with its exact JetStream KV revision. If the current window is in its final quarter, advance its expiry, except for a loopback-client session. Publish the revision with a per-message TTL equal to the remaining explicit lifetime.
  3. Create the deterministic access-token verifier for the committed generation.
  4. Return the deterministic credential pair.

The KV revision is the cross-replica serialization boundary. A conflicting replica reloads the stable record and evaluates the newly committed state; no process-local lock is required for correctness.

If the response is lost after the stable update, presenting the immediately previous refresh generation with the same request ID during the new access token's useful lifetime recreates or returns the exact same deterministic credential pair. This also recovers a process failure between committing the stable rotation and creating its access record.

The stable record also stores the highest used generation. A generation is used when its refresh credential rotates successfully, or when its access token passes validation 30 seconds or more after the token was issued. Browsers write device storage to disk in batches, some seconds after a script stores a value. A client can use a new pair at once and then restart with the previous pair when the operating system ends the browser. The 30-second grace keeps that restart recoverable. Validation writes this value with the exact KV revision the first time a generation is used, and only after it reads the record through the stream leader. If the write fails, the request fails with a server error; it does not continue with an unrecorded use.

A client can lose more than one response, or lose its stored request ID. For example, a mobile browser can freeze or end a page after the server commits a rotation, or lose recent device-storage writes when the operating system ends the browser. The client then presents an older refresh generation that is equal to or newer than the used generation. No client has used a newer generation, so the server treats this as a lost response. The server rotates again from the current generation, records the presented generation as used, and returns a new pair. The unused newer pairs remain valid until the first use of a different pair makes them stale.

Any other presentation of an older generation is refresh-credential reuse. The server first deletes the stable renewable-session key, invalidating the winner and every outstanding access token for that session. It then records the revocation audit fact as a best-effort action. An audit outage cannot keep the credential active. Two concurrent refresh attempts with different request IDs therefore produce two pairs of different generations. When both pairs are used, the next refresh of the older pair revokes the session. Clients must serialize refreshes; the bundled frontend coalesces same-tab work and uses a per-server Web Lock so tabs on the same browser profile adopt one persisted rotation. Server-side OCC and reuse detection remain authoritative for clients without Web Locks.

Rotating the refresh credential does not immediately revoke the previous short-lived access token. Its fixed expiry bounds that overlap. Reuse detection, explicit logout, user auth-generation changes, and OAuth-client blocking revoke the stable authority, rejecting all overlap at its next validation on a current RUNTIME_STATE replica. A user auth-generation change rejects it within one minute in the worst case, on a replica whose User Auth projection lags (ADR-127). Established realtime sockets retain the same fixed-expiry bound described above.

Client behavior

Dedicated bundled-browser password and registration routes always select cookie-only authentication. External-identity account creation selects the same mode through its public ConnectRPC request. In that mode, the server creates the HttpOnly cookie session and does not create or return a bearer or refresh credential. Calls that do not select cookie-only mode keep the bearer response for programmatic clients. During a release upgrade, the bundled frontend validates the origin cookie, revokes any stored origin refresh or access authority on the server, and only then removes those local credentials.

The bundled frontend persists the access token, refresh credential, both expiry instants, OAuth client ID when applicable, and any in-flight refresh request ID in an independently keyed device-local per-server authentication record. Combined catalogue compatibility writes merge those authoritative fields instead of copying one tab's in-memory credential snapshot.

It refreshes shortly before access expiry, including when access expiry reaches the end of the current session window. The background renewal timer does not start a refresh while the page is hidden. It renews when the page is visible again. This decreases the number of rotations that a frozen page does not receive. API requests and realtime reconnects in a hidden page still renew when they need a new access token. A successful refresh in the final quarter advances that window without user action. The client also retries one unary ConnectRPC request after an Unauthenticated response when forced renewal succeeds. This renewal hook also applies to the initial remote viewer read after a tab starts. Transient network and server failures keep the credentials and request ID for retry. An invalid_grant response is permanent: the frontend marks only that server as requiring authentication, keeps the user's current route and other connected servers intact, and exposes the existing explicit reconnect action. It never starts OAuth automatically.

The token endpoint logs a fixed rejection reason for invalid request IDs, missing credentials, reuse, client mismatch, and blocked clients. The reason contains no token, client ID, user identity, or request metadata.

Realtime sockets are authenticated for the lifetime of the presented access token. At expiry the server cancels authorized work, sends a reconnecting authentication_required close when possible, and closes the socket. The frontend rotates once, reconnects the same per-server event bus with the new access token, and supplies its in-memory opaque resume cursor. The projection and route are not recreated.

Logout presents the refresh credential when available so the server revokes the whole renewable session, rather than only one access-token verifier. Programmatic clients and integrations use the same refresh grant and must implement request-ID persistence and refresh serialization.

Compatibility and deployment

This is an intentional 0.5 authentication boundary. Bearer records created by pre-renewal servers do not identify a renewable session and are rejected; affected users sign in once to obtain a credential pair. There is no legacy bearer fallback and no capability-negotiated dual mode.

A record without a used generation, which a server without this tracking wrote, keeps the strict rule: every stale generation outside exact recovery is reuse. Validation adds the value at the next access-token use, and a rotation adds it at the next refresh. During a rolling upgrade, a replica without this tracking does not record access-token use and drops the value when it rewrites the record. In that window, a copied older refresh credential can rotate the session without revocation. Detection starts again when an upgraded replica records the use of a newer generation.

Upgrade all serving replicas and bundled clients together. An older replica would treat a new short-lived access record as a sliding bearer record and could extend it beyond its intended expiry. Rolling back to a pre-renewal binary after issuing new credentials has the same problem; revoke the affected bearer sessions or require users to sign in again before such a rollback. Version 0.6 removes the browser-cookie migration route supplied by 0.5. A browser with only a 0.4 typed cookie must sign in again. Existing SCS cookie sessions keep their login, renewal, logout, and realtime behavior.

The additive fields on chatto.auth.v1.CreateExternalIdentityAccountResponse remain wire-compatible, but clients participating in human bearer auth must consume the complete pair and expiry values. Generated clients and public reference documentation ship with the server change. The pull request is labelled api-breaking-change, and the 0.5 release notes call out the one-time sign-in and coordinated-upgrade requirement.

Consequences

  • A copied access token is useful for at most its short fixed lifetime unless the attacker also obtains the rotating refresh credential.
  • Active users renew without navigation, OAuth popups, or losing their current server route and realtime projection.
  • Inactive sessions expire after one complete renewal window. Normal background refresh keeps an active session signed in.
  • Refresh reuse turns suspicious concurrency into whole-session revocation for subsequent requests and reconnects. Lost responses are recoverable through the exact persisted request ID, or by a new rotation while no newer generation is used. A client that used the newer pair after the 30-second grace and then lost it must sign in again. An established realtime socket cannot outlive the access token that authenticated it.
  • Reuse detection is later than before. The server cannot tell a copied refresh credential from a lost response until a client uses a newer generation. Until then, a copy that an attacker presents gets its own pair instead of revoking the session. When the attacker and the legitimate client both use their pairs, the next refresh of the older pair revokes the session. An attacker that makes its uses and refreshes alternate exactly with those of the legitimate client can keep both pairs active. A client that only keeps a realtime socket open after a rotation does not mark its generation until its next request or refresh, so it makes this period longer. Each lost-response rotation writes a log entry that contains no credential or identity.
  • Correctness across replicas comes from one JetStream KV revision boundary; browser locks improve contention but are not a security primitive.
  • RUNTIME_STATE gains one stable record per renewable bearer session plus short-lived verifier records for recent access generations. Raw credentials remain absent from storage, backups, logs, and audit events.
  • The frontend stores a longer-lived refresh credential in device-local browser storage. XSS on that client origin can therefore steal the complete renewable session, not only one short-lived access token. An attacker that keeps exclusive control of the rotating refresh credential can also keep the session active. Avoiding that risk would require a different trusted-client or cookie boundary that cannot serve Chatto's cross-origin multi-server frontend.
  • Cookie sessions and bot API keys keep their distinct lifecycle models; the refresh grant is not a universal credential protocol.
  • Pre-renewal bearer sessions are deliberately not migrated, simplifying the runtime state and avoiding an indefinitely supported insecure fallback.

Alternatives considered

  • Keep sliding opaque bearer tokens: simplest operationally, but leaves no upper bound on a stolen active token.
  • Give bearer tokens an absolute expiry and reopen OAuth: limits theft but interrupts normal work, repeats per server, and gives non-browser clients no pragmatic renewal path.
  • Use self-contained JWT access and refresh tokens: still requires mutable server state for single-use rotation, reuse detection, OAuth-client policy, and immediate user revocation, while adding key-rotation and clock concerns.
  • Store random raw refresh tokens: makes exact rotation straightforward but turns RUNTIME_STATE and its backups into a store of directly redeemable credentials.
  • Accept the previous refresh token for a grace period without a request ID: hides lost responses but also makes intentional replay indistinguishable from recovery and weakens reuse detection. The used generation instead accepts a stale credential only while no client has used a newer one, without a time limit.
  • Extend only the exact-recovery window: does not help a client that lost its persisted request ID with the response.
  • Replace the protocol with a general OAuth server package: packages such as Fosite use transactional storage operations for authorization and token sessions. Chatto's public refresh contract also requires deterministic lost-response recovery, a client-persisted request ID, reuse detection, and one JetStream revision boundary. Adapting that contract would reproduce the current protocol inside the package's storage layer. Chatto therefore keeps this narrow NATS-specific protocol and uses external packages where their storage contracts map directly, such as SCS for cookie sessions.

Records that name this record

Esc