Skip to content

ADR 0014 — Committed generation authority for access and MFA tokens ​

Context ​

Optimistic concurrency protects committed generation increments, but does not make a cache hit an authoritative revocation decision. PostgreSQL regressions written before this correction reproduced four independent failures in the existing composition, with positive controls:

  • A signed access token at N passed after SQL committed N+1 because the version cache still contained N.
  • A signed token at N+1 passed while the committed generation was N because comparison used <.
  • A lookup inside the writer's transaction observed its own uncommitted N+1 while an independent PostgreSQL connection still observed N.
  • A lookup started after commit joined an earlier inflight lookup and returned its old N.

The tests used the real context, repositories, singleton coalescer and middleware. Middleware cases used actual RS256 signing and validation, the ordinary token validation service, endpoint metadata and a real tenant membership. Cache decorators controlled inputs and barriers; they did not invent the final authorization result. Four behavioral failures, with no skipped tests, were recorded before production changes. An initial test-only delegate typing error was corrected before that execution.

Decision ​

Each decision reads committed primary state ​

The normal Auth composition selects CommittedTokenVersionResolver, backed by ICommittedTokenSecurityStateReader. Its immutable lookup distinguishes Found, NotFound and Unavailable. Found carries only UserId, TokenVersion, IsActive and IsDeleted. The adapter exposes a positive Database generation only for the requested, active, non-deleted user. Missing or invalid user state never creates a default generation. Unavailable never falls back to Redis.

Every call performs an independent parameterized autocommit SELECT through a dedicated Npgsql data source. It does not use the caller's DbContext, tracker, connection, transaction, Redis, local result cache or shared inflight task. Enlist=false prevents ambient TransactionScope enlistment. A fresh call in the same request or scope rereads SQL; results and connections are not singleton objects.

The SELECT is the temporal boundary. A statement that began before a revocation committed can return N. A new statement after that commit must observe N+1. This does not retrospectively cancel an authorization decision already begun, serialize a later business write with revocation, or make authentication and permission issuance one coherent snapshot.

The reader requires a writable primary and checks recovery/read-only state in the statement itself. For multiple hosts it also selects read-write sessions. With a single host the connection-selection attribute is removed from the reader copy because Npgsql 10.0.3 requires multiple hosts for that attribute; the mandatory SQL check still refuses standby or read-only state. Normal mapping is public."Users". That statement also verifies that the unqualified "Users" resolved by the effective search_path is the same table. A second Users table in an earlier schema causes refusal instead of silently reading another generation. Missing tables, denied permissions, read-only state and mapping mismatch are availability failures, not missing users. Arbitrary host mapping or connection-interceptor overrides require an explicit reader that preserves the contract; the default cannot infer such customizations.

One effective database configuration ​

Normal registration captures and validates the first effective DefaultPostgresConnection once. Both writer and reader resolve that same immutable settings object. Repeated normal registration uses the first settings instance; it cannot point the writer at B while the reader remains on A. Changing this database configuration requires restarting/recreating the provider. No additional connection-string key or secret is introduced. Load the final Auth database configuration before normal registration. A test host replacing only DbContext after registration does not implicitly reconfigure the independent authority. The integration WebApplicationFactory supplies its owned database with UseSetting before deferred application configuration, then verifies that the real writer and default reader observe the same committed account. No fake authority or cache fallback is used to make that test pass.

The reader derives a separate pool from those settings. It preserves the database, credentials, TLS and schema options, disables ambient enlistment and multiplexing, and requires connection reset. The writer retains its existing pool, three retries and 30-second command timeout. Reader open/command budgets and per-call deadline are 5 seconds, cancellation cleanup is 1 second, minimum pool size is zero and maximum is capped at 20 per host, respecting a smaller configured maximum or disabled pooling. With multiple hosts this is not an aggregate 20-connection limit. Cancellation and disposal can add cleanup time; this is not a strict wall-clock SLA.

The DI container owns one disposable data-source owner per provider. Each call closes its own reader, command and connection. Reading the generation adds primary-database traffic to protected requests; size capacity from observed workload rather than restoring a positive cache shortcut. No network operation occurs merely to register services.

Claims are positive and equal ​

Protected access and accepted MFA tokens require exactly one token_version claim containing nonempty ASCII decimal digits that parse as a positive Int32 with invariant culture. Missing, duplicate (even identical), signed, whitespace, Unicode-digit, zero, negative and overflow values are refused. Leading zeroes are accepted when the resulting integer is positive. The token's generation must equal the committed positive generation; future generations are refused too.

Global tokens retain their existing version bypass in this stage and still run their other checks. Endpoint/type/tenant/platform guards and all JTI and user-blacklist behavior remain in force. The initial access validation and committed lookup receive RequestAborted; caller cancellation propagates instead of being normalized into an invalid-token result or success.

Operational failures fail closed ​

Provider failures and internal timeouts produce Unavailable; they do not become NotFound or version zero. Caller cancellation propagates. Configuration errors fail composition visibly with fixed messages. Reader diagnostics contain fixed outcome codes and exception type only, without exception objects/messages, connection strings, SQL, user identifiers or token payloads. Programming errors are not indiscriminately classified as provider unavailability.

Composition and compatibility ​

AddInfrastructureGrydAuthServices installs the committed reader and adapter. Standalone AddGrydAuthTokenProcessor requires the host to supply a reader; missing registration is a composition error. Repeated normal processor registration cannot restore the cache-first adapter. An explicit trusted host reader/resolver override carries its own contract and is outside the default implementation guarantee.

The public legacy TokenVersionResolver, cache circuit breaker and coalescer may remain available for manual compatibility. They are not the normal authority and are not an availability fallback. AddGrydAuthTokenValidator for remote consumers continues without an identity database, local reader or signing key. The identity service still owns the default protected middleware decision.

/auth/validate is protected by endpoint metadata; access tokens run this gate and global tokens retain only the stated version bypass. ConsumerIdentityController keeps token revalidation and its user/membership checks; its tenant permission export now uses the independent committed reader below. The controller's repository recheck does not replace the normal protected middleware.

PlatformGrantResolver and CachedGroupCoverageReader use the shared committed generation for cache keys. That prevents selecting their key from an old positive version-cache hit; it does not prove that cached permission payloads or an issuance snapshot were produced under the same generation.

Validation contract ​

The four original behavioral oracles must pass after correction. In the inflight regression, the new seam holds the actual SQL result of reader A before returning it; reader B starts after commit and performs its own query. It does not replace the result with a stub. Original failing sources, outputs and hashes remain in the coordinator's evidence before this arrangement change.

Additional proofs cover same-scope fresh reads, rollback/commit, an old RepeatableRead caller, TransactionScope isolation, read-only refusal, divergent schema mapping, missing/inactive/deleted users, invalid generations, provider unavailability with warm cache and FailOpen, independent cancellation, strict claims, JTI regression, effective database configuration and owner disposal. Read-only refusal alone is not evidence from a physical standby server. Actual executed counts, CI results and browser limitations are recorded in the ledger, not implied by this list.

Native password tenant preparation (follow-up) ​

Native password login captures the original subject, exact hash, generation, requested AppId and trusted AppId policy before verification collaborators can mutate their input. After the existing tracking save, ICommittedPasswordLoginReader uses the same immutable database settings and reader pool to create an independent RepeatableRead, READ ONLY transaction. It reads user eligibility, AppIds, tenant overview/topology, roles, effective permissions and embedded platform grants in that one view. It ignores ambient filters and reapplies the subject, tenant and eligibility constraints. The guard checks the primary, default read-write state and the public mapping of all ten tables. The permission query remains owned by EffectivePermissionResolver; this path reads without cache. Cross-tenant grant rows confer nothing. Normal Auth DI registers the new reader with the existing owner; manual native-handler construction must supply it explicitly.

Hash and generation must match the original proof exactly. A concurrent technical rehash may therefore require another login. A mismatch or ineligible account returns INVALID_CREDENTIALS; operational unavailability returns AUTH_SESSION_PREPARATION_UNAVAILABLE (503), without fallback. Caller cancellation propagates. Work has a five-second deadline; rollback cleanup has a separate one-second budget, and asynchronous disposal can add time.

Preparation fixes a single/preferred/default tenant, a tenant-less platform snapshot, or an explicit legacy selection route. Explicit callers can still construct the legacy platform route. Immutable copied values reach the prepared issuer, without hash or plaintext. The selected-tenant branch keeps the MFA gate and uses pure session claims plus the shared signing/refresh/response pipeline. It never rediscovers tenants or reads cached grants. A revocation after the snapshot can still make its generation stale; the independent access authority refuses that token on use.

On the unchanged baseline, the PostgreSQL/Redis/HTTP regression reproduced a real delayed cache fill after login's last eviction: a new-generation signed JWT and response contained the revoked grant. The corrected single, preferred and default cases exclude it. Execution and merge status are in the ledger.

This partial follow-up does not cover legacy password revocation without generation advancement, global grant materialization, federation, refresh, switch, post-MFA, other authoritative permission decisions or removal of pre-commit security effects.

Native password platform preparation (follow-up) ​

For a new native password login with no eligible tenant, the same independent primary transaction also reads the subject's non-deleted platform assignments. PlatformGrant.OfRoles maps those roles to permissions before the transaction completes. No permission cache or platform resolver participates in this branch. PlatformLoginSnapshot copies those permissions into an immutable value; an empty grant remains valid preparation and preserves the existing NO_TENANT_ACCESS refusal at issuance.

PreparedPasswordLoginRoute.Platform is appended as value 3; existing values 0, 1 and 2 remain unchanged. Its required snapshot travels with the original verified generation and account flags. The issuer uses pure claims, the existing initial MFA gate with no tenant, and the shared platform signing, refresh and result pipeline. It does not reconstruct a mutable credential DTO or rediscover grants. A revocation after preparation may still stale that original generation; protected use continues through the independent committed access authority.

Custom implementations of ISessionClaimsWriter must add ForPlatform(PlatformLoginSnapshot snapshot, SessionAnchor session, DateTimeOffset? mfaVerifiedAt = null). This is an intentional source-contract addition: it must use the supplied copied permissions without I/O, a cache lookup or a fallback to ForPlatformAsync. The asynchronous method and explicit PlatformLegacy route retain their previous behavior for manual/federated callers. They do not gain the new native preparation guarantee. Initial MFA policy/factor reads remain outside the transaction; MFA completion and the other token families are separate stages.

The baseline regression uses a real composed service inside an outer RepeatableRead transaction. That service keeps an old assignment view while the independent generation reader sees the later committed generation; its real resolver fills Redis under that generation. A new HTTP password login begins only after the revocation commits. On the unchanged baseline, its correctly signed current- generation platform JWT contains the removed permission and opens the corresponding protected GET. The correction must exclude that permission and return 403 while preserving the surviving grant, its working HTTP control and the unchanged stale Redis entry. This demonstrates that composition scenario; it does not claim that ordinary HTTP/ReadCommitted requests create the same interleaving. Execution, checks and merge status belong to the planning ledger.

First-login completion commit ownership (follow-up) ​

Completing the first login changes the credential and then issues a new session. A normal HTTP request already saved and committed before signing. A host composing the handler inside an outer Auth transaction could instead receive a signed result before that owner's commit; rolling the outer transaction back left the old credential committed. This is an in-process composition regression, not a claim that ordinary HTTP requests open that outer transaction.

IGrydAuthUnitOfWork.ExecuteInOwnedTransactionAsync<TResult> is a required Auth capability. Its built-in implementation refuses an existing EF transaction, an enlisted or ambient transaction, pending writes, or pending aggregate domain events before invoking the callback. Clean tracked entities are allowed. Preflight refusal does not clear, detach, commit, roll back or mark the caller's existing work as failed. ExecuteInTransactionAsync retains its previous nesting behavior; the Core unit-of-work contract is unchanged.

The owned callback loads and validates the subject, performs the existing password/history change, clears the first-login flags, preserves the existing invalidations, and explicitly saves. A normal validation refusal aborts that owned attempt rather than returning a successful transaction result. Its rollback and write-failed protocol completes before the handler converts it back to the prior failure response. The handler rechecks cancellation after the password service, whose legacy catch still converts some infrastructure errors into a generic failure. Exceptions that escape the service or transaction protocol propagate without issuance; this stage does not redesign that existing error classification.

After the save/event loop, the callback copies identity, final generation and scalar response data without retaining a tracked User, a password hash or a password-service result. The final generation is the actual result of that operation: normally two increments, or one for historical credentials without PasswordSetAt metadata. It is not predicted, reloaded to a later generation, or wrapped in a synthetic PasswordLoginProof. Signing starts only after the owned commit and the current post-commit flush/disposal protocol return. Audit D11 may absorb a store failure; waiting for that protocol does not prove durable audit. An escaping commit/flush/disposal failure releases no session or automatic replay, even when the credential commit already happened. Recovery then uses a normal login with the new password.

External IGrydAuthUnitOfWork implementations must implement this new member with actual exclusive ownership and post-commit return semantics. There is no default adapter to the nesting method or fallback to a Save that merely participated in another transaction. Hosts wrapping first-login completion in an outer transaction must move that operation outside their wrapper; the handler refuses it with First-login completion requires an exclusive transaction boundary.

The committed reader binds subject and exact final generation in an independent primary RR/read-only view through the existing bounded pool, without credentials or legacy cache. It checks active/deleted/lockout/completion flags, preserves legacy overview eligibility and nullable metadata, and completes cleanup before Ready. Changed/ineligible proof returns 401 SESSION_INVALIDATED; unavailable preparation returns 503 AUTH_SESSION_PREPARATION_UNAVAILABLE. Neither signs, refreshes or replays; recover with the new password. Zero overview plus a grant stays platform; all other cases stay global, including one/default tenant. MFA is not repeated. The snapshot can age after cleanup; refresh/global and external security effects remain open. Execution, checks and merge status belong to the planning ledger.

Committed tenant grant ceiling (follow-up) ​

RoleAssignmentGuard requires ICommittedCallerPermissionReader and ICurrentUserService. It captures identity before awaiting: exactly one subject across raw sub or framework-mapped ClaimTypes.NameIdentifier, one tenant claim and one positive ASCII token_version. Duplicate subjects, both aliases (even equal), conflicts or service/context mismatch are refused. Normal AddGrydAuth composition supplies the singleton reader; manual hosts must implement this required capability without a cached adapter or latest-generation fallback.

The built-in reader reuses the bounded owner and committed-read protocol, independent of caller tracking or ambient transactions. It verifies an eligible subject and exact generation, then uses the existing uncached permission calculation for the explicit calculation tenant; it adds no membership-period or topology policy. Cleanup completes before Ready. Subject/generation/origin/ calculation bindings are checked before any permission is used: mismatch returns 401, whereas null/unknown/partial evidence returns 503. An empty bound set is not unavailability. See Authorization for HTTP codes and the snapshot-to-write, PUT and cancellation limits. Other permission decisions and synchronous security effects remain outside this follow-up.

Consumer tenant permission export (follow-up) ​

ConsumerIdentityController reuses ICommittedCallerPermissionReader for its authenticated tenant, with the original generation and all four bindings checked before exporting permissions. Proof and token metadata are copied before awaiting; exactly one raw or mapped subject is accepted. The existing primary RR/read-only protocol and cleanup complete before Ready, without another pool or cached fallback. See Remote identity consumer for simple 401/503 outcomes, the explicit lockout tightening and valid empty 200 response. Existing config/token-validation statuses and user/membership checks remain; reader 503 is not a universal endpoint failure mapping. Token roles and the separate platform resolver retain their contracts. This does not make the whole DTO atomic, fence later work, or correct downstream caches and other authorities.

Limits and subsequent stages ​

GET /auth/session still assembles its context through the existing tenant and platform resolvers/caches. It is not materialized from the native issuance snapshot; equality between its returned context and JWT grants is not guaranteed by this stage. Session-context/cache consistency remains a separate follow-up, with endpoint authorization and scope guards unchanged.

The original access-authority stage did not change issuance. The native follow-ups above cover selected-tenant and tenant-less platform password issuance; refresh/grace, global generation, legacy-token migration and the current pre-commit security effects remain separate work. It adds no User column or migration. Existing blacklists and evictions must remain until those separate guarantees have been established. Redis effects can still survive SQL rollback; this stage does not close CA-22/23/24, Auth/Files outbox adoption, P1 or P16.

A worker must never decide whether a revoked session can authorize an action. Later work must bind credentials and grants to the same validated generation across login, federation, refresh and selection, then safely separate security effects from durable integration reactions. Each later implementation stage follows the preceding stage's checks and merge into develop. Release and promotion to master remain with the maintainer.

Updated at:

Released under the MIT License.