diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md
index e2ce68c532..2305ae41cb 100644
--- a/design/architecture/microservices/game-session-service/operations.md
+++ b/design/architecture/microservices/game-session-service/operations.md
@@ -10,6 +10,12 @@ Target state commits a successful exact script pin, its resulting monotonic epoc
Current script-transition observability is narrower: patch/request convergence reads, instance-scoped pause/resume, region-epoch fencing, and existing version-fence paths do not yet provide complete `scriptPinEpoch` coverage across logs, traces, and control-plane reads. See the [Game Session implementation status](./README.md#implementation-status) and [runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps).
+### Namespace controller-index migration driver
+
+The namespace-qualified controller-index migration gate remains owned by [Session Behavior](../../system-architecture-session-behavior.md#legacy-controller-index-migration-gate). The `gameSessionMigrationDriverDist` task packages the normal Game Session jar and runtime classpath with a finite launcher; the driver does not start Spring or bind a gameplay listener. PostgreSQL access uses the co-located Unix socket, with no TCP fallback. The image source uses the Game Session service's pinned base image and a fixed unprivileged entrypoint. Each bounded observation round-trip to the trusted factory carries a fresh nonce and the cohort, fence, and storage identities; the driver checks the reply and re-reads local PostgreSQL and Redis identity and TLS state before continuing.
+
+Source and packaging proof do not authorize execution or establish immutable final-image authority. Non-empty retained binding conversion remains unsupported by this finite source path. The [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) records the actual implementation and proof limits; this section is not an invocation or provisioning procedure.
+
### Base-provenance admission cutover
Before deploying the new Game Session admission validation, Automation must already send a positive `script_patch_base_version_id` with every instance-bound Automation script command handoff, including local enqueue and remote follow-up scheduling. Migrations V3 and V4 add the provenance columns but leave legacy pinned and gameplay-command rows with an unknown base (`NULL`); Game Session must not backfill that history from mutable runtime state. An affected active pin may be repaired only by an explicitly authorized repin through the normal `expectedCurrentPin=EXPECT_EPOCH(scriptPinEpoch)` path, after the target publication and readiness checks succeed. Do not perform an automatic or blind repin. During the cutover, monitor `STALE_TIMELINE`, `INVALID_ARGUMENT`, and `game_session_script_event_publish_skips_total{reason="missing_base"}`, keep script admission fail-closed when provenance is missing or inconsistent, and keep ordinary gameplay admission and ticks available.
diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md
index c24a9496ab..8faf668d98 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -36,6 +36,7 @@ Deployment must not advertise retained credential/security-write workflows as re
- `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior.
- `AA-3.3`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) adds the player-visible lifecycle consequence that only an active, admissible realm is exposed; Temporal coordination does not become admission authority. Existing lifecycle and reconnect caveats remain.
+- The finite namespace controller-index migration-driver prefix is source and packaging preparation only. The most recent independent Common Security and Game Session full checks completed without failures or errors; those checks do not prove the newly adjudicated fixes or physical PostgreSQL/Redis execution. Distribution packaging, exact source-to-jar migration resource comparison, synthetic missing/changed/duplicate resource rejection, ShellCheck, and documentation checks pass. Physical PostgreSQL/Redis execution, final image build and immutable image authority, trusted bootstrap/execution, and live playable proof remain unrun; Docker-disabled local checks do not establish PostgreSQL fixture behavior. Issuer-index and region reconciliation and final Account admission have no proof in this slice. This status does not establish an empty retained-binding inventory, prove conversion of non-empty retained data, or authorize running the driver. `AA-2.1` and `AA-2.2` remain `partial` / `drift-found`; gameplay completion under #2967/#2898 remains separate. See [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#namespace-controller-index-migration-driver), the canonical [Legacy controller-index migration gate](../../architecture/system-architecture-session-behavior.md#legacy-controller-index-migration-gate), and the unrun [V34.3 intent request-ID PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java).
These links add decision provenance only; they do not upgrade player-access or session capability status.
@@ -48,8 +49,8 @@ These links add decision provenance only; they do not upgrade player-access or s
| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. |
| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. |
| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. |
-| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [GameplayPresence.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java); [AccountPresenceSnapshot.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java); [AccountRecentPresenceState.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. V11 adds nullable Account UUID evidence to the Game Session command ledger and repository round-trip mapping while preserving retained numeric Account IDs; focused repository and migration PostgreSQL cases are present but skipped locally because Docker is disabled. Internal Account-carrier typing is prepared across session, first-party, and presence records, while current numeric Account/JWT producers and numeric-only collaborators remain unchanged. Canonical Account UUID issuance and Entity roster/`PLAY` activation are absent; historical command `account_uuid` remains null without backfill, preserving numeric command evidence. Focused tests cover fail-closed first-party retained-context lookup, unreadable presence lookup without pruning, and bounded pre-mutation rejection of unreadable/wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests cover an unreadable session alias aborting before writes/deletes. Mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. |
-| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. |
+| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. The finite namespace controller-index migration-driver source and packaging prefix have focused source/protocol, packaging, resource-integrity, and static image-contract evidence, but do not prove namespace-aware atomic takeover. The V34.3 PostgreSQL fixture is unrun; physical PostgreSQL and Redis execution, final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Namespace-aware binding and [SESSION-02 atomic transfer](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) remain incomplete; issuer-index and region reconciliation plus retained-binding inventory/conversion remain open. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. |
+| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. |
| `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. |
The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above.
diff --git a/dev-tools/tests/game-session-migration-driver-image-contract.sh b/dev-tools/tests/game-session-migration-driver-image-contract.sh
new file mode 100644
index 0000000000..ce3311e395
--- /dev/null
+++ b/dev-tools/tests/game-session-migration-driver-image-contract.sh
@@ -0,0 +1,190 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+
+python3 - "$repo_root" <<'PY'
+from pathlib import Path
+import re
+import sys
+import zipfile
+
+
+root = Path(sys.argv[1])
+dockerfile = root / "k8s/game-session-migration-driver/Dockerfile"
+launcher_rel = "bin/game-session-migration-driver"
+launcher_path = "/opt/firemud/game-session-migration-driver/" + launcher_rel
+distribution = root / "services/game-session-service/build/distributions/game-session-migration-driver"
+
+
+def require(condition: bool, message: str) -> None:
+ if not condition:
+ raise SystemExit(f"FAIL: {message}")
+
+
+def compare_resource_entries(expected_entries: list[tuple[str, bytes]], packaged_entries: list[tuple[str, bytes]], description: str) -> None:
+ def indexed(entries: list[tuple[str, bytes]], source: str) -> dict[str, bytes]:
+ result: dict[str, bytes] = {}
+ for name, content in entries:
+ if name in result:
+ raise ValueError(f"{description}: duplicate {source} entry {name}")
+ result[name] = content
+ return result
+
+ expected = indexed(expected_entries, "source")
+ packaged = indexed(packaged_entries, "packaged")
+ missing = sorted(expected.keys() - packaged.keys())
+ extra = sorted(packaged.keys() - expected.keys())
+ if missing or extra:
+ raise ValueError(f"{description}: resource set differs (missing={missing}, extra={extra})")
+ mismatched = sorted(name for name in expected if expected[name] != packaged[name])
+ if mismatched:
+ raise ValueError(f"{description}: resource bytes differ for {mismatched}")
+
+
+def expect_resource_comparison_failure(expected: list[tuple[str, bytes]], packaged: list[tuple[str, bytes]], case: str) -> None:
+ try:
+ compare_resource_entries(expected, packaged, case)
+ except ValueError:
+ return
+ raise SystemExit(f"FAIL: synthetic {case} packaging defect was accepted")
+
+
+# Keep the comparison's failure modes covered without mutating packaged artifacts.
+synthetic_resource = "db/migration/V1__baseline.sql"
+compare_resource_entries([(synthetic_resource, b"migration")], [(synthetic_resource, b"migration")], "synthetic matching resources")
+expect_resource_comparison_failure([(synthetic_resource, b"migration")], [], "missing SQL")
+expect_resource_comparison_failure([(synthetic_resource, b"migration")], [(synthetic_resource, b"changed")], "changed bytes")
+expect_resource_comparison_failure(
+ [(synthetic_resource, b"migration")],
+ [(synthetic_resource, b"migration"), (synthetic_resource, b"migration")],
+ "duplicate jar entry",
+)
+
+
+docker_text = dockerfile.read_text(encoding="utf-8")
+docker_lines = [line.strip() for line in docker_text.splitlines() if line.strip()]
+service_dockerfile = root / "services/game-session-service/Dockerfile"
+service_text = service_dockerfile.read_text(encoding="utf-8")
+service_base_match = re.search(r"^ARG BASE_IMAGE=(\S+)$", service_text, re.MULTILINE)
+require(service_base_match is not None, "game-session service Dockerfile must declare its BASE_IMAGE")
+service_base = service_base_match.group(1)
+require(re.search(r"@sha256:[0-9a-f]{64}$", service_base) is not None, "game-session service BASE_IMAGE must use a lowercase SHA-256 digest pin")
+migration_base_match = re.search(r"^ARG BASE_IMAGE=(\S+)$", docker_text, re.MULTILINE)
+require(migration_base_match is not None, "migration-driver Dockerfile must declare its BASE_IMAGE")
+require(migration_base_match.group(1) == service_base, "migration-driver Dockerfile base image must match the game-session service pin")
+require("FROM ${BASE_IMAGE}" in docker_lines, "Dockerfile must use the BASE_IMAGE argument")
+require(
+ "COPY --chown=0:0 services/game-session-service/build/distributions/game-session-migration-driver/ "
+ "/opt/firemud/game-session-migration-driver/" in docker_lines,
+ "Dockerfile must copy the packaged distribution from the repository-root build context with root ownership",
+)
+permission_step_lines = [
+ "RUN chmod -R a+rX /opt/firemud/game-session-migration-driver \\",
+ "&& chmod -R a-w /opt/firemud/game-session-migration-driver \\",
+ "&& chmod a+x /opt/firemud/game-session-migration-driver/bin/game-session-migration-driver",
+]
+require(
+ [line for line in docker_lines if line.startswith(("RUN ", "&& "))] == permission_step_lines,
+ "Dockerfile must make the root-owned distribution readable/executable and non-writable before runtime",
+)
+require("USER 999:999" in docker_lines, "image default user must be uid/gid 999")
+require(
+ [line for line in docker_lines if line.startswith("USER ")] == ["USER 0:0", "USER 999:999"],
+ "image must select root only for distribution permissions, then return to uid/gid 999",
+)
+require(
+ docker_lines.index("USER 0:0") < docker_lines.index(permission_step_lines[0])
+ < docker_lines.index("USER 999:999") < docker_lines.index(f'ENTRYPOINT ["{launcher_path}"]'),
+ "distribution permissions must run as root before the non-root runtime entrypoint",
+)
+require(
+ f'ENTRYPOINT ["{launcher_path}"]' in docker_lines,
+ "image entrypoint must be the fixed finite migration-driver launcher",
+)
+require(
+ not any(line.startswith(("EXPOSE ", "CMD ")) for line in docker_lines),
+ "image must not add a startup command, port, or second default command",
+)
+require(not re.search(r"\b(?:PGDATA|serviceAccount|kubeconfig|password|secret)\b", docker_text, re.IGNORECASE), "Dockerfile must not configure storage, cluster credentials, or secrets")
+
+if not distribution.is_dir():
+ print("PASS: Dockerfile source contract; packaged distribution unavailable, artifact checks deferred")
+ raise SystemExit(0)
+
+launcher = distribution / launcher_rel
+require(launcher.is_file(), f"packaged launcher is missing: {launcher_rel}")
+require(launcher.stat().st_mode & 0o111, "packaged launcher must be executable")
+launcher_text = launcher.read_text(encoding="utf-8")
+launcher_class = (
+ "net.firedevops.firemud.gamesession.repository.CanonicalGameplayMigrationDriverLauncher"
+)
+implementation_main_class = (
+ "net.firedevops.firemud.gamesession.repository.CanonicalGameplayMigrationDriverMain"
+)
+require(
+ launcher_class in launcher_text,
+ "packaged launcher must invoke the stdout-isolating driver launcher class",
+)
+for dependency in (
+ "flyway-core-",
+ "flyway-database-postgresql-",
+ "postgresql-",
+ "junixsocket-common-",
+ "junixsocket-native-common-",
+):
+ require(dependency in launcher_text, f"packaged launcher classpath must include {dependency.rstrip('-')}")
+
+libraries = distribution / "lib"
+require(libraries.is_dir(), "distribution lib directory is missing")
+for dependency in (
+ "flyway-core-",
+ "flyway-database-postgresql-",
+ "postgresql-",
+ "junixsocket-common-",
+ "junixsocket-native-common-",
+ "netty-transport-native-unix-common-",
+):
+ require(any(path.name.startswith(dependency) for path in libraries.glob("*.jar")), f"distribution is missing {dependency.rstrip('-')} jar")
+
+app_jars = list(libraries.glob("game-session-service-*-plain.jar"))
+require(len(app_jars) == 1, "distribution must contain one game-session plain application jar")
+game_session_migration_root = root / "services/game-session-service/src/main/resources/db/migration"
+game_session_source_entries = [
+ (path.relative_to(game_session_migration_root.parent.parent).as_posix(), path.read_bytes())
+ for path in sorted(game_session_migration_root.rglob("*.sql"))
+]
+with zipfile.ZipFile(app_jars[0]) as app_jar:
+ app_entries = app_jar.namelist()
+ require(
+ launcher_class.replace(".", "/") + ".class" in app_entries,
+ "application jar is missing the stdout-isolating driver launcher class",
+ )
+ require(
+ implementation_main_class.replace(".", "/") + ".class" in app_entries,
+ "application jar is missing the finite migration-driver implementation class",
+ )
+ game_session_packaged_entries = [
+ (entry, app_jar.read(entry))
+ for entry in app_entries
+ if entry.startswith("db/migration/") and entry.endswith(".sql")
+ ]
+compare_resource_entries(game_session_source_entries, game_session_packaged_entries, "game-session migration resources")
+
+common_saga_jars = list(libraries.glob("common-saga-*.jar"))
+require(len(common_saga_jars) == 1, "distribution must contain exactly one common-saga jar")
+common_saga_migration_root = root / "services/common-saga/src/main/resources/db/migration"
+common_saga_source_entries = [
+ (path.relative_to(common_saga_migration_root.parent.parent).as_posix(), path.read_bytes())
+ for path in sorted(common_saga_migration_root.rglob("*.sql"))
+]
+with zipfile.ZipFile(common_saga_jars[0]) as common_saga_jar:
+ common_saga_packaged_entries = [
+ (entry, common_saga_jar.read(entry))
+ for entry in common_saga_jar.namelist()
+ if entry.startswith("db/migration/") and entry.endswith(".sql")
+ ]
+compare_resource_entries(common_saga_source_entries, common_saga_packaged_entries, "common-saga migration resources")
+
+print("PASS: pinned image source contract and packaged finite-driver distribution contents")
+PY
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 771f67f467..0a6c83c467 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -19,6 +19,7 @@ junit-platform = "6.1.3"
temporal = "1.40.0"
spring-grpc = "1.0.3"
postgresql = "42.7.14"
+junixsocket = "2.11.1"
springdoc-openapi = "3.1.1"
stripe-java = "34.0.0"
spring-cloud-gateway = "5.0.3"
@@ -91,6 +92,8 @@ argon2 = { module = "de.mkammerer:argon2-jvm", version.ref = "argon2" }
grpc-spring-boot-starter = { module = "org.springframework.grpc:spring-grpc-spring-boot-starter", version.ref = "spring-grpc" }
postgresql = { module = "org.postgresql:postgresql", version.ref = "postgresql" }
+junixsocket-common = { module = "com.kohlschutter.junixsocket:junixsocket-common", version.ref = "junixsocket" }
+junixsocket-native-common = { module = "com.kohlschutter.junixsocket:junixsocket-native-common", version.ref = "junixsocket" }
aws-sdk-s3 = { module = "software.amazon.awssdk:s3", version.ref = "aws-sdk" }
h2 = { module = "com.h2database:h2", version.ref = "h2" }
diff --git a/k8s/game-session-migration-driver/Dockerfile b/k8s/game-session-migration-driver/Dockerfile
new file mode 100644
index 0000000000..d814d3ed4b
--- /dev/null
+++ b/k8s/game-session-migration-driver/Dockerfile
@@ -0,0 +1,12 @@
+ARG BASE_IMAGE=ghcr.io/benhook1013/firemud-base:latest@sha256:a7309b5c6c785ea9cf220faa672080cf386a414e458fc8a544b882a00e57f7ec
+FROM ${BASE_IMAGE}
+
+WORKDIR /opt/firemud
+COPY --chown=0:0 services/game-session-service/build/distributions/game-session-migration-driver/ /opt/firemud/game-session-migration-driver/
+USER 0:0
+RUN chmod -R a+rX /opt/firemud/game-session-migration-driver \
+ && chmod -R a-w /opt/firemud/game-session-migration-driver \
+ && chmod a+x /opt/firemud/game-session-migration-driver/bin/game-session-migration-driver
+
+USER 999:999
+ENTRYPOINT ["/opt/firemud/game-session-migration-driver/bin/game-session-migration-driver"]
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java
new file mode 100644
index 0000000000..eb42f2e370
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java
@@ -0,0 +1,434 @@
+package net.firedevops.firemud.common.account.admission;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile;
+import tools.jackson.core.JacksonException;
+import tools.jackson.core.JsonParser;
+import tools.jackson.core.JsonToken;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Immutable, shape-only public-production lease carrier. This value authenticates no issuer,
+ * establishes no current source evidence, and never grants admission or proves COMMITTED state.
+ *
+ *
Tuple counters and membership versions inherit the public delegation validator's positive
+ * signed-long range. Values above that supported source range are rejected without substitution.
+ */
+public final class AccountGameplayAdmissionLeaseEvidence {
+ public static final String SCHEMA = "account-gameplay-admission-lease-evidence/v1";
+ public static final long MAX_DURATION_MILLIS = 15_000L;
+ public static final int MAX_EVIDENCE_BYTES = 64 * 1024;
+ public static final int MAX_DEPTH = 8;
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final Set FIELDS =
+ Set.of(
+ "schema",
+ "schemaVersion",
+ "mode",
+ "targetNamespace",
+ "callerWorkload",
+ "requestId",
+ "leaseId",
+ "leaseFence",
+ "bindingScope",
+ "leaseKind",
+ "authorityTuple",
+ "issuanceFence",
+ "membershipBaseline",
+ "outboxCheckpoints",
+ "tokenIdentityEvidence",
+ "evaluatedAt",
+ "expiresAt");
+ private final Map carrier;
+ private final String canonicalJson;
+ private final String digest;
+
+ private AccountGameplayAdmissionLeaseEvidence(Map source) {
+ Map value = Map.copyOf(object(freeze(source, 1, new ByteBudget())));
+ byte[] canonicalBytes = canonicalBytes(value);
+ Set expected = new java.util.HashSet<>(FIELDS);
+ LeaseKind kind = LeaseKind.valueOf(string(value, "leaseKind"));
+ if (kind == LeaseKind.RESUME) {
+ expected.add("resumeEpisodeId");
+ expected.add("expectedOldBindingGeneration");
+ } else if (value.containsKey("expectedOldBindingGeneration")) {
+ expected.add("expectedOldBindingGeneration");
+ }
+ exact(value, expected);
+ if (!SCHEMA.equals(value.get("schema"))
+ || !"1".equals(value.get("schemaVersion"))
+ || !"PUBLIC_PRODUCTION".equals(value.get("mode"))) throw invalid();
+ uuid(string(value, "requestId"), true);
+ uuid(string(value, "leaseId"), true);
+ if (kind == LeaseKind.RESUME) uuid(string(value, "resumeEpisodeId"), true);
+ if (value.containsKey("expectedOldBindingGeneration"))
+ positive(string(value, "expectedOldBindingGeneration"));
+ positive(string(value, "leaseFence"));
+ String namespace = string(value, "targetNamespace");
+ String peerUri = string(value, "callerWorkload");
+ GrpcPeerIdentity peer =
+ GrpcPeerIdentity.parseUri(peerUri)
+ .orElseThrow(AccountGameplayAdmissionLeaseEvidence::invalid);
+ if (!peer.uri().equals(peerUri)
+ || !namespace.equals(peer.namespace())
+ || !peer.isService("game-session-service")) throw invalid();
+
+ Map scope = object(value.get("bindingScope"));
+ exact(
+ scope,
+ Set.of(
+ "accountId",
+ "tenantId",
+ "realmId",
+ "worldSlug",
+ "realmSlug",
+ "playableStateNamespaceId",
+ "playableStateScope",
+ "gameInstanceId",
+ "characterId",
+ "sessionId",
+ "bindingGeneration",
+ "catalogRevision",
+ "pointerVersion",
+ "regionId",
+ "regionEpoch"));
+ for (String field :
+ List.of(
+ "accountId",
+ "tenantId",
+ "realmId",
+ "playableStateNamespaceId",
+ "gameInstanceId",
+ "characterId",
+ "sessionId",
+ "regionId")) uuid(string(scope, field), false);
+ for (String field :
+ List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch"))
+ positive(string(scope, field));
+ for (String field : List.of("worldSlug", "realmSlug")) text(string(scope, field));
+ if (!Set.of("SHARED", "ISOLATED").contains(scope.get("playableStateScope"))) throw invalid();
+ String tenant = string(scope, "tenantId");
+ String account = string(scope, "accountId");
+
+ Map baseline = object(value.get("membershipBaseline"));
+ exact(
+ baseline,
+ Set.of("membershipLifecycleState", "membershipVersion", "membershipAuthorityGeneration"));
+ MembershipLifecycleState.valueOf(string(baseline, "membershipLifecycleState"));
+ Map versions = object(baseline.get("membershipVersion"));
+ exact(versions, Set.of(tenant));
+ nonnegative(string(versions, tenant));
+ String membershipGeneration = string(baseline, "membershipAuthorityGeneration");
+ positive(membershipGeneration);
+ Map tuple = object(value.get("authorityTuple"));
+ // Reuse the profile's supported positive signed-long range, including exact values above 2^53.
+ try {
+ GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority(
+ tenant, tuple, versions);
+ } catch (RuntimeException failure) {
+ throw new IllegalArgumentException("Malformed public-tenant authority tuple", failure);
+ }
+ if (!membershipGeneration.equals(
+ object(tuple.get("membershipAuthorityGeneration")).get(tenant))) throw invalid();
+ String fence = string(value, "issuanceFence");
+ positive(fence);
+
+ List> checkpoints = list(value.get("outboxCheckpoints"));
+ Map coordinates = new LinkedHashMap<>();
+ byte[] previous = null;
+ for (Object entry : checkpoints) {
+ Map checkpoint = object(entry);
+ exact(checkpoint, Set.of("outboxStreamKey", "outboxSequence"));
+ String key = string(checkpoint, "outboxStreamKey");
+ text(key);
+ String sequence = string(checkpoint, "outboxSequence");
+ nonnegative(sequence);
+ byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
+ if (previous != null && Arrays.compareUnsigned(previous, bytes) >= 0) throw invalid();
+ previous = bytes;
+ coordinates.put(key, sequence);
+ }
+ String prefix = "account:auth-authority:v1:";
+ String issuerStream = prefix + "issuer/" + GameSessionAccountDelegationProfile.ISSUER;
+ String accountStream = prefix + "account/" + account;
+ String tenantStream = prefix + "tenant/" + tenant;
+ String membershipStream = prefix + "membership/" + account + "/" + tenant;
+ exact(coordinates, Set.of(issuerStream, accountStream, tenantStream, membershipStream));
+ for (String stream : List.of(tenantStream, membershipStream)) positive(coordinates.get(stream));
+ if (tuple.containsKey("accountSecurityCutoff")) {
+ cutoff(object(tuple.get("accountSecurityCutoff")), accountStream, coordinates);
+ }
+ if (tuple.containsKey("tenantBillingCutoff")) {
+ cutoff(
+ object(object(tuple.get("tenantBillingCutoff")).get(tenant)), tenantStream, coordinates);
+ }
+
+ Map token = object(value.get("tokenIdentityEvidence"));
+ exact(
+ token,
+ Set.of(
+ "accountId",
+ "operationId",
+ "issuanceRequestId",
+ "tokenJti",
+ "tokenSHA256",
+ "tokenGeneration",
+ "issuanceFence",
+ "tokenIdentityFence",
+ "tokenProfile",
+ "issuedAt",
+ "notBefore",
+ "expiresAt"));
+ uuid(string(token, "accountId"), false);
+ for (String field : List.of("operationId", "issuanceRequestId", "tokenJti"))
+ uuid(string(token, field), true);
+ if (!account.equals(token.get("accountId"))
+ || !fence.equals(token.get("issuanceFence"))
+ || !string(token, "tokenSHA256").matches("[0-9a-f]{64}")
+ || !GameSessionAccountDelegationProfile.PROFILE.equals(token.get("tokenProfile")))
+ throw invalid();
+ for (String field : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence"))
+ positive(string(token, field));
+ BigInteger issued = timestamp(token, "issuedAt").multiply(BigInteger.valueOf(1000L));
+ BigInteger notBefore = timestamp(token, "notBefore").multiply(BigInteger.valueOf(1000L));
+ BigInteger tokenExpiry = timestamp(token, "expiresAt").multiply(BigInteger.valueOf(1000L));
+ BigInteger evaluated = timestamp(value, "evaluatedAt");
+ BigInteger expiry = timestamp(value, "expiresAt");
+ BigInteger duration = expiry.subtract(evaluated);
+ if (issued.compareTo(evaluated) > 0
+ || notBefore.compareTo(issued) > 0
+ || expiry.compareTo(tokenExpiry) > 0
+ || duration.signum() <= 0
+ || duration.compareTo(BigInteger.valueOf(MAX_DURATION_MILLIS)) > 0) throw invalid();
+ carrier = value;
+ try {
+ canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8);
+ digest =
+ HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalBytes));
+ } catch (NoSuchAlgorithmException failure) {
+ throw new IllegalArgumentException("Cannot canonicalize lease evidence", failure);
+ }
+ }
+
+ public enum LeaseKind {
+ NEW_BINDING,
+ RESUME
+ }
+
+ public enum MembershipLifecycleState {
+ ACTIVE,
+ INACTIVE
+ }
+
+ /** Validates and defensively freezes original carriers without establishing their provenance. */
+ public static AccountGameplayAdmissionLeaseEvidence fromCarrier(Map carrier) {
+ if (carrier == null) throw invalid();
+ return new AccountGameplayAdmissionLeaseEvidence(carrier);
+ }
+
+ /** Accepts only the exact canonical serialization; duplicate and unknown fields fail closed. */
+ public static AccountGameplayAdmissionLeaseEvidence parseCanonical(String json) {
+ requireByteBound(json);
+ try {
+ // Inspect depth before allocating a nested object tree; duplicate detection applies here too.
+ try (JsonParser parser = JSON.createParser(json)) {
+ int depth = 0;
+ JsonToken token;
+ while ((token = parser.nextToken()) != null) {
+ if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY)
+ && ++depth > MAX_DEPTH) throw invalid();
+ if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) depth--;
+ }
+ }
+ AccountGameplayAdmissionLeaseEvidence result =
+ fromCarrier(object(JSON.readValue(json, Object.class)));
+ if (!result.canonicalJson.equals(json)) throw invalid();
+ return result;
+ } catch (JacksonException failure) {
+ throw new IllegalArgumentException("Malformed lease evidence", failure);
+ }
+ }
+
+ public Map carrier() {
+ return carrier;
+ }
+
+ public String canonicalJson() {
+ return canonicalJson;
+ }
+
+ public String sha256() {
+ return digest;
+ }
+
+ public BigInteger leaseFence() {
+ return positive(string(carrier, "leaseFence"));
+ }
+
+ public LeaseKind leaseKind() {
+ return LeaseKind.valueOf(string(carrier, "leaseKind"));
+ }
+
+ /** Exact original immutable carriers and their canonical digest define retry identity. */
+ public boolean hasSameIdentity(AccountGameplayAdmissionLeaseEvidence other) {
+ return other != null && carrier.equals(other.carrier) && digest.equals(other.digest);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof AccountGameplayAdmissionLeaseEvidence evidence
+ && hasSameIdentity(evidence);
+ }
+
+ @Override
+ public int hashCode() {
+ return carrier.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "AccountGameplayAdmissionLeaseEvidence[redacted]";
+ }
+
+ private static void cutoff(
+ Map cutoff, String stream, Map checkpoints) {
+ if (!stream.equals(cutoff.get("outboxStreamKey"))
+ || nonnegative(checkpoints.get(stream))
+ .compareTo(positive(string(cutoff, "outboxSequence")))
+ < 0) throw invalid();
+ }
+
+ private static BigInteger timestamp(Map object, String field) {
+ BigInteger value = positive(string(object, field));
+ if (value.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) throw invalid();
+ return value;
+ }
+
+ private static BigInteger positive(String value) {
+ BigInteger integer = nonnegative(value);
+ if (integer.signum() <= 0) throw invalid();
+ return integer;
+ }
+
+ private static BigInteger nonnegative(String value) {
+ if (value == null || !value.matches("0|[1-9][0-9]*")) throw invalid();
+ return new BigInteger(value);
+ }
+
+ private static void uuid(String value, boolean highEntropy) {
+ UUID parsed;
+ try {
+ parsed = UUID.fromString(value);
+ } catch (RuntimeException failure) {
+ throw invalid();
+ }
+ if (!parsed.toString().equals(value)
+ || parsed.equals(new UUID(0, 0))
+ || (highEntropy && (parsed.version() != 4 || parsed.variant() != 2))) throw invalid();
+ }
+
+ private static void text(String value) {
+ if (value.isBlank()
+ || value.length() > 2048
+ || value.codePoints().anyMatch(Character::isISOControl)) throw invalid();
+ }
+
+ private static String string(Map object, String field) {
+ if (!(object.get(field) instanceof String value)) throw invalid();
+ return value;
+ }
+
+ private static void exact(Map object, Set fields) {
+ if (!object.keySet().equals(fields)) throw invalid();
+ }
+
+ private static Map object(Object value) {
+ if (!(value instanceof Map, ?> map)) throw invalid();
+ Map result = new LinkedHashMap<>();
+ map.forEach(
+ (key, child) -> {
+ if (!(key instanceof String text)) throw invalid();
+ result.put(text, child);
+ });
+ return result;
+ }
+
+ private static List> list(Object value) {
+ if (!(value instanceof List> entries)) throw invalid();
+ return entries;
+ }
+
+ private static Object freeze(Object value, int depth, ByteBudget budget) {
+ if (depth > MAX_DEPTH) throw invalid();
+ budget.consume(1);
+ if (value instanceof Map, ?> map) {
+ Map result = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : map.entrySet()) {
+ if (!(entry.getKey() instanceof String key)) throw invalid();
+ budget.consume(requireByteBound(key) + 4);
+ result.put(key, freeze(entry.getValue(), depth + 1, budget));
+ }
+ return java.util.Collections.unmodifiableMap(result);
+ }
+ if (value instanceof List> values) {
+ List frozen = new ArrayList<>();
+ for (Object child : values) frozen.add(freeze(child, depth + 1, budget));
+ return List.copyOf(frozen);
+ }
+ if (!(value instanceof String text)) throw invalid();
+ budget.consume(requireByteBound(text) + 2);
+ return value;
+ }
+
+ private static int requireByteBound(String value) {
+ if (value == null || value.length() > MAX_EVIDENCE_BYTES) throw invalid();
+ int size = value.getBytes(StandardCharsets.UTF_8).length;
+ if (size > MAX_EVIDENCE_BYTES) throw invalid();
+ return size;
+ }
+
+ private static byte[] canonicalBytes(Map value) {
+ try {
+ String serialized = JSON.writeValueAsString(value);
+ requireByteBound(serialized);
+ byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialized);
+ if (bytes.length > MAX_EVIDENCE_BYTES) throw invalid();
+ return bytes;
+ } catch (IOException | JacksonException failure) {
+ throw new IllegalArgumentException("Cannot canonicalize lease evidence", failure);
+ }
+ }
+
+ private static final class ByteBudget {
+ private int remaining = MAX_EVIDENCE_BYTES;
+
+ private void consume(int count) {
+ remaining -= count;
+ if (remaining < 0) throw invalid();
+ }
+ }
+
+ private static IllegalArgumentException invalid() {
+ return new IllegalArgumentException("Malformed public-production admission lease evidence");
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java
new file mode 100644
index 0000000000..5887ecae23
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java
@@ -0,0 +1,390 @@
+package net.firedevops.firemud.common.security;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jws;
+import io.jsonwebtoken.Jwts;
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Strict RS256 compact-JWT verification for an explicitly selected route/profile policy.
+ *
+ * The result is immutable validated claims only. It is not an authenticated principal, admission
+ * decision, SecurityContext, active-registry proof, or current Account authority proof.
+ */
+public final class AccountAsymmetricJwtVerifier {
+ private static final int MAX_HEADER_BYTES = 2 * 1024;
+ private static final int MAX_CLAIMS_BYTES = 12 * 1024;
+ private static final int MAX_COMPACT_TOKEN_BYTES = 16 * 1024;
+ private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+
+ private final AccountPublicJwksCache keyCache;
+ private final Clock clock;
+
+ public AccountAsymmetricJwtVerifier(AccountPublicJwksCache keyCache, Clock clock) {
+ this.keyCache = Objects.requireNonNull(keyCache, "Account public JWKS cache is required");
+ this.clock = Objects.requireNonNull(clock, "clock is required");
+ }
+
+ /** Verifies a compact RS256 signature and exact route policy without granting authority. */
+ public VerifiedClaims verify(String compactJwt, ExplicitRouteProfilePolicy policy) {
+ Objects.requireNonNull(policy, "explicit route/profile policy is required");
+ try {
+ CompactParts parts = splitCompact(compactJwt, policy.maxCompactTokenBytes());
+ Map header = parseObject(parts.header(), MAX_HEADER_BYTES);
+ String keyId = validateHeader(header);
+ Map claims = parseObject(parts.claims(), MAX_CLAIMS_BYTES);
+ validateClaims(claims, policy, clock.instant());
+
+ RSAPublicKey key = keyCache.keyFor(keyId);
+ Jws verified =
+ Jwts.parser()
+ .verifyWith(key)
+ .clock(() -> Date.from(clock.instant()))
+ .clockSkewSeconds(policy.allowedClockSkewSeconds())
+ .build()
+ .parseSignedClaims(compactJwt);
+ if (!"RS256".equals(verified.getHeader().getAlgorithm())
+ || !keyId.equals(verified.getHeader().getKeyId())) {
+ throw new VerificationException();
+ }
+ Map immutableClaims = deepImmutableMap(claims);
+ policy.claimShapeValidator().validate(immutableClaims);
+ return new VerifiedClaims(
+ policy.routeId(), policy.profile(), policy.tokenType(), keyId, immutableClaims);
+ } catch (AccountPublicJwksCache.SourceUnavailableException unavailable) {
+ throw new VerificationUnavailableException();
+ } catch (VerificationException ex) {
+ throw ex;
+ } catch (RuntimeException ex) {
+ // Do not retain token, source, JWK, or parser details in externally visible failures.
+ throw new VerificationException();
+ }
+ }
+
+ private static CompactParts splitCompact(String compactJwt, int maximumBytes) {
+ if (compactJwt == null
+ || compactJwt.isEmpty()
+ || compactJwt.length() > maximumBytes
+ || compactJwt.length() > MAX_COMPACT_TOKEN_BYTES) {
+ throw new VerificationException();
+ }
+ for (int index = 0; index < compactJwt.length(); index++) {
+ if (compactJwt.charAt(index) > 0x7f) {
+ throw new VerificationException();
+ }
+ }
+ String[] parts = compactJwt.split("\\.", -1);
+ if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) {
+ throw new VerificationException();
+ }
+ return new CompactParts(
+ decodeSegment(parts[0]), decodeSegment(parts[1]), decodeSegment(parts[2]));
+ }
+
+ private static byte[] decodeSegment(String segment) {
+ if (!segment.matches("[A-Za-z0-9_-]+")) {
+ throw new VerificationException();
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(segment);
+ if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(segment)) {
+ throw new VerificationException();
+ }
+ return decoded;
+ } catch (IllegalArgumentException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static String validateHeader(Map header) {
+ if (!Set.of("alg", "kid", "typ").containsAll(header.keySet())
+ || !header.keySet().containsAll(Set.of("alg", "kid"))
+ || !"RS256".equals(header.get("alg"))
+ || !(header.get("kid") instanceof String kid)
+ || !KID.matcher(kid).matches()
+ || (header.containsKey("typ") && !"JWT".equals(header.get("typ")))) {
+ throw new VerificationException();
+ }
+ return kid;
+ }
+
+ private static Map parseObject(byte[] bytes, int maximumBytes) {
+ if (bytes.length == 0 || bytes.length > maximumBytes) {
+ throw new VerificationException();
+ }
+ try {
+ String json =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ Map parsed = JSON.readValue(json, OBJECT);
+ if (parsed == null) {
+ throw new VerificationException();
+ }
+ return parsed;
+ } catch (VerificationException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static void validateClaims(
+ Map claims, ExplicitRouteProfilePolicy policy, Instant now) {
+ if (!policy.allowedClaims().containsAll(claims.keySet())
+ || !claims.keySet().containsAll(policy.requiredClaims())
+ || !policy.issuer().equals(claims.get("iss"))
+ || !policy.audience().equals(claims.get("aud"))) {
+ throw new VerificationException();
+ }
+ long issuedAt = positiveIntegerClaim(claims, "iat");
+ long notBefore = positiveIntegerClaim(claims, "nbf");
+ long expiresAt = positiveIntegerClaim(claims, "exp");
+ long nowSeconds = now.getEpochSecond();
+ long skew = policy.allowedClockSkewSeconds();
+ if (issuedAt > safeAdd(nowSeconds, skew)
+ || notBefore > safeAdd(nowSeconds, skew)
+ || expiresAt <= safeSubtract(nowSeconds, skew)
+ || notBefore > expiresAt
+ || issuedAt >= expiresAt
+ || safeSubtract(notBefore, issuedAt) > skew
+ || safeSubtract(expiresAt, issuedAt) > policy.maximumLifetimeSeconds()) {
+ throw new VerificationException();
+ }
+
+ requireNonEmptyText(claims, "sub");
+ requireNonEmptyText(claims, "jti");
+ if (claims.containsKey("accountId")) {
+ requireNonEmptyText(claims, "accountId");
+ }
+ if (claims.containsKey("tokenGeneration")) {
+ positiveCounterClaim(claims, "tokenGeneration", policy);
+ }
+ if (claims.containsKey("issuanceFence")) {
+ positiveCounterClaim(claims, "issuanceFence", policy);
+ }
+ if (claims.containsKey("authorityTuple")
+ && !(claims.get("authorityTuple") instanceof Map, ?>)) {
+ throw new VerificationException();
+ }
+ if (claims.containsKey("membershipVersion")
+ && !(claims.get("membershipVersion") instanceof Map, ?>)) {
+ throw new VerificationException();
+ }
+ }
+
+ private static long positiveIntegerClaim(Map claims, String field) {
+ Object value = claims.get(field);
+ if (!(value instanceof Number number)) {
+ throw new VerificationException();
+ }
+ try {
+ long result = new BigDecimal(number.toString()).longValueExact();
+ if (result <= 0L) {
+ throw new VerificationException();
+ }
+ return result;
+ } catch (ArithmeticException | NumberFormatException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static void positiveCounterClaim(
+ Map claims, String field, ExplicitRouteProfilePolicy policy) {
+ if (!GameSessionAccountDelegationProfile.PROFILE.equals(policy.profile())) {
+ positiveIntegerClaim(claims, field);
+ return;
+ }
+ try {
+ AccountJwtExactValues.positiveDecimalCounter(claims.get(field));
+ } catch (IllegalArgumentException failure) {
+ throw new VerificationException();
+ }
+ }
+
+ private static void requireNonEmptyText(Map claims, String field) {
+ if (!(claims.get(field) instanceof String value) || value.isBlank() || value.length() > 512) {
+ throw new VerificationException();
+ }
+ }
+
+ private static long safeAdd(long left, long right) {
+ try {
+ return Math.addExact(left, right);
+ } catch (ArithmeticException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static long safeSubtract(long left, long right) {
+ try {
+ return Math.subtractExact(left, right);
+ } catch (ArithmeticException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static Map deepImmutableMap(Map source) {
+ Map result = new LinkedHashMap<>();
+ source.forEach((key, value) -> result.put(key, immutableValue(value)));
+ return Collections.unmodifiableMap(result);
+ }
+
+ private static Object immutableValue(Object value) {
+ if (value instanceof Map, ?> map) {
+ Map copy = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : map.entrySet()) {
+ if (!(entry.getKey() instanceof String key)) {
+ throw new VerificationException();
+ }
+ copy.put(key, immutableValue(entry.getValue()));
+ }
+ return Collections.unmodifiableMap(copy);
+ }
+ if (value instanceof List> list) {
+ List copy = new ArrayList<>(list.size());
+ for (Object item : list) {
+ copy.add(immutableValue(item));
+ }
+ return Collections.unmodifiableList(copy);
+ }
+ if (value == null
+ || value instanceof String
+ || value instanceof Number
+ || value instanceof Boolean) {
+ return value;
+ }
+ throw new VerificationException();
+ }
+
+ /** Explicit, caller-owned policy for one route and one token profile/type pair. */
+ public record ExplicitRouteProfilePolicy(
+ String routeId,
+ String profile,
+ String tokenType,
+ String issuer,
+ String audience,
+ Set requiredClaims,
+ Set optionalClaims,
+ long maximumLifetimeSeconds,
+ long allowedClockSkewSeconds,
+ int maxCompactTokenBytes,
+ ClaimShapeValidator claimShapeValidator) {
+ public ExplicitRouteProfilePolicy {
+ if (routeId == null
+ || routeId.isBlank()
+ || profile == null
+ || profile.isBlank()
+ || tokenType == null
+ || tokenType.isBlank()
+ || issuer == null
+ || issuer.isBlank()
+ || audience == null
+ || audience.isBlank()
+ || requiredClaims == null
+ || optionalClaims == null
+ || claimShapeValidator == null
+ || maximumLifetimeSeconds <= 0L
+ || maximumLifetimeSeconds > 300L
+ || allowedClockSkewSeconds < 0L
+ || allowedClockSkewSeconds > 60L
+ || maxCompactTokenBytes <= 0
+ || maxCompactTokenBytes > MAX_COMPACT_TOKEN_BYTES) {
+ throw new IllegalArgumentException("Account JWT route profile policy is invalid");
+ }
+ Set required = Set.copyOf(requiredClaims);
+ Set optional = Set.copyOf(optionalClaims);
+ if (required.isEmpty()
+ || !required.containsAll(Set.of("iss", "aud", "sub", "jti", "iat", "nbf", "exp"))
+ || !Collections.disjoint(required, optional)
+ || required.stream().anyMatch(value -> value == null || value.isBlank())
+ || optional.stream().anyMatch(value -> value == null || value.isBlank())) {
+ throw new IllegalArgumentException("Account JWT route profile policy is invalid");
+ }
+ requiredClaims = Collections.unmodifiableSet(new LinkedHashSet<>(required));
+ optionalClaims = Collections.unmodifiableSet(new LinkedHashSet<>(optional));
+ }
+
+ public Set allowedClaims() {
+ Set result = new LinkedHashSet<>(requiredClaims);
+ result.addAll(optionalClaims);
+ return Collections.unmodifiableSet(result);
+ }
+ }
+
+ /** Exact profile-shape validation performed only after the compact signature is verified. */
+ @FunctionalInterface
+ public interface ClaimShapeValidator {
+ void validate(Map immutableClaims);
+ }
+
+ /** Immutable claims and route metadata; intentionally carries no principal or authority. */
+ public record VerifiedClaims(
+ String routeId, String profile, String tokenType, String keyId, Map claims) {
+ public VerifiedClaims {
+ Objects.requireNonNull(routeId, "route ID is required");
+ Objects.requireNonNull(profile, "profile metadata is required");
+ Objects.requireNonNull(tokenType, "token type metadata is required");
+ Objects.requireNonNull(keyId, "verified key ID is required");
+ claims = deepImmutableMap(Objects.requireNonNull(claims, "verified claims are required"));
+ }
+
+ /** The constructor defensively deep-copies this value into immutable maps and lists. */
+ @Override
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP",
+ justification =
+ "VerifiedClaims canonicalizes the input with a recursive defensive copy; every nested map and list is unmodifiable.")
+ public Map claims() {
+ return claims;
+ }
+ }
+
+ public static final class VerificationException extends RuntimeException {
+ public VerificationException() {
+ super("Account JWT verification failed");
+ }
+ }
+
+ /**
+ * Source availability failure without retaining token, JWK, source, or underlying cause detail.
+ */
+ public static final class VerificationUnavailableException extends RuntimeException {
+ public VerificationUnavailableException() {
+ super("Account JWT verification is temporarily unavailable");
+ }
+ }
+
+ private record CompactParts(byte[] header, byte[] claims, byte[] signature) {}
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java
new file mode 100644
index 0000000000..473e97061d
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java
@@ -0,0 +1,24 @@
+package net.firedevops.firemud.common.security;
+
+import java.math.BigInteger;
+
+/** Exact decimal counter parsing at Account JWT inspection boundaries. */
+public final class AccountJwtExactValues {
+ private AccountJwtExactValues() {}
+
+ /** Parses canonical positive decimal-string authority counters without a BIGINT ceiling. */
+ public static BigInteger positiveDecimalCounter(Object value) {
+ if (!(value instanceof String text) || !text.matches("[1-9][0-9]*")) throw invalid();
+ return new BigInteger(text);
+ }
+
+ /** Parses a canonical unsigned decimal string where the owning field permits zero. */
+ public static BigInteger nonNegativeDecimalCounter(Object value) {
+ if (!(value instanceof String text) || !text.matches("0|[1-9][0-9]*")) throw invalid();
+ return new BigInteger(text);
+ }
+
+ private static IllegalArgumentException invalid() {
+ return new IllegalArgumentException("Account JWT counter is not a canonical decimal string");
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java
new file mode 100644
index 0000000000..43399fa59d
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java
@@ -0,0 +1,356 @@
+package net.firedevops.firemud.common.security;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Shared exact-shape helpers for the Account JWT profile validators. */
+final class AccountJwtProfileClaimSupport {
+ static final Set REQUIRED_BASE_CLAIMS =
+ Set.of(
+ "iss",
+ "sub",
+ "jti",
+ "accountId",
+ "aud",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence");
+ static final Set AUTHORITY_TUPLE_FIELDS =
+ Set.of(
+ "issuerAuthGeneration",
+ "accountAuthorityGeneration",
+ "tenantAuthorityGeneration",
+ "membershipAuthorityGeneration",
+ "privateRealmGrantVersions");
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+
+ private AccountJwtProfileClaimSupport() {}
+
+ static void requireClaimFields(
+ Map claims, Set required, Set optional) {
+ if (claims == null
+ || !claims.keySet().containsAll(required)
+ || !union(required, optional).containsAll(claims.keySet())) {
+ throw invalid();
+ }
+ }
+
+ static void requireCommonIdentity(Map claims, String issuer, String audience) {
+ requireCommonIdentity(claims, issuer, audience, false);
+ }
+
+ static void requireDelegationCommonIdentity(
+ Map claims, String issuer, String audience) {
+ requireCommonIdentity(claims, issuer, audience, true);
+ }
+
+ private static void requireCommonIdentity(
+ Map claims, String issuer, String audience, boolean decimalCounters) {
+ if (!issuer.equals(claims.get("iss")) || !audience.equals(claims.get("aud"))) {
+ throw invalid();
+ }
+ String subject = requireUuid(claims.get("sub"));
+ String accountId = requireUuid(claims.get("accountId"));
+ requireUuid(claims.get("jti"));
+ if (!subject.equals(accountId)) {
+ throw invalid();
+ }
+ requirePositiveLong(claims.get("iat"));
+ requirePositiveLong(claims.get("nbf"));
+ requirePositiveLong(claims.get("exp"));
+ if (decimalCounters) {
+ requirePositiveDecimalLong(claims.get("tokenGeneration"));
+ requirePositiveDecimalLong(claims.get("issuanceFence"));
+ } else {
+ requirePositiveLong(claims.get("tokenGeneration"));
+ requirePositiveLong(claims.get("issuanceFence"));
+ }
+ }
+
+ static String requireUuid(Object value) {
+ if (!(value instanceof String text)) {
+ throw invalid();
+ }
+ try {
+ UUID uuid = UUID.fromString(text);
+ if (!uuid.toString().equals(text) || new UUID(0L, 0L).equals(uuid)) {
+ throw invalid();
+ }
+ return text;
+ } catch (IllegalArgumentException failure) {
+ throw invalid();
+ }
+ }
+
+ static long requirePositiveLong(Object value) {
+ if (!(value instanceof Number number)) {
+ throw invalid();
+ }
+ try {
+ long result = new BigDecimal(number.toString()).longValueExact();
+ if (result <= 0L) {
+ throw invalid();
+ }
+ return result;
+ } catch (ArithmeticException | NumberFormatException failure) {
+ throw invalid();
+ }
+ }
+
+ static Map requireObjectMap(Object value) {
+ if (!(value instanceof Map, ?> source)) {
+ throw invalid();
+ }
+ Map result = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : source.entrySet()) {
+ if (!(entry.getKey() instanceof String key)) {
+ throw invalid();
+ }
+ result.put(key, entry.getValue());
+ }
+ return result;
+ }
+
+ static Map requireGenerationMap(Object value) {
+ return requireGenerationMap(value, false);
+ }
+
+ private static Map requireGenerationMap(Object value, boolean decimalCounters) {
+ Map source = requireObjectMap(value);
+ Map result = new LinkedHashMap<>();
+ source.forEach(
+ (key, generation) -> {
+ requireUuid(key);
+ result.put(
+ key,
+ decimalCounters
+ ? requirePositiveDecimalLong(generation)
+ : requirePositiveLong(generation));
+ });
+ return result;
+ }
+
+ static void requireRoleList(Object value) {
+ if (!(value instanceof List> roles)) {
+ throw invalid();
+ }
+ Set distinct = new java.util.HashSet<>();
+ for (Object role : roles) {
+ if (!(role instanceof String text)
+ || text.isBlank()
+ || text.length() > 64
+ || text.codePoints().anyMatch(Character::isISOControl)
+ || !distinct.add(text)) {
+ throw invalid();
+ }
+ }
+ }
+
+ static Map requireAuthorityTuple(
+ Object value,
+ boolean allowTenantBillingCutoff,
+ boolean requireUnscoped,
+ boolean requireAccountCutoffForAdvancedGeneration) {
+ return requireAuthorityTuple(
+ value,
+ allowTenantBillingCutoff,
+ requireUnscoped,
+ requireAccountCutoffForAdvancedGeneration,
+ false);
+ }
+
+ static Map requireDelegationAuthorityTuple(
+ Object value,
+ boolean allowTenantBillingCutoff,
+ boolean requireUnscoped,
+ boolean requireAccountCutoffForAdvancedGeneration) {
+ return requireAuthorityTuple(
+ value,
+ allowTenantBillingCutoff,
+ requireUnscoped,
+ requireAccountCutoffForAdvancedGeneration,
+ true);
+ }
+
+ private static Map requireAuthorityTuple(
+ Object value,
+ boolean allowTenantBillingCutoff,
+ boolean requireUnscoped,
+ boolean requireAccountCutoffForAdvancedGeneration,
+ boolean decimalCounters) {
+ Map tuple = requireObjectMap(value);
+ Set allowed = new java.util.HashSet<>(AUTHORITY_TUPLE_FIELDS);
+ allowed.add("accountSecurityCutoff");
+ if (allowTenantBillingCutoff) {
+ allowed.add("tenantBillingCutoff");
+ }
+ if (!allowed.containsAll(tuple.keySet())
+ || !tuple.keySet().containsAll(AUTHORITY_TUPLE_FIELDS)) {
+ throw invalid();
+ }
+ requirePositiveCounter(tuple.get("issuerAuthGeneration"), decimalCounters);
+ requirePositiveCounter(tuple.get("accountAuthorityGeneration"), decimalCounters);
+ Map tenantGenerations =
+ requireGenerationMap(tuple.get("tenantAuthorityGeneration"), decimalCounters);
+ Map membershipGenerations =
+ requireGenerationMap(tuple.get("membershipAuthorityGeneration"), decimalCounters);
+ if (requireUnscoped && (!tenantGenerations.isEmpty() || !membershipGenerations.isEmpty())) {
+ throw invalid();
+ }
+ if (!(tuple.get("privateRealmGrantVersions") instanceof List> grants)) {
+ throw invalid();
+ }
+ if (requireUnscoped && !grants.isEmpty()) {
+ throw invalid();
+ }
+ requireAuthorityTupleByteBound(tuple);
+ long accountGeneration =
+ requirePositiveCounter(tuple.get("accountAuthorityGeneration"), decimalCounters);
+ Object accountCutoff = tuple.get("accountSecurityCutoff");
+ if (tuple.containsKey("accountSecurityCutoff")) {
+ if (accountCutoff == null) {
+ throw invalid();
+ }
+ validateAccountSecurityCutoff(accountCutoff, accountGeneration);
+ } else if (requireAccountCutoffForAdvancedGeneration && accountGeneration != 1L) {
+ throw invalid();
+ }
+ Object billingCutoff = tuple.get("tenantBillingCutoff");
+ if (tuple.containsKey("tenantBillingCutoff")) {
+ if (!allowTenantBillingCutoff || billingCutoff == null) {
+ throw invalid();
+ }
+ validateTenantBillingCutoff(billingCutoff, decimalCounters);
+ }
+ return tuple;
+ }
+
+ static Map requireVersionMap(Object value) {
+ return requireGenerationMap(value);
+ }
+
+ static Map requireDelegationVersionMap(Object value) {
+ return requireGenerationMap(value, true);
+ }
+
+ private static long requirePositiveCounter(Object value, boolean decimalCounters) {
+ return decimalCounters ? requirePositiveDecimalLong(value) : requirePositiveLong(value);
+ }
+
+ private static long requirePositiveDecimalLong(Object value) {
+ try {
+ return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact();
+ } catch (IllegalArgumentException | ArithmeticException failure) {
+ throw invalid();
+ }
+ }
+
+ static void validateAccountSecurityCutoff(Object value, long accountGeneration) {
+ Map cutoff = requireObjectMap(value);
+ if (!cutoff
+ .keySet()
+ .equals(Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"))) {
+ throw invalid();
+ }
+ if (!(cutoff.get("accountAuthorityGeneration") instanceof String generation)
+ || !(cutoff.get("outboxStreamKey") instanceof String streamKey)
+ || !(cutoff.get("outboxSequence") instanceof String sequence)) {
+ throw invalid();
+ }
+ try {
+ GameSessionAccountDelegationProfile.AccountSecurityCutoff validatedCutoff =
+ new GameSessionAccountDelegationProfile.AccountSecurityCutoff(
+ generation, streamKey, sequence);
+ if (accountGeneration <= 1L
+ || !Long.toString(accountGeneration)
+ .equals(validatedCutoff.accountAuthorityGeneration())) {
+ throw invalid();
+ }
+ } catch (IllegalArgumentException failure) {
+ throw invalid();
+ }
+ }
+
+ private static void validateTenantBillingCutoff(Object value, boolean decimalCounters) {
+ Map cutoffs = requireObjectMap(value);
+ if (cutoffs.isEmpty()) {
+ throw invalid();
+ }
+ cutoffs.forEach(
+ (tenantId, cutoffValue) -> {
+ requireUuid(tenantId);
+ Map cutoff = requireObjectMap(cutoffValue);
+ if (!cutoff
+ .keySet()
+ .equals(
+ Set.of(
+ "tenantAuthorityGeneration",
+ "tenantBillingSequence",
+ "outboxStreamKey",
+ "outboxSequence"))) {
+ throw invalid();
+ }
+ requirePositiveCounter(cutoff.get("tenantAuthorityGeneration"), decimalCounters);
+ requirePositiveCounter(cutoff.get("tenantBillingSequence"), decimalCounters);
+ requirePositiveCounter(cutoff.get("outboxSequence"), decimalCounters);
+ requireBoundedText(cutoff.get("outboxStreamKey"), 2048);
+ });
+ }
+
+ static void requireBoundedText(Object value, int maximumLength) {
+ if (!(value instanceof String text)
+ || text.isBlank()
+ || text.length() > maximumLength
+ || text.codePoints().anyMatch(Character::isISOControl)) {
+ throw invalid();
+ }
+ }
+
+ static void requireExactAccountAuthorityStream(Object value, String accountId) {
+ String expected = "account:auth-authority:v1:account/" + requireUuid(accountId);
+ if (!expected.equals(value)) {
+ throw invalid();
+ }
+ }
+
+ static void requireExactTenantAuthorityStream(Object value, String tenantId) {
+ String expected = "account:auth-authority:v1:tenant/" + requireUuid(tenantId);
+ if (!expected.equals(value)) {
+ throw invalid();
+ }
+ }
+
+ static AccountAsymmetricJwtVerifier.VerificationException invalid() {
+ return new AccountAsymmetricJwtVerifier.VerificationException();
+ }
+
+ private static Set union(Set required, Set optional) {
+ Set result = new java.util.HashSet<>(Objects.requireNonNull(required));
+ result.addAll(Objects.requireNonNull(optional));
+ return result;
+ }
+
+ private static void requireAuthorityTupleByteBound(Map tuple) {
+ byte[] canonicalBytes;
+ try {
+ canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(tuple));
+ } catch (IOException failure) {
+ throw invalid();
+ }
+ if (canonicalBytes.length > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) {
+ throw invalid();
+ }
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java
new file mode 100644
index 0000000000..819d8f5ac9
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java
@@ -0,0 +1,500 @@
+package net.firedevops.firemud.common.security;
+
+import java.math.BigInteger;
+import java.net.URI;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.MessageDigest;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.RSAPublicKeySpec;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * A finite public-only RS256 key cache bound to one owner-supplied, authenticated JWKS source.
+ *
+ * The source and its identity pin are deliberately injected by the owning service. This class
+ * does not discover endpoints, read Kubernetes credentials, or establish signer readiness. A
+ * verified key is only cryptographic evidence; callers still have to prove active registry state
+ * and current Account authority independently.
+ */
+public final class AccountPublicJwksCache {
+ public static final int MAX_JWKS_BYTES = 256 * 1024;
+ public static final int MAX_KEYS = 64;
+ private static final int MAX_REMEMBERED_KIDS = 256;
+ private static final int MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT = 256;
+ private static final Duration MIN_UNKNOWN_KID_REFRESH_INTERVAL = Duration.ofSeconds(1);
+ private static final Duration STALE_SOURCE_RETRY_BACKOFF = Duration.ofSeconds(1);
+ private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+ private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?");
+ private static final Pattern UID =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
+ private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+
+ private final TrustedPublicJwksSource source;
+ private final SourceIdentity expectedSource;
+ private final Clock clock;
+ private final Duration maximumAge;
+ private final Object monitor = new Object();
+ private final Map rememberedFingerprints = new LinkedHashMap<>();
+ private final Set hardDeniedKids = new LinkedHashSet<>();
+
+ private Map keys = Map.of();
+ private boolean hardCutoverQuarantined;
+ private Instant loadedAt;
+ private String loadedJwksFingerprint;
+ private Instant lastUnknownKidRefreshAt;
+ private Instant lastStaleRefreshFailureAt;
+ private StaleRefreshFailure lastStaleRefreshFailure;
+ private final Set unknownKidsRefreshedForSnapshot = new LinkedHashSet<>();
+
+ public AccountPublicJwksCache(
+ TrustedPublicJwksSource source,
+ SourceIdentity expectedSource,
+ Clock clock,
+ Duration maximumAge) {
+ this.source = Objects.requireNonNull(source, "trusted public JWKS source is required");
+ this.expectedSource = Objects.requireNonNull(expectedSource, "source pin is required");
+ this.clock = Objects.requireNonNull(clock, "clock is required");
+ this.maximumAge = Objects.requireNonNull(maximumAge, "maximum cache age is required");
+ if (maximumAge.isNegative()
+ || maximumAge.isZero()
+ || maximumAge.compareTo(Duration.ofMinutes(5)) > 0) {
+ throw new IllegalArgumentException("Account public JWKS cache age is outside its bound");
+ }
+ }
+
+ /**
+ * Returns a currently usable key; unknown-kid lookups can trigger at most one refresh per second.
+ */
+ public RSAPublicKey keyFor(String kid) {
+ if (kid == null || !KID.matcher(kid).matches()) {
+ throw new UnknownKeyException();
+ }
+ synchronized (monitor) {
+ rejectHardDenied(kid);
+ Instant now = clock.instant();
+ boolean cachedKidKnown = keys.containsKey(kid);
+ if (!cachedKidKnown && loadedAt != null) {
+ if (now.isBefore(loadedAt) || !unknownKidRefreshEligible(now)) {
+ throw new UnknownKeyException();
+ }
+ }
+ if (!isFresh(now)
+ && lastStaleRefreshFailureAt != null
+ && !now.isBefore(lastStaleRefreshFailureAt)
+ && Duration.between(lastStaleRefreshFailureAt, now).compareTo(STALE_SOURCE_RETRY_BACKOFF)
+ < 0) {
+ if (unknownKidsRefreshedForSnapshot.contains(kid)) {
+ throw new UnknownKeyException();
+ }
+ throw staleRefreshFailureException();
+ }
+ if (isFresh(now)) {
+ RSAPublicKey existing = keys.get(kid);
+ if (existing != null) {
+ return existing;
+ }
+ if (!unknownKidsRefreshedForSnapshot.contains(kid)
+ && unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ recordUnknownKidRefresh(kid, now);
+ refreshFromSource();
+ rejectHardDenied(kid);
+ RSAPublicKey refreshed = keys.get(kid);
+ if (refreshed != null) {
+ return refreshed;
+ }
+ if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ }
+ throw new UnknownKeyException();
+ }
+
+ try {
+ if (!cachedKidKnown && loadedAt != null) {
+ recordUnknownKidRefresh(kid, now);
+ }
+ refreshFromSource();
+ } catch (SourceUnavailableException unavailable) {
+ recordStaleRefreshFailure(StaleRefreshFailure.SOURCE_UNAVAILABLE);
+ if (loadedAt != null
+ && !cachedKidKnown
+ && unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ throw unavailable;
+ } catch (InvalidJwksException invalid) {
+ recordStaleRefreshFailure(StaleRefreshFailure.INVALID_JWKS);
+ throw invalid;
+ }
+ rejectHardDenied(kid);
+ RSAPublicKey refreshed = keys.get(kid);
+ if (refreshed == null) {
+ if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ throw new UnknownKeyException();
+ }
+ return refreshed;
+ }
+ }
+
+ /**
+ * Permanently denies this kid for this cache instance, including during source outages. If the
+ * finite deny history is exhausted, the instance enters terminal fail-closed quarantine so no key
+ * can be re-admitted without growing or evicting deny history.
+ */
+ public void invalidateKid(String kid) {
+ if (kid == null || !KID.matcher(kid).matches()) {
+ throw new IllegalArgumentException("Account public JWKS key identifier is invalid");
+ }
+ synchronized (monitor) {
+ if (!hardDeniedKids.contains(kid) && hardDeniedKids.size() >= MAX_KEYS) {
+ hardCutoverQuarantined = true;
+ throw new IllegalStateException("Account public JWKS hard-cutover bound is exhausted");
+ }
+ hardDeniedKids.add(kid);
+ Map remaining = new LinkedHashMap<>(keys);
+ remaining.remove(kid);
+ keys = Collections.unmodifiableMap(remaining);
+ }
+ }
+
+ /** Exposes only the non-secret source pin for integration correspondence checks. */
+ public SourceIdentity sourceIdentity() {
+ return expectedSource;
+ }
+
+ private boolean isFresh(Instant now) {
+ if (loadedAt == null || now.isBefore(loadedAt)) {
+ return false;
+ }
+ return Duration.between(loadedAt, now).compareTo(maximumAge) < 0;
+ }
+
+ private boolean unknownKidRefreshEligible(Instant now) {
+ return lastUnknownKidRefreshAt == null
+ || (!now.isBefore(lastUnknownKidRefreshAt)
+ && Duration.between(lastUnknownKidRefreshAt, now)
+ .compareTo(MIN_UNKNOWN_KID_REFRESH_INTERVAL)
+ >= 0);
+ }
+
+ private void recordUnknownKidRefresh(String kid, Instant now) {
+ lastUnknownKidRefreshAt = now;
+ if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ }
+
+ private void refreshFromSource() {
+ final PublicJwksSnapshot snapshot;
+ try {
+ snapshot = source.load();
+ } catch (SourceUnavailableException unavailable) {
+ if (loadedAt == null || !isFresh(clock.instant())) {
+ throw new SourceUnavailableException();
+ }
+ return;
+ } catch (RuntimeException invalidSource) {
+ throw new InvalidJwksException();
+ }
+ if (snapshot == null || !expectedSource.equals(snapshot.sourceIdentity())) {
+ throw new InvalidJwksException();
+ }
+
+ byte[] snapshotBytes = snapshot.jwksBytes();
+ Map parsed = parseJwks(snapshotBytes);
+ Map nextFingerprints = new LinkedHashMap<>(rememberedFingerprints);
+ for (Map.Entry entry : parsed.entrySet()) {
+ String fingerprint = fingerprint(entry.getValue());
+ String prior = nextFingerprints.putIfAbsent(entry.getKey(), fingerprint);
+ if (prior != null && !prior.equals(fingerprint)) {
+ throw new InvalidJwksException();
+ }
+ if (nextFingerprints.size() > MAX_REMEMBERED_KIDS) {
+ throw new InvalidJwksException();
+ }
+ }
+ rememberedFingerprints.clear();
+ rememberedFingerprints.putAll(nextFingerprints);
+ keys = Collections.unmodifiableMap(parsed);
+ String nextJwksFingerprint = fingerprintBytes(snapshotBytes);
+ if (!Objects.equals(loadedJwksFingerprint, nextJwksFingerprint)) {
+ unknownKidsRefreshedForSnapshot.clear();
+ }
+ loadedJwksFingerprint = nextJwksFingerprint;
+ loadedAt = clock.instant();
+ lastStaleRefreshFailureAt = null;
+ lastStaleRefreshFailure = null;
+ }
+
+ private void recordStaleRefreshFailure(StaleRefreshFailure failure) {
+ lastStaleRefreshFailureAt = clock.instant();
+ lastStaleRefreshFailure = failure;
+ }
+
+ private RuntimeException staleRefreshFailureException() {
+ return switch (lastStaleRefreshFailure) {
+ case SOURCE_UNAVAILABLE -> new SourceUnavailableException();
+ case INVALID_JWKS -> new InvalidJwksException();
+ };
+ }
+
+ private void rejectHardDenied(String kid) {
+ if (hardCutoverQuarantined || hardDeniedKids.contains(kid)) {
+ throw new UnknownKeyException();
+ }
+ }
+
+ private static Map parseJwks(byte[] bytes) {
+ if (bytes == null || bytes.length == 0 || bytes.length > MAX_JWKS_BYTES) {
+ throw new InvalidJwksException();
+ }
+ try {
+ String text = strictUtf8(bytes);
+ Map root = JSON.readValue(text, OBJECT);
+ requireExactFields(root, Set.of("keys"));
+ if (!(root.get("keys") instanceof List> list) || list.isEmpty() || list.size() > MAX_KEYS) {
+ throw new InvalidJwksException();
+ }
+ Map parsed = new LinkedHashMap<>();
+ for (Object item : list) {
+ if (!(item instanceof Map, ?> raw)) {
+ throw new InvalidJwksException();
+ }
+ Map key = stringKeyedMap(raw);
+ Set allowed = Set.of("kty", "use", "alg", "kid", "n", "e", "key_ops");
+ if (!allowed.containsAll(key.keySet())
+ || !key.keySet().containsAll(Set.of("kty", "use", "alg", "kid", "n", "e"))) {
+ throw new InvalidJwksException();
+ }
+ if (!(key.get("kty") instanceof String kty)
+ || !"RSA".equals(kty)
+ || !(key.get("use") instanceof String use)
+ || !"sig".equals(use)
+ || !(key.get("alg") instanceof String alg)
+ || !"RS256".equals(alg)
+ || !(key.get("kid") instanceof String kid)
+ || !KID.matcher(kid).matches()) {
+ throw new InvalidJwksException();
+ }
+ if (key.containsKey("key_ops")
+ && (!(key.get("key_ops") instanceof List> ops) || !ops.equals(List.of("verify")))) {
+ throw new InvalidJwksException();
+ }
+ BigInteger modulus = decodeUnsigned(key.get("n"), 2048);
+ BigInteger exponent = decodeUnsigned(key.get("e"), 8);
+ if (modulus.bitLength() < 3072
+ || modulus.bitLength() > 16384
+ || !modulus.testBit(0)
+ || !BigInteger.valueOf(65537).equals(exponent)) {
+ throw new InvalidJwksException();
+ }
+ RSAPublicKey publicKey =
+ (RSAPublicKey)
+ KeyFactory.getInstance("RSA")
+ .generatePublic(new RSAPublicKeySpec(modulus, exponent));
+ if (parsed.putIfAbsent(kid, publicKey) != null) {
+ throw new InvalidJwksException();
+ }
+ }
+ return parsed;
+ } catch (InvalidJwksException ex) {
+ throw ex;
+ } catch (GeneralSecurityException | RuntimeException ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static BigInteger decodeUnsigned(Object encodedValue, int maximumBytes) {
+ if (!(encodedValue instanceof String encoded)
+ || encoded.isEmpty()
+ || encoded.indexOf('=') >= 0
+ || !encoded.matches("[A-Za-z0-9_-]+")) {
+ throw new InvalidJwksException();
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(encoded);
+ if (decoded.length == 0
+ || decoded.length > maximumBytes
+ || decoded[0] == 0
+ || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(encoded)) {
+ throw new InvalidJwksException();
+ }
+ return new BigInteger(1, decoded);
+ } catch (IllegalArgumentException ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static void requireExactFields(Map object, Set expected) {
+ if (object == null || !object.keySet().equals(expected)) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static Map stringKeyedMap(Map, ?> source) {
+ Map result = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : source.entrySet()) {
+ if (!(entry.getKey() instanceof String key)
+ || result.putIfAbsent(key, entry.getValue()) != null) {
+ throw new InvalidJwksException();
+ }
+ }
+ return result;
+ }
+
+ private static String strictUtf8(byte[] bytes) {
+ try {
+ return StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ } catch (CharacterCodingException ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static String fingerprint(RSAPublicKey key) {
+ try {
+ byte[] material =
+ (key.getModulus().toString(16) + ":" + key.getPublicExponent().toString(16))
+ .getBytes(StandardCharsets.US_ASCII);
+ return java.util.HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(material));
+ } catch (Exception ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static String fingerprintBytes(byte[] bytes) {
+ try {
+ return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (Exception ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ /** Exact protected API/cluster/resource identity expected from every source read. */
+ public record SourceIdentity(
+ String environmentId,
+ String clusterId,
+ String clusterIncarnationUid,
+ String namespace,
+ String namespaceUid,
+ String configMapUid,
+ String bindingRevision,
+ String apiServerOrigin,
+ String servingCaSha256) {
+ public SourceIdentity {
+ if (environmentId == null
+ || !NAMESPACE.matcher(environmentId).matches()
+ || clusterId == null
+ || !CLUSTER.matcher(clusterId).matches()
+ || clusterIncarnationUid == null
+ || !UID.matcher(clusterIncarnationUid).matches()
+ || namespace == null
+ || !NAMESPACE.matcher(namespace).matches()
+ || namespaceUid == null
+ || !UID.matcher(namespaceUid).matches()
+ || configMapUid == null
+ || !UID.matcher(configMapUid).matches()
+ || bindingRevision == null
+ || !CLUSTER.matcher(bindingRevision).matches()
+ || apiServerOrigin == null
+ || !validApiOrigin(apiServerOrigin)
+ || servingCaSha256 == null
+ || !SHA256.matcher(servingCaSha256).matches()) {
+ throw new IllegalArgumentException("Account public JWKS source identity is invalid");
+ }
+ }
+
+ private static boolean validApiOrigin(String value) {
+ try {
+ URI uri = URI.create(value);
+ return "https".equalsIgnoreCase(uri.getScheme())
+ && uri.getHost() != null
+ && uri.getPort() > 0
+ && uri.getRawUserInfo() == null
+ && uri.getRawQuery() == null
+ && uri.getRawFragment() == null
+ && (uri.getRawPath() == null
+ || uri.getRawPath().isEmpty()
+ || "/".equals(uri.getRawPath()));
+ } catch (IllegalArgumentException invalid) {
+ return false;
+ }
+ }
+ }
+
+ /** Owner-provided authenticated retrieval seam; implementations must verify their trust pins. */
+ @FunctionalInterface
+ public interface TrustedPublicJwksSource {
+ PublicJwksSnapshot load() throws SourceUnavailableException;
+ }
+
+ /** A single exact public ConfigMap data value plus its independently established source pin. */
+ public record PublicJwksSnapshot(SourceIdentity sourceIdentity, byte[] jwksBytes) {
+ public PublicJwksSnapshot {
+ Objects.requireNonNull(sourceIdentity, "source identity is required");
+ jwksBytes = jwksBytes == null ? null : jwksBytes.clone();
+ }
+
+ @Override
+ public byte[] jwksBytes() {
+ return jwksBytes == null ? null : jwksBytes.clone();
+ }
+ }
+
+ public static final class SourceUnavailableException extends RuntimeException {
+ public SourceUnavailableException() {
+ super("Account public JWKS source is unavailable");
+ }
+ }
+
+ public static final class InvalidJwksException extends RuntimeException {
+ public InvalidJwksException() {
+ super("Account public JWKS source data is invalid");
+ }
+ }
+
+ public static final class UnknownKeyException extends RuntimeException {
+ public UnknownKeyException() {
+ super("Account public JWKS key is unavailable");
+ }
+ }
+
+ private enum StaleRefreshFailure {
+ SOURCE_UNAVAILABLE,
+ INVALID_JWKS
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidator.java
new file mode 100644
index 0000000000..0fcdeec4d2
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidator.java
@@ -0,0 +1,98 @@
+package net.firedevops.firemud.common.security;
+
+import java.util.Map;
+import java.util.Set;
+
+/** Validates distinct initial and exact-one-tenant public-production delegation claim forms. */
+public final class GameSessionAccountDelegationJwtProfileValidator {
+ public static final Set REQUIRED_CLAIMS =
+ AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS;
+ public static final Set OPTIONAL_CLAIMS =
+ Set.of("globalRoles", "scopedRoles", "tenantId");
+ private static final Set INITIAL_OPTIONAL_CLAIMS = Set.of("globalRoles", "scopedRoles");
+
+ private GameSessionAccountDelegationJwtProfileValidator() {}
+
+ /** Checks profile shape only; Account registry/currentness evidence is a separate predicate. */
+ public static void validateClaims(Map claims) {
+ if (claims == null) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ if (claims.containsKey("tenantId")) {
+ validatePublicTenantBoundClaims(claims);
+ return;
+ }
+ validateInitialClaims(claims);
+ }
+
+ /** The initial form remains explicitly unscoped; a bound JWT cannot authenticate LOGIN. */
+ public static void validateInitialClaims(Map claims) {
+ AccountJwtProfileClaimSupport.requireClaimFields(
+ claims, AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS, INITIAL_OPTIONAL_CLAIMS);
+ AccountJwtProfileClaimSupport.requireDelegationCommonIdentity(
+ claims,
+ GameSessionAccountDelegationProfile.ISSUER,
+ GameSessionAccountDelegationProfile.AUDIENCE);
+ AccountJwtProfileClaimSupport.requireDelegationAuthorityTuple(
+ claims.get("authorityTuple"), false, true, true);
+ requireExactAuthorityCutoffStreams(claims, null);
+ if (!AccountJwtProfileClaimSupport.requireDelegationVersionMap(claims.get("membershipVersion"))
+ .isEmpty()) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ if (claims.containsKey("globalRoles")) {
+ AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles"));
+ }
+ if (claims.containsKey("scopedRoles")
+ && !AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")).isEmpty()) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ }
+
+ /** Separate exact-one-tenant public-production form; no roles or non-public grants. */
+ public static void validatePublicTenantBoundClaims(Map claims) {
+ var required = new java.util.HashSet<>(REQUIRED_CLAIMS);
+ required.add("tenantId");
+ AccountJwtProfileClaimSupport.requireClaimFields(claims, required, Set.of());
+ AccountJwtProfileClaimSupport.requireDelegationCommonIdentity(
+ claims,
+ GameSessionAccountDelegationProfile.ISSUER,
+ GameSessionAccountDelegationProfile.AUDIENCE);
+ String accountId = AccountJwtProfileClaimSupport.requireUuid(claims.get("accountId"));
+ String tenantId = AccountJwtProfileClaimSupport.requireUuid(claims.get("tenantId"));
+ GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority(
+ tenantId,
+ AccountJwtProfileClaimSupport.requireObjectMap(claims.get("authorityTuple")),
+ AccountJwtProfileClaimSupport.requireObjectMap(claims.get("membershipVersion")));
+ requireExactAuthorityCutoffStreams(claims, accountId, tenantId);
+ }
+
+ private static void requireExactAuthorityCutoffStreams(
+ Map claims, String tenantId) {
+ requireExactAuthorityCutoffStreams(
+ claims, AccountJwtProfileClaimSupport.requireUuid(claims.get("accountId")), tenantId);
+ }
+
+ private static void requireExactAuthorityCutoffStreams(
+ Map claims, String accountId, String tenantId) {
+ Map tuple =
+ AccountJwtProfileClaimSupport.requireObjectMap(claims.get("authorityTuple"));
+ if (tuple.containsKey("accountSecurityCutoff")) {
+ Map cutoff =
+ AccountJwtProfileClaimSupport.requireObjectMap(tuple.get("accountSecurityCutoff"));
+ AccountJwtProfileClaimSupport.requireExactAccountAuthorityStream(
+ cutoff.get("outboxStreamKey"), accountId);
+ }
+ if (tenantId != null && tuple.containsKey("tenantBillingCutoff")) {
+ Map cutoffs =
+ AccountJwtProfileClaimSupport.requireObjectMap(tuple.get("tenantBillingCutoff"));
+ if (!cutoffs.keySet().equals(Set.of(tenantId))) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ Map cutoff =
+ AccountJwtProfileClaimSupport.requireObjectMap(cutoffs.get(tenantId));
+ AccountJwtProfileClaimSupport.requireExactTenantAuthorityStream(
+ cutoff.get("outboxStreamKey"), tenantId);
+ }
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java
new file mode 100644
index 0000000000..bfbf78ae4b
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java
@@ -0,0 +1,154 @@
+package net.firedevops.firemud.common.security;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+/**
+ * Bounded initial non-tenant and distinct public-production tenant-bound Account delegation forms.
+ *
+ * This declares claim shape only. It does not authenticate Game Session, verify a signature,
+ * prove signer promotion, establish current Account evidence, or authorize a call. It is separate
+ * from Social & Friends delegations and from generic backend JWT conventions.
+ */
+public final class GameSessionAccountDelegationProfile {
+ public static final String PROFILE = "game-session-account-delegation";
+ public static final String TYPE = "private_player_delegation";
+ public static final String ISSUER = "firemud-account-service";
+ public static final String AUDIENCE = "account-service";
+ public static final String TOKEN_TYPE_CLAIM = "tokenType";
+ public static final String TOKEN_PROFILE_CLAIM = "tokenProfile";
+ public static final long MAX_TOKEN_LIFETIME_SECONDS = 300L;
+ public static final int MAX_COMPACT_JWT_BYTES = 16 * 1024;
+ public static final int MAX_AUTHORITY_TUPLE_BYTES = 4 * 1024;
+ public static final int MAX_REGISTRY_RECORD_BYTES = 16 * 1024;
+ private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}");
+
+ private GameSessionAccountDelegationProfile() {}
+
+ /** Checks the supported public-production tenant-bound form, never an initial LOGIN tuple. */
+ public static void requirePublicTenantBoundAuthority(
+ String tenantId, Map tuple, Map membershipVersion) {
+ AccountJwtProfileClaimSupport.requireUuid(tenantId);
+ AccountJwtProfileClaimSupport.requireDelegationAuthorityTuple(tuple, true, false, true);
+ for (String field :
+ java.util.List.of("tenantAuthorityGeneration", "membershipAuthorityGeneration")) {
+ if (!AccountJwtProfileClaimSupport.requireDelegationVersionMap(tuple.get(field))
+ .keySet()
+ .equals(java.util.Set.of(tenantId))) throw AccountJwtProfileClaimSupport.invalid();
+ }
+ if (!AccountJwtProfileClaimSupport.requireDelegationVersionMap(membershipVersion)
+ .keySet()
+ .equals(java.util.Set.of(tenantId))
+ || !java.util.List.of().equals(tuple.get("privateRealmGrantVersions"))) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ if (tuple.containsKey("tenantBillingCutoff")) {
+ Map cutoff =
+ AccountJwtProfileClaimSupport.requireObjectMap(tuple.get("tenantBillingCutoff"));
+ if (!cutoff.keySet().equals(java.util.Set.of(tenantId)))
+ throw AccountJwtProfileClaimSupport.invalid();
+ var value = AccountJwtProfileClaimSupport.requireObjectMap(cutoff.get(tenantId));
+ var generation =
+ AccountJwtProfileClaimSupport.requireObjectMap(tuple.get("tenantAuthorityGeneration"));
+ if (!java.util.Objects.equals(
+ generation.get(tenantId), value.get("tenantAuthorityGeneration"))) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ }
+ }
+
+ /** Returns the exact required unscoped authority tuple for an initial credential login. */
+ public static Map authorityTuple(
+ long issuerAuthGeneration, long accountAuthorityGeneration) {
+ if (accountAuthorityGeneration != 1L) {
+ throw new IllegalArgumentException(
+ "Advanced Account authority requires its exact current security cutoff");
+ }
+ return authorityTuple(issuerAuthGeneration, accountAuthorityGeneration, Optional.empty());
+ }
+
+ /** Returns the exact tuple, carrying the Account cutoff only when source evidence proves it. */
+ public static Map authorityTuple(
+ long issuerAuthGeneration,
+ long accountAuthorityGeneration,
+ Optional accountSecurityCutoff) {
+ if (issuerAuthGeneration <= 0L || accountAuthorityGeneration <= 0L) {
+ throw new IllegalArgumentException("Account delegation generations must be positive");
+ }
+ Objects.requireNonNull(accountSecurityCutoff, "Account cutoff applicability is required");
+ if ((accountAuthorityGeneration == 1L) != accountSecurityCutoff.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Account security cutoff presence does not match the source generation");
+ }
+ accountSecurityCutoff.ifPresent(
+ cutoff -> {
+ if (!Long.toString(accountAuthorityGeneration)
+ .equals(cutoff.accountAuthorityGeneration())) {
+ throw new IllegalArgumentException("Account security cutoff generation is stale");
+ }
+ });
+ Map tuple = new LinkedHashMap<>();
+ tuple.put("issuerAuthGeneration", Long.toString(issuerAuthGeneration));
+ tuple.put("accountAuthorityGeneration", Long.toString(accountAuthorityGeneration));
+ tuple.put("tenantAuthorityGeneration", Map.of());
+ tuple.put("membershipAuthorityGeneration", Map.of());
+ tuple.put("privateRealmGrantVersions", java.util.List.of());
+ accountSecurityCutoff.ifPresent(cutoff -> tuple.put("accountSecurityCutoff", cutoff.toMap()));
+ return Map.copyOf(tuple);
+ }
+
+ /** Exact optional Account cutoff value carried by this profile's authority tuple. */
+ public record AccountSecurityCutoff(
+ String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {
+ public AccountSecurityCutoff {
+ requirePositiveDecimal(accountAuthorityGeneration, "cutoff generation");
+ requirePositiveDecimal(outboxSequence, "cutoff outbox sequence");
+ requireAccountAuthorityStream(outboxStreamKey);
+ for (int index = 0; index < outboxStreamKey.length(); index++) {
+ if (Character.isISOControl(outboxStreamKey.charAt(index))) {
+ throw new IllegalArgumentException("Account security cutoff stream is malformed");
+ }
+ }
+ }
+
+ private static void requireAccountAuthorityStream(String value) {
+ String prefix = "account:auth-authority:v1:account/";
+ if (value == null || value.length() > 2048 || !value.startsWith(prefix)) {
+ throw new IllegalArgumentException("Account security cutoff stream is malformed");
+ }
+ String accountId = value.substring(prefix.length());
+ UUID parsed;
+ try {
+ parsed = UUID.fromString(accountId);
+ } catch (IllegalArgumentException failure) {
+ throw new IllegalArgumentException("Account security cutoff stream is malformed");
+ }
+ if (!parsed.toString().equals(accountId) || parsed.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException("Account security cutoff stream is malformed");
+ }
+ }
+
+ public Map toMap() {
+ return Map.of(
+ "accountAuthorityGeneration", accountAuthorityGeneration,
+ "outboxStreamKey", outboxStreamKey,
+ "outboxSequence", outboxSequence);
+ }
+
+ private static void requirePositiveDecimal(String value, String field) {
+ if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) {
+ throw new IllegalArgumentException("Account security cutoff " + field + " is malformed");
+ }
+ try {
+ Long.parseLong(value);
+ } catch (NumberFormatException ex) {
+ throw new IllegalArgumentException(
+ "Account security cutoff " + field + " exceeds the supported range");
+ }
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java
new file mode 100644
index 0000000000..1fe597cdc1
--- /dev/null
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java
@@ -0,0 +1,362 @@
+package net.firedevops.firemud.common.account.admission;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+import org.junit.jupiter.api.Test;
+
+class AccountGameplayAdmissionLeaseEvidenceTest {
+ private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111";
+ private static final String TENANT = "22222222-2222-4222-8222-222222222222";
+ private static final String OTHER = "33333333-3333-4333-8333-333333333333";
+ private static final String HIGH = "9007199254740993";
+ private static final String PREFIX = "account:auth-authority:v1:";
+
+ @Test
+ void retainsExactCanonicalRetryIdentityAndCountersAboveDoublePrecision() {
+ var value = evidence();
+ var parsed = AccountGameplayAdmissionLeaseEvidence.parseCanonical(value.canonicalJson());
+ assertThat(parsed).isEqualTo(value);
+ assertThat(value.hasSameIdentity(parsed)).isTrue();
+ assertThat(value.sha256()).matches("[0-9a-f]{64}");
+ assertThat(value.leaseFence()).isEqualTo(new BigInteger(HIGH));
+ assertThat(value.canonicalJson())
+ .contains("\"membershipVersion\":{\"" + TENANT + "\":\"" + HIGH + "\"}");
+ assertThat(value.toString()).doesNotContain(ACCOUNT, value.sha256());
+ }
+
+ @Test
+ void lifecycleShapeCarriesInactiveWithoutGrantingAuthority() {
+ Map carrier = fixture();
+ object(carrier, "membershipBaseline").put("membershipLifecycleState", "INACTIVE");
+ assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier).sha256())
+ .isNotEqualTo(evidence().sha256());
+ }
+
+ @Test
+ void everyCompleteCarrierContributesToDigest() {
+ List>> changes =
+ List.of(
+ c ->
+ object(object(c, "membershipBaseline"), "membershipVersion")
+ .put(TENANT, "9007199254740994"),
+ c -> object(c, "authorityTuple").put("issuerAuthGeneration", "2"),
+ c -> object(c, "bindingScope").put("worldSlug", "another-world"),
+ c -> object(c, "tokenIdentityEvidence").put("tokenSHA256", "b".repeat(64)),
+ c -> c.put("expiresAt", "1014000"),
+ c -> checkpoints(c).get(0).put("outboxSequence", "1"));
+ for (Consumer> change : changes) {
+ var carrier = fixture();
+ change.accept(carrier);
+ var changed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier);
+ assertThat(changed.sha256()).isNotEqualTo(evidence().sha256());
+ assertThat(changed.hasSameIdentity(evidence())).isFalse();
+ }
+ }
+
+ @Test
+ void rejectsBaselineMissingExtraScalarWrongTenantAndMismatchedGeneration() {
+ rejects(c -> c.remove("membershipBaseline"));
+ rejects(c -> object(c, "membershipBaseline").put("extra", "1"));
+ rejects(c -> object(c, "membershipBaseline").remove("membershipAuthorityGeneration"));
+ rejects(c -> object(c, "membershipBaseline").put("membershipVersion", HIGH));
+ rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(OTHER, HIGH)));
+ rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(TENANT, "01")));
+ rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(TENANT, 1L)));
+ rejects(c -> object(c, "membershipBaseline").put("membershipAuthorityGeneration", "2"));
+ rejects(
+ c ->
+ object(c, "membershipBaseline")
+ .put("membershipVersion", Map.of(TENANT, "9223372036854775808")));
+ }
+
+ @Test
+ void rejectsDuplicateUnorderedMissingExtraAndMalformedCheckpoints() {
+ rejects(c -> checkpoints(c).add(new LinkedHashMap<>(checkpoints(c).get(0))));
+ rejects(c -> java.util.Collections.swap(checkpoints(c), 0, 1));
+ rejects(c -> checkpoints(c).remove(0));
+ rejects(c -> checkpoints(c).get(0).put("outboxSequence", "00"));
+ rejects(c -> checkpoints(c).get(2).put("outboxSequence", "0"));
+ rejects(c -> checkpoints(c).get(0).put("eventId", OTHER));
+ }
+
+ @Test
+ void rejectsWrongModeScopePeerTokenAndResumeEpisode() {
+ rejects(c -> c.put("mode", "PRIVATE"));
+ rejects(c -> c.put("leaseKind", "REFRESH"));
+ rejects(c -> c.put("resumeEpisodeId", OTHER));
+ rejects(c -> c.put("leaseKind", "RESUME"));
+ rejects(c -> object(c, "bindingScope").put("playableStateScope", "PUBLIC_PRODUCTION"));
+ rejects(c -> object(c, "bindingScope").put("regionId", "region-1"));
+ rejects(c -> c.put("targetNamespace", "other"));
+ rejects(c -> c.put("callerWorkload", "spiffe://firemud/ns/test/sa/account-service"));
+ rejects(c -> object(c, "tokenIdentityEvidence").put("accountId", OTHER));
+ rejects(c -> object(c, "tokenIdentityEvidence").put("issuanceFence", "2"));
+ rejects(c -> object(c, "tokenIdentityEvidence").put("tokenBytes", "secret"));
+ rejects(c -> object(c, "tokenIdentityEvidence").put("tokenProfile", "gameplay-connect"));
+ var resume = fixture();
+ resume.put("leaseKind", "RESUME");
+ resume.put("resumeEpisodeId", OTHER);
+ resume.put("expectedOldBindingGeneration", "7");
+ assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(resume).leaseKind())
+ .isEqualTo(AccountGameplayAdmissionLeaseEvidence.LeaseKind.RESUME);
+ }
+
+ @Test
+ void retainsExplicitPriorGenerationWithoutDerivingHistory() {
+ var initial = fixture();
+ var prior = fixture();
+ prior.put("expectedOldBindingGeneration", "7");
+ var priorValue = AccountGameplayAdmissionLeaseEvidence.fromCarrier(prior);
+ assertThat(priorValue.sha256())
+ .isNotEqualTo(AccountGameplayAdmissionLeaseEvidence.fromCarrier(initial).sha256());
+ assertThat(AccountGameplayAdmissionLeaseEvidence.parseCanonical(priorValue.canonicalJson()))
+ .isEqualTo(priorValue);
+ rejects(c -> c.put("expectedOldBindingGeneration", "0"));
+ rejects(c -> c.put("expectedOldBindingGeneration", null));
+ rejects(
+ c -> {
+ c.put("leaseKind", "RESUME");
+ c.put("resumeEpisodeId", OTHER);
+ });
+ }
+
+ @Test
+ void rejectsExpiredLongerThanSlaOrExtendingTokenAndNoncanonicalParsing() {
+ rejects(c -> c.put("expiresAt", "1000000"));
+ rejects(c -> c.put("expiresAt", "1015001"));
+ rejects(c -> object(c, "tokenIdentityEvidence").put("expiresAt", "1014"));
+ rejects(c -> object(c, "tokenIdentityEvidence").put("notBefore", "1001"));
+ rejects(c -> c.put("leaseFence", "+1"));
+ rejects(c -> c.put("schemaVersion", "2"));
+ String json = evidence().canonicalJson();
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(" " + json))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(json + "{}"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(null))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ AccountGameplayAdmissionLeaseEvidence.parseCanonical(
+ json.replace(
+ "\"schemaVersion\":\"1\"",
+ "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\"")))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void cutoffReferencesMustBeCoveredByCompleteCheckpointCoordinates() {
+ var carrier = fixture();
+ object(carrier, "authorityTuple").put("accountAuthorityGeneration", "2");
+ object(carrier, "authorityTuple")
+ .put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "2",
+ "outboxStreamKey",
+ PREFIX + "account/" + ACCOUNT,
+ "outboxSequence",
+ "1"));
+ checkpoints(carrier).get(0).put("outboxSequence", "1");
+ assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier)).isNotNull();
+ checkpoints(carrier).get(0).put("outboxSequence", "2");
+ var retained = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier);
+ assertThat(object(retained.carrier(), "authorityTuple").get("accountSecurityCutoff"))
+ .isEqualTo(object(carrier, "authorityTuple").get("accountSecurityCutoff"));
+ checkpoints(carrier).get(0).put("outboxSequence", "0");
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier))
+ .isInstanceOf(IllegalArgumentException.class);
+ var billing = fixture();
+ object(billing, "authorityTuple")
+ .put(
+ "tenantBillingCutoff",
+ Map.of(
+ TENANT,
+ Map.of(
+ "tenantAuthorityGeneration",
+ HIGH,
+ "tenantBillingSequence",
+ "7",
+ "outboxStreamKey",
+ PREFIX + "tenant/" + TENANT,
+ "outboxSequence",
+ HIGH)));
+ assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing)).isNotNull();
+ checkpoints(billing).get(3).put("outboxSequence", "9007199254740994");
+ assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing)).isNotNull();
+ checkpoints(billing).get(3).put("outboxSequence", "2");
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing))
+ .isInstanceOf(IllegalArgumentException.class);
+ object(billing, "authorityTuple")
+ .put(
+ "tenantBillingCutoff",
+ Map.of(
+ TENANT,
+ Map.of(
+ "tenantAuthorityGeneration",
+ HIGH,
+ "tenantBillingSequence",
+ "7",
+ "outboxStreamKey",
+ PREFIX + "account/" + ACCOUNT,
+ "outboxSequence",
+ "1")));
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void rejectsOversizedDeepCyclicAndNullCarriersBeforeBuildingUnboundedEvidence() {
+ rejects(
+ c ->
+ c.put(
+ "large", "a".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1)));
+ rejects(c -> c.put("large", "界".repeat(22000)));
+ rejects(
+ c -> {
+ Map nested = Map.of("leaf", "value");
+ for (int index = 0; index < 10; index++) {
+ nested = Map.of("nested", nested);
+ }
+ c.put("nested", nested);
+ });
+ rejects(c -> c.put("cycle", c));
+ rejects(c -> c.put("nullable", null));
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(null))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ AccountGameplayAdmissionLeaseEvidence.parseCanonical(
+ " ".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ AccountGameplayAdmissionLeaseEvidence.parseCanonical(
+ "[".repeat(10) + "\"value\"" + "]".repeat(10)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void freezesNestedMapsAndCheckpointListsAgainstCallerMutation() {
+ var carrier = fixture();
+ var value = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier);
+ String original = value.canonicalJson();
+ object(object(carrier, "membershipBaseline"), "membershipVersion").put(TENANT, "2");
+ checkpoints(carrier).clear();
+ assertThat(value.canonicalJson()).isEqualTo(original);
+ assertThatThrownBy(
+ () -> object(value.carrier(), "authorityTuple").put("issuerAuthGeneration", "2"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ assertThatThrownBy(() -> checkpoints(value.carrier()).clear())
+ .isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ private static AccountGameplayAdmissionLeaseEvidence evidence() {
+ return AccountGameplayAdmissionLeaseEvidence.fromCarrier(fixture());
+ }
+
+ private static void rejects(Consumer> change) {
+ var value = fixture();
+ change.accept(value);
+ assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(value))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map object(Map value, String key) {
+ return (Map) value.get(key);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static List> checkpoints(Map value) {
+ return (List>) value.get("outboxCheckpoints");
+ }
+
+ static Map fixture() {
+ Map value = new LinkedHashMap<>();
+ value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA);
+ value.put("schemaVersion", "1");
+ value.put("mode", "PUBLIC_PRODUCTION");
+ value.put("targetNamespace", "test");
+ value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service");
+ value.put("requestId", OTHER);
+ value.put("leaseId", TENANT);
+ value.put("leaseFence", HIGH);
+ value.put("leaseKind", "NEW_BINDING");
+ Map scope = new LinkedHashMap<>();
+ for (String key :
+ List.of(
+ "realmId",
+ "playableStateNamespaceId",
+ "gameInstanceId",
+ "characterId",
+ "sessionId",
+ "regionId")) scope.put(key, OTHER);
+ scope.put("accountId", ACCOUNT);
+ scope.put("tenantId", TENANT);
+ scope.put("worldSlug", "world");
+ scope.put("realmSlug", "realm");
+ scope.put("playableStateScope", "SHARED");
+ for (String key :
+ List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch"))
+ scope.put(key, HIGH);
+ value.put("bindingScope", scope);
+ Map tuple = new LinkedHashMap<>();
+ tuple.put("issuerAuthGeneration", "1");
+ tuple.put("accountAuthorityGeneration", "1");
+ tuple.put("tenantAuthorityGeneration", Map.of(TENANT, HIGH));
+ tuple.put("membershipAuthorityGeneration", Map.of(TENANT, HIGH));
+ tuple.put("privateRealmGrantVersions", List.of());
+ value.put("authorityTuple", tuple);
+ value.put("issuanceFence", HIGH);
+ value.put(
+ "membershipBaseline",
+ new LinkedHashMap<>(
+ Map.of(
+ "membershipLifecycleState",
+ "ACTIVE",
+ "membershipVersion",
+ new LinkedHashMap<>(Map.of(TENANT, HIGH)),
+ "membershipAuthorityGeneration",
+ HIGH)));
+ List> checkpoints = new ArrayList<>();
+ for (String suffix :
+ List.of(
+ "account/" + ACCOUNT,
+ "issuer/firemud-account-service",
+ "membership/" + ACCOUNT + "/" + TENANT,
+ "tenant/" + TENANT)) {
+ checkpoints.add(
+ new LinkedHashMap<>(
+ Map.of(
+ "outboxStreamKey",
+ PREFIX + suffix,
+ "outboxSequence",
+ suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : HIGH)));
+ }
+ value.put("outboxCheckpoints", checkpoints);
+ Map token = new LinkedHashMap<>();
+ token.put("accountId", ACCOUNT);
+ for (String key : List.of("operationId", "issuanceRequestId", "tokenJti"))
+ token.put(key, OTHER);
+ token.put("tokenSHA256", "a".repeat(64));
+ token.put("tokenProfile", "game-session-account-delegation");
+ for (String key : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence"))
+ token.put(key, HIGH);
+ token.put("issuedAt", "999");
+ token.put("notBefore", "999");
+ token.put("expiresAt", "1300");
+ value.put("tokenIdentityEvidence", token);
+ value.put("evaluatedAt", "1000000");
+ value.put("expiresAt", "1015000");
+ return value;
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java
new file mode 100644
index 0000000000..412799731e
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java
@@ -0,0 +1,576 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class AccountAsymmetricJwtVerifierTest {
+ private static final Instant NOW = Instant.parse("2026-10-05T10:00:00Z");
+ private static final String KID = "signer-1";
+ private static final AccountPublicJwksCache.SourceIdentity PIN =
+ new AccountPublicJwksCache.SourceIdentity(
+ "prod",
+ "cluster-a",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-prod",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-7",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+ private static final Set CLAIMS =
+ Set.of(
+ "iss",
+ "sub",
+ "jti",
+ "accountId",
+ "aud",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence");
+
+ private final MutableClock clock = new MutableClock(NOW);
+ private KeyPair keyPair;
+ private AccountAsymmetricJwtVerifier verifier;
+ private AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy policy;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ keyPair = rsa3072();
+ String jwks = jwks(jwk(KID, (RSAPublicKey) keyPair.getPublic()));
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(
+ () ->
+ new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, jwks.getBytes(StandardCharsets.UTF_8)),
+ PIN,
+ clock,
+ Duration.ofSeconds(30));
+ verifier = new AccountAsymmetricJwtVerifier(cache, clock);
+ policy =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "credential-authenticate-account",
+ GameSessionAccountDelegationProfile.PROFILE,
+ GameSessionAccountDelegationProfile.TYPE,
+ GameSessionAccountDelegationProfile.ISSUER,
+ GameSessionAccountDelegationProfile.AUDIENCE,
+ CLAIMS,
+ Set.of(),
+ GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS,
+ 5,
+ GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES,
+ GameSessionAccountDelegationJwtProfileValidator::validateClaims);
+ }
+
+ @Test
+ void verifiesRealRs256SignatureAndReturnsOnlyImmutableRouteBoundClaims() throws Exception {
+ String token =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+
+ AccountAsymmetricJwtVerifier.VerifiedClaims verified = verifier.verify(token, policy);
+
+ assertThat(verified.routeId()).isEqualTo("credential-authenticate-account");
+ assertThat(verified.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE);
+ assertThat(verified.tokenType()).isEqualTo(GameSessionAccountDelegationProfile.TYPE);
+ assertThat(verified.keyId()).isEqualTo(KID);
+ assertThat(verified.claims().get("iss")).isEqualTo(GameSessionAccountDelegationProfile.ISSUER);
+ assertThat(verified.claims()).doesNotContainKeys("tokenType", "tokenProfile");
+ assertThat(verified.getClass().getDeclaredFields())
+ .extracting(java.lang.reflect.Field::getName)
+ .containsExactlyInAnyOrder("routeId", "profile", "tokenType", "keyId", "claims");
+ assertThatThrownBy(() -> verified.claims().put("extra", "value"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ @SuppressWarnings("unchecked")
+ Map tuple = (Map) verified.claims().get("authorityTuple");
+ assertThatThrownBy(() -> tuple.put("tenant", "x"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ assertThat(verified.claims().get("iat")).isInstanceOf(Number.class);
+ assertThat(verified.claims().get("tokenGeneration")).isEqualTo("1");
+ assertThat(verified.claims().get("issuanceFence")).isEqualTo("1");
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void verifiedClaimsDeepCopyAndFreezeCallerOwnedNestedValues() {
+ Map nested = new LinkedHashMap<>();
+ List nestedList = new java.util.ArrayList<>();
+ Map listEntry = new LinkedHashMap<>();
+ listEntry.put("value", "before");
+ nestedList.add(listEntry);
+ nested.put("items", nestedList);
+ Map source = new LinkedHashMap<>();
+ source.put("nested", nested);
+
+ AccountAsymmetricJwtVerifier.VerifiedClaims verified =
+ new AccountAsymmetricJwtVerifier.VerifiedClaims("route", "profile", "type", "kid", source);
+
+ listEntry.put("value", "after");
+ nestedList.add("after");
+ nested.put("added", true);
+ source.put("added", true);
+
+ Map, ?> copiedNested = (Map, ?>) verified.claims().get("nested");
+ List> copiedList = (List>) copiedNested.get("items");
+ Map, ?> copiedListEntry = (Map, ?>) copiedList.get(0);
+ assertThat(copiedListEntry.get("value")).isEqualTo("before");
+ assertThat(copiedList).hasSize(1);
+ assertThat(copiedNested.containsKey("added")).isFalse();
+ assertThat(verified.claims()).doesNotContainKey("added");
+ assertThatThrownBy(() -> ((Map) copiedNested).put("added", true))
+ .isInstanceOf(UnsupportedOperationException.class);
+ assertThatThrownBy(() -> ((List) copiedList).add("value"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ assertThatThrownBy(() -> ((Map) copiedListEntry).put("value", "after"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ @Test
+ void rejectsNumericDelegationCountersWithoutChangingNumericJwtTimes() throws Exception {
+ Map numericTokenGeneration =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ numericTokenGeneration.put("tokenGeneration", 1L);
+ assertDenied(token(numericTokenGeneration, "RS256", KID, "JWT", keyPair));
+
+ Map numericFence =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ numericFence.put("issuanceFence", 1L);
+ assertDenied(token(numericFence, "RS256", KID, "JWT", keyPair));
+ }
+
+ @Test
+ void preservesCanonicalCounterBeyondLongRangeAtVerifierBoundary() throws Exception {
+ String beyondLong = "9223372036854775808";
+ Map claims =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ claims.put("tokenGeneration", beyondLong);
+ AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy exactCounterPolicy =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ policy.routeId(),
+ policy.profile(),
+ policy.tokenType(),
+ policy.issuer(),
+ policy.audience(),
+ policy.requiredClaims(),
+ policy.optionalClaims(),
+ policy.maximumLifetimeSeconds(),
+ policy.allowedClockSkewSeconds(),
+ policy.maxCompactTokenBytes(),
+ ignored -> {});
+
+ AccountAsymmetricJwtVerifier.VerifiedClaims verified =
+ verifier.verify(token(claims, "RS256", KID, "JWT", keyPair), exactCounterPolicy);
+
+ assertThat(verified.claims().get("tokenGeneration")).isEqualTo(beyondLong);
+ }
+
+ @Test
+ void preservesSignedDelegationCountersAboveJavascriptIntegerPrecision() throws Exception {
+ String largeCounter = "9007199254740993";
+ Map claims =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ claims.put("issuanceFence", largeCounter);
+ Map tuple = new LinkedHashMap<>();
+ tuple.put("issuerAuthGeneration", largeCounter);
+ tuple.put("accountAuthorityGeneration", "1");
+ tuple.put("tenantAuthorityGeneration", Map.of());
+ tuple.put("membershipAuthorityGeneration", Map.of());
+ tuple.put("privateRealmGrantVersions", java.util.List.of());
+ claims.put("authorityTuple", tuple);
+
+ AccountAsymmetricJwtVerifier.VerifiedClaims verified =
+ verifier.verify(token(claims, "RS256", KID, "JWT", keyPair), policy);
+
+ assertThat(verified.claims().get("tokenGeneration")).isEqualTo("1");
+ assertThat(verified.claims().get("issuanceFence")).isEqualTo(largeCounter);
+ assertThat(verified.claims().get("authorityTuple")).isInstanceOf(Map.class);
+ Map, ?> verifiedTuple = (Map, ?>) verified.claims().get("authorityTuple");
+ assertThat(verifiedTuple.get("issuerAuthGeneration")).isEqualTo(largeCounter);
+ assertThat(verifiedTuple.get("accountAuthorityGeneration")).isEqualTo("1");
+ }
+
+ @Test
+ void wrongIssuerAudienceHeaderTypeAlgorithmAndTimeAreDenied() throws Exception {
+ Map wrongIssuer =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ wrongIssuer.put("iss", "other-issuer");
+ assertDenied(token(wrongIssuer, "RS256", KID, "JWT", keyPair));
+
+ Map wrongAudience =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ wrongAudience.put("aud", "other-audience");
+ assertDenied(token(wrongAudience, "RS256", KID, "JWT", keyPair));
+
+ assertDenied(
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "HS256",
+ KID,
+ "JWT",
+ keyPair));
+ assertDenied(
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "private_player_delegation",
+ keyPair));
+ assertDenied(
+ token(
+ validClaims(
+ NOW.getEpochSecond() - 400, NOW.getEpochSecond() - 400, NOW.getEpochSecond() - 1),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair));
+ assertDenied(
+ token(
+ validClaims(
+ NOW.getEpochSecond() + 20, NOW.getEpochSecond() + 20, NOW.getEpochSecond() + 100),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair));
+ }
+
+ @Test
+ void rejectsDuplicateTrailingExtraClaimsAndMismatchedSignatureKey() throws Exception {
+ String validPayload =
+ claimsJson(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120));
+ assertDenied(
+ rawToken(
+ "{\"alg\":\"RS256\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}",
+ validPayload.replaceFirst("\\{", "{\"iss\":\"duplicate\","),
+ keyPair));
+ assertDenied(
+ rawToken(
+ "{\"alg\":\"RS256\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}",
+ validPayload + " {}",
+ keyPair));
+ Map extra =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ extra.put("unrecognized", true);
+ assertDenied(token(extra, "RS256", KID, "JWT", keyPair));
+
+ KeyPair other = rsa3072();
+ assertDenied(
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ other));
+ }
+
+ @Test
+ void cacheUnavailableAfterMaximumAgeDoesNotPermitStaleSignatureUse() throws Exception {
+ String jwks = jwks(jwk(KID, (RSAPublicKey) keyPair.getPublic()));
+ boolean[] unavailable = {false};
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(
+ () -> {
+ if (unavailable[0]) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, jwks.getBytes(StandardCharsets.UTF_8));
+ },
+ PIN,
+ clock,
+ Duration.ofSeconds(5));
+ AccountAsymmetricJwtVerifier staleVerifier = new AccountAsymmetricJwtVerifier(cache, clock);
+ String valid =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+ assertThat(staleVerifier.verify(valid, policy).claims().get("jti"))
+ .isEqualTo("22222222-2222-4222-8222-222222222222");
+ unavailable[0] = true;
+ clock.advance(Duration.ofSeconds(6));
+ assertThatThrownBy(() -> staleVerifier.verify(valid, policy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationUnavailableException.class)
+ .hasMessage("Account JWT verification is temporarily unavailable")
+ .hasNoCause();
+ assertThatThrownBy(() -> staleVerifier.verify("not-a-token", policy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasMessage("Account JWT verification failed")
+ .hasNoCause();
+ }
+
+ @Test
+ void unknownKidForcesOneSnapshotRefreshAndThenVerifiesAgainstTheNewPublicKey() throws Exception {
+ KeyPair rotated = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference currentJwks =
+ new AtomicReference<>(jwks(jwk(KID, (RSAPublicKey) keyPair.getPublic())));
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(
+ () -> {
+ loads.incrementAndGet();
+ return new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, currentJwks.get().getBytes(StandardCharsets.UTF_8));
+ },
+ PIN,
+ clock,
+ Duration.ofSeconds(30));
+ AccountAsymmetricJwtVerifier rotationVerifier = new AccountAsymmetricJwtVerifier(cache, clock);
+ String oldToken =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+ rotationVerifier.verify(oldToken, policy);
+ currentJwks.set(
+ jwks(
+ jwk(KID, (RSAPublicKey) keyPair.getPublic())
+ + ","
+ + jwk("signer-2", (RSAPublicKey) rotated.getPublic())));
+
+ String rotatedToken =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ "signer-2",
+ "JWT",
+ rotated);
+ assertThat(rotationVerifier.verify(rotatedToken, policy).claims().get("iss"))
+ .isEqualTo(GameSessionAccountDelegationProfile.ISSUER);
+ assertThat(rotationVerifier.verify(rotatedToken, policy).claims().get("iss"))
+ .isEqualTo(GameSessionAccountDelegationProfile.ISSUER);
+ assertThat(loads).hasValue(2);
+ }
+
+ @Test
+ void claimShapeValidationRunsOnlyAfterSuccessfulSignatureVerification() throws Exception {
+ AtomicInteger shapeValidations = new AtomicInteger();
+ AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy observingPolicy =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "credential-authenticate-account",
+ GameSessionAccountDelegationProfile.PROFILE,
+ GameSessionAccountDelegationProfile.TYPE,
+ GameSessionAccountDelegationProfile.ISSUER,
+ GameSessionAccountDelegationProfile.AUDIENCE,
+ CLAIMS,
+ Set.of(),
+ GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS,
+ 5,
+ GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES,
+ claims -> {
+ shapeValidations.incrementAndGet();
+ GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims);
+ });
+ String valid =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+
+ verifier.verify(valid, observingPolicy);
+ assertThat(shapeValidations).hasValue(1);
+
+ String invalidSignature = corruptSignature(valid);
+ assertThatThrownBy(() -> verifier.verify(invalidSignature, observingPolicy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasNoCause();
+ assertThat(shapeValidations).hasValue(1);
+ }
+
+ private void assertDenied(String token) {
+ assertDenied(verifier, token);
+ }
+
+ private static void assertDenied(AccountAsymmetricJwtVerifier verifier, String token) {
+ assertThatThrownBy(() -> verifier.verify(token, policyForTest()))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasMessage("Account JWT verification failed")
+ .hasNoCause();
+ }
+
+ private static AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy policyForTest() {
+ return new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "credential-authenticate-account",
+ GameSessionAccountDelegationProfile.PROFILE,
+ GameSessionAccountDelegationProfile.TYPE,
+ GameSessionAccountDelegationProfile.ISSUER,
+ GameSessionAccountDelegationProfile.AUDIENCE,
+ CLAIMS,
+ Set.of(),
+ 300,
+ 5,
+ 16 * 1024,
+ GameSessionAccountDelegationJwtProfileValidator::validateClaims);
+ }
+
+ private static Map validClaims(long issuedAt, long notBefore, long expiresAt) {
+ Map claims = new LinkedHashMap<>();
+ claims.put("iss", GameSessionAccountDelegationProfile.ISSUER);
+ claims.put("sub", "11111111-1111-4111-8111-111111111111");
+ claims.put("jti", "22222222-2222-4222-8222-222222222222");
+ claims.put("accountId", "11111111-1111-4111-8111-111111111111");
+ claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE);
+ claims.put("iat", issuedAt);
+ claims.put("nbf", notBefore);
+ claims.put("exp", expiresAt);
+ claims.put("tokenGeneration", "1");
+ claims.put(
+ "authorityTuple",
+ Map.of(
+ "issuerAuthGeneration", "1",
+ "accountAuthorityGeneration", "1",
+ "tenantAuthorityGeneration", Map.of(),
+ "membershipAuthorityGeneration", Map.of(),
+ "privateRealmGrantVersions", java.util.List.of()));
+ claims.put("membershipVersion", Map.of());
+ claims.put("issuanceFence", "1");
+ return claims;
+ }
+
+ private static String token(
+ Map claims, String algorithm, String kid, String typ, KeyPair signer)
+ throws Exception {
+ String header =
+ "{\"alg\":\"" + algorithm + "\",\"kid\":\"" + kid + "\",\"typ\":\"" + typ + "\"}";
+ return rawToken(header, claimsJson(claims), signer);
+ }
+
+ private static String rawToken(String header, String payload, KeyPair signer) throws Exception {
+ Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
+ String headerSegment = encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8));
+ String payloadSegment = encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8));
+ byte[] signingInput =
+ (headerSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII);
+ Signature signature = Signature.getInstance("SHA256withRSA");
+ signature.initSign(signer.getPrivate());
+ signature.update(signingInput);
+ return headerSegment + "." + payloadSegment + "." + encoder.encodeToString(signature.sign());
+ }
+
+ private static String corruptSignature(String token) {
+ int separator = token.lastIndexOf('.');
+ char replacement = token.charAt(separator + 1) == 'A' ? 'B' : 'A';
+ return token.substring(0, separator + 1) + replacement + token.substring(separator + 2);
+ }
+
+ private static String claimsJson(Map claims) {
+ // Build the canonical profile's bounded nested object explicitly so test tokens exercise the
+ // same normal JSON shapes without relying on an unrelated mapper configuration.
+ StringBuilder json = new StringBuilder("{");
+ boolean first = true;
+ for (Map.Entry entry : claims.entrySet()) {
+ if (!first) {
+ json.append(',');
+ }
+ first = false;
+ json.append('"').append(entry.getKey()).append("\":");
+ Object value = entry.getValue();
+ if (value instanceof String text) {
+ json.append('"').append(text).append('"');
+ } else if (value instanceof Number || value instanceof Boolean) {
+ json.append(value);
+ } else if ("membershipVersion".equals(entry.getKey())) {
+ json.append("{}");
+ } else if ("authorityTuple".equals(entry.getKey())) {
+ Map, ?> tuple = (Map, ?>) value;
+ json.append("{\"issuerAuthGeneration\":\"")
+ .append(tuple.get("issuerAuthGeneration"))
+ .append("\",\"accountAuthorityGeneration\":\"")
+ .append(tuple.get("accountAuthorityGeneration"))
+ .append("\",\"tenantAuthorityGeneration\":{},")
+ .append("\"membershipAuthorityGeneration\":{},\"privateRealmGrantVersions\":[]}");
+ } else {
+ throw new IllegalArgumentException("Unexpected test claim");
+ }
+ }
+ json.append('}');
+ return json.toString();
+ }
+
+ private static String jwks(String key) {
+ return "{\"keys\":[" + key + "]}";
+ }
+
+ private static String jwk(String kid, RSAPublicKey key) {
+ byte[] modulus = unsigned(key.getModulus().toByteArray());
+ byte[] exponent = unsigned(key.getPublicExponent().toByteArray());
+ return "{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\""
+ + kid
+ + "\",\"n\":\""
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(modulus)
+ + "\",\"e\":\""
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(exponent)
+ + "\"}";
+ }
+
+ private static byte[] unsigned(byte[] value) {
+ return value.length > 1 && value[0] == 0
+ ? java.util.Arrays.copyOfRange(value, 1, value.length)
+ : value;
+ }
+
+ private static KeyPair rsa3072() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(3072);
+ return generator.generateKeyPair();
+ }
+
+ private static final class MutableClock extends Clock {
+ private Instant current;
+
+ private MutableClock(Instant current) {
+ this.current = current;
+ }
+
+ void advance(Duration duration) {
+ current = current.plus(duration);
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return ZoneId.of("UTC");
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public Instant instant() {
+ return current;
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java
new file mode 100644
index 0000000000..90fe42cfbb
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java
@@ -0,0 +1,543 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.Base64;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.Test;
+
+class AccountPublicJwksCacheTest {
+ private static final Instant INITIAL = Instant.parse("2026-10-05T10:00:00Z");
+ private static final AccountPublicJwksCache.SourceIdentity PIN =
+ new AccountPublicJwksCache.SourceIdentity(
+ "prod",
+ "cluster-a",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-prod",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-7",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+
+ @Test
+ void parsesStrongPublicOnlyKeysAndRetainsBothKeysPresentInOneSnapshot() throws Exception {
+ KeyPair oldKey = rsa3072();
+ KeyPair newKey = rsa3072();
+ String jwks =
+ jwks(
+ jwk("old", (RSAPublicKey) oldKey.getPublic())
+ + ","
+ + jwk("new", (RSAPublicKey) newKey.getPublic()));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache = cache(clock, () -> snapshot(jwks));
+
+ assertThat(cache.keyFor("old")).isEqualTo(oldKey.getPublic());
+ assertThat(cache.keyFor("new")).isEqualTo(newKey.getPublic());
+ assertThat(cache.sourceIdentity()).isEqualTo(PIN);
+ }
+
+ @Test
+ void unknownKidGetsOneForcedLoadThenCooldownPreventsRefreshStorm() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ return snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ });
+
+ assertThatThrownBy(() -> cache.keyFor("unknown"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThatThrownBy(() -> cache.keyFor("unknown"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(1);
+
+ clock.advance(Duration.ofSeconds(1));
+ assertThatThrownBy(() -> cache.keyFor("unknown-two"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(2);
+ }
+
+ @Test
+ void distinctUnknownKidsShareRefreshCooldownAndRotationRefreshWorksAfterOneSecond()
+ throws Exception {
+ KeyPair known = rsa3072();
+ KeyPair rotated = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference currentJwks =
+ new AtomicReference<>(jwks(jwk("known", (RSAPublicKey) known.getPublic())));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ return snapshot(currentJwks.get());
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ assertThatThrownBy(() -> cache.keyFor("unknown-one"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(2);
+
+ assertThatThrownBy(() -> cache.keyFor("unknown-two"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThatThrownBy(() -> cache.keyFor("unknown-three"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ assertThat(loads).hasValue(2);
+
+ currentJwks.set(
+ jwks(
+ jwk("known", (RSAPublicKey) known.getPublic())
+ + ","
+ + jwk("rotated", (RSAPublicKey) rotated.getPublic())));
+ clock.advance(Duration.ofSeconds(1));
+ assertThat(cache.keyFor("rotated")).isEqualTo(rotated.getPublic());
+ assertThat(loads).hasValue(3);
+
+ assertThatThrownBy(() -> cache.keyFor("unknown-after-rotation"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(3);
+ }
+
+ @Test
+ void unavailableUnknownKidRefreshIsRateLimitedAndBackwardClockFailsClosed() throws Exception {
+ KeyPair known = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("known", (RSAPublicKey) known.getPublic())));
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ unavailable.set(true);
+ clock.advance(Duration.ofMillis(500));
+ assertThatThrownBy(() -> cache.keyFor("unknown-one"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(2);
+
+ clock.advance(Duration.ofMillis(250));
+ clock.advance(Duration.ofMillis(-500));
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ assertThatThrownBy(() -> cache.keyFor("unknown-two"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(2);
+
+ clock.advance(Duration.ofSeconds(10));
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThat(loads).hasValue(3);
+ }
+
+ @Test
+ void neverLoadedUnknownKidRetriesSourceAfterUnavailableResponseBackoff() {
+ AtomicInteger loads = new AtomicInteger();
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ });
+
+ assertThatThrownBy(() -> cache.keyFor("future"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThatThrownBy(() -> cache.keyFor("future"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThat(loads).hasValue(1);
+
+ clock.advance(Duration.ofSeconds(1));
+ assertThatThrownBy(() -> cache.keyFor("future"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThat(loads).hasValue(2);
+ }
+
+ @Test
+ void staleUnavailableDistinctUnknownKidsDoNotGrowRefreshHistoryPastItsBound() throws Exception {
+ KeyPair known = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("known", (RSAPublicKey) known.getPublic())));
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ unavailable.set(true);
+ clock.advance(Duration.ofSeconds(11));
+
+ for (int i = 0; i < 260; i++) {
+ String kid = "unknown-" + i;
+ assertThatThrownBy(() -> cache.keyFor(kid))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ clock.advance(Duration.ofSeconds(1));
+ }
+
+ assertThat(loads).hasValue(261);
+ assertThat(rememberedUnknownKidRefreshCount(cache)).isEqualTo(256);
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThat(loads).hasValue(262);
+ }
+
+ private static int rememberedUnknownKidRefreshCount(AccountPublicJwksCache cache)
+ throws ReflectiveOperationException {
+ java.lang.reflect.Field field =
+ AccountPublicJwksCache.class.getDeclaredField("unknownKidsRefreshedForSnapshot");
+ field.setAccessible(true);
+ return ((java.util.Set>) field.get(cache)).size();
+ }
+
+ @Test
+ void previousUnknownKidIsRetriedAfterCacheAgeAndCanResolveALaterPublishedKey() throws Exception {
+ KeyPair known = rsa3072();
+ KeyPair later = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference currentJwks =
+ new AtomicReference<>(jwks(jwk("known", (RSAPublicKey) known.getPublic())));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ return snapshot(currentJwks.get());
+ });
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ assertThatThrownBy(() -> cache.keyFor("future"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+
+ currentJwks.set(
+ jwks(
+ jwk("known", (RSAPublicKey) known.getPublic())
+ + ","
+ + jwk("future", (RSAPublicKey) later.getPublic())));
+ clock.advance(Duration.ofSeconds(11));
+
+ assertThat(cache.keyFor("future")).isEqualTo(later.getPublic());
+ assertThat(loads).hasValue(3);
+ }
+
+ @Test
+ void knownKeyUsesOnlyStillFreshCacheDuringUnavailableSourceAndNeverExtendsAge() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ unavailable.set(true);
+ clock.advance(Duration.ofSeconds(4));
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ clock.advance(Duration.ofSeconds(7));
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ }
+
+ @Test
+ void repeatedStaleKnownKeyLookupsRemainUnavailableDuringSourceOutage() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ if (loads.incrementAndGet() > 1) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ clock.advance(Duration.ofSeconds(11));
+
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThat(loads).hasValue(2);
+ }
+
+ @Test
+ void repeatedStaleKnownKeyLookupsBackOffInvalidJwksAndRetryAfterOneSecond() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference currentJwks =
+ new AtomicReference<>(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ return snapshot(currentJwks.get());
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ clock.advance(Duration.ofSeconds(11));
+ currentJwks.set("not-json");
+
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+ assertThat(loads).hasValue(2);
+
+ currentJwks.set(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ clock.advance(Duration.ofSeconds(1));
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ assertThat(loads).hasValue(3);
+ }
+
+ @Test
+ void changedSourceIdentityAndReusedKidMaterialAreRejected() throws Exception {
+ KeyPair first = rsa3072();
+ KeyPair replacement = rsa3072();
+ AtomicReference next =
+ new AtomicReference<>(snapshot(jwks(jwk("same", (RSAPublicKey) first.getPublic()))));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache = cache(clock, next::get);
+ assertThat(cache.keyFor("same")).isEqualTo(first.getPublic());
+
+ next.set(snapshot(jwks(jwk("same", (RSAPublicKey) replacement.getPublic()))));
+ clock.advance(Duration.ofSeconds(11));
+ assertThatThrownBy(() -> cache.keyFor("same"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+
+ byte[] wrongSourceBytes =
+ jwks(jwk("x", (RSAPublicKey) first.getPublic()))
+ .getBytes(java.nio.charset.StandardCharsets.UTF_8);
+ AccountPublicJwksCache wrongSource =
+ cache(
+ clock,
+ () -> new AccountPublicJwksCache.PublicJwksSnapshot(otherPin(), wrongSourceBytes));
+ assertThatThrownBy(() -> wrongSource.keyFor("x"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+ }
+
+ @Test
+ void hardCutoverDenialOverridesFreshCacheAndUnavailableSource() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("cut", (RSAPublicKey) key.getPublic())));
+ });
+ assertThat(cache.keyFor("cut")).isEqualTo(key.getPublic());
+ cache.invalidateKid("cut");
+ unavailable.set(true);
+
+ assertThatThrownBy(() -> cache.keyFor("cut"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ }
+
+ @Test
+ void hardCutoverBoundExhaustionQuarantinesAllKeysWithoutRefreshing() throws Exception {
+ KeyPair revoked = rsa3072();
+ KeyPair current = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(
+ jwks(
+ jwk("revoked65", (RSAPublicKey) revoked.getPublic())
+ + ","
+ + jwk("current", (RSAPublicKey) current.getPublic())));
+ });
+
+ assertThat(cache.keyFor("revoked65")).isEqualTo(revoked.getPublic());
+ assertThat(cache.keyFor("current")).isEqualTo(current.getPublic());
+ assertThat(loads).hasValue(1);
+
+ for (int i = 0; i < AccountPublicJwksCache.MAX_KEYS; i++) {
+ cache.invalidateKid("denied" + i);
+ }
+ assertThat(cache.keyFor("current")).isEqualTo(current.getPublic());
+ assertThatThrownBy(() -> cache.keyFor("denied0"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+
+ assertThatThrownBy(() -> cache.invalidateKid("revoked65"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Account public JWKS hard-cutover bound is exhausted");
+ assertQuarantined(cache, "revoked65", "denied0", "current");
+ assertThat(loads).hasValue(1);
+
+ clock.advance(Duration.ofSeconds(11));
+ assertQuarantined(cache, "revoked65", "denied0", "current");
+ assertThat(loads).hasValue(1);
+
+ unavailable.set(true);
+ assertQuarantined(cache, "revoked65", "denied0", "current");
+ assertThat(loads).hasValue(1);
+ }
+
+ private static void assertQuarantined(AccountPublicJwksCache cache, String... kids) {
+ for (String kid : kids) {
+ assertThatThrownBy(() -> cache.keyFor(kid))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ }
+ }
+
+ @Test
+ void rejectsPrivateWeakDuplicateTrailingAndNonCanonicalJwks() throws Exception {
+ KeyPair strong = rsa3072();
+ String publicKey = jwk("valid", (RSAPublicKey) strong.getPublic());
+ MutableClock clock = new MutableClock(INITIAL);
+ for (String invalid :
+ new String[] {
+ jwks(publicKey.substring(0, publicKey.length() - 1) + ",\"d\":\"private\"}"),
+ jwks(jwk("weak", (RSAPublicKey) rsa2048().getPublic())),
+ "{\"keys\":[" + publicKey + "," + publicKey + "]}",
+ jwks(publicKey) + " {}",
+ jwks(publicKey.replace("\"key_ops\":[\"verify\"]", "\"key_ops\":[\"sign\"]"))
+ }) {
+ AccountPublicJwksCache cache = cache(clock, () -> snapshot(invalid));
+ assertThatThrownBy(() -> cache.keyFor("valid"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+ }
+ }
+
+ private static AccountPublicJwksCache cache(
+ MutableClock clock, AccountPublicJwksCache.TrustedPublicJwksSource source) {
+ return new AccountPublicJwksCache(source, PIN, clock, Duration.ofSeconds(10));
+ }
+
+ private static AccountPublicJwksCache.PublicJwksSnapshot snapshot(String json) {
+ return new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, json.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
+
+ private static AccountPublicJwksCache.SourceIdentity otherPin() {
+ return new AccountPublicJwksCache.SourceIdentity(
+ "prod",
+ "cluster-b",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-prod",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-7",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+ }
+
+ private static KeyPair rsa3072() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(3072);
+ return generator.generateKeyPair();
+ }
+
+ private static KeyPair rsa2048() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return generator.generateKeyPair();
+ }
+
+ private static String jwks(String keys) {
+ return "{\"keys\":[" + keys + "]}";
+ }
+
+ private static String jwk(String kid, RSAPublicKey key) {
+ String modulus =
+ Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(unsigned(key.getModulus().toByteArray()));
+ String exponent =
+ Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(unsigned(key.getPublicExponent().toByteArray()));
+ return "{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\""
+ + kid
+ + "\",\"n\":\""
+ + modulus
+ + "\",\"e\":\""
+ + exponent
+ + "\",\"key_ops\":[\"verify\"]}";
+ }
+
+ private static byte[] unsigned(byte[] value) {
+ if (value.length > 1 && value[0] == 0) {
+ return java.util.Arrays.copyOfRange(value, 1, value.length);
+ }
+ return value;
+ }
+
+ private static final class MutableClock extends Clock {
+ private Instant current;
+
+ private MutableClock(Instant current) {
+ this.current = current;
+ }
+
+ void advance(Duration duration) {
+ current = current.plus(duration);
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return ZoneId.of("UTC");
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public Instant instant() {
+ return current;
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java
new file mode 100644
index 0000000000..253ba0c2dd
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java
@@ -0,0 +1,334 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+
+class GameSessionAccountDelegationJwtProfileValidatorTest {
+ @Test
+ void rejectsNullClaimsBeforeSelectingEitherDelegationForm() {
+ assertThatThrownBy(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(null))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasNoCause();
+ }
+
+ @Test
+ void independentlyScopedAccountAndTenantUuidsMayEqualWithoutRelaxingExactMapKeys() {
+ var claims = validClaims();
+ var tuple = object(claims.get("authorityTuple"));
+ tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT, "5"));
+ tuple.put("membershipAuthorityGeneration", Map.of(ACCOUNT, "7"));
+ claims.put("tenantId", ACCOUNT);
+ claims.put("authorityTuple", tuple);
+ claims.put("membershipVersion", Map.of(ACCOUNT, "3"));
+ assertThatCode(
+ () ->
+ GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims(
+ claims))
+ .doesNotThrowAnyException();
+ assertThatThrownBy(
+ () -> GameSessionAccountDelegationJwtProfileValidator.validateInitialClaims(claims))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class);
+ claims.put("membershipVersion", Map.of("22222222-2222-4222-8222-222222222222", "3"));
+ assertInvalid(claims);
+ }
+
+ @Test
+ void publicTenantBoundFormKeepsIndependentOneTenantVersionsAndCannotAuthenticateInitialLogin() {
+ String tenant = "22222222-2222-4222-8222-222222222222";
+ Map claims = validClaims();
+ var tuple = object(claims.get("authorityTuple"));
+ tuple.put("tenantAuthorityGeneration", Map.of(tenant, "5"));
+ tuple.put("membershipAuthorityGeneration", Map.of(tenant, "7"));
+ claims.put("tenantId", tenant);
+ claims.put("authorityTuple", tuple);
+ claims.put("membershipVersion", Map.of(tenant, "3"));
+ assertThatCode(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims))
+ .doesNotThrowAnyException();
+ assertThatThrownBy(
+ () -> GameSessionAccountDelegationJwtProfileValidator.validateInitialClaims(claims))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class);
+ claims.put("membershipVersion", Map.of());
+ assertInvalid(claims);
+ claims.put("membershipVersion", Map.of(ACCOUNT, "3"));
+ assertInvalid(claims);
+ claims.put("membershipVersion", Map.of(tenant, "3", ACCOUNT, "4"));
+ assertInvalid(claims);
+ }
+
+ @Test
+ void tenantBillingCutoffMustUseTheExactTenantStreamAndAccountCutoffMustUseTheTokenAccount() {
+ String tenant = "22222222-2222-4222-8222-222222222222";
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put("accountAuthorityGeneration", "12");
+ tuple.put("tenantAuthorityGeneration", Map.of(tenant, "5"));
+ tuple.put("membershipAuthorityGeneration", Map.of(tenant, "7"));
+ tuple.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "44"));
+ tuple.put(
+ "tenantBillingCutoff",
+ Map.of(
+ tenant,
+ Map.of(
+ "tenantAuthorityGeneration",
+ "5",
+ "tenantBillingSequence",
+ "8",
+ "outboxStreamKey",
+ "account:auth-authority:v1:tenant/" + tenant,
+ "outboxSequence",
+ "45")));
+ claims.put("tenantId", tenant);
+ claims.put("authorityTuple", tuple);
+ claims.put("membershipVersion", Map.of(tenant, "3"));
+
+ assertThatCode(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims))
+ .doesNotThrowAnyException();
+
+ Map crossAccount = object(tuple);
+ crossAccount.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/33333333-3333-4333-8333-333333333333",
+ "outboxSequence",
+ "44"));
+ claims.put("authorityTuple", crossAccount);
+ assertInvalid(claims);
+
+ Map crossTenantStream = object(tuple);
+ crossTenantStream.put(
+ "tenantBillingCutoff",
+ Map.of(
+ tenant,
+ Map.of(
+ "tenantAuthorityGeneration",
+ "5",
+ "tenantBillingSequence",
+ "8",
+ "outboxStreamKey",
+ "account:auth-authority:v1:tenant/33333333-3333-4333-8333-333333333333",
+ "outboxSequence",
+ "45")));
+ claims.put("authorityTuple", crossTenantStream);
+ assertInvalid(claims);
+
+ Map crossTenantKey = object(tuple);
+ crossTenantKey.put(
+ "tenantBillingCutoff",
+ Map.of(
+ "33333333-3333-4333-8333-333333333333",
+ Map.of(
+ "tenantAuthorityGeneration",
+ "5",
+ "tenantBillingSequence",
+ "8",
+ "outboxStreamKey",
+ "account:auth-authority:v1:tenant/" + tenant,
+ "outboxSequence",
+ "45")));
+ claims.put("authorityTuple", crossTenantKey);
+ assertInvalid(claims);
+ }
+
+ @Test
+ void tenantDiscriminatorNeverAdoptsInitialEmptyTuple() {
+ var claims = validClaims();
+ claims.put("tenantId", "22222222-2222-4222-8222-222222222222");
+ assertInvalid(claims);
+ }
+
+ private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111";
+
+ @Test
+ void acceptsExactUnscopedDelegationAndOptionalEmptyRoleCollections() {
+ Map claims = validClaims();
+
+ assertThatCode(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims))
+ .doesNotThrowAnyException();
+ claims.put("globalRoles", List.of());
+ claims.put("scopedRoles", Map.of());
+ assertThatCode(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims))
+ .doesNotThrowAnyException();
+ }
+
+ @Test
+ void acceptsIndependentPositiveAccountGenerationAndCutoffSequenceWithExactAccountScope() {
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put("accountAuthorityGeneration", "12");
+ tuple.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "44"));
+ claims.put("authorityTuple", tuple);
+
+ assertThatCode(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims))
+ .doesNotThrowAnyException();
+
+ Map wrongGeneration = object(claims.get("authorityTuple"));
+ wrongGeneration.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "11",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "44"));
+ claims.put("authorityTuple", wrongGeneration);
+ assertInvalid(claims);
+
+ Map malformedSequence = object(tuple);
+ malformedSequence.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "044"));
+ claims.put("authorityTuple", malformedSequence);
+ assertInvalid(claims);
+
+ Map zeroSequence = object(tuple);
+ zeroSequence.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "0"));
+ claims.put("authorityTuple", zeroSequence);
+ assertInvalid(claims);
+
+ Map wrongScope = object(tuple);
+ wrongScope.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:tenant/22222222-2222-4222-8222-222222222222",
+ "outboxSequence",
+ "44"));
+ claims.put("authorityTuple", wrongScope);
+ assertInvalid(claims);
+
+ Map wrongAccountScope = object(tuple);
+ wrongAccountScope.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ "12",
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/33333333-3333-4333-8333-333333333333",
+ "outboxSequence",
+ "44"));
+ claims.put("authorityTuple", wrongAccountScope);
+ assertInvalid(claims);
+ }
+
+ @Test
+ void rejectsTenantAuthorityScopeAndUnexpectedClaims() {
+ Map scoped = validClaims();
+ Map tuple = object(scoped.get("authorityTuple"));
+ tuple.put("tenantAuthorityGeneration", Map.of("22222222-2222-4222-8222-222222222222", 2L));
+ scoped.put("authorityTuple", tuple);
+ assertInvalid(scoped);
+
+ Map scopedRoles = validClaims();
+ scopedRoles.put(
+ "scopedRoles", Map.of("22222222-2222-4222-8222-222222222222", List.of("reader")));
+ assertInvalid(scopedRoles);
+
+ Map billing = validClaims();
+ tuple = object(billing.get("authorityTuple"));
+ tuple.put("tenantBillingCutoff", Map.of("22222222-2222-4222-8222-222222222222", Map.of()));
+ billing.put("authorityTuple", tuple);
+ assertInvalid(billing);
+ }
+
+ @Test
+ void rejectsNumericOrNoncanonicalAuthorityCountersWhileKeepingEpochTimesNumeric() {
+ Map numericTokenGeneration = validClaims();
+ numericTokenGeneration.put("tokenGeneration", 1L);
+ assertInvalid(numericTokenGeneration);
+
+ Map numericFence = validClaims();
+ numericFence.put("issuanceFence", 1L);
+ assertInvalid(numericFence);
+
+ Map numericTuple = validClaims();
+ Map tuple = object(numericTuple.get("authorityTuple"));
+ tuple.put("issuerAuthGeneration", 1L);
+ numericTuple.put("authorityTuple", tuple);
+ assertInvalid(numericTuple);
+
+ Map leadingZero = validClaims();
+ leadingZero.put("issuanceFence", "01");
+ assertInvalid(leadingZero);
+
+ Map fractionalTime = validClaims();
+ fractionalTime.put("iat", 1.5d);
+ assertInvalid(fractionalTime);
+ }
+
+ private static Map validClaims() {
+ Map claims = new LinkedHashMap<>();
+ claims.put("iss", GameSessionAccountDelegationProfile.ISSUER);
+ claims.put("sub", ACCOUNT);
+ claims.put("accountId", ACCOUNT);
+ claims.put("jti", UUID.randomUUID().toString());
+ claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE);
+ claims.put("iat", 1L);
+ claims.put("nbf", 1L);
+ claims.put("exp", 300L);
+ claims.put("tokenGeneration", "1");
+ claims.put("issuanceFence", "1");
+ claims.put(
+ "authorityTuple",
+ Map.of(
+ "issuerAuthGeneration", "1",
+ "accountAuthorityGeneration", "1",
+ "tenantAuthorityGeneration", Map.of(),
+ "membershipAuthorityGeneration", Map.of(),
+ "privateRealmGrantVersions", List.of()));
+ claims.put("membershipVersion", Map.of());
+ return claims;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map object(Object value) {
+ return new LinkedHashMap<>((Map) value);
+ }
+
+ private static void assertInvalid(Map claims) {
+ assertThatThrownBy(() -> GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasNoCause();
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java
new file mode 100644
index 0000000000..6add388f56
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java
@@ -0,0 +1,104 @@
+package unit.net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.Map;
+import java.util.Optional;
+import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile;
+import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff;
+import org.junit.jupiter.api.Test;
+
+class GameSessionAccountDelegationProfileTest {
+ @Test
+ void declaresOnlyTheAccountAudienceCredentialLoginProfileAndFiniteBounds() {
+ assertThat(GameSessionAccountDelegationProfile.PROFILE)
+ .isEqualTo("game-session-account-delegation");
+ assertThat(GameSessionAccountDelegationProfile.TYPE).isEqualTo("private_player_delegation");
+ assertThat(GameSessionAccountDelegationProfile.ISSUER).isEqualTo("firemud-account-service");
+ assertThat(GameSessionAccountDelegationProfile.AUDIENCE).isEqualTo("account-service");
+ assertThat(GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS).isEqualTo(300L);
+ assertThat(GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES).isPositive();
+ assertThat(GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES).isPositive();
+ assertThat(GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES).isPositive();
+ }
+
+ @Test
+ void sequenceZeroNonTenantAuthorityTupleHasExactGenerationAndEmptyScopeShape() {
+ Map tuple = GameSessionAccountDelegationProfile.authorityTuple(7L, 1L);
+
+ assertThat(tuple)
+ .containsOnlyKeys(
+ "issuerAuthGeneration",
+ "accountAuthorityGeneration",
+ "tenantAuthorityGeneration",
+ "membershipAuthorityGeneration",
+ "privateRealmGrantVersions")
+ .containsEntry("issuerAuthGeneration", "7")
+ .containsEntry("accountAuthorityGeneration", "1")
+ .containsEntry("tenantAuthorityGeneration", Map.of())
+ .containsEntry("membershipAuthorityGeneration", Map.of())
+ .containsEntry("privateRealmGrantVersions", java.util.List.of());
+ }
+
+ @Test
+ void includesOnlyAnExplicitlyApplicableAccountCutoff() {
+ AccountSecurityCutoff cutoff =
+ new AccountSecurityCutoff(
+ "12", "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", "44");
+
+ Map tuple =
+ GameSessionAccountDelegationProfile.authorityTuple(7L, 12L, Optional.of(cutoff));
+
+ assertThat(tuple)
+ .containsOnlyKeys(
+ "issuerAuthGeneration",
+ "accountAuthorityGeneration",
+ "tenantAuthorityGeneration",
+ "membershipAuthorityGeneration",
+ "privateRealmGrantVersions",
+ "accountSecurityCutoff")
+ .containsEntry("accountSecurityCutoff", cutoff.toMap());
+ assertThat(tuple)
+ .containsEntry("issuerAuthGeneration", "7")
+ .containsEntry("accountAuthorityGeneration", "12");
+ assertThat(GameSessionAccountDelegationProfile.authorityTuple(7L, 1L, Optional.empty()))
+ .doesNotContainKey("accountSecurityCutoff");
+ }
+
+ @Test
+ void rejectsMalformedCutoffCountersAndNonAccountStreamScopes() {
+ assertThatThrownBy(
+ () ->
+ new AccountSecurityCutoff(
+ "12",
+ "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111",
+ "044"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountSecurityCutoff(
+ "12",
+ "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111",
+ "0"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountSecurityCutoff(
+ "12",
+ "account:auth-authority:v1:tenant/11111111-1111-4111-8111-111111111111",
+ "44"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ GameSessionAccountDelegationProfile.authorityTuple(
+ 7L,
+ 12L,
+ Optional.of(
+ new AccountSecurityCutoff(
+ "11",
+ "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111",
+ "44"))))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+}
diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts
index f1cc7d92b6..046cb29776 100644
--- a/services/game-session-service/build.gradle.kts
+++ b/services/game-session-service/build.gradle.kts
@@ -6,10 +6,20 @@ plugins {
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
+import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.OutputDirectories
import org.gradle.api.tasks.TaskAction
+import org.gradle.jvm.application.tasks.CreateStartScripts
+import org.gradle.process.CommandLineArgumentProvider
import org.springframework.boot.gradle.tasks.run.BootRun
+abstract class MigrationDriverTestClasspathArgumentProvider : CommandLineArgumentProvider {
+ @get:Classpath abstract val testClasspath: ConfigurableFileCollection
+
+ override fun asArguments(): Iterable =
+ listOf("-Dfiremud.migration-driver-test-classpath=${testClasspath.asPath}")
+}
+
abstract class CreateDirectoriesTask : DefaultTask() {
@get:OutputDirectories abstract val outputDirectories: ConfigurableFileCollection
@@ -50,7 +60,12 @@ dependencies {
implementation(libs.spring.boot.starter.websocket)
implementation(project(":common-saga"))
implementation(project(":common-security"))
+ implementation(libs.flyway.core)
+ implementation(libs.flyway.database.postgresql)
+ implementation(libs.junixsocket.common)
+ implementation(libs.postgresql)
implementation(libs.jjwt.api)
+ runtimeOnly(libs.junixsocket.native.common)
runtimeOnly(libs.jjwt.impl)
runtimeOnly(libs.jjwt.jackson)
testFixturesImplementation(project(":entity-management-service"))
@@ -68,6 +83,8 @@ dependencies {
testFixturesImplementation(libs.spring.boot.starter.web)
testFixturesImplementation(libs.grpc.spring.boot.starter)
testFixturesCompileOnly(libs.spotbugs.annotations)
+ testCompileOnly(libs.spotbugs.annotations)
+ add("integrationTestCompileOnly", libs.spotbugs.annotations)
testFixturesImplementation("io.grpc:grpc-netty-shaded:${libs.versions.grpc.get()}")
testFixturesImplementation("io.grpc:grpc-protobuf:${libs.versions.grpc.get()}")
testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}")
@@ -91,9 +108,46 @@ tasks.named("bootRun") {
val isWindows = System.getProperty("os.name").lowercase().contains("windows")
tasks.withType().configureEach {
+ jvmArgumentProviders.add(
+ objects.newInstance().apply {
+ testClasspath.from(classpath)
+ },
+ )
if (isWindows) {
maxParallelForks = 1
forkEvery = 0
doNotTrackState("Workaround for Windows file locking on test binary output")
}
}
+
+val migrationDriverMainClass =
+ "net.firedevops.firemud.gamesession.repository.CanonicalGameplayMigrationDriverLauncher"
+val migrationDriverDistribution = layout.buildDirectory.dir("distributions/game-session-migration-driver")
+val migrationDriverScripts = layout.buildDirectory.dir("generated/game-session-migration-driver-scripts")
+
+val createMigrationDriverStartScripts =
+ tasks.register("createMigrationDriverStartScripts") {
+ group = "distribution"
+ description = "Creates the finite Game Session canonical gameplay migration driver launcher."
+ applicationName = "game-session-migration-driver"
+ mainClass.set(migrationDriverMainClass)
+ classpath = files(tasks.named("jar"), configurations.named("runtimeClasspath"))
+ outputDir = migrationDriverScripts.get().asFile
+ }
+
+val gameSessionMigrationDriverDist =
+ tasks.register("gameSessionMigrationDriverDist") {
+ group = "distribution"
+ description = "Packages the finite, non-listening Game Session migration driver and runtime classpath."
+ dependsOn(tasks.named("jar"), createMigrationDriverStartScripts)
+ into(migrationDriverDistribution)
+ from(createMigrationDriverStartScripts) {
+ into("bin")
+ }
+ from(tasks.named("jar")) {
+ into("lib")
+ }
+ from(configurations.named("runtimeClasspath")) {
+ into("lib")
+ }
+ }
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountCoverageEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountCoverageEvidence.java
new file mode 100644
index 0000000000..e04bcd0d8c
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountCoverageEvidence.java
@@ -0,0 +1,85 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Exact account-wide coverage carrier bound to a durable binding transition. */
+public sealed interface CanonicalGameplayAccountCoverageEvidence
+ permits CanonicalGameplayAccountCoverageEvidence.NoActiveFlow,
+ CanonicalGameplayAccountCoverageEvidence.Historical {
+ State state();
+
+ static NoActiveFlow noActiveFlow() {
+ return new NoActiveFlow();
+ }
+
+ static Historical historical(
+ UUID operationId,
+ BigInteger operationFence,
+ UUID historicalAccountAdmissionFence,
+ UUID coverageFence,
+ UUID accountId,
+ BigInteger inventorySnapshotRevision,
+ BigInteger coverageGeneration) {
+ return new Historical(
+ operationId,
+ operationFence,
+ historicalAccountAdmissionFence,
+ coverageFence,
+ accountId,
+ inventorySnapshotRevision,
+ coverageGeneration);
+ }
+
+ enum State {
+ NO_ACTIVE_ACCOUNT_WIDE_FLOW,
+ HISTORICAL
+ }
+
+ record NoActiveFlow() implements CanonicalGameplayAccountCoverageEvidence {
+ @Override
+ public State state() {
+ return State.NO_ACTIVE_ACCOUNT_WIDE_FLOW;
+ }
+ }
+
+ record Historical(
+ UUID operationId,
+ BigInteger operationFence,
+ UUID historicalAccountAdmissionFence,
+ UUID coverageFence,
+ UUID accountId,
+ BigInteger inventorySnapshotRevision,
+ BigInteger coverageGeneration)
+ implements CanonicalGameplayAccountCoverageEvidence {
+ public Historical {
+ requireNonNil(operationId, "operationId");
+ requirePositive(operationFence, "operationFence");
+ requireNonNil(historicalAccountAdmissionFence, "historicalAccountAdmissionFence");
+ requireNonNil(coverageFence, "coverageFence");
+ requireNonNil(accountId, "accountId");
+ requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision");
+ requirePositive(coverageGeneration, "coverageGeneration");
+ }
+
+ @Override
+ public State state() {
+ return State.HISTORICAL;
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountIndexMember.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountIndexMember.java
new file mode 100644
index 0000000000..fd5e5533b9
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountIndexMember.java
@@ -0,0 +1,41 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Base64;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Exact versioned Redis set member for one tenant-qualified canonical gameplay binding. */
+public record CanonicalGameplayAccountIndexMember(
+ CanonicalGameplayBindingRef bindingRef, BigInteger bindingGeneration, UUID accountIndexFence) {
+ private static final String PREFIX = "accountIndexMember/v1:";
+
+ public CanonicalGameplayAccountIndexMember {
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ Objects.requireNonNull(bindingGeneration, "bindingGeneration");
+ Objects.requireNonNull(accountIndexFence, "accountIndexFence");
+ if (bindingGeneration.signum() <= 0) {
+ throw new IllegalArgumentException("bindingGeneration must be positive");
+ }
+ if (accountIndexFence.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException("accountIndexFence must not be nil");
+ }
+ }
+
+ public static CanonicalGameplayAccountIndexMember of(
+ CanonicalGameplayBindingInventoryEntry binding) {
+ Objects.requireNonNull(binding, "binding");
+ return new CanonicalGameplayAccountIndexMember(
+ binding.bindingRef(), binding.bindingGeneration(), binding.accountIndexFence());
+ }
+
+ /**
+ * Encodes the specified member tuple without normalizing its canonical bindingRef bytes.
+ * Base64url makes the member unambiguous while retaining a delimiter-safe generation/fence suffix
+ * for the single-key Lua stale-generation guard.
+ */
+ public String value() {
+ String encodedRef = Base64.getUrlEncoder().withoutPadding().encodeToString(bindingRef.bytes());
+ return PREFIX + encodedRef + ":" + bindingGeneration + ":" + accountIndexFence;
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionDecision.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionDecision.java
new file mode 100644
index 0000000000..e0c2737536
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionDecision.java
@@ -0,0 +1,228 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence;
+import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget;
+
+/**
+ * Exact, non-admitting Game Session readback of one Account lease-bound binding decision.
+ *
+ * The decision identifier is the existing binding transition identifier. This value does not
+ * represent the controller switch, Account finalization, or gameplay admission.
+ */
+public final class CanonicalGameplayAdmissionDecision {
+ private final UUID bindingDecisionId;
+ private final AccountGameplayAdmissionLeaseEvidence leaseEvidence;
+ private final CanonicalGameplayBindingIdentity candidate;
+ private final BigInteger bindingGeneration;
+ private final BigInteger expectedOldBindingGeneration;
+ private final UUID resumeEpisodeId;
+ private final CanonicalPlayableTarget targetEvidence;
+
+ public CanonicalGameplayAdmissionDecision(
+ UUID bindingDecisionId,
+ AccountGameplayAdmissionLeaseEvidence leaseEvidence,
+ CanonicalGameplayBindingIdentity candidate,
+ BigInteger bindingGeneration,
+ BigInteger expectedOldBindingGeneration,
+ CanonicalPlayableTarget targetEvidence) {
+ this.bindingDecisionId = requireNonNil(bindingDecisionId, "bindingDecisionId");
+ this.leaseEvidence = Objects.requireNonNull(leaseEvidence, "leaseEvidence");
+ this.candidate = Objects.requireNonNull(candidate, "candidate");
+ this.bindingGeneration = requirePositive(bindingGeneration, "bindingGeneration");
+ this.targetEvidence = Objects.requireNonNull(targetEvidence, "targetEvidence");
+ if (expectedOldBindingGeneration != null && expectedOldBindingGeneration.signum() <= 0) {
+ throw new IllegalArgumentException("expectedOldBindingGeneration must be positive");
+ }
+
+ Map carrier = leaseEvidence.carrier();
+ Map scope = object(carrier.get("bindingScope"), "bindingScope");
+ requireEqual(text(carrier, "targetNamespace"), targetEvidence.targetNamespace(), "namespace");
+ requireEqual(text(scope, "accountId"), candidate.accountId().toString(), "accountId");
+ requireEqual(text(scope, "tenantId"), candidate.tenantId().toString(), "tenantId");
+ requireEqual(
+ text(scope, "tenantId"), targetEvidence.canonicalTenantId().toString(), "target tenantId");
+ requireEqual(text(scope, "realmId"), targetEvidence.realmId().toString(), "realmId");
+ requireEqual(text(scope, "worldSlug"), targetEvidence.worldSlug(), "worldSlug");
+ requireEqual(text(scope, "realmSlug"), targetEvidence.realmSlug(), "realmSlug");
+ requireEqual(
+ text(scope, "playableStateNamespaceId"),
+ candidate.playableStateNamespaceId().toString(),
+ "playableStateNamespaceId");
+ requireEqual(
+ text(scope, "playableStateNamespaceId"),
+ targetEvidence.playableStateNamespaceId().toString(),
+ "target playableStateNamespaceId");
+ requireEqual(
+ text(scope, "playableStateScope"), candidate.playableStateScope(), "playableStateScope");
+ requireEqual(
+ text(scope, "playableStateScope"),
+ targetEvidence.playableStateScope(),
+ "target playableStateScope");
+ requireEqual(
+ text(scope, "gameInstanceId"), candidate.gameInstanceId().toString(), "gameInstanceId");
+ requireEqual(
+ text(scope, "gameInstanceId"),
+ targetEvidence.canonicalGameInstanceId().toString(),
+ "target canonicalGameInstanceId");
+ requireEqual(text(scope, "characterId"), candidate.characterId().toString(), "characterId");
+ requireEqual(text(scope, "sessionId"), candidate.sessionId(), "sessionId");
+ requireEqual(
+ positiveString(scope, "bindingGeneration"), bindingGeneration, "bindingGeneration");
+ requireEqual(
+ positiveString(scope, "catalogRevision"),
+ BigInteger.valueOf(targetEvidence.catalogRevision()),
+ "catalogRevision");
+ requireEqual(
+ positiveString(scope, "pointerVersion"),
+ BigInteger.valueOf(targetEvidence.pointerVersion()),
+ "pointerVersion");
+ requireEqual(text(scope, "regionId"), candidate.regionId().toString(), "regionId");
+ requireEqual(positiveString(scope, "regionEpoch"), candidate.regionEpoch(), "regionEpoch");
+ requireEqual(
+ BigInteger.valueOf(targetEvidence.gameInstanceId()),
+ BigInteger.valueOf(candidate.runtimeGameInstanceId()),
+ "runtimeGameInstanceId");
+
+ Object expectedOld = carrier.get("expectedOldBindingGeneration");
+ this.expectedOldBindingGeneration =
+ expectedOld == null ? null : positiveString(carrier, "expectedOldBindingGeneration");
+ if (!Objects.equals(this.expectedOldBindingGeneration, expectedOldBindingGeneration)) {
+ throw new IllegalArgumentException(
+ "lease expectedOldBindingGeneration differs from the durable prior generation");
+ }
+ if (leaseEvidence.leaseKind() == AccountGameplayAdmissionLeaseEvidence.LeaseKind.RESUME) {
+ if (expectedOldBindingGeneration == null) {
+ throw new IllegalArgumentException(
+ "RESUME lease requires an exact durable prior generation");
+ }
+ this.resumeEpisodeId = UUID.fromString(text(carrier, "resumeEpisodeId"));
+ } else {
+ this.resumeEpisodeId = null;
+ }
+ }
+
+ /** The existing transition ID is the binding decision ID; no second decision ledger is used. */
+ public UUID bindingDecisionId() {
+ return bindingDecisionId;
+ }
+
+ public UUID transitionId() {
+ return bindingDecisionId;
+ }
+
+ public UUID requestId() {
+ return UUID.fromString(text(leaseEvidence.carrier(), "requestId"));
+ }
+
+ public UUID leaseId() {
+ return UUID.fromString(text(leaseEvidence.carrier(), "leaseId"));
+ }
+
+ public BigInteger leaseFence() {
+ return leaseEvidence.leaseFence();
+ }
+
+ public String leaseSha256() {
+ return leaseEvidence.sha256();
+ }
+
+ /** Returns the complete canonical evidence unchanged, including its authority and checkpoints. */
+ public String leaseEvidenceJson() {
+ return leaseEvidence.canonicalJson();
+ }
+
+ public BigInteger leaseExpiresAtEpochMillis() {
+ return positiveString(leaseEvidence.carrier(), "expiresAt");
+ }
+
+ public AccountGameplayAdmissionLeaseEvidence leaseEvidence() {
+ return leaseEvidence;
+ }
+
+ public AccountGameplayAdmissionLeaseEvidence.LeaseKind leaseKind() {
+ return leaseEvidence.leaseKind();
+ }
+
+ public UUID resumeEpisodeId() {
+ return resumeEpisodeId;
+ }
+
+ public BigInteger expectedOldBindingGeneration() {
+ return expectedOldBindingGeneration;
+ }
+
+ public CanonicalGameplayBindingIdentity candidate() {
+ return candidate;
+ }
+
+ public BigInteger bindingGeneration() {
+ return bindingGeneration;
+ }
+
+ /**
+ * The exact point-in-time catalog, OPEN pointer, and launch evidence re-read for this decision.
+ */
+ public CanonicalPlayableTarget targetEvidence() {
+ return targetEvidence;
+ }
+
+ public Status status() {
+ return Status.PROVISIONAL;
+ }
+
+ public enum Status {
+ PROVISIONAL
+ }
+
+ private static UUID requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (new UUID(0L, 0L).equals(value)) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ return value;
+ }
+
+ private static BigInteger requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ return value;
+ }
+
+ private static Map object(Object value, String name) {
+ if (!(value instanceof Map, ?> map)) {
+ throw new IllegalArgumentException("Lease evidence has no object " + name);
+ }
+ @SuppressWarnings("unchecked")
+ Map result = (Map) map;
+ return result;
+ }
+
+ private static String text(Map value, String name) {
+ Object field = value.get(name);
+ if (!(field instanceof String text) || text.isBlank()) {
+ throw new IllegalArgumentException("Lease evidence has no canonical text " + name);
+ }
+ return text;
+ }
+
+ private static BigInteger positiveString(Map value, String name) {
+ String text = text(value, name);
+ if (!text.matches("[1-9][0-9]*")) {
+ throw new IllegalArgumentException(
+ "Lease evidence has no canonical positive integer " + name);
+ }
+ return new BigInteger(text);
+ }
+
+ private static void requireEqual(Object actual, Object expected, String name) {
+ if (!Objects.equals(actual, expected)) {
+ throw new IllegalArgumentException("Lease bindingScope differs from exact " + name);
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingAccountIndexObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingAccountIndexObligation.java
new file mode 100644
index 0000000000..775a95ebe6
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingAccountIndexObligation.java
@@ -0,0 +1,103 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Exact member-level account-index work; REQUIRED is not evidence of execution or readback. */
+public record CanonicalGameplayBindingAccountIndexObligation(
+ UUID transitionId,
+ int ordinal,
+ CanonicalGameplayBindingRef bindingRef,
+ UUID accountId,
+ UUID tenantId,
+ Action action,
+ BigInteger bindingGeneration,
+ BigInteger expectedPriorGeneration,
+ UUID accountIndexFence,
+ ExecutionPhase executionPhase,
+ Status status,
+ BigInteger inventoryRevision,
+ ProjectionState projectionState,
+ String projectedMember,
+ BigInteger projectionInventoryRevision) {
+ public CanonicalGameplayBindingAccountIndexObligation {
+ requireNonNil(transitionId, "transitionId");
+ if (ordinal < 0) {
+ throw new IllegalArgumentException("ordinal must not be negative");
+ }
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ requireNonNil(accountId, "accountId");
+ requireNonNil(tenantId, "tenantId");
+ Objects.requireNonNull(action, "action");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ if (expectedPriorGeneration != null && expectedPriorGeneration.signum() < 0) {
+ throw new IllegalArgumentException("expectedPriorGeneration must not be negative");
+ }
+ requireNonNil(accountIndexFence, "accountIndexFence");
+ Objects.requireNonNull(executionPhase, "executionPhase");
+ Objects.requireNonNull(status, "status");
+ requirePositive(inventoryRevision, "inventoryRevision");
+ Objects.requireNonNull(projectionState, "projectionState");
+ switch (projectionState) {
+ case REQUIRED -> {
+ if (projectedMember != null || projectionInventoryRevision != null) {
+ throw new IllegalArgumentException(
+ "unobserved account-index obligation cannot carry Redis readback evidence");
+ }
+ }
+ case PRESENT_AWAITING_COVERAGE -> {
+ if (projectedMember == null || projectedMember.isBlank()) {
+ throw new IllegalArgumentException(
+ "present account-index projection requires the exact Redis member");
+ }
+ requirePositive(projectionInventoryRevision, "projectionInventoryRevision");
+ }
+ case ABSENT_AWAITING_COVERAGE -> {
+ if (projectedMember != null) {
+ throw new IllegalArgumentException(
+ "absent account-index projection cannot carry a present member");
+ }
+ requirePositive(projectionInventoryRevision, "projectionInventoryRevision");
+ }
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum Action {
+ ADD_OR_RETAIN,
+ REMOVE
+ }
+
+ public enum ExecutionPhase {
+ BEFORE_FINAL_CAS,
+ AFTER_FINAL_CAS
+ }
+
+ public enum Status {
+ REQUIRED
+ }
+
+ /**
+ * Local Redis observation is retained separately from the still-required v2 owner
+ * acknowledgement. It is never admission evidence or account-wide coverage proof.
+ */
+ public enum ProjectionState {
+ REQUIRED,
+ PRESENT_AWAITING_COVERAGE,
+ ABSENT_AWAITING_COVERAGE
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingAccountIndexProjectionReceipt.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingAccountIndexProjectionReceipt.java
new file mode 100644
index 0000000000..6b6e25cf35
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingAccountIndexProjectionReceipt.java
@@ -0,0 +1,65 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * Durable exact-member Redis readback evidence retained while the canonical v2 account-index
+ * acknowledgement is still outstanding.
+ */
+public record CanonicalGameplayBindingAccountIndexProjectionReceipt(
+ UUID transitionId,
+ int obligationOrdinal,
+ CanonicalGameplayBindingRef bindingRef,
+ UUID accountId,
+ UUID tenantId,
+ BigInteger bindingGeneration,
+ UUID accountIndexFence,
+ BigInteger bindingInventoryRevision,
+ BigInteger projectionInventoryRevision,
+ String member,
+ State state) {
+ public CanonicalGameplayBindingAccountIndexProjectionReceipt {
+ requireNonNil(transitionId, "transitionId");
+ if (obligationOrdinal < 0) {
+ throw new IllegalArgumentException("obligationOrdinal must not be negative");
+ }
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ requireNonNil(accountId, "accountId");
+ requireNonNil(tenantId, "tenantId");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ requireNonNil(accountIndexFence, "accountIndexFence");
+ requirePositive(bindingInventoryRevision, "bindingInventoryRevision");
+ requirePositive(projectionInventoryRevision, "projectionInventoryRevision");
+ Objects.requireNonNull(member, "member");
+ Objects.requireNonNull(state, "state");
+ if (state != State.PRESENT_AWAITING_COVERAGE) {
+ throw new IllegalArgumentException("only retained exact PRESENT readback is supported here");
+ }
+ var expected =
+ new CanonicalGameplayAccountIndexMember(bindingRef, bindingGeneration, accountIndexFence)
+ .value();
+ if (!expected.equals(member)) {
+ throw new IllegalArgumentException("member does not match the exact durable binding tuple");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum State {
+ PRESENT_AWAITING_COVERAGE
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIdentity.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIdentity.java
new file mode 100644
index 0000000000..6e2c8f09ca
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIdentity.java
@@ -0,0 +1,85 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Canonical binding identity and separately retained runtime/issuer routing evidence. */
+public record CanonicalGameplayBindingIdentity(
+ UUID accountId,
+ UUID tenantId,
+ UUID playableStateNamespaceId,
+ UUID characterId,
+ String playableStateScope,
+ UUID gameInstanceId,
+ long runtimeGameInstanceId,
+ String sessionId,
+ UUID regionId,
+ BigInteger regionEpoch,
+ UUID issuerId,
+ BigInteger issuerAuthGeneration,
+ BigInteger issuerIndexLayoutVersion,
+ BigInteger issuerIndexPartitionCount,
+ BigInteger issuerIndexPartitionCapacity) {
+ public CanonicalGameplayBindingIdentity {
+ Objects.requireNonNull(accountId, "accountId");
+ Objects.requireNonNull(tenantId, "tenantId");
+ Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId");
+ Objects.requireNonNull(characterId, "characterId");
+ Objects.requireNonNull(playableStateScope, "playableStateScope");
+ Objects.requireNonNull(gameInstanceId, "gameInstanceId");
+ Objects.requireNonNull(sessionId, "sessionId");
+ Objects.requireNonNull(regionId, "regionId");
+ Objects.requireNonNull(regionEpoch, "regionEpoch");
+ Objects.requireNonNull(issuerId, "issuerId");
+ Objects.requireNonNull(issuerAuthGeneration, "issuerAuthGeneration");
+ Objects.requireNonNull(issuerIndexLayoutVersion, "issuerIndexLayoutVersion");
+ Objects.requireNonNull(issuerIndexPartitionCount, "issuerIndexPartitionCount");
+ Objects.requireNonNull(issuerIndexPartitionCapacity, "issuerIndexPartitionCapacity");
+ requireNonNil(accountId, "accountId");
+ requireNonNil(tenantId, "tenantId");
+ requireNonNil(playableStateNamespaceId, "playableStateNamespaceId");
+ requireNonNil(characterId, "characterId");
+ requireNonNil(gameInstanceId, "gameInstanceId");
+ if (runtimeGameInstanceId <= 0L) {
+ throw new IllegalArgumentException("runtimeGameInstanceId must be positive");
+ }
+ requireNonNil(regionId, "regionId");
+ requireNonNil(issuerId, "issuerId");
+ if (!playableStateScope.equals("SHARED") && !playableStateScope.equals("ISOLATED")) {
+ throw new IllegalArgumentException("playableStateScope must be SHARED or ISOLATED");
+ }
+ requirePositive(regionEpoch, "regionEpoch");
+ requirePositive(issuerAuthGeneration, "issuerAuthGeneration");
+ requirePositive(issuerIndexLayoutVersion, "issuerIndexLayoutVersion");
+ requirePositive(issuerIndexPartitionCount, "issuerIndexPartitionCount");
+ requirePositive(issuerIndexPartitionCapacity, "issuerIndexPartitionCapacity");
+ // Validate the canonical session identifier now; no normalization is performed.
+ try {
+ UUID canonicalSessionId = UUID.fromString(sessionId);
+ if (!canonicalSessionId.toString().equals(sessionId)) {
+ throw new IllegalArgumentException("sessionId must use canonical UUID text");
+ }
+ requireNonNil(canonicalSessionId, "sessionId");
+ } catch (IllegalArgumentException malformed) {
+ throw new IllegalArgumentException("sessionId must use canonical UUID text", malformed);
+ }
+ CanonicalGameplayBindingRef.of(tenantId, gameInstanceId, sessionId);
+ }
+
+ public CanonicalGameplayBindingRef bindingRef() {
+ return CanonicalGameplayBindingRef.of(tenantId, gameInstanceId, sessionId);
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingInventoryEntry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingInventoryEntry.java
new file mode 100644
index 0000000000..b836d88ac6
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingInventoryEntry.java
@@ -0,0 +1,61 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** One exact canonical binding row in a repeatable Game Session inventory snapshot. */
+public record CanonicalGameplayBindingInventoryEntry(
+ CanonicalGameplayBindingIdentity identity,
+ CanonicalGameplayBindingRef bindingRef,
+ BigInteger bindingGeneration,
+ UUID accountIndexFence,
+ UUID issuerReservationId,
+ UUID transitionId,
+ Lifecycle lifecycle,
+ IndexState accountIndexState,
+ IndexState issuerIndexState,
+ BigInteger inventoryRevision) {
+ public CanonicalGameplayBindingInventoryEntry {
+ Objects.requireNonNull(identity, "identity");
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ requireNonNil(accountIndexFence, "accountIndexFence");
+ requireNonNil(issuerReservationId, "issuerReservationId");
+ requireNonNil(transitionId, "transitionId");
+ Objects.requireNonNull(lifecycle, "lifecycle");
+ Objects.requireNonNull(accountIndexState, "accountIndexState");
+ Objects.requireNonNull(issuerIndexState, "issuerIndexState");
+ requirePositive(inventoryRevision, "inventoryRevision");
+ if (!identity.bindingRef().equals(bindingRef)) {
+ throw new IllegalArgumentException("stored bindingRef does not match canonical identity");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum Lifecycle {
+ CANDIDATE_PREPARED,
+ PROVISIONAL,
+ ACTIVE,
+ TERMINAL_UNRESOLVED,
+ TERMINAL
+ }
+
+ public enum IndexState {
+ REPAIR_REQUIRED,
+ ACKNOWLEDGED
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingInventorySnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingInventorySnapshot.java
new file mode 100644
index 0000000000..99f2d169e7
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingInventorySnapshot.java
@@ -0,0 +1,46 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.List;
+import java.util.Objects;
+
+/** Immutable full inventory read; the revision and every typed row come from one DB snapshot. */
+public record CanonicalGameplayBindingInventorySnapshot(
+ BigInteger inventoryRevision,
+ List bindings,
+ List transitions,
+ List reservations,
+ List accountIndexObligations,
+ List issuerIndexObligations,
+ List regionBridgeObligations) {
+ public CanonicalGameplayBindingInventorySnapshot {
+ Objects.requireNonNull(inventoryRevision, "inventoryRevision");
+ if (inventoryRevision.signum() < 0) {
+ throw new IllegalArgumentException("inventoryRevision must not be negative");
+ }
+ bindings = List.copyOf(Objects.requireNonNull(bindings, "bindings"));
+ transitions = List.copyOf(Objects.requireNonNull(transitions, "transitions"));
+ reservations = List.copyOf(Objects.requireNonNull(reservations, "reservations"));
+ accountIndexObligations =
+ List.copyOf(Objects.requireNonNull(accountIndexObligations, "accountIndexObligations"));
+ issuerIndexObligations =
+ List.copyOf(Objects.requireNonNull(issuerIndexObligations, "issuerIndexObligations"));
+ regionBridgeObligations =
+ List.copyOf(Objects.requireNonNull(regionBridgeObligations, "regionBridgeObligations"));
+ if (bindings.stream().anyMatch(row -> row.inventoryRevision().compareTo(inventoryRevision) > 0)
+ || transitions.stream()
+ .anyMatch(row -> row.inventoryRevision().compareTo(inventoryRevision) > 0)
+ || reservations.stream()
+ .anyMatch(row -> row.inventoryRevision().compareTo(inventoryRevision) > 0)) {
+ throw new IllegalArgumentException("snapshot cannot contain rows newer than its revision");
+ }
+ if (accountIndexObligations.stream()
+ .anyMatch(row -> row.inventoryRevision().compareTo(inventoryRevision) > 0)
+ || issuerIndexObligations.stream()
+ .anyMatch(row -> row.inventoryRevision().compareTo(inventoryRevision) > 0)
+ || regionBridgeObligations.stream()
+ .anyMatch(row -> row.inventoryRevision().compareTo(inventoryRevision) > 0)) {
+ throw new IllegalArgumentException("snapshot cannot contain obligations newer than revision");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java
new file mode 100644
index 0000000000..55cd2f72fb
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java
@@ -0,0 +1,41 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Issuer-index obligation joined to one exact capacity reservation. */
+public record CanonicalGameplayBindingIssuerIndexObligation(
+ UUID transitionId,
+ CanonicalGameplayBindingRef bindingRef,
+ BigInteger bindingGeneration,
+ UUID reservationId,
+ Status status,
+ BigInteger inventoryRevision) {
+ public CanonicalGameplayBindingIssuerIndexObligation {
+ requireNonNil(transitionId, "transitionId");
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ requireNonNil(reservationId, "reservationId");
+ Objects.requireNonNull(status, "status");
+ requirePositive(inventoryRevision, "inventoryRevision");
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum Status {
+ REQUIRED
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingProvisionalCasEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingProvisionalCasEvidence.java
new file mode 100644
index 0000000000..fa7725cce3
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingProvisionalCasEvidence.java
@@ -0,0 +1,98 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.util.Objects;
+
+/** Exact durable source/candidate tuple allowed to attempt the non-admitting tenant-local CAS. */
+public record CanonicalGameplayBindingProvisionalCasEvidence(
+ CanonicalGameplayBindingTransitionSnapshot transition,
+ CanonicalGameplayBindingInventoryEntry candidate,
+ CanonicalIssuerPartitionReservation candidateReservation,
+ CanonicalGameplayBindingInventoryEntry expectedPrior,
+ CanonicalIssuerPartitionReservation expectedPriorReservation,
+ CanonicalGameplayLegacyMigrationDisposition initialBindingMigrationDisposition) {
+ public CanonicalGameplayBindingProvisionalCasEvidence {
+ Objects.requireNonNull(transition, "transition");
+ Objects.requireNonNull(candidate, "candidate");
+ Objects.requireNonNull(candidateReservation, "candidateReservation");
+ if ((expectedPrior == null) != (expectedPriorReservation == null)) {
+ throw new IllegalArgumentException(
+ "expected prior binding and its reservation must be supplied together");
+ }
+ boolean initialBinding = expectedPrior == null;
+ if ((transition.expectedPriorBindingRef() == null) != initialBinding
+ || (transition.expectedPriorBindingGeneration() == null) != initialBinding) {
+ throw new IllegalArgumentException(
+ "nullable prior source must match the exact durable transition tuple");
+ }
+ if (initialBinding != (initialBindingMigrationDisposition != null)) {
+ throw new IllegalArgumentException(
+ "first binding requires an exact VERIFIED legacy migration disposition;"
+ + " transfers do not");
+ }
+
+ if (transition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED
+ && transition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) {
+ throw new IllegalArgumentException("transition is not a retryable provisional operation");
+ }
+ CanonicalGameplayBindingInventoryEntry.Lifecycle expectedCandidateLifecycle =
+ transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED
+ ? CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED
+ : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL;
+ if (candidate.lifecycle() != expectedCandidateLifecycle
+ || candidate.accountIndexState()
+ != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED
+ || candidate.issuerIndexState()
+ != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) {
+ throw new IllegalArgumentException("candidate is not an exact non-admissible transition row");
+ }
+ CanonicalGameplayBindingIdentity next = candidate.identity();
+ if (!candidate.bindingRef().equals(transition.bindingRef())
+ || !candidate.transitionId().equals(transition.transitionId())
+ || !candidate.bindingGeneration().equals(transition.bindingGeneration())
+ || !candidate.accountIndexFence().equals(transition.candidateAccountIndexFence())
+ || !candidateReservation.reservationId().equals(transition.issuerReservationId())
+ || !candidateReservation.reservationFence().equals(transition.reservationFence())
+ || !candidateReservation.owner().equals(next)
+ || !candidateReservation.bindingGeneration().equals(candidate.bindingGeneration())
+ || !candidateReservation.transitionId().equals(transition.transitionId())
+ || !candidateReservation.inventoryRevision().equals(transition.inventoryRevision())
+ || candidateReservation.lifecycle()
+ != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) {
+ throw new IllegalArgumentException(
+ "candidate and reservation are not the exact transition row");
+ }
+
+ if (initialBinding) {
+ if (transition.expectedPriorBindingRef() != null
+ || transition.expectedPriorBindingGeneration() != null) {
+ throw new IllegalArgumentException("initial binding must carry no prior generation");
+ }
+ } else {
+ CanonicalGameplayBindingIdentity prior = expectedPrior.identity();
+ if (expectedPrior.lifecycle() != CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE
+ || expectedPrior.accountIndexState()
+ != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED
+ || expectedPrior.issuerIndexState()
+ != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED
+ || !Objects.equals(expectedPrior.bindingRef(), transition.expectedPriorBindingRef())
+ || !Objects.equals(
+ expectedPrior.bindingGeneration(), transition.expectedPriorBindingGeneration())
+ || !next.accountId().equals(prior.accountId())
+ || !next.tenantId().equals(prior.tenantId())
+ || !next.playableStateNamespaceId().equals(prior.playableStateNamespaceId())
+ || !next.characterId().equals(prior.characterId())
+ || !expectedPriorReservation.reservationId().equals(expectedPrior.issuerReservationId())
+ || !expectedPriorReservation.owner().equals(prior)
+ || !expectedPriorReservation.bindingGeneration().equals(expectedPrior.bindingGeneration())
+ || !expectedPriorReservation.transitionId().equals(expectedPrior.transitionId())
+ || !expectedPriorReservation.inventoryRevision().equals(expectedPrior.inventoryRevision())
+ || expectedPriorReservation.lifecycle()
+ != CanonicalIssuerPartitionReservation.Lifecycle.BOUND
+ || next.equals(prior)
+ || candidate.bindingGeneration().compareTo(expectedPrior.bindingGeneration()) <= 0) {
+ throw new IllegalArgumentException(
+ "candidate and prior do not form the exact controller transfer");
+ }
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRef.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRef.java
new file mode 100644
index 0000000000..bae5d79dcb
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRef.java
@@ -0,0 +1,190 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Exact {@code bindingRef/v1} bytes used by the canonical issuer-partition contract. */
+public final class CanonicalGameplayBindingRef {
+ private static final byte[] DOMAIN = "bindingRef/v1".getBytes(StandardCharsets.US_ASCII);
+
+ private final byte[] bytes;
+
+ private CanonicalGameplayBindingRef(byte[] bytes) {
+ this.bytes = bytes.clone();
+ }
+
+ public static CanonicalGameplayBindingRef of(
+ UUID tenantId, UUID gameInstanceId, String sessionId) {
+ Objects.requireNonNull(tenantId, "tenantId");
+ Objects.requireNonNull(gameInstanceId, "gameInstanceId");
+ return of(tenantId.toString(), gameInstanceId.toString(), sessionId);
+ }
+
+ public static CanonicalGameplayBindingRef of(
+ String tenantId, String gameInstanceId, String sessionId) {
+ byte[] tenantBytes = encodeCanonicalIdentifier(tenantId, "tenantId");
+ byte[] instanceBytes = encodeCanonicalIdentifier(gameInstanceId, "gameInstanceId");
+ byte[] sessionBytes = encodeCanonicalIdentifier(sessionId, "sessionId");
+
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ appendSegment(output, DOMAIN);
+ appendSegment(output, tenantBytes);
+ appendSegment(output, instanceBytes);
+ appendSegment(output, sessionBytes);
+ return new CanonicalGameplayBindingRef(output.toByteArray());
+ }
+
+ /** Rehydrates an exact persisted carrier without translating or normalizing its segments. */
+ public static CanonicalGameplayBindingRef fromExactBytes(byte[] exactBytes) {
+ Objects.requireNonNull(exactBytes, "exactBytes");
+ Cursor cursor = new Cursor(exactBytes);
+ byte[] domain = cursor.readSegment();
+ if (!Arrays.equals(domain, DOMAIN)) {
+ throw new IllegalArgumentException("bindingRef has an unsupported version prefix");
+ }
+ validateIdentifierSegment(cursor.readSegment(), "tenantId");
+ validateIdentifierSegment(cursor.readSegment(), "gameInstanceId");
+ validateIdentifierSegment(cursor.readSegment(), "sessionId");
+ if (!cursor.atEnd()) {
+ throw new IllegalArgumentException("bindingRef contains trailing bytes");
+ }
+ return new CanonicalGameplayBindingRef(exactBytes);
+ }
+
+ public byte[] bytes() {
+ return bytes.clone();
+ }
+
+ /** Applies the canonical unsigned-big-endian SHA-256 partition function. */
+ public int partitionId(int partitionCount) {
+ if (partitionCount <= 0) {
+ throw new IllegalArgumentException("partitionCount must be positive");
+ }
+ return partitionId(BigInteger.valueOf(partitionCount)).intValueExact();
+ }
+
+ /** Applies the canonical partition function without narrowing the configured count. */
+ public BigInteger partitionId(BigInteger partitionCount) {
+ Objects.requireNonNull(partitionCount, "partitionCount");
+ if (partitionCount.signum() <= 0) {
+ throw new IllegalArgumentException("partitionCount must be positive");
+ }
+ try {
+ byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes);
+ return new BigInteger(1, digest).mod(partitionCount);
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("JVM does not provide SHA-256", impossible);
+ }
+ }
+
+ private static byte[] encodeCanonicalIdentifier(String value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.isEmpty() || !value.equals(value.strip())) {
+ throw new IllegalArgumentException(name + " must be a non-empty canonical identifier");
+ }
+ for (int offset = 0; offset < value.length(); ) {
+ int codePoint = value.codePointAt(offset);
+ if (Character.isISOControl(codePoint)) {
+ throw new IllegalArgumentException(name + " must not contain control characters");
+ }
+ offset += Character.charCount(codePoint);
+ }
+ try {
+ ByteBuffer encoded =
+ StandardCharsets.UTF_8
+ .newEncoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .encode(CharBuffer.wrap(value));
+ byte[] bytes = new byte[encoded.remaining()];
+ encoded.get(bytes);
+ return bytes;
+ } catch (CharacterCodingException malformed) {
+ throw new IllegalArgumentException(name + " must be valid UTF-8", malformed);
+ }
+ }
+
+ private static void appendSegment(ByteArrayOutputStream output, byte[] bytes) {
+ byte[] length = Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII);
+ output.writeBytes(length);
+ output.write(':');
+ output.writeBytes(bytes);
+ }
+
+ private static void validateIdentifierSegment(byte[] bytes, String name) {
+ try {
+ String value =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ if (!Arrays.equals(bytes, encodeCanonicalIdentifier(value, name))) {
+ throw new IllegalArgumentException(name + " does not retain its exact UTF-8 bytes");
+ }
+ } catch (CharacterCodingException malformed) {
+ throw new IllegalArgumentException(name + " must be valid UTF-8", malformed);
+ }
+ }
+
+ private static final class Cursor {
+ private final byte[] bytes;
+ private int offset;
+
+ private Cursor(byte[] bytes) {
+ this.bytes = bytes.clone();
+ }
+
+ private byte[] readSegment() {
+ int start = offset;
+ while (offset < bytes.length && bytes[offset] >= '0' && bytes[offset] <= '9') {
+ offset++;
+ }
+ if (start == offset || offset >= bytes.length || bytes[offset] != ':') {
+ throw new IllegalArgumentException("bindingRef segment has an invalid byte length");
+ }
+ if (offset - start > 1 && bytes[start] == '0') {
+ throw new IllegalArgumentException("bindingRef segment length has a leading zero");
+ }
+ int length;
+ try {
+ length =
+ Integer.parseInt(new String(bytes, start, offset - start, StandardCharsets.US_ASCII));
+ } catch (NumberFormatException malformedLength) {
+ throw new IllegalArgumentException("bindingRef segment length is invalid", malformedLength);
+ }
+ offset++;
+ if (length < 0 || bytes.length - offset < length) {
+ throw new IllegalArgumentException("bindingRef segment is truncated");
+ }
+ byte[] segment = Arrays.copyOfRange(bytes, offset, offset + length);
+ offset += length;
+ return segment;
+ }
+
+ private boolean atEnd() {
+ return offset == bytes.length;
+ }
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof CanonicalGameplayBindingRef ref && Arrays.equals(bytes, ref.bytes);
+ }
+
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(bytes);
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java
new file mode 100644
index 0000000000..17ba59d994
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java
@@ -0,0 +1,55 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Exact intended region-lease bridge tuple; it contains no acknowledgement or success claim. */
+public record CanonicalGameplayBindingRegionBridgeObligation(
+ UUID transitionId,
+ CanonicalGameplayBindingRef bindingRef,
+ BigInteger bindingGeneration,
+ UUID accountId,
+ UUID tenantId,
+ UUID gameInstanceId,
+ long runtimeGameInstanceId,
+ String sessionId,
+ UUID regionId,
+ BigInteger regionEpoch,
+ Status status,
+ BigInteger inventoryRevision) {
+ public CanonicalGameplayBindingRegionBridgeObligation {
+ requireNonNil(transitionId, "transitionId");
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ requireNonNil(accountId, "accountId");
+ requireNonNil(tenantId, "tenantId");
+ requireNonNil(gameInstanceId, "gameInstanceId");
+ if (runtimeGameInstanceId <= 0L) {
+ throw new IllegalArgumentException("runtimeGameInstanceId must be positive");
+ }
+ Objects.requireNonNull(sessionId, "sessionId");
+ requireNonNil(regionId, "regionId");
+ requirePositive(regionEpoch, "regionEpoch");
+ Objects.requireNonNull(status, "status");
+ requirePositive(inventoryRevision, "inventoryRevision");
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum Status {
+ REQUIRED
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingTransitionRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingTransitionRequest.java
new file mode 100644
index 0000000000..f1511f26a6
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingTransitionRequest.java
@@ -0,0 +1,35 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Caller-owned transition identity and exact prior-binding compare tuple. */
+public record CanonicalGameplayBindingTransitionRequest(
+ UUID transitionId,
+ UUID candidateAccountIndexFence,
+ CanonicalGameplayBindingIdentity candidate,
+ CanonicalIssuerReservationFenceEvidence issuerReservation,
+ CanonicalGameplayBindingRef expectedPriorBindingRef,
+ BigInteger expectedPriorBindingGeneration) {
+ public CanonicalGameplayBindingTransitionRequest {
+ requireNonNil(transitionId, "transitionId");
+ requireNonNil(candidateAccountIndexFence, "candidateAccountIndexFence");
+ Objects.requireNonNull(candidate, "candidate");
+ Objects.requireNonNull(issuerReservation, "issuerReservation");
+ if ((expectedPriorBindingRef == null) != (expectedPriorBindingGeneration == null)) {
+ throw new IllegalArgumentException(
+ "expected prior binding ref and generation must be supplied together");
+ }
+ if (expectedPriorBindingGeneration != null && expectedPriorBindingGeneration.signum() <= 0) {
+ throw new IllegalArgumentException("expectedPriorBindingGeneration must be positive");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingTransitionSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingTransitionSnapshot.java
new file mode 100644
index 0000000000..f411f1976b
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingTransitionSnapshot.java
@@ -0,0 +1,67 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Durable prepared candidate; PREPARED is explicitly non-admissible. */
+public record CanonicalGameplayBindingTransitionSnapshot(
+ UUID transitionId,
+ CanonicalGameplayBindingIdentity candidate,
+ BigInteger bindingGeneration,
+ CanonicalGameplayBindingRef bindingRef,
+ BigInteger inventoryRevision,
+ UUID issuerReservationId,
+ UUID reservationFence,
+ UUID candidateAccountIndexFence,
+ CanonicalGameplayBindingRef expectedPriorBindingRef,
+ BigInteger expectedPriorBindingGeneration,
+ Status status,
+ CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence) {
+ public CanonicalGameplayBindingTransitionSnapshot {
+ Objects.requireNonNull(transitionId, "transitionId");
+ Objects.requireNonNull(candidate, "candidate");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ Objects.requireNonNull(bindingRef, "bindingRef");
+ requirePositive(inventoryRevision, "inventoryRevision");
+ Objects.requireNonNull(issuerReservationId, "issuerReservationId");
+ Objects.requireNonNull(reservationFence, "reservationFence");
+ Objects.requireNonNull(candidateAccountIndexFence, "candidateAccountIndexFence");
+ if (candidateAccountIndexFence.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException("candidateAccountIndexFence must not be nil");
+ }
+ Objects.requireNonNull(status, "status");
+ Objects.requireNonNull(accountCoverageEvidence, "accountCoverageEvidence");
+ if (accountCoverageEvidence
+ instanceof CanonicalGameplayAccountCoverageEvidence.Historical historical
+ && !historical.accountId().equals(candidate.accountId())) {
+ throw new IllegalArgumentException(
+ "historical account coverage evidence belongs to another account");
+ }
+ if ((expectedPriorBindingRef == null) != (expectedPriorBindingGeneration == null)) {
+ throw new IllegalArgumentException(
+ "expected prior binding ref and generation must be supplied together");
+ }
+ if (expectedPriorBindingGeneration != null && expectedPriorBindingGeneration.signum() <= 0) {
+ throw new IllegalArgumentException("expectedPriorBindingGeneration must be positive");
+ }
+ if (!bindingRef.equals(candidate.bindingRef())) {
+ throw new IllegalArgumentException("bindingRef must be derived from candidate identity");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum Status {
+ PREPARED,
+ PROVISIONAL,
+ COMMITTED,
+ ABORTED,
+ AMBIGUOUS
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationDisposition.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationDisposition.java
new file mode 100644
index 0000000000..38f4a7217d
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationDisposition.java
@@ -0,0 +1,41 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Typed receipt required before global account-index coverage may acquire its account fence. */
+public record CanonicalGameplayLegacyMigrationDisposition(
+ UUID cohortId,
+ UUID ownerOperationId,
+ UUID legacyWriterFence,
+ BigInteger sourceSnapshotRevision,
+ BigInteger canonicalInventoryRevision,
+ BigInteger namespaceIndexReadbackRevision,
+ String evidenceDigest) {
+ public CanonicalGameplayLegacyMigrationDisposition {
+ requireNonNil(cohortId, "cohortId");
+ requireNonNil(ownerOperationId, "ownerOperationId");
+ requireNonNil(legacyWriterFence, "legacyWriterFence");
+ requirePositive(sourceSnapshotRevision, "sourceSnapshotRevision");
+ requirePositive(canonicalInventoryRevision, "canonicalInventoryRevision");
+ requirePositive(namespaceIndexReadbackRevision, "namespaceIndexReadbackRevision");
+ if (evidenceDigest == null || !evidenceDigest.matches("sha256:[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("evidenceDigest must be a canonical SHA-256 digest");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationReadback.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationReadback.java
new file mode 100644
index 0000000000..1693eae4df
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationReadback.java
@@ -0,0 +1,30 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.util.List;
+import java.util.Objects;
+
+/** Exact typed session-record and controller-index observations returned by the Redis owner. */
+public record CanonicalGameplayLegacyMigrationReadback(
+ List sessionRecords,
+ List characterIndexRecords,
+ List remainingLegacySourceKeyDigests,
+ List unexpectedNamespaceKeyDigests) {
+ public CanonicalGameplayLegacyMigrationReadback {
+ sessionRecords = List.copyOf(Objects.requireNonNull(sessionRecords, "sessionRecords"));
+ characterIndexRecords =
+ List.copyOf(Objects.requireNonNull(characterIndexRecords, "characterIndexRecords"));
+ remainingLegacySourceKeyDigests =
+ List.copyOf(
+ Objects.requireNonNull(
+ remainingLegacySourceKeyDigests, "remainingLegacySourceKeyDigests"));
+ unexpectedNamespaceKeyDigests =
+ List.copyOf(
+ Objects.requireNonNull(unexpectedNamespaceKeyDigests, "unexpectedNamespaceKeyDigests"));
+ if (sessionRecords.stream().anyMatch(Objects::isNull)
+ || characterIndexRecords.stream().anyMatch(Objects::isNull)
+ || remainingLegacySourceKeyDigests.stream().anyMatch(Objects::isNull)
+ || unexpectedNamespaceKeyDigests.stream().anyMatch(Objects::isNull)) {
+ throw new IllegalArgumentException("Redis readback must not contain null observations");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationSourceSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationSourceSnapshot.java
new file mode 100644
index 0000000000..63cf41d20a
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationSourceSnapshot.java
@@ -0,0 +1,78 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * Sanitized structural inventory of the legacy Redis families. Raw keys and serialized values are
+ * deliberately not retained; a trusted source adapter must enumerate every family itself.
+ */
+public record CanonicalGameplayLegacyMigrationSourceSnapshot(
+ Set scannedFamilies, List entries) {
+ private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}");
+ private static final Set REQUIRED_FAMILIES =
+ Set.copyOf(
+ EnumSet.of(
+ Family.TENANT_SESSION_CONTEXT,
+ Family.SESSION_ALIAS_CONTEXT,
+ Family.GAMEPLAY_IDENTITY_CONTEXT,
+ Family.GAMEPLAY_NAME_CONTEXT,
+ Family.MOVEMENT_EFFECT,
+ Family.DURABLE_EFFECT));
+
+ public CanonicalGameplayLegacyMigrationSourceSnapshot {
+ scannedFamilies = Set.copyOf(Objects.requireNonNull(scannedFamilies, "scannedFamilies"));
+ entries = List.copyOf(Objects.requireNonNull(entries, "entries"));
+ if (entries.stream().anyMatch(Objects::isNull)) {
+ throw new IllegalArgumentException("legacy source entries must not contain null");
+ }
+ if (entries.stream().map(Entry::sourceKeyDigest).distinct().count() != entries.size()) {
+ throw new IllegalArgumentException("legacy source key digests must be unique per snapshot");
+ }
+ }
+
+ /** The adapter must prove these concrete key families, not assert a generic SCAN was empty. */
+ public boolean enumeratedEveryKnownFamily() {
+ return scannedFamilies.equals(REQUIRED_FAMILIES)
+ && entries.stream().noneMatch(entry -> entry.family() == Family.UNCLASSIFIED);
+ }
+
+ /**
+ * V29 intentionally has no legacy numeric-to-UUID/namespace backfill. Until that exact trusted
+ * mapping owner exists, no retained row may be removed or relabelled; only an enumerated empty
+ * legacy cohort is reconciled.
+ */
+ public boolean everyEntryIsReconciled() {
+ return enumeratedEveryKnownFamily() && entries.isEmpty();
+ }
+
+ public enum Family {
+ TENANT_SESSION_CONTEXT,
+ SESSION_ALIAS_CONTEXT,
+ GAMEPLAY_IDENTITY_CONTEXT,
+ GAMEPLAY_NAME_CONTEXT,
+ MOVEMENT_EFFECT,
+ DURABLE_EFFECT,
+ UNCLASSIFIED
+ }
+
+ public enum Disposition {
+ UNMAPPABLE,
+ CREDENTIAL_BEARING,
+ UNKNOWN
+ }
+
+ /** Contains only a key digest and safe structural classification; never an asserted mapping. */
+ public record Entry(Family family, String sourceKeyDigest, Disposition disposition) {
+ public Entry {
+ Objects.requireNonNull(family, "family");
+ Objects.requireNonNull(disposition, "disposition");
+ if (sourceKeyDigest == null || !SHA256.matcher(sourceKeyDigest).matches()) {
+ throw new IllegalArgumentException("sourceKeyDigest must be a canonical SHA-256 digest");
+ }
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java
new file mode 100644
index 0000000000..2009d765b9
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java
@@ -0,0 +1,92 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Credential-free immutable identities tying a migration operation to one physical cohort.
+ *
+ * {@code kubernetesClusterUid} is the trusted factory's kube-system namespace incarnation
+ * identity, paired with separately revalidated cluster kind, node, and network evidence; it is not
+ * claimed to be a Kubernetes Cluster object UID. The storage UID fields may identify an exact
+ * ephemeral volume as {@code namespaceUid/podUid/volumeName}, when backed by the immutable Pod
+ * specification and mount readback; they are not claimed to be PVC object UIDs. The producer Pod,
+ * container, and node fields identify the actual co-located migration owner process and its PG
+ * Pod/container/Node evidence, not the migration-driver container. A trusted factory must retain
+ * and recheck the broader evidence behind these compact identities.
+ */
+public record CanonicalGameplayLegacyMigrationStorageIdentity(
+ String kubernetesClusterUid,
+ String kubernetesNamespaceUid,
+ String producerPodUid,
+ String producerContainerId,
+ String producerNodeUid,
+ String postgresSystemIdentifier,
+ long postgresDatabaseOid,
+ String postgresStorageUid,
+ String redisRunId,
+ String redisStorageUid) {
+ public CanonicalGameplayLegacyMigrationStorageIdentity {
+ requireText(kubernetesClusterUid, "kubernetesClusterUid");
+ requireText(kubernetesNamespaceUid, "kubernetesNamespaceUid");
+ requireText(producerPodUid, "producerPodUid");
+ requireText(producerContainerId, "producerContainerId");
+ requireText(producerNodeUid, "producerNodeUid");
+ requireText(postgresSystemIdentifier, "postgresSystemIdentifier");
+ requireText(postgresStorageUid, "postgresStorageUid");
+ requireText(redisRunId, "redisRunId");
+ requireText(redisStorageUid, "redisStorageUid");
+ if (!postgresSystemIdentifier.matches("[1-9][0-9]{0,19}")
+ || new BigInteger(postgresSystemIdentifier).bitLength() > 64) {
+ throw new IllegalArgumentException("postgresSystemIdentifier must be an unsigned 64-bit id");
+ }
+ if (postgresDatabaseOid <= 0L || postgresDatabaseOid > 0xffff_ffffL) {
+ throw new IllegalArgumentException(
+ "postgresDatabaseOid must be a positive unsigned 32-bit id");
+ }
+ }
+
+ /** Stable digest of the exact, non-secret physical identity tuple. */
+ public String digest() {
+ List fields =
+ List.of(
+ kubernetesClusterUid,
+ kubernetesNamespaceUid,
+ producerPodUid,
+ producerContainerId,
+ producerNodeUid,
+ postgresSystemIdentifier,
+ Long.toUnsignedString(postgresDatabaseOid),
+ postgresStorageUid,
+ redisRunId,
+ redisStorageUid);
+ StringBuilder framed = new StringBuilder("canonical-gameplay-storage-identity/v1|");
+ fields.forEach(
+ field ->
+ framed.append(field.getBytes(StandardCharsets.UTF_8).length).append(':').append(field));
+ try {
+ return "sha256:"
+ + HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(framed.toString().getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException(
+ "SHA-256 is unavailable for migration storage identity", impossible);
+ }
+ }
+
+ private static void requireText(String value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.isBlank()
+ || !value.equals(value.strip())
+ || value.chars().anyMatch(Character::isISOControl)) {
+ throw new IllegalArgumentException(name + " must be a non-blank canonical identity value");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalIssuerPartitionReservation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalIssuerPartitionReservation.java
new file mode 100644
index 0000000000..46a1c67c9a
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalIssuerPartitionReservation.java
@@ -0,0 +1,62 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Complete typed durable reservation evidence, never an aggregate capacity acknowledgement. */
+public record CanonicalIssuerPartitionReservation(
+ UUID reservationId,
+ CanonicalGameplayBindingIdentity owner,
+ BigInteger bindingGeneration,
+ UUID transitionId,
+ BigInteger partitionId,
+ Lifecycle lifecycle,
+ UUID reservationFence,
+ UUID issuerCoverageOperationId,
+ BigInteger issuerCoverageOperationFence,
+ BigInteger coverageFence,
+ BigInteger inventorySnapshotRevision,
+ BigInteger inventoryRevision) {
+ public CanonicalIssuerPartitionReservation {
+ requireNonNil(reservationId, "reservationId");
+ Objects.requireNonNull(owner, "owner");
+ requirePositive(bindingGeneration, "bindingGeneration");
+ requireNonNil(transitionId, "transitionId");
+ Objects.requireNonNull(lifecycle, "lifecycle");
+ requireNonNil(reservationFence, "reservationFence");
+ requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId");
+ requirePositive(issuerCoverageOperationFence, "issuerCoverageOperationFence");
+ requirePositive(coverageFence, "coverageFence");
+ requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision");
+ requirePositive(inventoryRevision, "inventoryRevision");
+ Objects.requireNonNull(partitionId, "partitionId");
+ if (partitionId.signum() < 0 || partitionId.compareTo(owner.issuerIndexPartitionCount()) >= 0) {
+ throw new IllegalArgumentException("partitionId must be within the pinned issuer layout");
+ }
+ if (!partitionId.equals(owner.bindingRef().partitionId(owner.issuerIndexPartitionCount()))) {
+ throw new IllegalArgumentException("partitionId does not match the canonical bindingRef");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ public enum Lifecycle {
+ RESERVED,
+ BOUND,
+ RELEASE_PENDING,
+ RELEASED
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalIssuerReservationFenceEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalIssuerReservationFenceEvidence.java
new file mode 100644
index 0000000000..8e87be9f6d
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalIssuerReservationFenceEvidence.java
@@ -0,0 +1,37 @@
+package net.firedevops.firemud.gamesession.binding;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Caller-owned reservation and coverage fences; this is intent, not acknowledgement evidence. */
+public record CanonicalIssuerReservationFenceEvidence(
+ UUID reservationId,
+ UUID reservationFence,
+ UUID issuerCoverageOperationId,
+ BigInteger issuerCoverageOperationFence,
+ BigInteger coverageFence,
+ BigInteger inventorySnapshotRevision) {
+ public CanonicalIssuerReservationFenceEvidence {
+ requireNonNil(reservationId, "reservationId");
+ requireNonNil(reservationFence, "reservationFence");
+ requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId");
+ requirePositive(issuerCoverageOperationFence, "issuerCoverageOperationFence");
+ requirePositive(coverageFence, "coverageFence");
+ requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision");
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException(name + " must not be nil");
+ }
+ }
+
+ private static void requirePositive(BigInteger value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.signum() <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionOwnerProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionOwnerProof.java
new file mode 100644
index 0000000000..ab0b11d88e
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionOwnerProof.java
@@ -0,0 +1,103 @@
+package net.firedevops.firemud.gamesession.dto;
+
+import java.time.Instant;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+/** Exact Game Session owner readback for one canonical first-OPEN request. */
+public record CanonicalInitialAdmissionOwnerProof(
+ Outcome outcome,
+ String initialAdmissionRequestId,
+ String requestDigest,
+ String targetNamespace,
+ UUID canonicalTenantId,
+ String worldSlug,
+ UUID realmId,
+ UUID playableStateNamespaceId,
+ String playableStateScope,
+ UUID canonicalGameInstanceId,
+ UUID canonicalVersionId,
+ long activeLifecycleEpoch,
+ long expectedCatalogRevision,
+ CanonicalInitialAdmissionRequest.OriginKind originKind,
+ Long expectedPriorPointerVersion,
+ UUID holdId,
+ UUID holdFence,
+ String holdBindingDigest,
+ Long committedPointerVersion,
+ Long auditEventId,
+ String proofDigest,
+ boolean positiveDurableAbort,
+ Instant terminalAt) {
+ public enum Outcome {
+ PENDING,
+ COMMITTED,
+ ABORTED
+ }
+
+ private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern PROOF_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}");
+
+ public CanonicalInitialAdmissionOwnerProof {
+ Objects.requireNonNull(outcome, "outcome");
+ Objects.requireNonNull(initialAdmissionRequestId, "initialAdmissionRequestId");
+ Objects.requireNonNull(requestDigest, "requestDigest");
+ Objects.requireNonNull(targetNamespace, "targetNamespace");
+ Objects.requireNonNull(canonicalTenantId, "canonicalTenantId");
+ Objects.requireNonNull(worldSlug, "worldSlug");
+ Objects.requireNonNull(realmId, "realmId");
+ Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId");
+ Objects.requireNonNull(playableStateScope, "playableStateScope");
+ Objects.requireNonNull(canonicalGameInstanceId, "canonicalGameInstanceId");
+ Objects.requireNonNull(canonicalVersionId, "canonicalVersionId");
+ Objects.requireNonNull(originKind, "originKind");
+ Objects.requireNonNull(holdId, "holdId");
+ Objects.requireNonNull(holdFence, "holdFence");
+ Objects.requireNonNull(holdBindingDigest, "holdBindingDigest");
+ if (!REQUEST_DIGEST.matcher(requestDigest).matches()
+ || !PROOF_DIGEST.matcher(holdBindingDigest).matches()) {
+ throw new IllegalArgumentException("Owner proof digest fields have invalid representations");
+ }
+ if (activeLifecycleEpoch <= 0L || expectedCatalogRevision <= 0L) {
+ throw new IllegalArgumentException("Owner proof contains a non-positive canonical fence");
+ }
+ if (outcome == Outcome.COMMITTED) {
+ if (committedPointerVersion == null
+ || committedPointerVersion <= 0L
+ || auditEventId == null
+ || auditEventId <= 0L
+ || proofDigest == null
+ || !PROOF_DIGEST.matcher(proofDigest).matches()
+ || terminalAt == null
+ || positiveDurableAbort) {
+ throw new IllegalArgumentException(
+ "COMMITTED proof must carry its exact pointer and audit");
+ }
+ } else if (outcome == Outcome.ABORTED) {
+ if (committedPointerVersion != null
+ || auditEventId != null
+ || proofDigest == null
+ || !PROOF_DIGEST.matcher(proofDigest).matches()
+ || terminalAt == null
+ || !positiveDurableAbort) {
+ throw new IllegalArgumentException(
+ "ABORTED proof must carry positive durable fencing and no commit result");
+ }
+ } else if (committedPointerVersion != null
+ || auditEventId != null
+ || proofDigest != null
+ || positiveDurableAbort
+ || terminalAt != null) {
+ throw new IllegalArgumentException("PENDING is not terminal owner proof");
+ }
+ }
+
+ public boolean provesCommit() {
+ return outcome == Outcome.COMMITTED;
+ }
+
+ public boolean provesAbort() {
+ return outcome == Outcome.ABORTED && positiveDurableAbort;
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java
new file mode 100644
index 0000000000..3d8be169e7
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java
@@ -0,0 +1,178 @@
+package net.firedevops.firemud.gamesession.dto;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+
+/** Exact first-OPEN intent plus the immutable World-issued hold identity. */
+public record CanonicalInitialAdmissionRequest(
+ String targetNamespace,
+ UUID canonicalTenantId,
+ String worldSlug,
+ UUID realmId,
+ UUID playableStateNamespaceId,
+ String playableStateScope,
+ UUID canonicalGameInstanceId,
+ UUID canonicalVersionId,
+ long activeLifecycleEpoch,
+ long expectedCatalogRevision,
+ OriginKind originKind,
+ Long expectedPriorPointerVersion,
+ String initialAdmissionRequestId,
+ String requestDigest,
+ UUID holdId,
+ UUID holdFence,
+ String holdBindingDigest) {
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final Pattern SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*");
+ private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern WORLD_BINDING_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}");
+ private static final String DIGEST_DOMAIN = "game-session-canonical-initial-admission/v1";
+
+ /** The only first-OPEN origin preconditions accepted by the canonical contract. */
+ public enum OriginKind {
+ NO_PRIOR_POINTER,
+ EXPECT_CLOSED
+ }
+
+ public CanonicalInitialAdmissionRequest {
+ if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) {
+ throw new IllegalArgumentException("targetNamespace must be a canonical workload namespace");
+ }
+ requireNonNil(canonicalTenantId, "canonicalTenantId");
+ requireSlug(worldSlug, "worldSlug");
+ requireNonNil(realmId, "realmId");
+ requireNonNil(playableStateNamespaceId, "playableStateNamespaceId");
+ if (!"SHARED".equals(playableStateScope)) {
+ throw new IllegalArgumentException(
+ "Current canonical launch association supports only SHARED playable state");
+ }
+ requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId");
+ requireNonNil(canonicalVersionId, "canonicalVersionId");
+ requirePositive(activeLifecycleEpoch, "activeLifecycleEpoch");
+ requirePositive(expectedCatalogRevision, "expectedCatalogRevision");
+ Objects.requireNonNull(originKind, "originKind");
+ if (originKind == OriginKind.NO_PRIOR_POINTER) {
+ if (expectedPriorPointerVersion != null) {
+ throw new IllegalArgumentException(
+ "NO_PRIOR_POINTER must not carry expectedPriorPointerVersion");
+ }
+ } else if (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L) {
+ throw new IllegalArgumentException(
+ "EXPECT_CLOSED requires a positive exact expectedPriorPointerVersion");
+ }
+ // Match the 128-character owner attempt and immutable intent ledgers.
+ requireText(initialAdmissionRequestId, "initialAdmissionRequestId", 128);
+ if (!REQUEST_DIGEST.matcher(Objects.requireNonNull(requestDigest, "requestDigest")).matches()) {
+ throw new IllegalArgumentException(
+ "requestDigest must be bare lowercase 64-character SHA-256 hex");
+ }
+ requireNonNil(holdId, "holdId");
+ requireNonNil(holdFence, "holdFence");
+ if (!WORLD_BINDING_DIGEST
+ .matcher(Objects.requireNonNull(holdBindingDigest, "holdBindingDigest"))
+ .matches()) {
+ throw new IllegalArgumentException(
+ "holdBindingDigest must be World-prefixed SHA-256 over its canonical request bytes");
+ }
+ if (!computeRequestDigest(
+ targetNamespace,
+ canonicalTenantId,
+ worldSlug,
+ realmId,
+ playableStateNamespaceId,
+ playableStateScope,
+ canonicalGameInstanceId,
+ canonicalVersionId,
+ activeLifecycleEpoch,
+ expectedCatalogRevision,
+ originKind,
+ expectedPriorPointerVersion,
+ initialAdmissionRequestId)
+ .equals(requestDigest)) {
+ throw new IllegalArgumentException(
+ "requestDigest does not bind the exact initial admission input");
+ }
+ }
+
+ /**
+ * Game Session request digest, deliberately bare and distinct from World's sha256:-prefixed RFC
+ * 8785 hold-binding digest.
+ */
+ public static String computeRequestDigest(
+ String targetNamespace,
+ UUID canonicalTenantId,
+ String worldSlug,
+ UUID realmId,
+ UUID playableStateNamespaceId,
+ String playableStateScope,
+ UUID canonicalGameInstanceId,
+ UUID canonicalVersionId,
+ long activeLifecycleEpoch,
+ long expectedCatalogRevision,
+ OriginKind originKind,
+ Long expectedPriorPointerVersion,
+ String initialAdmissionRequestId) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ add(digest, DIGEST_DOMAIN);
+ add(digest, targetNamespace);
+ add(digest, canonicalTenantId.toString());
+ add(digest, worldSlug);
+ add(digest, realmId.toString());
+ add(digest, playableStateNamespaceId.toString());
+ add(digest, playableStateScope);
+ add(digest, canonicalGameInstanceId.toString());
+ add(digest, canonicalVersionId.toString());
+ add(digest, Long.toString(activeLifecycleEpoch));
+ add(digest, Long.toString(expectedCatalogRevision));
+ add(digest, originKind.name());
+ add(
+ digest,
+ expectedPriorPointerVersion == null ? "" : expectedPriorPointerVersion.toString());
+ add(digest, initialAdmissionRequestId);
+ return HexFormat.of().formatHex(digest.digest());
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private static void add(MessageDigest digest, String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array());
+ digest.update(bytes);
+ }
+
+ private static void requireSlug(String value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.length() > 120 || !SLUG.matcher(value).matches()) {
+ throw new IllegalArgumentException(name + " must be a canonical slug");
+ }
+ }
+
+ private static void requireText(String value, String name, int maxLength) {
+ Objects.requireNonNull(value, name);
+ if (value.isBlank() || value.codePointCount(0, value.length()) > maxLength) {
+ throw new IllegalArgumentException(name + " must contain 1.." + maxLength + " characters");
+ }
+ }
+
+ private static void requirePositive(long value, String name) {
+ if (value <= 0L) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (NIL_UUID.equals(value)) {
+ throw new IllegalArgumentException(name + " must be a non-nil UUID");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java
new file mode 100644
index 0000000000..38a3259ec3
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java
@@ -0,0 +1,136 @@
+package net.firedevops.firemud.gamesession.dto;
+
+import java.io.Serializable;
+import java.time.Instant;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome;
+import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind;
+
+/**
+ * Read-only canonical public-production route evidence carried beside Game Session's private row
+ * keys. Instances are assembled only after catalog, pointer-owner proof, and launch-association
+ * readback agree.
+ */
+public record CanonicalPlayableTarget(
+ String targetNamespace,
+ String tenantSlug,
+ UUID canonicalTenantId,
+ String worldSlug,
+ String worldDisplayName,
+ UUID realmId,
+ String realmSlug,
+ String realmDisplayName,
+ long gameSessionTenantId,
+ long gameInstanceId,
+ UUID playableStateNamespaceId,
+ String playableStateScope,
+ UUID canonicalGameInstanceId,
+ UUID canonicalVersionId,
+ long runtimeVersionId,
+ long catalogRevision,
+ long pointerVersion,
+ String admissionPointerSnapshotDigest,
+ long activeWorldEpoch,
+ String initialAdmissionRequestId,
+ String initialAdmissionRequestDigest,
+ OriginKind initialAdmissionOriginKind,
+ Long expectedPriorPointerVersion,
+ UUID holdId,
+ UUID holdFence,
+ String holdBindingDigest,
+ long auditEventId,
+ String ownerProofDigest,
+ Outcome ownerProofOutcome,
+ boolean positiveDurableAbort,
+ Instant ownerProofTerminalAt,
+ String characterCreationPolicy)
+ implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern OWNER_PROOF_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}");
+
+ public CanonicalPlayableTarget {
+ if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) {
+ throw new IllegalArgumentException("targetNamespace is not a valid owner namespace");
+ }
+ requireText(tenantSlug, "tenantSlug");
+ requireNonNil(canonicalTenantId, "canonicalTenantId");
+ requireText(worldSlug, "worldSlug");
+ requireText(worldDisplayName, "worldDisplayName");
+ requireNonNil(realmId, "realmId");
+ requireText(realmSlug, "realmSlug");
+ requireText(realmDisplayName, "realmDisplayName");
+ requirePositive(gameSessionTenantId, "gameSessionTenantId");
+ requirePositive(gameInstanceId, "gameInstanceId");
+ requireNonNil(playableStateNamespaceId, "playableStateNamespaceId");
+ if (!"SHARED".equals(playableStateScope) && !"ISOLATED".equals(playableStateScope)) {
+ throw new IllegalArgumentException("playableStateScope is not a supported catalog value");
+ }
+ requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId");
+ requireNonNil(canonicalVersionId, "canonicalVersionId");
+ requirePositive(runtimeVersionId, "runtimeVersionId");
+ requirePositive(catalogRevision, "catalogRevision");
+ requirePositive(pointerVersion, "pointerVersion");
+ if (admissionPointerSnapshotDigest == null
+ || !SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) {
+ throw new IllegalArgumentException(
+ "admissionPointerSnapshotDigest is not raw lowercase SHA-256 hex");
+ }
+ requirePositive(activeWorldEpoch, "activeWorldEpoch");
+ requireText(initialAdmissionRequestId, "initialAdmissionRequestId");
+ if (initialAdmissionRequestDigest == null
+ || !REQUEST_DIGEST.matcher(initialAdmissionRequestDigest).matches()) {
+ throw new IllegalArgumentException(
+ "initialAdmissionRequestDigest is not a canonical request digest");
+ }
+ Objects.requireNonNull(initialAdmissionOriginKind, "initialAdmissionOriginKind");
+ if (initialAdmissionOriginKind == OriginKind.NO_PRIOR_POINTER) {
+ if (expectedPriorPointerVersion != null) {
+ throw new IllegalArgumentException(
+ "NO_PRIOR_POINTER must not carry expectedPriorPointerVersion");
+ }
+ } else if (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L) {
+ throw new IllegalArgumentException("EXPECT_CLOSED requires an exact prior pointer version");
+ }
+ requireNonNil(holdId, "holdId");
+ requireNonNil(holdFence, "holdFence");
+ if (holdBindingDigest == null || !OWNER_PROOF_DIGEST.matcher(holdBindingDigest).matches()) {
+ throw new IllegalArgumentException("holdBindingDigest is not a canonical proof digest");
+ }
+ requirePositive(auditEventId, "auditEventId");
+ if (ownerProofDigest == null || !OWNER_PROOF_DIGEST.matcher(ownerProofDigest).matches()) {
+ throw new IllegalArgumentException("ownerProofDigest is not a canonical proof digest");
+ }
+ if (ownerProofOutcome != Outcome.COMMITTED || positiveDurableAbort) {
+ throw new IllegalArgumentException(
+ "Canonical playable target requires exact COMMITTED proof");
+ }
+ Objects.requireNonNull(ownerProofTerminalAt, "ownerProofTerminalAt");
+ requireText(characterCreationPolicy, "characterCreationPolicy");
+ }
+
+ private static void requireText(String value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.isBlank() || !value.equals(value.trim())) {
+ throw new IllegalArgumentException(name + " must be nonblank and trimmed");
+ }
+ }
+
+ private static void requirePositive(long value, String name) {
+ if (value <= 0L) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String name) {
+ Objects.requireNonNull(value, name);
+ if (NIL_UUID.equals(value)) {
+ throw new IllegalArgumentException(name + " must be a non-nil UUID");
+ }
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryConflictException.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryConflictException.java
new file mode 100644
index 0000000000..9d03f74bf4
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryConflictException.java
@@ -0,0 +1,12 @@
+package net.firedevops.firemud.gamesession.repository;
+
+/** Exact transition identity or compare-tuple conflicts never fall back to a new operation. */
+public final class CanonicalGameplayBindingInventoryConflictException extends RuntimeException {
+ public CanonicalGameplayBindingInventoryConflictException(String message) {
+ super(message);
+ }
+
+ public CanonicalGameplayBindingInventoryConflictException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java
new file mode 100644
index 0000000000..cdcc43539d
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java
@@ -0,0 +1,2327 @@
+package net.firedevops.firemud.gamesession.repository;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexProjectionReceipt;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIssuerIndexObligation;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition;
+import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation;
+import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof;
+import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest;
+import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.impl.DSL;
+
+/**
+ * Game Session-owned durable preparation ledger.
+ *
+ * This class deliberately has no Spring stereotype and a package-private API. It is not an
+ * admission, acknowledgement, Redis, or controller-CAS surface. A future transfer orchestrator must
+ * consume the complete stored evidence before it can make a candidate admissible.
+ */
+public final class CanonicalGameplayBindingInventoryRepository {
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory";
+ private static final String TRANSITION = "game_session_canonical_binding_transition";
+ private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation";
+ private static final String ACCOUNT_OBLIGATION =
+ "game_session_canonical_binding_account_index_obligation";
+ private static final String ISSUER_OBLIGATION =
+ "game_session_canonical_binding_issuer_index_obligation";
+ private static final String REGION_OBLIGATION =
+ "game_session_canonical_binding_region_bridge_obligation";
+ private static final String GENERATION = "game_session_canonical_binding_generation";
+ private static final String LEGACY_DISPOSITION =
+ "game_session_canonical_binding_legacy_disposition";
+ private final DSLContext dsl;
+
+ CanonicalGameplayBindingInventoryRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "dsl");
+ }
+
+ CanonicalGameplayBindingTransitionSnapshot prepare(
+ CanonicalGameplayBindingTransitionRequest request) {
+ Objects.requireNonNull(request, "request");
+ validateRequest(request);
+ return dsl.transactionResult(
+ configuration -> prepareInTransaction(DSL.using(configuration), request));
+ }
+
+ /**
+ * Reads the complete typed inventory and all retained repair obligations from one DB snapshot.
+ */
+ CanonicalGameplayBindingInventorySnapshot readSnapshot() {
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
+ BigInteger revision =
+ readBigInteger(
+ Objects.requireNonNull(
+ transaction.fetchOne(
+ "SELECT inventory_revision FROM "
+ + "game_session_canonical_binding_inventory_clock WHERE singleton_id = 1"),
+ "inventory revision clock row must exist"),
+ "inventory_revision");
+ List bindings =
+ transaction
+ .fetch(
+ "SELECT * FROM "
+ + INVENTORY
+ + " WHERE inventory_revision <= ? ORDER BY binding_ref",
+ decimal(revision))
+ .map(CanonicalGameplayBindingInventoryRepository::toInventoryEntry);
+ List transitions =
+ transaction
+ .fetch(
+ "SELECT t.transition_id, t.expected_prior_binding_ref,"
+ + " t.expected_prior_binding_generation, t.candidate_binding_generation,"
+ + " t.status, t.inventory_revision, t.issuer_reservation_id,"
+ + " t.candidate_account_index_fence, t.account_coverage_state,"
+ + " t.account_coverage_operation_id, t.account_coverage_lifecycle,"
+ + " t.account_coverage_operation_fence, t.account_admission_fence_kind,"
+ + " t.account_admission_fence, t.historical_account_admission_fence_kind,"
+ + " t.historical_account_admission_fence, t.resolved_scope_kind,"
+ + " t.resolved_scope_account_id, t.account_coverage_fence,"
+ + " t.account_coverage_generation, t.account_inventory_snapshot_revision,"
+ + " i.account_id, i.tenant_id, i.playable_state_namespace_id, i.character_id,"
+ + " i.playable_state_scope, i.game_instance_id,"
+ + " i.runtime_game_instance_id, i.session_id, i.region_id,"
+ + " i.region_epoch, i.issuer_id, i.issuer_auth_generation,"
+ + " i.issuer_index_layout_version, i.issuer_index_partition_count,"
+ + " i.issuer_index_partition_capacity, i.binding_ref, r.reservation_fence"
+ + " FROM "
+ + TRANSITION
+ + " t JOIN "
+ + INVENTORY
+ + " i ON i.binding_ref = t.candidate_binding_ref JOIN "
+ + RESERVATION
+ + " r ON r.reservation_id = t.issuer_reservation_id"
+ + " WHERE t.inventory_revision <= ? ORDER BY t.transition_id",
+ decimal(revision))
+ .map(CanonicalGameplayBindingInventoryRepository::toTransitionSnapshot);
+ List reservations =
+ transaction
+ .fetch(
+ "SELECT * FROM "
+ + RESERVATION
+ + " WHERE inventory_revision <= ? ORDER BY reservation_id",
+ decimal(revision))
+ .map(CanonicalGameplayBindingInventoryRepository::toReservation);
+ List accountObligations =
+ transaction
+ .fetch(
+ "SELECT o.*, i.playable_state_namespace_id, i.character_id,"
+ + " i.playable_state_scope, i.game_instance_id,"
+ + " i.runtime_game_instance_id, i.session_id, i.region_id,"
+ + " i.region_epoch, i.issuer_id, i.issuer_auth_generation,"
+ + " i.issuer_index_layout_version, i.issuer_index_partition_count,"
+ + " i.issuer_index_partition_capacity FROM "
+ + ACCOUNT_OBLIGATION
+ + " o JOIN "
+ + INVENTORY
+ + " i ON i.binding_ref = o.binding_ref"
+ + " WHERE o.inventory_revision <= ? ORDER BY o.transition_id, o.obligation_ordinal",
+ decimal(revision))
+ .map(CanonicalGameplayBindingInventoryRepository::toAccountObligation);
+ List issuerObligations =
+ transaction
+ .fetch(
+ "SELECT o.*, i.account_id, i.tenant_id, i.playable_state_namespace_id,"
+ + " i.character_id, i.playable_state_scope, i.game_instance_id,"
+ + " i.runtime_game_instance_id, i.session_id,"
+ + " i.region_id, i.region_epoch, i.issuer_id, i.issuer_auth_generation,"
+ + " i.issuer_index_layout_version, i.issuer_index_partition_count,"
+ + " i.issuer_index_partition_capacity FROM "
+ + ISSUER_OBLIGATION
+ + " o JOIN "
+ + INVENTORY
+ + " i ON i.binding_ref = o.binding_ref"
+ + " WHERE o.inventory_revision <= ? ORDER BY o.transition_id, o.binding_ref",
+ decimal(revision))
+ .map(CanonicalGameplayBindingInventoryRepository::toIssuerObligation);
+ List regionObligations =
+ transaction
+ .fetch(
+ "SELECT * FROM "
+ + REGION_OBLIGATION
+ + " WHERE inventory_revision <= ? ORDER BY transition_id",
+ decimal(revision))
+ .map(CanonicalGameplayBindingInventoryRepository::toRegionObligation);
+ return new CanonicalGameplayBindingInventorySnapshot(
+ revision,
+ bindings,
+ transitions,
+ reservations,
+ accountObligations,
+ issuerObligations,
+ regionObligations);
+ });
+ }
+
+ /**
+ * Loads the exact prepared transfer and its still-active source from one durable read snapshot.
+ * No Redis absence or caller-asserted acknowledgement is accepted as source evidence.
+ */
+ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID transitionId) {
+ Objects.requireNonNull(transitionId, "transitionId");
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
+ return loadProvisionalCasEvidence(transaction, transitionId, false);
+ });
+ }
+
+ /**
+ * Reads a lease-bound PROVISIONAL decision from its existing transition and current inventory.
+ * The supplied Account lease is only an expected value; all returned decision fields are loaded
+ * from durable Game Session rows and the canonical lease carrier is reparsed and digest-checked.
+ */
+ CanonicalGameplayAdmissionDecision readAdmissionDecision(
+ UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence) {
+ Objects.requireNonNull(bindingDecisionId, "bindingDecisionId");
+ Objects.requireNonNull(expectedLeaseEvidence, "expectedLeaseEvidence");
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
+ CanonicalGameplayBindingProvisionalCasEvidence operation =
+ loadProvisionalCasEvidence(transaction, bindingDecisionId, false);
+ if (operation.transition().status()
+ != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL
+ || operation.candidate().lifecycle()
+ != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) {
+ throw conflict("Only an exact durable PROVISIONAL transition is a decision");
+ }
+ Record row = readTransition(transaction, bindingDecisionId);
+ CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(row, operation);
+ if (!stored.leaseEvidence().hasSameIdentity(expectedLeaseEvidence)) {
+ throw conflict("Expected Account lease differs from the immutable stored decision");
+ }
+ return stored;
+ });
+ }
+
+ /**
+ * Persists exact Redis PRESENT readback for the candidate account member without satisfying the
+ * account-index obligation. Account-wide v2 coverage remains a separate required owner result.
+ */
+ CanonicalGameplayBindingAccountIndexProjectionReceipt markCandidateAccountIndexPresent(
+ CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, String member) {
+ Objects.requireNonNull(expectedEvidence, "expectedEvidence");
+ Objects.requireNonNull(member, "member");
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ BigInteger currentRevision = lockInventoryRevision(transaction);
+ UUID transitionId = expectedEvidence.transition().transitionId();
+ lockLeaseBoundRuntimeBeforeTransition(
+ transaction, transitionId, expectedEvidence.candidate().bindingRef().bytes(), null);
+ CanonicalGameplayBindingProvisionalCasEvidence current =
+ loadProvisionalCasEvidence(transaction, transitionId, true);
+ requireAccountCoverageEvidenceCurrent(
+ transaction,
+ current.candidate().identity().accountId(),
+ current.transition().accountCoverageEvidence());
+ requireSameProvisionalOperation(expectedEvidence, current);
+ if (current.transition().status()
+ != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) {
+ throw conflict("Only the exact PROVISIONAL candidate may project its account member");
+ }
+ CanonicalGameplayAccountIndexMember exactMember =
+ CanonicalGameplayAccountIndexMember.of(current.candidate());
+ if (!exactMember.value().equals(member)) {
+ throw conflict("Redis readback member differs from the exact durable candidate tuple");
+ }
+
+ List obligations =
+ loadAccountIndexObligations(transaction, transitionId, true);
+ int expectedObligations = current.expectedPrior() == null ? 1 : 2;
+ if (obligations.size() != expectedObligations) {
+ throw conflict("The exact transition no longer has every required account obligation");
+ }
+ var candidateObligation = obligations.getFirst();
+ if (candidateObligation.ordinal() != 0
+ || candidateObligation.action()
+ != CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN
+ || candidateObligation.executionPhase()
+ != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS
+ || !candidateObligation.bindingRef().equals(current.candidate().bindingRef())
+ || !candidateObligation.accountId().equals(current.candidate().identity().accountId())
+ || !candidateObligation.tenantId().equals(current.candidate().identity().tenantId())
+ || !candidateObligation
+ .bindingGeneration()
+ .equals(current.candidate().bindingGeneration())
+ || !candidateObligation
+ .accountIndexFence()
+ .equals(current.candidate().accountIndexFence())
+ || candidateObligation.status()
+ != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED) {
+ throw conflict("The account-index candidate obligation differs from durable ownership");
+ }
+ if (candidateObligation.projectionState()
+ == CanonicalGameplayBindingAccountIndexObligation.ProjectionState
+ .PRESENT_AWAITING_COVERAGE) {
+ if (!member.equals(candidateObligation.projectedMember())) {
+ throw conflict("A prior exact account-index readback retained a different member");
+ }
+ return projectionReceipt(candidateObligation);
+ }
+ if (candidateObligation.projectionState()
+ != CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED) {
+ throw conflict(
+ "Candidate account-index obligation is in a conflicting projection state");
+ }
+
+ BigInteger transitionRevision = current.transition().inventoryRevision();
+ BigInteger nextRevision = currentRevision.add(BigInteger.ONE);
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + TRANSITION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND status = 'PROVISIONAL'"
+ + " AND inventory_revision = ? AND candidate_binding_ref = ?"
+ + " AND candidate_binding_generation = ? AND candidate_account_index_fence = ?",
+ decimal(nextRevision),
+ transitionId,
+ decimal(transitionRevision),
+ current.candidate().bindingRef().bytes(),
+ decimal(current.transition().bindingGeneration()),
+ current.transition().candidateAccountIndexFence()),
+ "Durable transition changed before account-index readback persistence");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + INVENTORY
+ + " SET inventory_revision = ?"
+ + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'PROVISIONAL'"
+ + " AND binding_generation = ? AND account_index_fence = ?"
+ + " AND account_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.candidate().bindingRef().bytes(),
+ transitionId,
+ decimal(current.transition().bindingGeneration()),
+ current.transition().candidateAccountIndexFence(),
+ decimal(transitionRevision)),
+ "Durable candidate changed before account-index readback persistence");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + ACCOUNT_OBLIGATION
+ + " SET projection_state = 'PRESENT_AWAITING_COVERAGE',"
+ + " projection_member = ?, projection_inventory_revision = ?, inventory_revision = ?"
+ + " WHERE transition_id = ? AND obligation_ordinal = 0"
+ + " AND action = 'ADD_OR_RETAIN' AND projection_state = 'REQUIRED'"
+ + " AND binding_ref = ? AND account_id = ? AND tenant_id = ?"
+ + " AND binding_generation = ? AND account_index_fence = ?"
+ + " AND inventory_revision = ?",
+ member,
+ decimal(nextRevision),
+ decimal(nextRevision),
+ transitionId,
+ candidateObligation.bindingRef().bytes(),
+ candidateObligation.accountId(),
+ candidateObligation.tenantId(),
+ decimal(candidateObligation.bindingGeneration()),
+ candidateObligation.accountIndexFence(),
+ decimal(transitionRevision)),
+ "Durable candidate account-index obligation changed before readback persistence");
+ requireCount(
+ transaction.execute(
+ "UPDATE "
+ + ACCOUNT_OBLIGATION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND obligation_ordinal = 1"
+ + " AND inventory_revision = ?",
+ decimal(nextRevision),
+ transitionId,
+ decimal(transitionRevision)),
+ current.expectedPrior() == null ? 0 : 1,
+ "Durable prior account-index obligation changed before readback persistence");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + ISSUER_OBLIGATION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND inventory_revision = ?",
+ decimal(nextRevision),
+ transitionId,
+ decimal(transitionRevision)),
+ "Durable issuer obligation changed before account-index readback persistence");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + REGION_OBLIGATION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND inventory_revision = ?",
+ decimal(nextRevision),
+ transitionId,
+ decimal(transitionRevision)),
+ "Durable region obligation changed before account-index readback persistence");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + RESERVATION
+ + " SET inventory_revision = ?"
+ + " WHERE reservation_id = ? AND transition_id = ?"
+ + " AND lifecycle = 'RESERVED' AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.transition().issuerReservationId(),
+ transitionId,
+ decimal(transitionRevision)),
+ "Durable issuer reservation changed before account-index readback persistence");
+ requireOne(
+ transaction.execute(
+ "UPDATE game_session_canonical_binding_inventory_clock"
+ + " SET inventory_revision = ? WHERE singleton_id = 1"
+ + " AND inventory_revision = ?",
+ decimal(nextRevision),
+ decimal(currentRevision)),
+ "Durable inventory revision compare-and-set lost during account-index readback");
+ var saved = loadAccountIndexObligations(transaction, transitionId, false).getFirst();
+ return projectionReceipt(saved);
+ });
+ }
+
+ /**
+ * Records exact Redis provisional readback for this operation. This advances only the durable
+ * preparation lifecycle; it does not acknowledge external indexes, the region bridge, or admit
+ * the candidate.
+ */
+ CanonicalGameplayBindingTransitionSnapshot markProvisional(
+ CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence) {
+ return markProvisional(expectedEvidence, null);
+ }
+
+ /**
+ * Records exact Redis lease-bound provisional readback and its unchanged Account lease plus
+ * point-in-time route evidence in one transition/inventory revision compare-and-set.
+ */
+ CanonicalGameplayBindingTransitionSnapshot markProvisional(
+ CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence,
+ CanonicalGameplayAdmissionDecision expectedDecision) {
+ Objects.requireNonNull(expectedEvidence, "expectedEvidence");
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ BigInteger currentRevision = lockInventoryRevision(transaction);
+ if (expectedDecision != null) {
+ lockLeaseBoundRuntimeBeforeTransition(
+ transaction,
+ expectedEvidence.transition().transitionId(),
+ expectedEvidence.candidate().bindingRef().bytes(),
+ expectedDecision.targetEvidence());
+ }
+ CanonicalGameplayBindingProvisionalCasEvidence current =
+ loadProvisionalCasEvidence(
+ transaction, expectedEvidence.transition().transitionId(), true);
+ requireAccountCoverageEvidenceCurrent(
+ transaction,
+ current.candidate().identity().accountId(),
+ current.transition().accountCoverageEvidence());
+ requireSameProvisionalOperation(expectedEvidence, current);
+ if (current.expectedPrior() == null && expectedDecision == null) {
+ throw conflict(
+ "First-binding provisional publication requires the exact Account lease decision");
+ }
+ if (current.transition().status()
+ == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) {
+ Record row = findTransition(transaction, current.transition().transitionId());
+ if (expectedDecision == null) {
+ if (row.get("admission_lease_id", UUID.class) != null) {
+ throw conflict("A lease-bound decision cannot be retried through legacy publish");
+ }
+ } else {
+ CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(row, current);
+ requireSameAdmissionDecision(expectedDecision, stored);
+ }
+ return current.transition();
+ }
+ if (current.transition().status()
+ != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) {
+ throw conflict("Only the exact PREPARED operation can become PROVISIONAL");
+ }
+
+ BigInteger priorRevision = current.transition().inventoryRevision();
+ BigInteger nextRevision = currentRevision.add(BigInteger.ONE);
+ if (expectedDecision != null) {
+ requireDecisionMatchesOperation(expectedDecision, current);
+ }
+ int transitionChanged =
+ expectedDecision == null
+ ? updateLegacyProvisionalTransition(
+ transaction, current, priorRevision, nextRevision)
+ : updateLeaseBoundProvisionalTransition(
+ transaction, current, expectedDecision, priorRevision, nextRevision);
+ requireOne(
+ transitionChanged, "Durable transition compare-and-set lost its exact prepared row");
+ int candidateChanged =
+ transaction.execute(
+ "UPDATE "
+ + INVENTORY
+ + " SET lifecycle = 'PROVISIONAL', inventory_revision = ?"
+ + " WHERE binding_ref = ? AND transition_id = ?"
+ + " AND lifecycle = 'CANDIDATE_PREPARED'"
+ + " AND binding_generation = ? AND account_index_fence = ?"
+ + " AND account_index_state = 'REPAIR_REQUIRED'"
+ + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.candidate().bindingRef().bytes(),
+ current.transition().transitionId(),
+ decimal(current.transition().bindingGeneration()),
+ current.transition().candidateAccountIndexFence(),
+ decimal(priorRevision));
+ requireOne(
+ candidateChanged, "Durable candidate compare-and-set lost its exact prepared row");
+ requireCount(
+ transaction.execute(
+ "UPDATE "
+ + ACCOUNT_OBLIGATION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.transition().transitionId(),
+ decimal(priorRevision)),
+ current.expectedPrior() == null ? 1 : 2,
+ "Durable account-index obligations changed during provisional publication");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + ISSUER_OBLIGATION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.transition().transitionId(),
+ decimal(priorRevision)),
+ "Durable issuer-index obligation changed during provisional publication");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + REGION_OBLIGATION
+ + " SET inventory_revision = ?"
+ + " WHERE transition_id = ? AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.transition().transitionId(),
+ decimal(priorRevision)),
+ "Durable region-bridge obligation changed during provisional publication");
+ requireOne(
+ transaction.execute(
+ "UPDATE "
+ + RESERVATION
+ + " SET inventory_revision = ?"
+ + " WHERE reservation_id = ? AND transition_id = ?"
+ + " AND lifecycle = 'RESERVED' AND inventory_revision = ?",
+ decimal(nextRevision),
+ current.transition().issuerReservationId(),
+ current.transition().transitionId(),
+ decimal(priorRevision)),
+ "Durable issuer reservation changed during provisional publication");
+ requireOne(
+ transaction.execute(
+ "UPDATE game_session_canonical_binding_inventory_clock"
+ + " SET inventory_revision = ? WHERE singleton_id = 1"
+ + " AND inventory_revision = ?",
+ decimal(nextRevision),
+ decimal(currentRevision)),
+ "Durable inventory revision compare-and-set lost during provisional publication");
+ return loadProvisionalCasEvidence(
+ transaction, expectedEvidence.transition().transitionId(), true)
+ .transition();
+ });
+ }
+
+ private static int updateLegacyProvisionalTransition(
+ DSLContext transaction,
+ CanonicalGameplayBindingProvisionalCasEvidence current,
+ BigInteger priorRevision,
+ BigInteger nextRevision) {
+ String expectedPriorPredicate = expectedPriorPredicate(current);
+ List values = new ArrayList<>();
+ values.add(decimal(nextRevision));
+ values.add(current.transition().transitionId());
+ values.add(decimal(priorRevision));
+ values.add(current.candidate().bindingRef().bytes());
+ values.add(decimal(current.transition().bindingGeneration()));
+ values.add(current.transition().candidateAccountIndexFence());
+ addExpectedPriorValues(values, current);
+ return transaction.execute(
+ "UPDATE "
+ + TRANSITION
+ + " SET status = 'PROVISIONAL', inventory_revision = ?"
+ + " WHERE transition_id = ? AND status = 'PREPARED'"
+ + " AND inventory_revision = ? AND candidate_binding_ref = ?"
+ + " AND candidate_binding_generation = ?"
+ + " AND candidate_account_index_fence = ? "
+ + expectedPriorPredicate
+ + " AND admission_request_id IS NULL AND admission_lease_id IS NULL",
+ values.toArray());
+ }
+
+ private static String expectedPriorPredicate(
+ CanonicalGameplayBindingProvisionalCasEvidence current) {
+ return current.expectedPrior() == null
+ ? "AND expected_prior_binding_ref IS NULL AND expected_prior_binding_generation IS NULL"
+ : "AND expected_prior_binding_ref = ? AND expected_prior_binding_generation = ?";
+ }
+
+ private static void addExpectedPriorValues(
+ List values, CanonicalGameplayBindingProvisionalCasEvidence current) {
+ if (current.expectedPrior() != null) {
+ values.add(current.expectedPrior().bindingRef().bytes());
+ values.add(decimal(current.expectedPrior().bindingGeneration()));
+ }
+ }
+
+ private static void lockLeaseBoundRuntimeBeforeTransition(
+ DSLContext transaction,
+ UUID transitionId,
+ byte[] candidateBindingRef,
+ CanonicalPlayableTarget expectedTarget) {
+ // Keep the runtime-before-transition lock order: resolve without row locks, then acquire only
+ // the exact candidate runtime row before CAS evidence locks the transition. The V34 trigger
+ // rechecks the complete launch tuple when the transition is updated.
+ Record targetLink =
+ transaction.fetchOne(
+ "SELECT transition.status, transition.admission_lease_id,"
+ + " transition.admission_target_tenant_id,"
+ + " transition.admission_target_game_session_tenant_id,"
+ + " transition.admission_target_game_instance_id,"
+ + " transition.admission_target_canonical_game_instance_id,"
+ + " candidate.tenant_id AS candidate_tenant_id,"
+ + " candidate.runtime_game_instance_id,"
+ + " candidate.game_instance_id AS candidate_game_instance_id,"
+ + " launch.canonical_tenant_id AS launch_canonical_tenant_id,"
+ + " launch.game_session_tenant_id,"
+ + " launch.game_instance_id AS launch_game_instance_id,"
+ + " launch.game_instance_uuid AS launch_game_instance_uuid"
+ + " FROM "
+ + TRANSITION
+ + " transition JOIN "
+ + INVENTORY
+ + " candidate ON candidate.binding_ref = transition.candidate_binding_ref"
+ + " JOIN game_session_canonical_instance_launch launch"
+ + " ON launch.canonical_tenant_id = candidate.tenant_id"
+ + " AND launch.game_instance_id = candidate.runtime_game_instance_id"
+ + " AND launch.game_instance_uuid = candidate.game_instance_id"
+ + " WHERE transition.transition_id = ? AND candidate.binding_ref = ?",
+ transitionId,
+ candidateBindingRef);
+ if (targetLink == null) {
+ if (expectedTarget != null) {
+ throw conflict("Lease-bound decision has no exact candidate launch identity");
+ }
+ return;
+ }
+
+ if (expectedTarget == null) {
+ String status = targetLink.get("status", String.class);
+ if (targetLink.get("admission_lease_id", UUID.class) == null
+ || (!"PROVISIONAL".equals(status) && !"AMBIGUOUS".equals(status))) {
+ return;
+ }
+ }
+
+ UUID canonicalTenantId =
+ expectedTarget == null
+ ? targetLink.get("admission_target_tenant_id", UUID.class)
+ : expectedTarget.canonicalTenantId();
+ Long gameSessionTenantId =
+ expectedTarget == null
+ ? targetLink.get("admission_target_game_session_tenant_id", Long.class)
+ : expectedTarget.gameSessionTenantId();
+ Long gameInstanceId =
+ expectedTarget == null
+ ? targetLink.get("admission_target_game_instance_id", Long.class)
+ : expectedTarget.gameInstanceId();
+ UUID canonicalGameInstanceId =
+ expectedTarget == null
+ ? targetLink.get("admission_target_canonical_game_instance_id", UUID.class)
+ : expectedTarget.canonicalGameInstanceId();
+
+ if (canonicalTenantId == null
+ || gameSessionTenantId == null
+ || gameInstanceId == null
+ || canonicalGameInstanceId == null
+ || !Objects.equals(canonicalTenantId, targetLink.get("candidate_tenant_id", UUID.class))
+ || !Objects.equals(
+ canonicalTenantId, targetLink.get("launch_canonical_tenant_id", UUID.class))
+ || !Objects.equals(
+ gameSessionTenantId, targetLink.get("game_session_tenant_id", Long.class))
+ || !Objects.equals(gameInstanceId, targetLink.get("runtime_game_instance_id", Long.class))
+ || !Objects.equals(gameInstanceId, targetLink.get("launch_game_instance_id", Long.class))
+ || !Objects.equals(
+ canonicalGameInstanceId, targetLink.get("candidate_game_instance_id", UUID.class))
+ || !Objects.equals(
+ canonicalGameInstanceId, targetLink.get("launch_game_instance_uuid", UUID.class))) {
+ throw conflict("Lease-bound decision does not identify the exact candidate runtime row");
+ }
+
+ Record runtime =
+ transaction.fetchOne(
+ "SELECT id FROM game_instances"
+ + " WHERE tenant_id = ? AND id = ? AND game_instance_uuid = ? FOR UPDATE",
+ gameSessionTenantId,
+ gameInstanceId,
+ canonicalGameInstanceId);
+ if (runtime == null) {
+ throw conflict("Lease-bound decision has no exact current Game Instance row");
+ }
+ }
+
+ private static int updateLeaseBoundProvisionalTransition(
+ DSLContext transaction,
+ CanonicalGameplayBindingProvisionalCasEvidence current,
+ CanonicalGameplayAdmissionDecision decision,
+ BigInteger priorRevision,
+ BigInteger nextRevision) {
+ List values = new ArrayList<>();
+ values.add(decimal(nextRevision));
+ values.addAll(admissionDecisionValues(decision));
+ values.add(current.transition().transitionId());
+ values.add(decimal(priorRevision));
+ values.add(current.candidate().bindingRef().bytes());
+ values.add(decimal(current.transition().bindingGeneration()));
+ values.add(current.transition().candidateAccountIndexFence());
+ String expectedPriorPredicate = expectedPriorPredicate(current);
+ addExpectedPriorValues(values, current);
+ values.add(decision.leaseExpiresAtEpochMillis().toString());
+ String assignments =
+ "admission_request_id = ?, admission_lease_id = ?, admission_lease_fence = ?,"
+ + " admission_lease_kind = ?, admission_lease_digest = ?,"
+ + " admission_lease_evidence = ?, admission_resume_episode_id = ?,"
+ + " admission_expected_old_binding_generation = ?, admission_lease_expires_at = ?,"
+ + " admission_target_namespace = ?, admission_target_tenant_slug = ?,"
+ + " admission_target_tenant_id = ?, admission_target_world_slug = ?,"
+ + " admission_target_world_display_name = ?, admission_target_realm_id = ?,"
+ + " admission_target_realm_slug = ?, admission_target_realm_display_name = ?,"
+ + " admission_target_game_session_tenant_id = ?, admission_target_game_instance_id = ?,"
+ + " admission_target_playable_state_namespace_id = ?,"
+ + " admission_target_playable_state_scope = ?,"
+ + " admission_target_canonical_game_instance_id = ?,"
+ + " admission_target_canonical_version_id = ?, admission_target_runtime_version_id = ?,"
+ + " admission_target_catalog_revision = ?, admission_target_pointer_version = ?,"
+ + " admission_target_pointer_snapshot_digest = ?,"
+ + " admission_target_active_world_epoch = ?,"
+ + " admission_target_initial_admission_request_id = ?,"
+ + " admission_target_initial_admission_request_digest = ?,"
+ + " admission_target_origin_kind = ?,"
+ + " admission_target_expected_prior_pointer_version = ?,"
+ + " admission_target_hold_id = ?, admission_target_hold_fence = ?,"
+ + " admission_target_hold_binding_digest = ?, admission_target_audit_event_id = ?,"
+ + " admission_target_owner_proof_digest = ?,"
+ + " admission_target_owner_proof_outcome = ?,"
+ + " admission_target_positive_durable_abort = ?,"
+ + " admission_target_terminal_at = ?::timestamptz,"
+ + " admission_target_character_creation_policy = ?";
+ return transaction.execute(
+ "UPDATE "
+ + TRANSITION
+ + " SET status = 'PROVISIONAL', inventory_revision = ?, "
+ + assignments
+ + " WHERE transition_id = ? AND status = 'PREPARED'"
+ + " AND inventory_revision = ? AND candidate_binding_ref = ?"
+ + " AND candidate_binding_generation = ? AND candidate_account_index_fence = ?"
+ + " "
+ + expectedPriorPredicate
+ + " AND admission_request_id IS NULL AND admission_lease_id IS NULL"
+ + " AND CAST(? AS NUMERIC) > FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000)",
+ values.toArray());
+ }
+
+ private static List admissionDecisionValues(CanonicalGameplayAdmissionDecision decision) {
+ CanonicalPlayableTarget target = decision.targetEvidence();
+ List values = new ArrayList<>();
+ values.add(decision.requestId());
+ values.add(decision.leaseId());
+ values.add(decimal(decision.leaseFence()));
+ values.add(decision.leaseKind().name());
+ values.add(decision.leaseSha256());
+ values.add(decision.leaseEvidenceJson());
+ values.add(decision.resumeEpisodeId());
+ values.add(
+ decision.expectedOldBindingGeneration() == null
+ ? null
+ : decimal(decision.expectedOldBindingGeneration()));
+ values.add(decimal(decision.leaseExpiresAtEpochMillis()));
+ values.add(target.targetNamespace());
+ values.add(target.tenantSlug());
+ values.add(target.canonicalTenantId());
+ values.add(target.worldSlug());
+ values.add(target.worldDisplayName());
+ values.add(target.realmId());
+ values.add(target.realmSlug());
+ values.add(target.realmDisplayName());
+ values.add(target.gameSessionTenantId());
+ values.add(target.gameInstanceId());
+ values.add(target.playableStateNamespaceId());
+ values.add(target.playableStateScope());
+ values.add(target.canonicalGameInstanceId());
+ values.add(target.canonicalVersionId());
+ values.add(target.runtimeVersionId());
+ values.add(target.catalogRevision());
+ values.add(target.pointerVersion());
+ values.add(target.admissionPointerSnapshotDigest());
+ values.add(target.activeWorldEpoch());
+ values.add(target.initialAdmissionRequestId());
+ values.add(target.initialAdmissionRequestDigest());
+ values.add(target.initialAdmissionOriginKind().name());
+ values.add(target.expectedPriorPointerVersion());
+ values.add(target.holdId());
+ values.add(target.holdFence());
+ values.add(target.holdBindingDigest());
+ values.add(target.auditEventId());
+ values.add(target.ownerProofDigest());
+ values.add(target.ownerProofOutcome().name());
+ values.add(target.positiveDurableAbort());
+ values.add(OffsetDateTime.ofInstant(target.ownerProofTerminalAt(), ZoneOffset.UTC));
+ values.add(target.characterCreationPolicy());
+ return values;
+ }
+
+ private static List loadAccountIndexObligations(
+ DSLContext transaction, UUID transitionId, boolean forUpdate) {
+ return transaction
+ .fetch(
+ "SELECT o.*, i.playable_state_namespace_id, i.character_id,"
+ + " i.playable_state_scope, i.game_instance_id, i.runtime_game_instance_id,"
+ + " i.session_id, i.region_id, i.region_epoch, i.issuer_id,"
+ + " i.issuer_auth_generation, i.issuer_index_layout_version,"
+ + " i.issuer_index_partition_count, i.issuer_index_partition_capacity"
+ + " FROM "
+ + ACCOUNT_OBLIGATION
+ + " o JOIN "
+ + INVENTORY
+ + " i ON i.binding_ref = o.binding_ref WHERE o.transition_id = ?"
+ + " ORDER BY o.obligation_ordinal"
+ + (forUpdate ? " FOR UPDATE OF o" : ""),
+ transitionId)
+ .map(CanonicalGameplayBindingInventoryRepository::toAccountObligation);
+ }
+
+ private static CanonicalGameplayBindingAccountIndexProjectionReceipt projectionReceipt(
+ CanonicalGameplayBindingAccountIndexObligation obligation) {
+ if (obligation.projectionState()
+ != CanonicalGameplayBindingAccountIndexObligation.ProjectionState
+ .PRESENT_AWAITING_COVERAGE) {
+ throw conflict("No exact PRESENT account-index readback is durably retained");
+ }
+ return new CanonicalGameplayBindingAccountIndexProjectionReceipt(
+ obligation.transitionId(),
+ obligation.ordinal(),
+ obligation.bindingRef(),
+ obligation.accountId(),
+ obligation.tenantId(),
+ obligation.bindingGeneration(),
+ obligation.accountIndexFence(),
+ obligation.inventoryRevision(),
+ obligation.projectionInventoryRevision(),
+ obligation.projectedMember(),
+ CanonicalGameplayBindingAccountIndexProjectionReceipt.State.PRESENT_AWAITING_COVERAGE);
+ }
+
+ private static CanonicalGameplayAdmissionDecision toAdmissionDecision(
+ Record row, CanonicalGameplayBindingProvisionalCasEvidence operation) {
+ if (row == null
+ || !operation.transition().transitionId().equals(row.get("transition_id", UUID.class))) {
+ throw conflict("Durable binding decision row is missing or changed");
+ }
+ String canonicalEvidence = row.get("admission_lease_evidence", String.class);
+ if (canonicalEvidence == null) {
+ throw conflict("Transition has no Account lease-bound admission decision");
+ }
+ AccountGameplayAdmissionLeaseEvidence lease;
+ try {
+ lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical(canonicalEvidence);
+ } catch (RuntimeException malformed) {
+ throw conflict("Stored Account lease evidence is not canonical: " + malformed.getMessage());
+ }
+ CanonicalPlayableTarget target = toAdmissionTarget(row);
+ CanonicalGameplayAdmissionDecision decision;
+ try {
+ decision =
+ new CanonicalGameplayAdmissionDecision(
+ operation.transition().transitionId(),
+ lease,
+ operation.candidate().identity(),
+ operation.transition().bindingGeneration(),
+ operation.transition().expectedPriorBindingGeneration(),
+ target);
+ } catch (RuntimeException mismatch) {
+ throw conflict(
+ "Stored lease and current target do not bind the exact durable candidate: "
+ + mismatch.getMessage());
+ }
+ if (!decision.requestId().equals(row.get("admission_request_id", UUID.class))
+ || !decision.leaseId().equals(row.get("admission_lease_id", UUID.class))
+ || !decision.leaseFence().equals(readBigInteger(row, "admission_lease_fence"))
+ || !decision.leaseKind().name().equals(row.get("admission_lease_kind", String.class))
+ || !decision.leaseSha256().equals(row.get("admission_lease_digest", String.class))
+ || !decision.leaseEvidenceJson().equals(canonicalEvidence)
+ || !Objects.equals(
+ decision.resumeEpisodeId(), row.get("admission_resume_episode_id", UUID.class))
+ || !Objects.equals(
+ decision.expectedOldBindingGeneration(),
+ nullableBigInteger(row, "admission_expected_old_binding_generation"))
+ || !decision
+ .leaseExpiresAtEpochMillis()
+ .equals(readBigInteger(row, "admission_lease_expires_at"))) {
+ throw conflict("Stored Account lease columns differ from the exact canonical carrier");
+ }
+ return decision;
+ }
+
+ private static CanonicalPlayableTarget toAdmissionTarget(Record row) {
+ try {
+ return new CanonicalPlayableTarget(
+ row.get("admission_target_namespace", String.class),
+ row.get("admission_target_tenant_slug", String.class),
+ row.get("admission_target_tenant_id", UUID.class),
+ row.get("admission_target_world_slug", String.class),
+ row.get("admission_target_world_display_name", String.class),
+ row.get("admission_target_realm_id", UUID.class),
+ row.get("admission_target_realm_slug", String.class),
+ row.get("admission_target_realm_display_name", String.class),
+ row.get("admission_target_game_session_tenant_id", Long.class),
+ row.get("admission_target_game_instance_id", Long.class),
+ row.get("admission_target_playable_state_namespace_id", UUID.class),
+ row.get("admission_target_playable_state_scope", String.class),
+ row.get("admission_target_canonical_game_instance_id", UUID.class),
+ row.get("admission_target_canonical_version_id", UUID.class),
+ row.get("admission_target_runtime_version_id", Long.class),
+ row.get("admission_target_catalog_revision", Long.class),
+ row.get("admission_target_pointer_version", Long.class),
+ row.get("admission_target_pointer_snapshot_digest", String.class),
+ row.get("admission_target_active_world_epoch", Long.class),
+ row.get("admission_target_initial_admission_request_id", String.class),
+ row.get("admission_target_initial_admission_request_digest", String.class),
+ CanonicalInitialAdmissionRequest.OriginKind.valueOf(
+ row.get("admission_target_origin_kind", String.class)),
+ row.get("admission_target_expected_prior_pointer_version", Long.class),
+ row.get("admission_target_hold_id", UUID.class),
+ row.get("admission_target_hold_fence", UUID.class),
+ row.get("admission_target_hold_binding_digest", String.class),
+ row.get("admission_target_audit_event_id", Long.class),
+ row.get("admission_target_owner_proof_digest", String.class),
+ CanonicalInitialAdmissionOwnerProof.Outcome.valueOf(
+ row.get("admission_target_owner_proof_outcome", String.class)),
+ row.get("admission_target_positive_durable_abort", Boolean.class),
+ row.get("admission_target_terminal_at", OffsetDateTime.class).toInstant(),
+ row.get("admission_target_character_creation_policy", String.class));
+ } catch (RuntimeException malformed) {
+ throw conflict(
+ "Stored canonical current-target evidence is incomplete or invalid: "
+ + malformed.getMessage());
+ }
+ }
+
+ private static void requireDecisionMatchesOperation(
+ CanonicalGameplayAdmissionDecision decision,
+ CanonicalGameplayBindingProvisionalCasEvidence operation) {
+ if (!decision.bindingDecisionId().equals(operation.transition().transitionId())
+ || !decision.candidate().equals(operation.candidate().identity())
+ || !decision.bindingGeneration().equals(operation.transition().bindingGeneration())
+ || !Objects.equals(
+ decision.expectedOldBindingGeneration(),
+ operation.transition().expectedPriorBindingGeneration())) {
+ throw conflict("Lease-bound decision differs from the exact durable transition");
+ }
+ }
+
+ private static void requireSameAdmissionDecision(
+ CanonicalGameplayAdmissionDecision expected, CanonicalGameplayAdmissionDecision current) {
+ if (!expected.bindingDecisionId().equals(current.bindingDecisionId())
+ || !expected.leaseEvidence().hasSameIdentity(current.leaseEvidence())
+ || !expected.candidate().equals(current.candidate())
+ || !expected.bindingGeneration().equals(current.bindingGeneration())
+ || !Objects.equals(
+ expected.expectedOldBindingGeneration(), current.expectedOldBindingGeneration())
+ || !expected.targetEvidence().equals(current.targetEvidence())) {
+ throw conflict("The immutable lease-bound decision changed during provisional publication");
+ }
+ }
+
+ private static CanonicalGameplayBindingProvisionalCasEvidence loadProvisionalCasEvidence(
+ DSLContext transaction, UUID transitionId, boolean forUpdate) {
+ String lock = forUpdate ? " FOR UPDATE" : "";
+ Record transition =
+ transaction.fetchOne(
+ "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?" + lock, transitionId);
+ if (transition == null) {
+ throw conflict("Durable binding transition does not exist");
+ }
+ byte[] candidateRef = transition.get("candidate_binding_ref", byte[].class);
+ Record candidateRow =
+ transaction.fetchOne(
+ "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?" + lock, candidateRef);
+ UUID reservationId = transition.get("issuer_reservation_id", UUID.class);
+ Record reservationRow =
+ transaction.fetchOne(
+ "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?" + lock, reservationId);
+ byte[] expectedPriorRef = transition.get("expected_prior_binding_ref", byte[].class);
+ BigInteger expectedPriorGeneration =
+ nullableBigInteger(transition, "expected_prior_binding_generation");
+ if ((expectedPriorRef == null) != (expectedPriorGeneration == null)) {
+ throw conflict("Durable transition has an incomplete nullable prior tuple");
+ }
+ boolean initialBinding = expectedPriorRef == null;
+ if (candidateRow == null || reservationRow == null) {
+ throw conflict("Durable transition is missing its exact candidate or reservation row");
+ }
+ Record priorRow = null;
+ Record priorReservationRow = null;
+ CanonicalGameplayLegacyMigrationDisposition initialBindingDisposition = null;
+ if (initialBinding) {
+ Record active =
+ transaction.fetchOne(
+ "SELECT binding_ref FROM "
+ + INVENTORY
+ + " WHERE tenant_id = ? AND playable_state_namespace_id = ?"
+ + " AND character_id = ? AND lifecycle = 'ACTIVE'"
+ + (forUpdate ? " FOR UPDATE" : ""),
+ transition.get("tenant_id", UUID.class),
+ transition.get("playable_state_namespace_id", UUID.class),
+ transition.get("character_id", UUID.class));
+ if (active != null) {
+ throw conflict("A first binding cannot proceed while an active controller exists");
+ }
+ initialBindingDisposition =
+ readVerifiedLegacyDisposition(
+ transaction, readCurrentInventoryRevision(transaction), forUpdate);
+ } else {
+ priorRow =
+ transaction.fetchOne(
+ "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?" + lock, expectedPriorRef);
+ if (priorRow == null) {
+ throw conflict("Durable transfer is missing its exact prior source row");
+ }
+ priorReservationRow =
+ transaction.fetchOne(
+ "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?" + lock,
+ priorRow.get("issuer_reservation_id", UUID.class));
+ if (priorReservationRow == null) {
+ throw conflict("Durable transfer is missing its exact prior issuer reservation");
+ }
+ }
+
+ CanonicalGameplayBindingTransitionSnapshot transitionSnapshot =
+ toTransitionSnapshot(transition, candidateRow, reservationRow);
+ if (initialBinding) {
+ requireReadAccountCoverageEvidenceCurrent(
+ transaction,
+ transitionSnapshot.candidate().accountId(),
+ transitionSnapshot.accountCoverageEvidence());
+ }
+ CanonicalGameplayBindingInventoryEntry candidate = toInventoryEntry(candidateRow);
+ CanonicalIssuerPartitionReservation reservation = toReservation(reservationRow);
+ CanonicalGameplayBindingInventoryEntry prior =
+ priorRow == null ? null : toInventoryEntry(priorRow);
+ CanonicalIssuerPartitionReservation priorReservation =
+ priorReservationRow == null ? null : toReservation(priorReservationRow);
+ CanonicalGameplayBindingProvisionalCasEvidence evidence =
+ new CanonicalGameplayBindingProvisionalCasEvidence(
+ transitionSnapshot,
+ candidate,
+ reservation,
+ prior,
+ priorReservation,
+ initialBindingDisposition);
+ List accountObligations =
+ transaction
+ .fetch(
+ "SELECT o.*, i.playable_state_namespace_id, i.character_id,"
+ + " i.playable_state_scope, i.game_instance_id, i.runtime_game_instance_id,"
+ + " i.session_id, i.region_id, i.region_epoch, i.issuer_id,"
+ + " i.issuer_auth_generation, i.issuer_index_layout_version,"
+ + " i.issuer_index_partition_count, i.issuer_index_partition_capacity"
+ + " FROM "
+ + ACCOUNT_OBLIGATION
+ + " o JOIN "
+ + INVENTORY
+ + " i ON i.binding_ref = o.binding_ref WHERE o.transition_id = ?"
+ + " ORDER BY o.obligation_ordinal"
+ + (forUpdate ? " FOR UPDATE OF o" : ""),
+ transitionId)
+ .map(CanonicalGameplayBindingInventoryRepository::toAccountObligation);
+ Record issuerObligationRow =
+ transaction.fetchOne(
+ "SELECT o.*, i.account_id, i.tenant_id, i.playable_state_namespace_id,"
+ + " i.character_id, i.playable_state_scope, i.game_instance_id,"
+ + " i.runtime_game_instance_id, i.session_id, i.region_id, i.region_epoch,"
+ + " i.issuer_id, i.issuer_auth_generation, i.issuer_index_layout_version,"
+ + " i.issuer_index_partition_count, i.issuer_index_partition_capacity"
+ + " FROM "
+ + ISSUER_OBLIGATION
+ + " o JOIN "
+ + INVENTORY
+ + " i ON i.binding_ref = o.binding_ref WHERE o.transition_id = ?"
+ + " AND o.binding_ref = ?"
+ + (forUpdate ? " FOR UPDATE OF o" : ""),
+ transitionId,
+ candidateRef);
+ CanonicalGameplayBindingIssuerIndexObligation issuerObligation =
+ issuerObligationRow == null ? null : toIssuerObligation(issuerObligationRow);
+ Record regionObligationRow =
+ transaction.fetchOne(
+ "SELECT * FROM "
+ + REGION_OBLIGATION
+ + " WHERE transition_id = ?"
+ + (forUpdate ? " FOR UPDATE" : ""),
+ transitionId);
+ CanonicalGameplayBindingRegionBridgeObligation regionObligation =
+ regionObligationRow == null ? null : toRegionObligation(regionObligationRow);
+ requireExactProvisionalRows(evidence, accountObligations, issuerObligation, regionObligation);
+ return evidence;
+ }
+
+ private static void requireExactProvisionalRows(
+ CanonicalGameplayBindingProvisionalCasEvidence evidence,
+ List accountObligations,
+ CanonicalGameplayBindingIssuerIndexObligation issuerObligation,
+ CanonicalGameplayBindingRegionBridgeObligation regionObligation) {
+ var transition = evidence.transition();
+ var candidate = evidence.candidate();
+ var prior = evidence.expectedPrior();
+ var reservation = evidence.candidateReservation();
+ var priorReservation = evidence.expectedPriorReservation();
+ if (!reservation.owner().equals(candidate.identity())
+ || !reservation.owner().bindingRef().equals(candidate.bindingRef())
+ || !reservation.transitionId().equals(transition.transitionId())
+ || !reservation.bindingGeneration().equals(transition.bindingGeneration())
+ || !reservation.reservationId().equals(transition.issuerReservationId())
+ || !reservation.reservationFence().equals(transition.reservationFence())
+ || reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED
+ || !reservation.inventoryRevision().equals(transition.inventoryRevision())
+ || ((prior == null) != (priorReservation == null))
+ || ((prior == null) != (evidence.initialBindingMigrationDisposition() != null))
+ || accountObligations.size() != (prior == null ? 1 : 2)) {
+ throw conflict(
+ "Durable reservation or account obligations differ from this exact transition");
+ }
+ var candidateAccount = accountObligations.getFirst();
+ if (!candidateAccount.transitionId().equals(transition.transitionId())
+ || candidateAccount.ordinal() != 0
+ || !candidateAccount.bindingRef().equals(candidate.bindingRef())
+ || !candidateAccount.accountId().equals(candidate.identity().accountId())
+ || !candidateAccount.tenantId().equals(candidate.identity().tenantId())
+ || candidateAccount.action()
+ != CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN
+ || !candidateAccount.bindingGeneration().equals(candidate.bindingGeneration())
+ || !Objects.equals(
+ candidateAccount.expectedPriorGeneration(), transition.expectedPriorBindingGeneration())
+ || !candidateAccount.accountIndexFence().equals(candidate.accountIndexFence())
+ || candidateAccount.executionPhase()
+ != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS
+ || candidateAccount.status()
+ != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED
+ || !candidateAccount.inventoryRevision().equals(transition.inventoryRevision())) {
+ throw conflict("Durable account-index repair obligations differ from this exact transition");
+ }
+ if (prior == null) {
+ if (transition.expectedPriorBindingRef() != null
+ || transition.expectedPriorBindingGeneration() != null) {
+ throw conflict("Initial-binding transition retained an unexpected prior source");
+ }
+ } else {
+ if (priorReservation == null
+ || !priorReservation.owner().equals(prior.identity())
+ || !priorReservation.owner().bindingRef().equals(prior.bindingRef())
+ || !priorReservation.transitionId().equals(prior.transitionId())
+ || !priorReservation.bindingGeneration().equals(prior.bindingGeneration())
+ || !priorReservation.reservationId().equals(prior.issuerReservationId())
+ || priorReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.BOUND
+ || !priorReservation.inventoryRevision().equals(prior.inventoryRevision())) {
+ throw conflict("Durable prior reservation differs from the exact transfer source");
+ }
+ var priorAccount = accountObligations.get(1);
+ if (!priorAccount.transitionId().equals(transition.transitionId())
+ || priorAccount.ordinal() != 1
+ || !priorAccount.bindingRef().equals(prior.bindingRef())
+ || !priorAccount.accountId().equals(prior.identity().accountId())
+ || !priorAccount.tenantId().equals(prior.identity().tenantId())
+ || priorAccount.action() != CanonicalGameplayBindingAccountIndexObligation.Action.REMOVE
+ || !priorAccount.bindingGeneration().equals(prior.bindingGeneration())
+ || !priorAccount.expectedPriorGeneration().equals(prior.bindingGeneration())
+ || !priorAccount.accountIndexFence().equals(prior.accountIndexFence())
+ || priorAccount.executionPhase()
+ != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.AFTER_FINAL_CAS
+ || priorAccount.status() != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED
+ || !priorAccount.inventoryRevision().equals(transition.inventoryRevision())) {
+ throw conflict("Durable prior account-index obligation differs from the exact transfer");
+ }
+ }
+ if (issuerObligation == null
+ || !issuerObligation.transitionId().equals(transition.transitionId())
+ || !issuerObligation.bindingRef().equals(candidate.bindingRef())
+ || !issuerObligation.bindingGeneration().equals(candidate.bindingGeneration())
+ || !issuerObligation.reservationId().equals(reservation.reservationId())
+ || issuerObligation.status()
+ != CanonicalGameplayBindingIssuerIndexObligation.Status.REQUIRED
+ || !issuerObligation.inventoryRevision().equals(transition.inventoryRevision())
+ || regionObligation == null
+ || !regionObligation.transitionId().equals(transition.transitionId())
+ || !regionObligation.bindingRef().equals(candidate.bindingRef())
+ || !regionObligation.bindingGeneration().equals(candidate.bindingGeneration())
+ || !regionObligation.accountId().equals(candidate.identity().accountId())
+ || !regionObligation.tenantId().equals(candidate.identity().tenantId())
+ || !regionObligation.gameInstanceId().equals(candidate.identity().gameInstanceId())
+ || regionObligation.runtimeGameInstanceId() != candidate.identity().runtimeGameInstanceId()
+ || !regionObligation.sessionId().equals(candidate.identity().sessionId())
+ || !regionObligation.regionId().equals(candidate.identity().regionId())
+ || !regionObligation.regionEpoch().equals(candidate.identity().regionEpoch())
+ || regionObligation.status()
+ != CanonicalGameplayBindingRegionBridgeObligation.Status.REQUIRED
+ || !regionObligation.inventoryRevision().equals(transition.inventoryRevision())) {
+ throw conflict("Durable issuer or region obligations differ from this exact transition");
+ }
+ }
+
+ private static void requireSameProvisionalOperation(
+ CanonicalGameplayBindingProvisionalCasEvidence expected,
+ CanonicalGameplayBindingProvisionalCasEvidence current) {
+ if (!expected.transition().transitionId().equals(current.transition().transitionId())
+ || !expected.transition().bindingRef().equals(current.transition().bindingRef())
+ || !expected
+ .transition()
+ .bindingGeneration()
+ .equals(current.transition().bindingGeneration())
+ || !expected
+ .transition()
+ .issuerReservationId()
+ .equals(current.transition().issuerReservationId())
+ || !expected.transition().reservationFence().equals(current.transition().reservationFence())
+ || !expected
+ .transition()
+ .candidateAccountIndexFence()
+ .equals(current.transition().candidateAccountIndexFence())
+ || !expected
+ .transition()
+ .accountCoverageEvidence()
+ .equals(current.transition().accountCoverageEvidence())
+ || !Objects.equals(
+ expected.initialBindingMigrationDisposition(),
+ current.initialBindingMigrationDisposition())
+ || !Objects.equals(
+ expected.transition().expectedPriorBindingRef(),
+ current.transition().expectedPriorBindingRef())
+ || !Objects.equals(
+ expected.transition().expectedPriorBindingGeneration(),
+ current.transition().expectedPriorBindingGeneration())
+ || !expected.candidate().identity().equals(current.candidate().identity())
+ || !expected.candidate().bindingRef().equals(current.candidate().bindingRef())
+ || !expected
+ .candidateReservation()
+ .reservationId()
+ .equals(current.candidateReservation().reservationId())
+ || !expected.candidateReservation().owner().equals(current.candidateReservation().owner())
+ || !expected
+ .candidateReservation()
+ .bindingGeneration()
+ .equals(current.candidateReservation().bindingGeneration())
+ || !expected
+ .candidateReservation()
+ .transitionId()
+ .equals(current.candidateReservation().transitionId())
+ || !expected
+ .candidateReservation()
+ .partitionId()
+ .equals(current.candidateReservation().partitionId())
+ || expected.candidateReservation().lifecycle() != current.candidateReservation().lifecycle()
+ || !expected
+ .candidateReservation()
+ .reservationFence()
+ .equals(current.candidateReservation().reservationFence())
+ || !expected
+ .candidateReservation()
+ .issuerCoverageOperationId()
+ .equals(current.candidateReservation().issuerCoverageOperationId())
+ || !expected
+ .candidateReservation()
+ .issuerCoverageOperationFence()
+ .equals(current.candidateReservation().issuerCoverageOperationFence())
+ || !expected
+ .candidateReservation()
+ .coverageFence()
+ .equals(current.candidateReservation().coverageFence())
+ || !expected
+ .candidateReservation()
+ .inventorySnapshotRevision()
+ .equals(current.candidateReservation().inventorySnapshotRevision())
+ || !Objects.equals(expected.expectedPrior(), current.expectedPrior())
+ || !Objects.equals(
+ expected.expectedPriorReservation(), current.expectedPriorReservation())) {
+ throw conflict("The durable operation changed after its exact Redis readback");
+ }
+ }
+
+ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction(
+ DSLContext transaction, CanonicalGameplayBindingTransitionRequest request) {
+ BigInteger revision = lockInventoryRevision(transaction);
+ CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence =
+ lockAccountCoverageEvidence(transaction, request.candidate().accountId());
+ boolean initialBinding = request.expectedPriorBindingRef() == null;
+ if (initialBinding) {
+ readVerifiedLegacyDisposition(transaction, revision, true);
+ }
+ Record existing = findTransition(transaction, request.transitionId());
+ if (existing != null) {
+ CanonicalGameplayBindingTransitionSnapshot retry =
+ requireExactRetry(transaction, request, existing);
+ if (!retry.accountCoverageEvidence().equals(accountCoverageEvidence)) {
+ throw conflict("Same transition retry carries stale account-wide coverage evidence");
+ }
+ return retry;
+ }
+
+ CanonicalGameplayBindingIdentity candidate = request.candidate();
+ byte[] candidateRef = candidate.bindingRef().bytes();
+ CanonicalGameplayBindingRef expectedPriorBindingRef = request.expectedPriorBindingRef();
+ byte[] expectedPriorRef =
+ expectedPriorBindingRef == null ? null : expectedPriorBindingRef.bytes();
+ Record active = findActiveController(transaction, candidate);
+ if (expectedPriorRef == null) {
+ if (active != null) {
+ throw conflict("First binding cannot proceed while an active controller exists");
+ }
+ } else {
+ if (active == null
+ || !Arrays.equals(active.get("binding_ref", byte[].class), expectedPriorRef)
+ || !readBigInteger(active, "binding_generation")
+ .equals(request.expectedPriorBindingGeneration())
+ || !Objects.equals(active.get("account_id", UUID.class), candidate.accountId())
+ || !"ACKNOWLEDGED".equals(active.get("account_index_state", String.class))
+ || !"ACKNOWLEDGED".equals(active.get("issuer_index_state", String.class))) {
+ throw conflict("The exact expected prior controller binding is no longer active");
+ }
+ if (Arrays.equals(expectedPriorRef, candidateRef)) {
+ throw conflict("A transfer candidate must have a distinct exact bindingRef");
+ }
+ }
+
+ Record unresolved = findUnresolvedController(transaction, candidate);
+ if (unresolved != null) {
+ throw conflict("An unresolved candidate or repair obligation already fences this controller");
+ }
+
+ ensureGenerationRow(transaction, candidate);
+ Record generationRow =
+ Objects.requireNonNull(
+ transaction.fetchOne(
+ "SELECT last_issued_generation FROM "
+ + GENERATION
+ + " WHERE tenant_id = ? AND playable_state_namespace_id = ? AND character_id = ? FOR UPDATE",
+ candidate.tenantId(),
+ candidate.playableStateNamespaceId(),
+ candidate.characterId()),
+ "binding generation authority row must exist");
+ BigInteger lastIssued = readBigInteger(generationRow, "last_issued_generation");
+ BigInteger priorGeneration =
+ expectedPriorRef == null ? BigInteger.ZERO : request.expectedPriorBindingGeneration();
+ if (lastIssued.compareTo(priorGeneration) < 0) {
+ throw conflict("The durable generation authority is behind the exact prior binding");
+ }
+ BigInteger candidateGeneration = lastIssued.add(BigInteger.ONE);
+ BigInteger nextRevision = revision.add(BigInteger.ONE);
+ BigInteger partitionId =
+ candidate.bindingRef().partitionId(candidate.issuerIndexPartitionCount());
+ CanonicalGameplayBindingTransitionSnapshot prepared =
+ new CanonicalGameplayBindingTransitionSnapshot(
+ request.transitionId(),
+ candidate,
+ candidateGeneration,
+ candidate.bindingRef(),
+ nextRevision,
+ request.issuerReservation().reservationId(),
+ request.issuerReservation().reservationFence(),
+ request.candidateAccountIndexFence(),
+ expectedPriorBindingRef,
+ expectedPriorRef == null ? null : request.expectedPriorBindingGeneration(),
+ CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED,
+ accountCoverageEvidence);
+
+ int generationUpdated =
+ transaction.execute(
+ "UPDATE "
+ + GENERATION
+ + " SET last_issued_generation = ? WHERE tenant_id = ?"
+ + " AND playable_state_namespace_id = ? AND character_id = ?"
+ + " AND last_issued_generation = ?",
+ decimal(candidateGeneration),
+ candidate.tenantId(),
+ candidate.playableStateNamespaceId(),
+ candidate.characterId(),
+ decimal(lastIssued));
+ requireOne(generationUpdated, "binding generation compare-and-set lost its locked row");
+
+ insertCandidate(transaction, request, prepared, partitionId);
+ insertTransition(transaction, request, prepared, expectedPriorRef);
+ insertAccountObligations(transaction, request, prepared, active, expectedPriorRef);
+ insertReservation(transaction, request, prepared, partitionId, nextRevision);
+ insertIssuerObligation(transaction, prepared);
+ insertRegionObligation(transaction, prepared);
+
+ int revisionUpdated =
+ transaction.execute(
+ "UPDATE game_session_canonical_binding_inventory_clock"
+ + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = ?",
+ decimal(nextRevision),
+ decimal(revision));
+ requireOne(revisionUpdated, "durable inventory revision compare-and-set lost its locked row");
+ return prepared;
+ }
+
+ private static void validateRequest(CanonicalGameplayBindingTransitionRequest request) {
+ request.candidate().bindingRef().partitionId(request.candidate().issuerIndexPartitionCount());
+ if (request.candidateAccountIndexFence().equals(NIL_UUID)) {
+ throw new IllegalArgumentException("candidateAccountIndexFence must not be nil");
+ }
+ }
+
+ private static void ensureGenerationRow(
+ DSLContext transaction, CanonicalGameplayBindingIdentity candidate) {
+ transaction.execute(
+ "INSERT INTO "
+ + GENERATION
+ + " (tenant_id, playable_state_namespace_id, character_id, last_issued_generation) "
+ + "VALUES (?, ?, ?, 0) ON CONFLICT DO NOTHING",
+ candidate.tenantId(),
+ candidate.playableStateNamespaceId(),
+ candidate.characterId());
+ }
+
+ private static BigInteger lockInventoryRevision(DSLContext transaction) {
+ return readBigInteger(
+ Objects.requireNonNull(
+ transaction.fetchOne(
+ "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock"
+ + " WHERE singleton_id = 1 FOR UPDATE"),
+ "inventory revision clock row must exist"),
+ "inventory_revision");
+ }
+
+ private static BigInteger readCurrentInventoryRevision(DSLContext transaction) {
+ return readBigInteger(
+ Objects.requireNonNull(
+ transaction.fetchOne(
+ "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock"
+ + " WHERE singleton_id = 1"),
+ "canonical inventory clock row is missing"),
+ "inventory_revision");
+ }
+
+ private static CanonicalGameplayLegacyMigrationDisposition readVerifiedLegacyDisposition(
+ DSLContext transaction, BigInteger currentInventoryRevision, boolean forShare) {
+ Record row =
+ transaction.fetchOne(
+ "SELECT * FROM "
+ + LEGACY_DISPOSITION
+ + " WHERE singleton_id = 1"
+ + (forShare ? " FOR SHARE" : ""));
+ if (row == null || !"VERIFIED".equals(row.get("disposition_state", String.class))) {
+ throw conflict(
+ "First binding requires the exact VERIFIED legacy-index migration fence;"
+ + " account coverage state alone is not migration proof");
+ }
+ CanonicalGameplayLegacyMigrationDisposition disposition;
+ try {
+ disposition =
+ new CanonicalGameplayLegacyMigrationDisposition(
+ row.get("cohort_id", UUID.class),
+ row.get("owner_operation_id", UUID.class),
+ row.get("legacy_writer_fence", UUID.class),
+ readBigInteger(row, "source_snapshot_revision"),
+ readBigInteger(row, "canonical_inventory_revision"),
+ readBigInteger(row, "namespace_index_readback_revision"),
+ row.get("evidence_digest", String.class));
+ } catch (RuntimeException malformed) {
+ throw conflict("The VERIFIED legacy-index migration disposition is incomplete or invalid");
+ }
+ if (disposition.canonicalInventoryRevision().compareTo(currentInventoryRevision) > 0) {
+ throw conflict("The VERIFIED legacy disposition is newer than current canonical inventory");
+ }
+ return disposition;
+ }
+
+ private static CanonicalGameplayAccountCoverageEvidence lockAccountCoverageEvidence(
+ DSLContext transaction, UUID accountId) {
+ transaction.execute(
+ "INSERT INTO game_session_canonical_account_coverage_control "
+ + "(account_id, state, last_operation_fence) "
+ + "VALUES (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0) ON CONFLICT (account_id) DO NOTHING",
+ accountId);
+ Record control =
+ Objects.requireNonNull(
+ transaction.fetchOne(
+ "SELECT * FROM game_session_canonical_account_coverage_control "
+ + "WHERE account_id = ? FOR UPDATE",
+ accountId),
+ "account coverage control row must exist");
+ return accountCoverageEvidenceFromControl(control, accountId);
+ }
+
+ private static void requireReadAccountCoverageEvidenceCurrent(
+ DSLContext transaction, UUID accountId, CanonicalGameplayAccountCoverageEvidence expected) {
+ Record control =
+ transaction.fetchOne(
+ "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?",
+ accountId);
+ if (control == null
+ || !accountCoverageEvidenceFromControl(control, accountId).equals(expected)) {
+ throw conflict("First-binding account-coverage fence is missing or changed");
+ }
+ }
+
+ private static CanonicalGameplayAccountCoverageEvidence accountCoverageEvidenceFromControl(
+ Record control, UUID accountId) {
+ String state = control.get("state", String.class);
+ if ("ACTIVE".equals(state)) {
+ throw conflict("Account-wide admission fence blocks a new binding transition");
+ }
+ if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) {
+ return CanonicalGameplayAccountCoverageEvidence.noActiveFlow();
+ }
+ if ("HISTORICAL".equals(state)) {
+ return CanonicalGameplayAccountCoverageEvidence.historical(
+ control.get("current_operation_id", UUID.class),
+ readBigInteger(control, "current_operation_fence"),
+ control.get("historical_account_admission_fence", UUID.class),
+ control.get("coverage_fence", UUID.class),
+ accountId,
+ readBigInteger(control, "inventory_snapshot_revision"),
+ readBigInteger(control, "coverage_generation"));
+ }
+ throw conflict("Account coverage control state is unknown and cannot authorize a transition");
+ }
+
+ private static void requireAccountCoverageEvidenceCurrent(
+ DSLContext transaction, UUID accountId, CanonicalGameplayAccountCoverageEvidence expected) {
+ CanonicalGameplayAccountCoverageEvidence current =
+ lockAccountCoverageEvidence(transaction, accountId);
+ if (!current.equals(expected)) {
+ throw conflict("Binding transition account-coverage carrier is stale or mismatched");
+ }
+ }
+
+ private static Record findTransition(DSLContext transaction, UUID transitionId) {
+ return transaction.fetchOne(
+ "SELECT * FROM " + TRANSITION + " WHERE transition_id = ? FOR UPDATE", transitionId);
+ }
+
+ /** Reads a transition without acquiring a row lock for callers in read-only transactions. */
+ private static Record readTransition(DSLContext transaction, UUID transitionId) {
+ return transaction.fetchOne(
+ "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?", transitionId);
+ }
+
+ private static Record findActiveController(
+ DSLContext transaction, CanonicalGameplayBindingIdentity candidate) {
+ return transaction.fetchOne(
+ "SELECT * FROM "
+ + INVENTORY
+ + " WHERE tenant_id = ? AND playable_state_namespace_id = ? AND character_id = ?"
+ + " AND lifecycle = 'ACTIVE' FOR UPDATE",
+ candidate.tenantId(),
+ candidate.playableStateNamespaceId(),
+ candidate.characterId());
+ }
+
+ private static Record findUnresolvedController(
+ DSLContext transaction, CanonicalGameplayBindingIdentity candidate) {
+ Record openTransition =
+ transaction.fetchOne(
+ "SELECT transition_id FROM "
+ + TRANSITION
+ + " WHERE tenant_id = ? AND playable_state_namespace_id = ? AND character_id = ?"
+ + " AND status IN ('PREPARED', 'PROVISIONAL', 'AMBIGUOUS') LIMIT 1",
+ candidate.tenantId(),
+ candidate.playableStateNamespaceId(),
+ candidate.characterId());
+ if (openTransition != null) {
+ return openTransition;
+ }
+ return transaction.fetchOne(
+ "SELECT transition_id FROM "
+ + INVENTORY
+ + " WHERE tenant_id = ? AND playable_state_namespace_id = ? AND character_id = ?"
+ + " AND lifecycle IN ('CANDIDATE_PREPARED', 'PROVISIONAL', 'TERMINAL_UNRESOLVED') LIMIT 1",
+ candidate.tenantId(),
+ candidate.playableStateNamespaceId(),
+ candidate.characterId());
+ }
+
+ private static CanonicalGameplayBindingTransitionSnapshot requireExactRetry(
+ DSLContext transaction,
+ CanonicalGameplayBindingTransitionRequest request,
+ Record transition) {
+ CanonicalGameplayBindingIdentity candidate = request.candidate();
+ CanonicalGameplayBindingRef expectedRef = request.expectedPriorBindingRef();
+ byte[] storedPriorRef = transition.get("expected_prior_binding_ref", byte[].class);
+ CanonicalGameplayBindingRef storedPriorBindingRef =
+ storedPriorRef == null ? null : CanonicalGameplayBindingRef.fromExactBytes(storedPriorRef);
+ BigInteger storedPriorGeneration =
+ nullableBigInteger(transition, "expected_prior_binding_generation");
+ String storedStatus = transition.get("status", String.class);
+ String expectedCandidateLifecycle =
+ "PROVISIONAL".equals(storedStatus) ? "PROVISIONAL" : "CANDIDATE_PREPARED";
+ if (!Objects.equals(transition.get("transition_id", UUID.class), request.transitionId())
+ || (!"PREPARED".equals(storedStatus) && !"PROVISIONAL".equals(storedStatus))
+ || !Objects.equals(storedPriorBindingRef, expectedRef)
+ || !Objects.equals(storedPriorGeneration, request.expectedPriorBindingGeneration())
+ || !Objects.equals(transition.get("tenant_id", UUID.class), candidate.tenantId())
+ || !Objects.equals(
+ transition.get("playable_state_namespace_id", UUID.class),
+ candidate.playableStateNamespaceId())
+ || !Objects.equals(transition.get("character_id", UUID.class), candidate.characterId())
+ || !Arrays.equals(
+ transition.get("candidate_binding_ref", byte[].class), candidate.bindingRef().bytes())
+ || !Objects.equals(
+ transition.get("candidate_account_index_fence", UUID.class),
+ request.candidateAccountIndexFence())
+ || !Objects.equals(
+ transition.get("issuer_reservation_id", UUID.class),
+ request.issuerReservation().reservationId())) {
+ throw conflict("The same transition identity was retried with a different exact request");
+ }
+ if (expectedRef == null && findActiveController(transaction, candidate) != null) {
+ throw conflict("A first-binding retry cannot proceed while an active controller exists");
+ }
+ Record binding =
+ transaction.fetchOne(
+ "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE",
+ candidate.bindingRef().bytes());
+ if (binding == null
+ || !toIdentity(binding).equals(candidate)
+ || !expectedCandidateLifecycle.equals(binding.get("lifecycle", String.class))
+ || !"REPAIR_REQUIRED".equals(binding.get("account_index_state", String.class))
+ || !"REPAIR_REQUIRED".equals(binding.get("issuer_index_state", String.class))
+ || !readBigInteger(binding, "binding_generation")
+ .equals(readBigInteger(transition, "candidate_binding_generation"))
+ || !readBigInteger(binding, "inventory_revision")
+ .equals(readBigInteger(transition, "inventory_revision"))
+ || !Objects.equals(
+ binding.get("account_index_fence", UUID.class), request.candidateAccountIndexFence())
+ || !Objects.equals(
+ binding.get("issuer_reservation_id", UUID.class),
+ request.issuerReservation().reservationId())) {
+ throw conflict("Stored candidate identity differs from the exact transition retry");
+ }
+ Record reservation =
+ transaction.fetchOne(
+ "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE",
+ request.issuerReservation().reservationId());
+ if (reservation == null
+ || !toIdentity(reservation).equals(candidate)
+ || !Arrays.equals(
+ reservation.get("binding_ref", byte[].class), candidate.bindingRef().bytes())
+ || !Objects.equals(
+ reservation.get("reservation_fence", UUID.class),
+ request.issuerReservation().reservationFence())
+ || !Objects.equals(
+ reservation.get("issuer_coverage_operation_id", UUID.class),
+ request.issuerReservation().issuerCoverageOperationId())
+ || !readBigInteger(reservation, "issuer_coverage_operation_fence")
+ .equals(request.issuerReservation().issuerCoverageOperationFence())
+ || !readBigInteger(reservation, "coverage_fence")
+ .equals(request.issuerReservation().coverageFence())
+ || !readBigInteger(reservation, "inventory_snapshot_revision")
+ .equals(request.issuerReservation().inventorySnapshotRevision())
+ || !Objects.equals(reservation.get("account_id", UUID.class), candidate.accountId())
+ || !Objects.equals(reservation.get("tenant_id", UUID.class), candidate.tenantId())
+ || !Objects.equals(
+ reservation.get("game_instance_id", UUID.class), candidate.gameInstanceId())
+ || !Objects.equals(
+ reservation.get("runtime_game_instance_id", Long.class),
+ candidate.runtimeGameInstanceId())
+ || !Objects.equals(reservation.get("session_id", String.class), candidate.sessionId())
+ || !Objects.equals(reservation.get("issuer_id", UUID.class), candidate.issuerId())
+ || !readBigInteger(reservation, "issuer_auth_generation")
+ .equals(candidate.issuerAuthGeneration())
+ || !readBigInteger(reservation, "issuer_index_layout_version")
+ .equals(candidate.issuerIndexLayoutVersion())
+ || !Objects.equals(
+ readBigInteger(reservation, "issuer_index_partition_count"),
+ candidate.issuerIndexPartitionCount())
+ || !Objects.equals(
+ readBigInteger(reservation, "issuer_index_partition_capacity"),
+ candidate.issuerIndexPartitionCapacity())
+ || !Objects.equals(
+ readBigInteger(reservation, "partition_id"),
+ candidate.bindingRef().partitionId(candidate.issuerIndexPartitionCount()))) {
+ throw conflict("Stored reservation evidence differs from the exact transition retry");
+ }
+ requireExactStoredObligations(transaction, request, transition, binding, reservation);
+ return toTransitionSnapshot(transition, binding, reservation);
+ }
+
+ private static void requireExactStoredObligations(
+ DSLContext transaction,
+ CanonicalGameplayBindingTransitionRequest request,
+ Record transition,
+ Record candidate,
+ Record reservation) {
+ CanonicalGameplayBindingRef expectedPriorBindingRef = request.expectedPriorBindingRef();
+ byte[] expectedPriorRef =
+ expectedPriorBindingRef == null ? null : expectedPriorBindingRef.bytes();
+ Record source =
+ expectedPriorRef == null
+ ? null
+ : transaction.fetchOne(
+ "SELECT * FROM "
+ + INVENTORY
+ + " WHERE binding_ref = ? AND lifecycle = 'ACTIVE' FOR UPDATE",
+ expectedPriorRef);
+ if (expectedPriorRef != null
+ && (source == null
+ || !readBigInteger(source, "binding_generation")
+ .equals(request.expectedPriorBindingGeneration()))) {
+ throw conflict("Stored exact prior controller evidence is no longer active");
+ }
+ var obligations =
+ transaction.fetch(
+ "SELECT * FROM "
+ + ACCOUNT_OBLIGATION
+ + " WHERE transition_id = ? ORDER BY obligation_ordinal FOR UPDATE",
+ request.transitionId());
+ int expectedCount = source == null ? 1 : 2;
+ if (obligations.size() != expectedCount) {
+ throw conflict("Stored transition does not retain every required account-index obligation");
+ }
+ Record add = obligations.get(0);
+ BigInteger candidateGeneration = readBigInteger(transition, "candidate_binding_generation");
+ BigInteger expectedPriorGeneration = request.expectedPriorBindingGeneration();
+ if (!Arrays.equals(
+ add.get("binding_ref", byte[].class), request.candidate().bindingRef().bytes())
+ || !"ADD_OR_RETAIN".equals(add.get("action", String.class))
+ || !"BEFORE_FINAL_CAS".equals(add.get("execution_phase", String.class))
+ || !"REQUIRED".equals(add.get("status", String.class))
+ || !readBigInteger(add, "binding_generation").equals(candidateGeneration)
+ || !Objects.equals(add.get("account_id", UUID.class), request.candidate().accountId())
+ || !Objects.equals(add.get("tenant_id", UUID.class), request.candidate().tenantId())
+ || !Objects.equals(
+ nullableBigInteger(add, "expected_prior_generation"), expectedPriorGeneration)
+ || !Objects.equals(
+ add.get("account_index_fence", UUID.class), request.candidateAccountIndexFence())
+ || !readBigInteger(add, "inventory_revision")
+ .equals(readBigInteger(transition, "inventory_revision"))) {
+ throw conflict("Stored candidate account-index obligation differs from the exact retry");
+ }
+ if (source != null) {
+ Record remove = obligations.get(1);
+ if (!Arrays.equals(remove.get("binding_ref", byte[].class), expectedPriorRef)
+ || !"REMOVE".equals(remove.get("action", String.class))
+ || !"AFTER_FINAL_CAS".equals(remove.get("execution_phase", String.class))
+ || !"REQUIRED".equals(remove.get("status", String.class))
+ || !Objects.equals(
+ remove.get("account_id", UUID.class), source.get("account_id", UUID.class))
+ || !Objects.equals(
+ remove.get("tenant_id", UUID.class), source.get("tenant_id", UUID.class))
+ || !readBigInteger(remove, "binding_generation")
+ .equals(request.expectedPriorBindingGeneration())
+ || !readBigInteger(remove, "expected_prior_generation")
+ .equals(request.expectedPriorBindingGeneration())
+ || !Objects.equals(
+ remove.get("account_index_fence", UUID.class),
+ source.get("account_index_fence", UUID.class))
+ || !readBigInteger(remove, "inventory_revision")
+ .equals(readBigInteger(transition, "inventory_revision"))) {
+ throw conflict("Stored prior account-index obligation differs from the exact retry");
+ }
+ }
+ Record issuerObligation =
+ transaction.fetchOne(
+ "SELECT * FROM "
+ + ISSUER_OBLIGATION
+ + " WHERE transition_id = ? AND binding_ref = ? FOR UPDATE",
+ request.transitionId(),
+ request.candidate().bindingRef().bytes());
+ if (issuerObligation == null
+ || !"REQUIRED".equals(issuerObligation.get("status", String.class))
+ || !Arrays.equals(
+ issuerObligation.get("binding_ref", byte[].class),
+ request.candidate().bindingRef().bytes())
+ || !Objects.equals(
+ issuerObligation.get("reservation_id", UUID.class),
+ request.issuerReservation().reservationId())
+ || !readBigInteger(issuerObligation, "binding_generation").equals(candidateGeneration)
+ || !readBigInteger(issuerObligation, "inventory_revision")
+ .equals(readBigInteger(transition, "inventory_revision"))) {
+ throw conflict("Stored issuer-index obligation differs from the exact retry");
+ }
+ Record regionObligation =
+ transaction.fetchOne(
+ "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE",
+ request.transitionId());
+ if (regionObligation == null
+ || !"REQUIRED".equals(regionObligation.get("status", String.class))
+ || !Arrays.equals(
+ regionObligation.get("binding_ref", byte[].class),
+ request.candidate().bindingRef().bytes())
+ || !readBigInteger(regionObligation, "binding_generation").equals(candidateGeneration)
+ || !Objects.equals(
+ regionObligation.get("region_id", UUID.class), request.candidate().regionId())
+ || !Objects.equals(
+ regionObligation.get("account_id", UUID.class), request.candidate().accountId())
+ || !Objects.equals(
+ regionObligation.get("tenant_id", UUID.class), request.candidate().tenantId())
+ || !Objects.equals(
+ regionObligation.get("game_instance_id", UUID.class),
+ request.candidate().gameInstanceId())
+ || !Objects.equals(
+ regionObligation.get("runtime_game_instance_id", Long.class),
+ request.candidate().runtimeGameInstanceId())
+ || !Objects.equals(
+ regionObligation.get("session_id", String.class), request.candidate().sessionId())
+ || !readBigInteger(regionObligation, "region_epoch")
+ .equals(request.candidate().regionEpoch())
+ || !readBigInteger(regionObligation, "inventory_revision")
+ .equals(readBigInteger(transition, "inventory_revision"))) {
+ throw conflict("Stored region bridge request differs from the exact retry");
+ }
+ if (!Objects.equals(reservation.get("transition_id", UUID.class), request.transitionId())
+ || !Objects.equals(
+ reservation.get("account_id", UUID.class), request.candidate().accountId())
+ || !Objects.equals(reservation.get("tenant_id", UUID.class), request.candidate().tenantId())
+ || !Objects.equals(
+ reservation.get("game_instance_id", UUID.class), request.candidate().gameInstanceId())
+ || !Objects.equals(
+ reservation.get("runtime_game_instance_id", Long.class),
+ request.candidate().runtimeGameInstanceId())
+ || !Objects.equals(
+ reservation.get("session_id", String.class), request.candidate().sessionId())
+ || !Objects.equals(reservation.get("issuer_id", UUID.class), request.candidate().issuerId())
+ || !readBigInteger(reservation, "issuer_auth_generation")
+ .equals(request.candidate().issuerAuthGeneration())
+ || !readBigInteger(reservation, "issuer_index_layout_version")
+ .equals(request.candidate().issuerIndexLayoutVersion())
+ || !Objects.equals(
+ readBigInteger(reservation, "issuer_index_partition_count"),
+ request.candidate().issuerIndexPartitionCount())
+ || !Objects.equals(
+ readBigInteger(reservation, "issuer_index_partition_capacity"),
+ request.candidate().issuerIndexPartitionCapacity())
+ || !Objects.equals(
+ readBigInteger(reservation, "partition_id"),
+ request
+ .candidate()
+ .bindingRef()
+ .partitionId(request.candidate().issuerIndexPartitionCount()))
+ || !readBigInteger(reservation, "inventory_revision")
+ .equals(readBigInteger(transition, "inventory_revision"))
+ || !Arrays.equals(
+ reservation.get("binding_ref", byte[].class), request.candidate().bindingRef().bytes())
+ || !readBigInteger(reservation, "binding_generation").equals(candidateGeneration)
+ || !"RESERVED".equals(reservation.get("lifecycle", String.class))) {
+ throw conflict("Stored issuer reservation owner or lifecycle differs from the exact retry");
+ }
+ }
+
+ private static void insertCandidate(
+ DSLContext transaction,
+ CanonicalGameplayBindingTransitionRequest request,
+ CanonicalGameplayBindingTransitionSnapshot prepared,
+ BigInteger partitionId) {
+ CanonicalGameplayBindingIdentity identity = request.candidate();
+ transaction.execute(
+ "INSERT INTO "
+ + INVENTORY
+ + " (binding_ref, account_id, tenant_id, playable_state_namespace_id, character_id,"
+ + " playable_state_scope, game_instance_id, runtime_game_instance_id, session_id,"
+ + " binding_generation, region_id,"
+ + " region_epoch, issuer_id, issuer_auth_generation, issuer_index_layout_version,"
+ + " issuer_index_partition_count, issuer_index_partition_capacity, issuer_partition_id,"
+ + " account_index_fence, issuer_reservation_id, transition_id, lifecycle,"
+ + " account_index_state, issuer_index_state, inventory_revision)"
+ + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,"
+ + " 'CANDIDATE_PREPARED', 'REPAIR_REQUIRED', 'REPAIR_REQUIRED', ?)",
+ prepared.bindingRef().bytes(),
+ identity.accountId(),
+ identity.tenantId(),
+ identity.playableStateNamespaceId(),
+ identity.characterId(),
+ identity.playableStateScope(),
+ identity.gameInstanceId(),
+ identity.runtimeGameInstanceId(),
+ identity.sessionId(),
+ decimal(prepared.bindingGeneration()),
+ identity.regionId(),
+ decimal(identity.regionEpoch()),
+ identity.issuerId(),
+ decimal(identity.issuerAuthGeneration()),
+ decimal(identity.issuerIndexLayoutVersion()),
+ decimal(identity.issuerIndexPartitionCount()),
+ decimal(identity.issuerIndexPartitionCapacity()),
+ decimal(partitionId),
+ request.candidateAccountIndexFence(),
+ request.issuerReservation().reservationId(),
+ request.transitionId(),
+ decimal(prepared.inventoryRevision()));
+ }
+
+ private static void insertTransition(
+ DSLContext transaction,
+ CanonicalGameplayBindingTransitionRequest request,
+ CanonicalGameplayBindingTransitionSnapshot prepared,
+ byte[] expectedPriorRef) {
+ BigInteger expectedPriorGeneration = request.expectedPriorBindingGeneration();
+ CanonicalGameplayAccountCoverageEvidence evidence = prepared.accountCoverageEvidence();
+ UUID coverageOperationId = null;
+ String coverageLifecycle = null;
+ BigInteger coverageOperationFence = null;
+ UUID historicalAccountAdmissionFence = null;
+ String resolvedScopeKind = "NOT_APPLICABLE";
+ UUID resolvedScopeAccountId = null;
+ UUID coverageFence = null;
+ BigInteger coverageGeneration = null;
+ BigInteger accountSnapshotRevision = null;
+ if (evidence instanceof CanonicalGameplayAccountCoverageEvidence.Historical historical) {
+ coverageOperationId = historical.operationId();
+ coverageLifecycle = "HISTORICAL";
+ coverageOperationFence = historical.operationFence();
+ historicalAccountAdmissionFence = historical.historicalAccountAdmissionFence();
+ resolvedScopeKind = "ACCOUNT_WIDE";
+ resolvedScopeAccountId = historical.accountId();
+ coverageFence = historical.coverageFence();
+ coverageGeneration = historical.coverageGeneration();
+ accountSnapshotRevision = historical.inventorySnapshotRevision();
+ }
+ transaction.execute(
+ "INSERT INTO "
+ + TRANSITION
+ + " (transition_id, tenant_id, playable_state_namespace_id, character_id,"
+ + " expected_prior_binding_ref, expected_prior_binding_generation, candidate_binding_ref,"
+ + " candidate_binding_generation, candidate_account_index_fence, issuer_reservation_id,"
+ + " status, inventory_revision, account_coverage_state, account_coverage_operation_id,"
+ + " account_coverage_lifecycle, account_coverage_operation_fence,"
+ + " account_admission_fence_kind, account_admission_fence,"
+ + " historical_account_admission_fence_kind, historical_account_admission_fence,"
+ + " resolved_scope_kind, resolved_scope_account_id, account_coverage_fence,"
+ + " account_coverage_generation, account_inventory_snapshot_revision)"
+ + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PREPARED', ?, ?, ?, ?, ?,"
+ + " 'NOT_APPLICABLE', NULL, ?, ?, ?, ?, ?, ?, ?)",
+ request.transitionId(),
+ request.candidate().tenantId(),
+ request.candidate().playableStateNamespaceId(),
+ request.candidate().characterId(),
+ expectedPriorRef,
+ expectedPriorGeneration == null ? null : decimal(expectedPriorGeneration),
+ prepared.bindingRef().bytes(),
+ decimal(prepared.bindingGeneration()),
+ request.candidateAccountIndexFence(),
+ request.issuerReservation().reservationId(),
+ decimal(prepared.inventoryRevision()),
+ evidence.state().name(),
+ coverageOperationId,
+ coverageLifecycle,
+ coverageOperationFence == null ? null : decimal(coverageOperationFence),
+ historicalAccountAdmissionFence == null ? "NOT_APPLICABLE" : "VALUE",
+ historicalAccountAdmissionFence,
+ resolvedScopeKind,
+ resolvedScopeAccountId,
+ coverageFence,
+ coverageGeneration == null ? null : decimal(coverageGeneration),
+ accountSnapshotRevision == null ? null : decimal(accountSnapshotRevision));
+ }
+
+ private static void insertAccountObligations(
+ DSLContext transaction,
+ CanonicalGameplayBindingTransitionRequest request,
+ CanonicalGameplayBindingTransitionSnapshot prepared,
+ Record active,
+ byte[] expectedPriorRef) {
+ BigInteger expectedPriorGeneration = request.expectedPriorBindingGeneration();
+ transaction.execute(
+ "INSERT INTO "
+ + ACCOUNT_OBLIGATION
+ + " (transition_id, obligation_ordinal, binding_ref, account_id, tenant_id, action,"
+ + " binding_generation, expected_prior_generation, account_index_fence, execution_phase,"
+ + " status, inventory_revision) VALUES (?, 0, ?, ?, ?, 'ADD_OR_RETAIN', ?, ?, ?,"
+ + " 'BEFORE_FINAL_CAS', 'REQUIRED', ?)",
+ request.transitionId(),
+ prepared.bindingRef().bytes(),
+ request.candidate().accountId(),
+ request.candidate().tenantId(),
+ decimal(prepared.bindingGeneration()),
+ expectedPriorGeneration == null ? null : decimal(expectedPriorGeneration),
+ request.candidateAccountIndexFence(),
+ decimal(prepared.inventoryRevision()));
+ if (active != null) {
+ transaction.execute(
+ "INSERT INTO "
+ + ACCOUNT_OBLIGATION
+ + " (transition_id, obligation_ordinal, binding_ref, account_id, tenant_id, action,"
+ + " binding_generation, expected_prior_generation, account_index_fence, execution_phase,"
+ + " status, inventory_revision) VALUES (?, 1, ?, ?, ?, 'REMOVE', ?, ?, ?,"
+ + " 'AFTER_FINAL_CAS', 'REQUIRED', ?)",
+ request.transitionId(),
+ active.get("binding_ref", byte[].class),
+ active.get("account_id", UUID.class),
+ active.get("tenant_id", UUID.class),
+ active.get("binding_generation", BigDecimal.class),
+ active.get("binding_generation", BigDecimal.class),
+ active.get("account_index_fence", UUID.class),
+ decimal(prepared.inventoryRevision()));
+ }
+ }
+
+ private static void insertReservation(
+ DSLContext transaction,
+ CanonicalGameplayBindingTransitionRequest request,
+ CanonicalGameplayBindingTransitionSnapshot prepared,
+ BigInteger partitionId,
+ BigInteger inventoryRevision) {
+ CanonicalGameplayBindingIdentity owner = request.candidate();
+ var fenceEvidence = request.issuerReservation();
+ transaction.execute(
+ "INSERT INTO "
+ + RESERVATION
+ + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id,"
+ + " runtime_game_instance_id, session_id,"
+ + " binding_generation, transition_id, issuer_id, issuer_auth_generation, partition_id,"
+ + " playable_state_namespace_id, character_id, playable_state_scope, region_id, region_epoch,"
+ + " issuer_index_layout_version, issuer_index_partition_count,"
+ + " issuer_index_partition_capacity, lifecycle, reservation_fence,"
+ + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence,"
+ + " inventory_snapshot_revision, inventory_revision)"
+ + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RESERVED', ?, ?, ?, ?, ?, ?)",
+ fenceEvidence.reservationId(),
+ prepared.bindingRef().bytes(),
+ owner.accountId(),
+ owner.tenantId(),
+ owner.gameInstanceId(),
+ owner.runtimeGameInstanceId(),
+ owner.sessionId(),
+ decimal(prepared.bindingGeneration()),
+ request.transitionId(),
+ owner.issuerId(),
+ decimal(owner.issuerAuthGeneration()),
+ decimal(partitionId),
+ owner.playableStateNamespaceId(),
+ owner.characterId(),
+ owner.playableStateScope(),
+ owner.regionId(),
+ decimal(owner.regionEpoch()),
+ decimal(owner.issuerIndexLayoutVersion()),
+ decimal(owner.issuerIndexPartitionCount()),
+ decimal(owner.issuerIndexPartitionCapacity()),
+ fenceEvidence.reservationFence(),
+ fenceEvidence.issuerCoverageOperationId(),
+ decimal(fenceEvidence.issuerCoverageOperationFence()),
+ decimal(fenceEvidence.coverageFence()),
+ decimal(fenceEvidence.inventorySnapshotRevision()),
+ decimal(inventoryRevision));
+ }
+
+ private static void insertIssuerObligation(
+ DSLContext transaction, CanonicalGameplayBindingTransitionSnapshot prepared) {
+ transaction.execute(
+ "INSERT INTO "
+ + ISSUER_OBLIGATION
+ + " (transition_id, binding_ref, binding_generation, reservation_id, status, inventory_revision)"
+ + " VALUES (?, ?, ?, ?, 'REQUIRED', ?)",
+ prepared.transitionId(),
+ prepared.bindingRef().bytes(),
+ decimal(prepared.bindingGeneration()),
+ prepared.issuerReservationId(),
+ decimal(prepared.inventoryRevision()));
+ }
+
+ private static void insertRegionObligation(
+ DSLContext transaction, CanonicalGameplayBindingTransitionSnapshot prepared) {
+ CanonicalGameplayBindingIdentity identity = prepared.candidate();
+ transaction.execute(
+ "INSERT INTO "
+ + REGION_OBLIGATION
+ + " (transition_id, binding_ref, binding_generation, account_id, tenant_id,"
+ + " game_instance_id, runtime_game_instance_id, session_id, region_id, region_epoch,"
+ + " status, inventory_revision)"
+ + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'REQUIRED', ?)",
+ prepared.transitionId(),
+ prepared.bindingRef().bytes(),
+ decimal(prepared.bindingGeneration()),
+ identity.accountId(),
+ identity.tenantId(),
+ identity.gameInstanceId(),
+ identity.runtimeGameInstanceId(),
+ identity.sessionId(),
+ identity.regionId(),
+ decimal(identity.regionEpoch()),
+ decimal(prepared.inventoryRevision()));
+ }
+
+ private static CanonicalGameplayBindingTransitionSnapshot toTransitionSnapshot(
+ Record transition, Record binding, Record reservation) {
+ CanonicalGameplayBindingIdentity identity = toIdentity(binding);
+ CanonicalGameplayBindingRef ref = identity.bindingRef();
+ if (!Arrays.equals(binding.get("binding_ref", byte[].class), ref.bytes())) {
+ throw conflict("Stored canonical bindingRef does not match the exact typed identity");
+ }
+ return new CanonicalGameplayBindingTransitionSnapshot(
+ transition.get("transition_id", UUID.class),
+ identity,
+ readBigInteger(transition, "candidate_binding_generation"),
+ ref,
+ readBigInteger(transition, "inventory_revision"),
+ binding.get("issuer_reservation_id", UUID.class),
+ reservation.get("reservation_fence", UUID.class),
+ transition.get("candidate_account_index_fence", UUID.class),
+ optionalRef(transition.get("expected_prior_binding_ref", byte[].class)),
+ nullableBigInteger(transition, "expected_prior_binding_generation"),
+ CanonicalGameplayBindingTransitionSnapshot.Status.valueOf(
+ transition.get("status", String.class)),
+ toAccountCoverageEvidence(transition, identity.accountId()));
+ }
+
+ private static CanonicalGameplayBindingTransitionSnapshot toTransitionSnapshot(Record row) {
+ CanonicalGameplayBindingIdentity identity = toIdentity(row);
+ CanonicalGameplayBindingRef ref = identity.bindingRef();
+ if (!Arrays.equals(row.get("binding_ref", byte[].class), ref.bytes())) {
+ throw conflict("Stored transition candidate does not match its exact typed identity");
+ }
+ return new CanonicalGameplayBindingTransitionSnapshot(
+ row.get("transition_id", UUID.class),
+ identity,
+ readBigInteger(row, "candidate_binding_generation"),
+ ref,
+ readBigInteger(row, "inventory_revision"),
+ row.get("issuer_reservation_id", UUID.class),
+ row.get("reservation_fence", UUID.class),
+ row.get("candidate_account_index_fence", UUID.class),
+ optionalRef(row.get("expected_prior_binding_ref", byte[].class)),
+ nullableBigInteger(row, "expected_prior_binding_generation"),
+ CanonicalGameplayBindingTransitionSnapshot.Status.valueOf(row.get("status", String.class)),
+ toAccountCoverageEvidence(row, identity.accountId()));
+ }
+
+ private static CanonicalGameplayAccountCoverageEvidence toAccountCoverageEvidence(
+ Record row, UUID accountId) {
+ String state = row.get("account_coverage_state", String.class);
+ if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) {
+ if (row.get("account_coverage_operation_id", UUID.class) != null
+ || row.get("account_coverage_lifecycle", String.class) != null
+ || row.get("account_coverage_operation_fence") != null
+ || !"NOT_APPLICABLE".equals(row.get("account_admission_fence_kind", String.class))
+ || row.get("account_admission_fence", UUID.class) != null
+ || !"NOT_APPLICABLE"
+ .equals(row.get("historical_account_admission_fence_kind", String.class))
+ || row.get("historical_account_admission_fence", UUID.class) != null
+ || !"NOT_APPLICABLE".equals(row.get("resolved_scope_kind", String.class))
+ || row.get("resolved_scope_account_id", UUID.class) != null
+ || row.get("account_coverage_fence", UUID.class) != null
+ || row.get("account_coverage_generation") != null
+ || row.get("account_inventory_snapshot_revision") != null) {
+ throw conflict("Stored no-active account evidence carries a fabricated operation tuple");
+ }
+ return CanonicalGameplayAccountCoverageEvidence.noActiveFlow();
+ }
+ if (!"HISTORICAL".equals(state)
+ || !"HISTORICAL".equals(row.get("account_coverage_lifecycle", String.class))
+ || !"NOT_APPLICABLE".equals(row.get("account_admission_fence_kind", String.class))
+ || row.get("account_admission_fence", UUID.class) != null
+ || !"VALUE".equals(row.get("historical_account_admission_fence_kind", String.class))
+ || !"ACCOUNT_WIDE".equals(row.get("resolved_scope_kind", String.class))
+ || !accountId.equals(row.get("resolved_scope_account_id", UUID.class))) {
+ throw conflict(
+ "Stored historical account evidence is incomplete or belongs to another owner");
+ }
+ return CanonicalGameplayAccountCoverageEvidence.historical(
+ row.get("account_coverage_operation_id", UUID.class),
+ readBigInteger(row, "account_coverage_operation_fence"),
+ row.get("historical_account_admission_fence", UUID.class),
+ row.get("account_coverage_fence", UUID.class),
+ row.get("resolved_scope_account_id", UUID.class),
+ readBigInteger(row, "account_inventory_snapshot_revision"),
+ readBigInteger(row, "account_coverage_generation"));
+ }
+
+ private static CanonicalGameplayBindingInventoryEntry toInventoryEntry(Record row) {
+ CanonicalGameplayBindingIdentity identity = toIdentity(row);
+ CanonicalGameplayBindingRef ref = identity.bindingRef();
+ if (!Arrays.equals(row.get("binding_ref", byte[].class), ref.bytes())) {
+ throw conflict("Stored canonical bindingRef does not match the exact typed identity");
+ }
+ return new CanonicalGameplayBindingInventoryEntry(
+ identity,
+ ref,
+ readBigInteger(row, "binding_generation"),
+ row.get("account_index_fence", UUID.class),
+ row.get("issuer_reservation_id", UUID.class),
+ row.get("transition_id", UUID.class),
+ CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(
+ row.get("lifecycle", String.class)),
+ CanonicalGameplayBindingInventoryEntry.IndexState.valueOf(
+ row.get("account_index_state", String.class)),
+ CanonicalGameplayBindingInventoryEntry.IndexState.valueOf(
+ row.get("issuer_index_state", String.class)),
+ readBigInteger(row, "inventory_revision"));
+ }
+
+ private static CanonicalIssuerPartitionReservation toReservation(Record row) {
+ CanonicalGameplayBindingIdentity owner = toIdentity(row);
+ CanonicalGameplayBindingRef ref = owner.bindingRef();
+ if (!Arrays.equals(row.get("binding_ref", byte[].class), ref.bytes())) {
+ throw conflict("Stored reservation owner does not match its exact bindingRef");
+ }
+ return new CanonicalIssuerPartitionReservation(
+ row.get("reservation_id", UUID.class),
+ owner,
+ readBigInteger(row, "binding_generation"),
+ row.get("transition_id", UUID.class),
+ readBigInteger(row, "partition_id"),
+ CanonicalIssuerPartitionReservation.Lifecycle.valueOf(row.get("lifecycle", String.class)),
+ row.get("reservation_fence", UUID.class),
+ row.get("issuer_coverage_operation_id", UUID.class),
+ readBigInteger(row, "issuer_coverage_operation_fence"),
+ readBigInteger(row, "coverage_fence"),
+ readBigInteger(row, "inventory_snapshot_revision"),
+ readBigInteger(row, "inventory_revision"));
+ }
+
+ private static CanonicalGameplayBindingAccountIndexObligation toAccountObligation(Record row) {
+ CanonicalGameplayBindingIdentity identity = toIdentity(row);
+ CanonicalGameplayBindingRef ref = identity.bindingRef();
+ if (!Arrays.equals(row.get("binding_ref", byte[].class), ref.bytes())
+ || !Objects.equals(row.get("account_id", UUID.class), identity.accountId())
+ || !Objects.equals(row.get("tenant_id", UUID.class), identity.tenantId())) {
+ throw conflict("Stored account obligation owner differs from its exact bindingRef");
+ }
+ return new CanonicalGameplayBindingAccountIndexObligation(
+ row.get("transition_id", UUID.class),
+ row.get("obligation_ordinal", Integer.class),
+ ref,
+ row.get("account_id", UUID.class),
+ row.get("tenant_id", UUID.class),
+ CanonicalGameplayBindingAccountIndexObligation.Action.valueOf(
+ row.get("action", String.class)),
+ readBigInteger(row, "binding_generation"),
+ nullableBigInteger(row, "expected_prior_generation"),
+ row.get("account_index_fence", UUID.class),
+ CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.valueOf(
+ row.get("execution_phase", String.class)),
+ CanonicalGameplayBindingAccountIndexObligation.Status.valueOf(
+ row.get("status", String.class)),
+ readBigInteger(row, "inventory_revision"),
+ CanonicalGameplayBindingAccountIndexObligation.ProjectionState.valueOf(
+ row.get("projection_state", String.class)),
+ row.get("projection_member", String.class),
+ nullableBigInteger(row, "projection_inventory_revision"));
+ }
+
+ private static CanonicalGameplayBindingIssuerIndexObligation toIssuerObligation(Record row) {
+ CanonicalGameplayBindingIdentity identity = toIdentity(row);
+ CanonicalGameplayBindingRef ref = identity.bindingRef();
+ if (!Arrays.equals(row.get("binding_ref", byte[].class), ref.bytes())) {
+ throw conflict("Stored issuer obligation owner differs from its exact bindingRef");
+ }
+ return new CanonicalGameplayBindingIssuerIndexObligation(
+ row.get("transition_id", UUID.class),
+ ref,
+ readBigInteger(row, "binding_generation"),
+ row.get("reservation_id", UUID.class),
+ CanonicalGameplayBindingIssuerIndexObligation.Status.valueOf(
+ row.get("status", String.class)),
+ readBigInteger(row, "inventory_revision"));
+ }
+
+ private static CanonicalGameplayBindingRegionBridgeObligation toRegionObligation(Record row) {
+ UUID tenantId = row.get("tenant_id", UUID.class);
+ UUID gameInstanceId = row.get("game_instance_id", UUID.class);
+ String sessionId = row.get("session_id", String.class);
+ CanonicalGameplayBindingRef ref =
+ CanonicalGameplayBindingRef.of(tenantId, gameInstanceId, sessionId);
+ if (!Arrays.equals(row.get("binding_ref", byte[].class), ref.bytes())) {
+ throw conflict("Stored region obligation bindingRef differs from its exact owner tuple");
+ }
+ return new CanonicalGameplayBindingRegionBridgeObligation(
+ row.get("transition_id", UUID.class),
+ ref,
+ readBigInteger(row, "binding_generation"),
+ row.get("account_id", UUID.class),
+ tenantId,
+ gameInstanceId,
+ row.get("runtime_game_instance_id", Long.class),
+ sessionId,
+ row.get("region_id", UUID.class),
+ readBigInteger(row, "region_epoch"),
+ CanonicalGameplayBindingRegionBridgeObligation.Status.valueOf(
+ row.get("status", String.class)),
+ readBigInteger(row, "inventory_revision"));
+ }
+
+ private static CanonicalGameplayBindingIdentity toIdentity(Record row) {
+ return new CanonicalGameplayBindingIdentity(
+ row.get("account_id", UUID.class),
+ row.get("tenant_id", UUID.class),
+ row.get("playable_state_namespace_id", UUID.class),
+ row.get("character_id", UUID.class),
+ row.get("playable_state_scope", String.class),
+ row.get("game_instance_id", UUID.class),
+ row.get("runtime_game_instance_id", Long.class),
+ row.get("session_id", String.class),
+ row.get("region_id", UUID.class),
+ readBigInteger(row, "region_epoch"),
+ row.get("issuer_id", UUID.class),
+ readBigInteger(row, "issuer_auth_generation"),
+ readBigInteger(row, "issuer_index_layout_version"),
+ readBigInteger(row, "issuer_index_partition_count"),
+ readBigInteger(row, "issuer_index_partition_capacity"));
+ }
+
+ private static BigInteger nullableBigInteger(Record row, String name) {
+ BigDecimal value = row.get(name, BigDecimal.class);
+ return value == null ? null : value.toBigIntegerExact();
+ }
+
+ private static CanonicalGameplayBindingRef optionalRef(byte[] bytes) {
+ return bytes == null ? null : CanonicalGameplayBindingRef.fromExactBytes(bytes);
+ }
+
+ private static BigInteger readBigInteger(Record row, String name) {
+ BigInteger value = nullableBigInteger(row, name);
+ if (value == null) {
+ throw conflict("Required exact numeric evidence is missing: " + name);
+ }
+ return value;
+ }
+
+ private static BigDecimal decimal(BigInteger value) {
+ return new BigDecimal(value);
+ }
+
+ private static void requireOne(int changed, String message) {
+ if (changed != 1) {
+ throw conflict(message);
+ }
+ }
+
+ private static void requireCount(int changed, int expected, String message) {
+ if (changed != expected) {
+ throw conflict(message);
+ }
+ }
+
+ private static CanonicalGameplayBindingInventoryConflictException conflict(String message) {
+ return new CanonicalGameplayBindingInventoryConflictException(message);
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconciler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconciler.java
new file mode 100644
index 0000000000..eb363cd188
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconciler.java
@@ -0,0 +1,362 @@
+package net.firedevops.firemud.gamesession.repository;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot;
+import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity;
+import org.springframework.data.redis.connection.RedisClusterConnection;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.core.Cursor;
+import org.springframework.data.redis.core.RedisCallback;
+import org.springframework.data.redis.core.ScanOptions;
+import org.springframework.data.redis.core.StringRedisTemplate;
+
+/**
+ * Read-only namespace reconciliation for a fully fenced, physically empty disposable cohort.
+ * Nonempty canonical rows and any target namespace key are retained and denied; this adapter does
+ * not contain an active-session serializer or delete path. Only the exact canonical issuer
+ * generation projection key family is outside this namespace result; its owner gate is separate.
+ */
+final class CanonicalGameplayFreshNamespaceRedisReconciler
+ implements CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner {
+ private static final String TARGET_PREFIX = "session:game:";
+ private static final String SCAN_PATTERN = TARGET_PREFIX + "*";
+ private static final String ISSUER_GENERATION_PREFIX = "session:game:auth:issuer-generation:v1:";
+ private static final Pattern CANONICAL_UUID =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final ScanLimits DEFAULT_LIMITS =
+ new ScanLimits(128, 5_000, 20_000, 1_024, Duration.ofSeconds(30));
+
+ private final StringRedisTemplate redis;
+ private final CanonicalGameplayLegacyRedisSource legacySource;
+ private final ScanLimits limits;
+
+ CanonicalGameplayFreshNamespaceRedisReconciler(StringRedisTemplate redis) {
+ this(redis, DEFAULT_LIMITS);
+ }
+
+ CanonicalGameplayFreshNamespaceRedisReconciler(StringRedisTemplate redis, ScanLimits limits) {
+ this.redis = Objects.requireNonNull(redis, "redis");
+ this.legacySource = new CanonicalGameplayLegacyRedisSource(redis);
+ this.limits = Objects.requireNonNull(limits, "limits");
+ }
+
+ /**
+ * Proves the complete empty-only precondition and repeats physical legacy/target scans. This
+ * fresh-cohort operation deliberately performs no Redis mutation.
+ */
+ @Override
+ public void rebuildExact(
+ CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort,
+ CanonicalGameplayLegacyMigrationSourceSnapshot legacySnapshot,
+ CanonicalGameplayBindingInventorySnapshot canonicalSnapshot) {
+ Objects.requireNonNull(cohort, "cohort");
+ Objects.requireNonNull(legacySnapshot, "legacySnapshot");
+ requireEmptyCanonicalSnapshot(canonicalSnapshot);
+ requireEmptyLegacySnapshot(legacySnapshot, "durable legacy source snapshot");
+
+ FenceIdentity fence = FenceIdentity.capture(cohort);
+ long startedAt = System.nanoTime();
+ requireFenceAndTime(cohort, fence, startedAt);
+ requireStandaloneRedisTopology();
+ requireFenceAndTime(cohort, fence, startedAt);
+ CanonicalGameplayLegacyMigrationSourceSnapshot currentLegacy =
+ legacySource.captureEveryKnownFamily(cohort);
+ requireFenceAndTime(cohort, fence, startedAt);
+ requireEmptyLegacySnapshot(currentLegacy, "live legacy source inventory");
+ if (!legacySnapshot.equals(currentLegacy)) {
+ throw conflict("Legacy source inventory changed before namespace reconciliation");
+ }
+
+ Set physicalKeys = scanTargetTwice(cohort, fence, startedAt);
+ requireNoNamespaceKeys(physicalKeys);
+ requireFenceAndTime(cohort, fence, startedAt);
+ }
+
+ /**
+ * Returns empty record lists only after independent complete live legacy and target-family
+ * inventories prove that the same fenced cohort still has no retained rows.
+ */
+ @Override
+ public CanonicalGameplayLegacyMigrationReadback readBackExact(
+ CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort,
+ CanonicalGameplayBindingInventorySnapshot canonicalSnapshot) {
+ Objects.requireNonNull(cohort, "cohort");
+ requireEmptyCanonicalSnapshot(canonicalSnapshot);
+
+ FenceIdentity fence = FenceIdentity.capture(cohort);
+ long startedAt = System.nanoTime();
+ requireFenceAndTime(cohort, fence, startedAt);
+ requireStandaloneRedisTopology();
+ requireFenceAndTime(cohort, fence, startedAt);
+ CanonicalGameplayLegacyMigrationSourceSnapshot currentLegacy =
+ legacySource.captureEveryKnownFamily(cohort);
+ requireFenceAndTime(cohort, fence, startedAt);
+ requireEmptyLegacySnapshot(currentLegacy, "readback legacy source inventory");
+
+ Set physicalKeys = scanTargetTwice(cohort, fence, startedAt);
+ requireNoNamespaceKeys(physicalKeys);
+ requireFenceAndTime(cohort, fence, startedAt);
+ return new CanonicalGameplayLegacyMigrationReadback(List.of(), List.of(), List.of(), List.of());
+ }
+
+ private Set